Calling startActivity() from outside of an Activity?
if your android version is below Android - 6 then you need to add this line otherwise it will work above Android - 6.
...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...
Alarm Manager Example
I tried the solution from XXX and while it did initially work, at some point it stopped working. The onReceive
never got called again. I spent hours trying to figure out what it could be. What I came to realize is that the Intent
for whatever mysterious reason was no longer being called. To get around this, I discovered that you really do need to specify an action for the receiver in the manifest. Example:
<receiver android:name=".Alarm" android:exported="true">
<intent-filter>
<action android:name="mypackage.START_ALARM" >
</action>
</intent-filter>
</receiver>
Note that the name is ".Alarm"
with the period. In XXX's setAlarm
method, create the Intent
as follows:
Intent i = new Intent("mypackage.START_ALARM");
The START_ALARM
message can be whatever you want it to be. I just gave it that name for demonstration purposes.
I have not seen receivers defined in the manifest without an intent filter that specifies the action. Creating them the way XXX has specified it seems kind of bogus. By specifying the action name, Android will be forced to create an instance of the BroadcastReceiver
using the class that corresponds to the action. If you rely upon context, be aware that Android has several different objects that are ALL called context and may not result in getting your BroadcastReceiver
created. Forcing Android to create an instance of your class using only the action message is far better than relying upon some iffy context that may never work.
Android: keeping a background service alive (preventing process death)
When you bind your Service to Activity with BIND_AUTO_CREATE your service is being killed just after your Activity is Destroyed and unbound. It does not depend on how you've implemented your Services unBind method it will be still killed.
The other way is to start your Service with startService method from your Activity. This way even if your Activity is destroyed your service won't be destroyed or even paused but you have to pause/destroy it by yourself with stopSelf/stopService when appropriate.
Dart: mapping a list (list.map)
you can use
moviesTitles.map((title) => Tab(text: title)).toList()
example:
bottom: new TabBar(
controller: _controller,
isScrollable: true,
tabs:
moviesTitles.map((title) => Tab(text: title)).toList()
,
),
How to make shadow on border-bottom?
Try:
_x000D_
_x000D_
div{_x000D_
-webkit-box-shadow:0px 1px 1px #de1dde;_x000D_
-moz-box-shadow:0px 1px 1px #de1dde;_x000D_
box-shadow:0px 1px 1px #de1dde;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_
It generally adds a 1px blurred shadow 1px from the bottom of the box
box-shadow: [horizontal offset] [vertical offset] [blur radius] [color];
use video as background for div
Pure CSS method
It is possible to center a video inside an element just like a cover
sized background-image
without JS using the object-fit
attribute or CSS Transforms
.
2021 answer: object-fit
As pointed in the comments, it is possible to achieve the same result without CSS transform
, but using object-fit
, which I think it's an even better option for the same result:
_x000D_
_x000D_
.video-container {
height: 300px;
width: 300px;
position: relative;
}
.video-container video {
width: 100%;
height: 100%;
position: absolute;
object-fit: cover;
z-index: 0;
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
_x000D_
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
_x000D_
_x000D_
_x000D_
Previous answer: CSS Transform
You can set a video as a background to any HTML element easily thanks to transform
CSS property.
Note that you can use the transform
technique to center vertically and horizontally any HTML element.
_x000D_
_x000D_
.video-container {
height: 300px;
width: 300px;
overflow: hidden;
position: relative;
}
.video-container video {
min-width: 100%;
min-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
_x000D_
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
_x000D_
_x000D_
_x000D_
Error: JAVA_HOME is not defined correctly executing maven
If you are using mac-OS , export JAVA_HOME=/usr/libexec/java_home
need to be changed to export JAVA_HOME=$(/usr/libexec/java_home)
.
Steps to do this :
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
$ source .bash_profile
where /usr/libexec/java_home
is the path of your jvm
How do you determine the size of a file in C?
Try this --
fseek(fp, 0, SEEK_END);
unsigned long int file_size = ftell(fp);
rewind(fp);
What this does is first, seek to the end of the file; then, report where the file pointer is. Lastly (this is optional) it rewinds back to the beginning of the file. Note that fp
should be a binary stream.
file_size contains the number of bytes the file contains. Note that since (according to climits.h) the unsigned long type is limited to 4294967295 bytes (4 gigabytes) you'll need to find a different variable type if you're likely to deal with files larger than that.
Appending a line to a file only if it does not already exist
Here's a sed
version:
sed -e '\|include "/configs/projectname.conf"|h; ${x;s/incl//;{g;t};a\' -e 'include "/configs/projectname.conf"' -e '}' file
If your string is in a variable:
string='include "/configs/projectname.conf"'
sed -e "\|$string|h; \${x;s|$string||;{g;t};a\\" -e "$string" -e "}" file
glob exclude pattern
The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. There are only a few special characters: two different wild-cards, and character ranges are supported [from pymotw: glob – Filename pattern matching].
So you can exclude some files with patterns.
For example to exclude manifests files (files starting with _
) with glob, you can use:
files = glob.glob('files_path/[!_]*')
Converting BitmapImage to Bitmap and vice versa
I've just been trying to use the above in my code and I believe that there is a problem with the Bitmap2BitmapImage function (and possibly the other one as well).
using (MemoryStream ms = new MemoryStream())
Does the above line result in the stream being disposed of? Which means that the returned BitmapImage loses its content.
As I'm a WPF newbie I'm not sure that this is the correct technical explanation, but the code didn't work in my application until I removed the using directive.
How to capitalize the first letter of word in a string using Java?
class Test {
public static void main(String[] args) {
String newString="";
String test="Hii lets cheCk for BEING String";
String[] splitString = test.split(" ");
for(int i=0; i<splitString.length; i++){
newString= newString+ splitString[i].substring(0,1).toUpperCase()
+ splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
}
System.out.println("the new String is "+newString);
}
}
SQL Insert Query Using C#
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}
Cannot connect to Database server (mysql workbench)
For those who ignored that the initial error message displaying is the following one:
The name org.freedesktop.secrets was not provided by any .service files
Make sure to install gnome-keyring using the following
sudo apt install gnome-keyring
how to fire event on file select
You could subscribe for the onchange event on the input field:
<input type="file" id="file" name="file" />
and then:
document.getElementById('file').onchange = function() {
// fire the upload here
};
Clearing a text field on button click
A simple JavaScript function will do the job.
function ClearFields() {
document.getElementById("textfield1").value = "";
document.getElementById("textfield2").value = "";
}
And just have your button call it:
<button type="button" onclick="ClearFields();">Clear</button>
What does void* mean and how to use it?
A pointer to void
is a "generic" pointer type. A void *
can be converted to any other pointer type without an explicit cast. You cannot dereference a void *
or do pointer arithmetic with it; you must convert it to a pointer to a complete data type first.
void *
is often used in places where you need to be able to work with different pointer types in the same code. One commonly cited example is the library function qsort
:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
base
is the address of an array, nmemb
is the number of elements in the array, size
is the size of each element, and compar
is a pointer to a function that compares two elements of the array. It gets called like so:
int iArr[10];
double dArr[30];
long lArr[50];
...
qsort(iArr, sizeof iArr/sizeof iArr[0], sizeof iArr[0], compareInt);
qsort(dArr, sizeof dArr/sizeof dArr[0], sizeof dArr[0], compareDouble);
qsort(lArr, sizeof lArr/sizeof lArr[0], sizeof lArr[0], compareLong);
The array expressions iArr
, dArr
, and lArr
are implicitly converted from array types to pointer types in the function call, and each is implicitly converted from "pointer to int
/double
/long
" to "pointer to void
".
The comparison functions would look something like:
int compareInt(const void *lhs, const void *rhs)
{
const int *x = lhs; // convert void * to int * by assignment
const int *y = rhs;
if (*x > *y) return 1;
if (*x == *y) return 0;
return -1;
}
By accepting void *
, qsort
can work with arrays of any type.
The disadvantage of using void *
is that you throw type safety out the window and into oncoming traffic. There's nothing to protect you from using the wrong comparison routine:
qsort(dArr, sizeof dArr/sizeof dArr[0], sizeof dArr[0], compareInt);
compareInt
is expecting its arguments to be pointing to int
s, but is actually working with double
s. There's no way to catch this problem at compile time; you'll just wind up with a missorted array.
How do you get the selected value of a Spinner?
This is another way:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
How do files get into the External Dependencies in Visual Studio C++?
The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).
You need to actually include the header (using a #include
directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.
Check if a string is palindrome
Note that reversing the whole string (either with the rbegin()
/rend()
range constructor or with std::reverse
) and comparing it with the input would perform unnecessary work.
It's sufficient to compare the first half of the string with the latter half, in reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
std::cout << "is a palindrome.\n";
else
std::cout << "is NOT a palindrome.\n";
}
demo: http://ideone.com/mq8qK
Creating a new empty branch for a new project
Let's say you have a master
branch with files/directories:
> git branch
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n
Step by step how to make an empty branch:
git checkout —orphan new_branch_name
- Make sure you are in the right directory before executing the following command:
ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
git rm -rf .
touch new_file
git add new_file
git commit -m 'added first file in the new branch'
git push origin new_branch_name
In step 2, we simply remove all the files locally to avoid confusion with the files on your new branch and those ones you keep in master
branch.
Then, we unlink all those files in step 3. Finally, step 4 and after are working with our new empty branch.
Once you're done, you can easily switch between your branches:
git checkout master
git checkout new_branch
GLYPHICONS - bootstrap icon font hex value
If you want to use glyph icons with bootstrap 2.3.2, Add the font files from bootstrap 3 to your project folder then copy this to your css file
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
Python socket connection timeout
You just need to use the socket settimeout()
method before attempting the connect()
, please note that after connecting you must settimeout(None)
to set the socket into blocking mode, such is required for the makefile .
Here is the code I am using:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)
Mapping two integers to one, in a unique and deterministic way
Say you have a 32 bit integer, why not just move A into the first 16 bit half and B into the other?
def vec_pack(vec):
return vec[0] + vec[1] * 65536;
def vec_unpack(number):
return [number % 65536, number // 65536];
Other than this being as space efficient as possible and cheap to compute, a really cool side effect is that you can do vector math on the packed number.
a = vec_pack([2,4])
b = vec_pack([1,2])
print(vec_unpack(a+b)) # [3, 6] Vector addition
print(vec_unpack(a-b)) # [1, 2] Vector subtraction
print(vec_unpack(a*2)) # [4, 8] Scalar multiplication
Reverse a string in Java
You can use a for statement too:
for (int y = 0; y < phrase.length(); y--){
char ch = phrase.charAt(y-1);
System.out.print(ch);
}
How to solve java.lang.NullPointerException error?
Just a shot in the dark(since you did not share the compiler
initialization code with us): the way you retrieve the compiler
causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE
.
JavaScript Nested function
When you declare a function within a function, the inner functions are only available in the scope in which they are declared, or in your case, the pad2
can only be called in the dmy
scope.
All the variables existing in dmy
are visible in pad2
, but it doesn't happen the other way around :D
Why won't my PHP app send a 404 error?
If you want to show the server’s default 404 page, you can load it in a frame like this:
echo '<iframe src="/something-bogus" width="100%" height="100%" frameBorder="0" border="0" scrolling="no"></iframe>';
How to start new activity on button click
The Most simple way to open activity on button click is:
- Create two activities under the res folder, add a button to the first activity and give a name to
onclick
function.
- There should be two java files for each activity.
- Below is the code:
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
SecondActivity.java
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
}
}
AndroidManifest.xml(Just add this block of code to the existing)
</activity>
<activity android:name=".SecondActivity">
</activity>
Java: using switch statement with enum under subclass
Write someMethod()
in this way:
public void someMethod() {
SomeClass.AnotherClass.MyEnum enumExample = SomeClass.AnotherClass.MyEnum.VALUE_A;
switch (enumExample) {
case VALUE_A:
break;
}
}
In switch statement you must use the constant name only.
Simplest way to merge ES6 Maps/Sets?
Based off of Asaf Katz's answer, here's a typescript version:
export function union<T> (...iterables: Array<Set<T>>): Set<T> {
const set = new Set<T>()
iterables.forEach(iterable => {
iterable.forEach(item => set.add(item))
})
return set
}
Jquery to open Bootstrap v3 modal of remote url
So basically, in jquery what we can do is to load href attribute using the load function. This way we can use the url in <a>
tag and load that in modal-body.
<a href='/site/login' class='ls-modal'>Login</a>
//JS script
$('.ls-modal').on('click', function(e){
e.preventDefault();
$('#myModal').modal('show').find('.modal-body').load($(this).attr('href'));
});
how to implement login auth in node.js
@alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:
function checkAuth(req, res, next) {
// if logined or it's login request, then go next route
if (isLogin || (req.path === '/login' && req.method === 'POST')) {
next()
} else {
res.send('Not logged in yet.')
}
}
app.use('/', checkAuth)
Node.js + Nginx - What now?
Node.js with Nginx configuration.
$ sudo nano /etc/nginx/sites-available/subdomain.your_domain.com
add the following configuration so that Nginx acting as a proxy redirect to port 3000 traffic from the server when we come from “subdomain.your_domain.com”
upstream subdomain.your_domain.com {
server 127.0.0.1:3000;
}
server {
listen 80;
listen [::]:80;
server_name subdomain.your_domain.com;
access_log /var/log/nginx/subdomain.your_domain.access.log;
error_log /var/log/nginx/subdomain.your_domain.error.log debug;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://subdomain.your_domain.com;
proxy_redirect off;
}
}
jQuery UI tabs. How to select a tab based on its id not based on index
I did it like this
if (document.location.hash != '') {
//get the index from URL hash
var tabSelect = document.location.hash.substr(1, document.location.hash.length);
console.log("tabSelect: " + tabSelect);
if (tabSelect == 'discount')
{
var index = $('#myTab a[href="#discount"]').parent().index();
$("#tabs").tabs("option", "active", index);
$($('#myTab a[href="#discount"]')).tab('show');
}
}
How to change port number for apache in WAMP
From the wampserver 3.x onwards, changing the listening port number of Apache does not require any particular Apache skills (http.conf, virtualhost,...), you just have to click button - assuming you're running Windows OS! :
- In the tray, right click green/running WAMP icon
- Select menu Tools
- In the section Port used by Apache: xx, click Use a port other than 80 (i.e. default port configuration)
- Enter the desired port number in the popup window - usually 8080 as alternative Web port
NB: For alternative port: check official IANA Service Name and Transport Protocol Port Number Registry
Passing a string array as a parameter to a function java
All the answers above are correct. But just note that you'll be passing the reference to the string array when you pass like this. If you make any modifications to the array in your called function, it will be reflected in the calling function also.
There is another concept called variable arguments in Java which you can look into. It basically works like this. Eg:-
String concat (String ... strings)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < strings.length; i++)
sb.append (strings [i]);
return sb.toString ();
}
Here we can call the function like concat(a,b,c,d) or any number of params you want.
More Info: http://today.java.net/pub/a/today/2004/04/19/varargs.html
How to display Woocommerce Category image?
You may also used foreach loop for display category image and etc from parent category given by parent id.
for example, i am giving 74 id of parent category, then i will display the image from child category and its slug also.
**<?php
$catTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC', 'child_of'=>'74'));
foreach($catTerms as $catTerm) : ?>
<?php $thumbnail_id = get_woocommerce_term_meta( $catTerm->term_id, 'thumbnail_id', true );
// get the image URL
$image = wp_get_attachment_url( $thumbnail_id ); ?>
<li><img src="<?php echo $image; ?>" width="152" height="245"/><span><?php echo $catTerm->name; ?></span></li>
<?php endforeach; ?>**
Does my application "contain encryption"?
I found this FAQ from the US Bureau of Industry and Security very helpful.
encryption
Question 15 (What is Note 4?) is the important point:
...
Examples of items that are excluded from Category 5, Part 2 by Note 4 include, but are not limited to, the following:
Consumer applications. Some examples:
piracy and theft prevention for software or music;
music, movies, tunes/music, digital photos – players, recorders and organizers
games/gaming – devices, runtime software, HDMI and other component interfaces, development tools
LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing);
printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies
household utilities and appliances
How to check for file lock?
You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.
public static string GetFileProcessName(string filePath)
{
Process[] procs = Process.GetProcesses();
string fileName = Path.GetFileName(filePath);
foreach (Process proc in procs)
{
if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)
{
ProcessModule[] arr = new ProcessModule[proc.Modules.Count];
foreach (ProcessModule pm in proc.Modules)
{
if (pm.ModuleName == fileName)
return proc.ProcessName;
}
}
}
return null;
}
How to return the output of stored procedure into a variable in sql server
Use this code, Working properly
CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT
AS
Begin
DECLARE @cnt int;
DECLARE @status int =0;
SET NOCOUNT OFF
SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
if(@cnt = 1)
Begin
return @status;
End
else
Begin
SET @status =1;
return @status;
End
END
Execute SP
DECLARE @statuss bit;
EXECUTE [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;
Named colors in matplotlib
I constantly forget the names of the colors I want to use and keep coming back to this question =)
The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.
I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.
I really didn't change much from the matplotlib example, but here is the code for completeness.
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]
n = len(sorted_names)
ncols = 4
nrows = n // ncols
fig, ax = plt.subplots(figsize=(12, 10))
# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols
for i, name in enumerate(sorted_names):
row = i % nrows
col = i // nrows
y = Y - (row * h) - h
xi_line = w * (col + 0.05)
xf_line = w * (col + 0.25)
xi_text = w * (col + 0.3)
ax.text(xi_text, y, name, fontsize=(h * 0.8),
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y + h * 0.1, xi_line, xf_line,
color=colors[name], linewidth=(h * 0.8))
ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()
fig.subplots_adjust(left=0, right=1,
top=1, bottom=0,
hspace=0, wspace=0)
plt.show()
Additional named colors
Updated 2017-10-25. I merged my previous updates into this section.
xkcd
If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:
plt.plot([1,2], lw=4, c='xkcd:baby poop green')
Now you have access to a plethora of named colors!
Tableau
The default Tableau colors are available in matplotlib via the 'tab:' prefix:
plt.plot([1,2], lw=4, c='tab:green')
There are ten distinct colors:
HTML
You can also plot colors by their HTML hex code:
plt.plot([1,2], lw=4, c='#8f9805')
This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...
For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py
.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
How to initialize a nested struct?
You can define a struct and create its object in another struct like i have done below:
package main
import "fmt"
type Address struct {
streetNumber int
streetName string
zipCode int
}
type Person struct {
name string
age int
address Address
}
func main() {
var p Person
p.name = "Vipin"
p.age = 30
p.address = Address{
streetName: "Krishna Pura",
streetNumber: 14,
zipCode: 475110,
}
fmt.Println("Name: ", p.name)
fmt.Println("Age: ", p.age)
fmt.Println("StreetName: ", p.address.streetName)
fmt.Println("StreeNumber: ", p.address.streetNumber)
}
Hope it helped you :)
How can I create an observable with a delay
It's little late to answer ... but just in case may be someone return to this question looking for an answer
'delay' is property(function) of an Observable
fakeObservable = Observable.create(obs => {
obs.next([1, 2, 3]);
obs.complete();
}).delay(3000);
This worked for me ...
In Java, how to append a string more efficiently?
You can use StringBuffer
or StringBuilder
for this. Both are for dynamic string manipulation. StringBuffer
is thread-safe where as StringBuilder
is not.
Use StringBuffer
in a multi-thread environment. But if it is single threaded StringBuilder
is recommended and it is much faster than StringBuffer
.
Git Push error: refusing to update checked out branch
Maybe your remote repo is in the branch which you want to push. You can try to checkout another branch in your remote machine. I did this, than these error disappeared, and I pushed success to my remote repo. Notice that I use ssh to connect my own server instead of github.com.
QtCreator: No valid kits found
I had a similar problems after installing Qt in Windows.
This could be because only the Qt creator was installed and not any of the Qt libraries during initial installation. When installing from scratch use the online installer and select the following to install:
For starting, select at least one version of Qt libs (ex Qt 5.15.1) and the c++ compiler of choice (ex MinGW 8.1.0 64-bit).
Select Developer and Designer Tools. I kept the selected defaults.
Note: The choice of the Qt libs and Tools can also be changed post initial installation using MaintenanceTool.exe under Qt installation dir C:\Qt
. See here.
keypress, ctrl+c (or some combo like that)
In my case, I was looking for a keydown ctrl key and click event.
My jquery looks like this:
$('.linkAccess').click( function (event) {
if(true === event.ctrlKey) {
/* Extract the value */
var $link = $('.linkAccess');
var value = $link.val();
/* Verified if the link is not null */
if('' !== value){
window.open(value);
}
}
});
Where "linkAccess" is the class name for some specific fields where I have a link and I want to access it using my combination of key and click.
Checking for an empty field with MySQL
This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.
$aUsers=$this->readToArray('
SELECT `userID`
FROM `users`
WHERE `userID`
IN(SELECT `userID`
FROM `users_indvSettings`
WHERE `indvSettingID`=5 AND `optionID`='.$time.')
AND `email` != "" AND `email` IS NOT NULL
');
Changing Shell Text Color (Windows)
Been looking into this for a while and not got any satisfactory answers, however...
1) ANSI escape sequences do work in a terminal on Linux
2) if you can tolerate a limited set of colo(u)rs try this:
print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")
In idle "hello" and "goodbye" are in blue and "error" is in red.
Not fantastic, but good enough for now, and easy!
Import file size limit in PHPMyAdmin
I am using Bitnami WAMP Stack 7.1.8-0 on my localhost. For me, the PHPMyAdmin maximum upload size limit was set to 80MiB as in the screenshot https://nimb.ws/fFxv7O. I managed to increase this size limit as explained below:
- Go to the folder where you have installed the Bitname WAMP Stack, for me, it is "E:\Bitnami WAMP Stack”
- Further inside, go to the path “apps\phpmyadmin\conf"
- Open the file httpd-app.conf in your favorite text editor
- Find the following two lines:
php_value upload_max_filesize 80M
php_value post_max_size 80M
(The 80M value at the end of these lines may be different for you)
Go ahead and change these values at the end of these two lines (80M in this case) according to your needs.
Restart WAMP server.
Now go to PHPMyAdmin and see, your upload size limit should be updated to whatever you set it to. That is it.
What is Domain Driven Design?
Here is another good article that you may check out on Domain Driven Design. if your application is anything serious than college assignment. The basic premise is structure everything around your entities and have a strong domain model. Differentiate between services that provide infrastructure related things (like sending email, persisting data) and services that actually do things that are your core business requirments.
Hope that helps.
How to convert an Image to base64 string in java?
The problem is that you are returning the toString()
of the call to Base64.encodeBase64(bytes)
which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.
Instead, you should do:
encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");
Converting JSON to XML in Java
If you want to replace any node value you can do like this
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
xml.replace("old value", "new value");
How to run Nginx within a Docker container without halting?
For all who come here trying to run a nginx image in a docker
container, that will run as a service
As there is no whole Dockerfile, here is my whole Dockerfile
solving the issue.
Nice and working. Thanks to all answers here in order to solve the final nginx issue.
FROM ubuntu:18.04
MAINTAINER stackoverfloguy "[email protected]"
RUN apt-get update -y
RUN apt-get install net-tools nginx ufw sudo -y
RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER docker
RUN sudo ufw default allow incoming
RUN sudo rm /etc/nginx/nginx.conf
RUN sudo rm /etc/nginx/sites-available/default
RUN sudo rm /var/www/html/index.nginx-debian.html
VOLUME /var/log
VOLUME /usr/share/nginx/html
VOLUME /etc/nginx
VOLUME /var/run
COPY conf/nginx.conf /etc/nginx/nginx.conf
COPY content/* /var/www/html/
COPY Dockerfile /var/www/html
COPY start.sh /etc/nginx/start.sh
RUN sudo chmod +x /etc/nginx/start.sh
RUN sudo chmod -R 777 /var/www/html
EXPOSE 80
EXPOSE 443
ENTRYPOINT sudo nginx -c /etc/nginx/nginx.conf -g 'daemon off;'
And run it with:
docker run -p 80:80 -p 443:443 -dit
What is the purpose of "&&" in a shell command?
Furthermore, you also have ||
which is the logical or, and also ;
which is just a separator which doesn't care what happend to the command before.
$ false || echo "Oops, fail"
Oops, fail
$ true || echo "Will not be printed"
$
$ true && echo "Things went well"
Things went well
$ false && echo "Will not be printed"
$
$ false ; echo "This will always run"
This will always run
Some details about this can be found here Lists of Commands in the Bash Manual.
How can I read SMS messages from the device programmatically in Android?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final String myPackageName = getPackageName();
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
startActivityForResult(intent, 1);
}else {
List<Sms> lst = getAllSms();
}
}else {
List<Sms> lst = getAllSms();
}
Set app as default SMS app
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final String myPackageName = getPackageName();
if (Telephony.Sms.getDefaultSmsPackage(mActivity).equals(myPackageName)) {
List<Sms> lst = getAllSms();
}
}
}
}
}
Function to get SMS
public List<Sms> getAllSms() {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/");
ContentResolver cr = mActivity.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
mActivity.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
objSms = new Sms();
objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
objSms.setAddress(c.getString(c
.getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setReadState(c.getString(c.getColumnIndex("read")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
objSms.setFolderName("inbox");
} else {
objSms.setFolderName("sent");
}
lstSms.add(objSms);
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS");
// }
c.close();
return lstSms;
}
Sms class is below:
public class Sms{
private String _id;
private String _address;
private String _msg;
private String _readState; //"0" for have not read sms and "1" for have read sms
private String _time;
private String _folderName;
public String getId(){
return _id;
}
public String getAddress(){
return _address;
}
public String getMsg(){
return _msg;
}
public String getReadState(){
return _readState;
}
public String getTime(){
return _time;
}
public String getFolderName(){
return _folderName;
}
public void setId(String id){
_id = id;
}
public void setAddress(String address){
_address = address;
}
public void setMsg(String msg){
_msg = msg;
}
public void setReadState(String readState){
_readState = readState;
}
public void setTime(String time){
_time = time;
}
public void setFolderName(String folderName){
_folderName = folderName;
}
}
Don't forget to define permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_SMS" />
Correct way to initialize HashMap and can HashMap hold different value types?
This is a change made with Java 1.5. What you list first is the old way, the second is the new way.
By using HashMap you can do things like:
HashMap<String, Doohickey> ourMap = new HashMap<String, Doohickey>();
....
Doohickey result = ourMap.get("bob");
If you didn't have the types on the map, you'd have to do this:
Doohickey result = (Doohickey) ourMap.get("bob");
It's really very useful. It helps you catch bugs and avoid writing all sorts of extra casts. It was one of my favorite features of 1.5 (and newer).
You can still put multiple things in the map, just specify it as Map, then you can put any object in (a String, another Map, and Integer, and three MyObjects if you are so inclined).
How can I use the MS JDBC driver with MS SQL Server 2008 Express?
The latest JDBC MSSQL connectivity driver can be found on
JDBC 4.0
The class file should be in the classpath. If you are using eclipse you can easily do the same by doing the following -->
Right Click Project Name --> Properties --> Java Build Path -->
Libraries --> Add External Jars
Also as already been pointed out by @Cheeso the correct way to access is jdbc:sqlserver://server:port;DatabaseName=dbname
Meanwhile please find a sample class for accessing MSSQL DB (2008 in my case).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from SampleTable";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://xx.xx.xx.xxxx:1433;databaseName=MyDBName", "DB_USER","DB_PASSWORD");
}
}
Hope this helps.
Clear text area
try this
$("#vinanghinguyen_images_bbocde").attr("value", "");
Multiple REPLACE function in Oracle
The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE
statements, and I don't think there is a better way.
If you are going to make heavy use of this, you could consider writing your own function:
CREATE TYPE t_text IS TABLE OF VARCHAR2(256);
CREATE FUNCTION multiple_replace(
in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
RETURN VARCHAR2
AS
v_result VARCHAR2(32767);
BEGIN
IF( in_old.COUNT <> in_new.COUNT ) THEN
RETURN in_text;
END IF;
v_result := in_text;
FOR i IN 1 .. in_old.COUNT LOOP
v_result := REPLACE( v_result, in_old(i), in_new(i) );
END LOOP;
RETURN v_result;
END;
and then use it like this:
SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
NEW t_text( 'text', 'tokens', 'replace' )
)
FROM dual
This is text with some tokens to replace
If all of your tokens have the same format ('#VAL' || i || '#'
), you could omit parameter in_old
and use your loop-counter instead.
How do I use disk caching in Picasso?
For caching, I would use OkHttp interceptors to gain control over caching policy. Check out this sample that's included in the OkHttp library.
RewriteResponseCacheControl.java
Here's how I'd use it with Picasso -
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)).build();
}
});
okHttpClient.setCache(new Cache(mainActivity.getCacheDir(), Integer.MAX_VALUE));
OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
Picasso picasso = new Picasso.Builder(mainActivity).downloader(okHttpDownloader).build();
picasso.load(imageURL).into(viewHolder.image);
Could not open input file: artisan
After struggling with this issue, I found out that you need to find where artisan resides by running sudo find / -name artisan
,
and from there run the command php artisan ....
CMake link to external library
arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:
You could add an "imported" library target, instead of a link-directory. Something like:
# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )
And then link as if this library was built by your project:
TARGET_LINK_LIBRARIES(GLBall mylib)
Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.
I do not know if this will solve your problem with "updated versions of libs".
jQuery see if any or no checkboxes are selected
You can do a simple return of the .length
here:
function areAnyChecked(formID) {
return !!$('#'+formID+' input[type=checkbox]:checked').length;
}
This look for checkboxes in the given form, sees if any are :checked
and returns true
if they are (since the length would be 0 otherwise). To make it a bit clearer, here's the non boolean converted version:
function howManyAreChecked(formID) {
return $('#'+formID+' input[type=checkbox]:checked').length;
}
This would return a count of how many were checked.
Android Center text on canvas
In my case, I didn't have to put the text in the middle of a canvas, but in a wheel that spins. Though I had to use this code to succeed:
fun getTextRect(textSize: Float, textPaint: TextPaint, string: String) : PointF {
val rect = RectF(left, top, right, bottom)
val rectHeight = Rect()
val cx = rect.centerX()
val cy = rect.centerY()
textPaint.getTextBounds(string, 0, string.length, rectHeight)
val y = cy + rectHeight.height()/2
val x = cx - textPaint.measureText(string)/2
return PointF(x, y)
}
Then I call this method from the View class:
private fun drawText(canvas: Canvas, paint: TextPaint, text: String, string: String) {
val pointF = getTextRect(paint.textSize, textPaint, string)
canvas.drawText(text, pointF!!.x, pointF.y, paint)
}
How to import the class within the same directory or sub directory?
You can import the module and have access through its name if you don't want to mix functions and classes with yours
import util # imports util.py
util.clean()
util.setup(4)
or you can import the functions and classes to your code
from util import clean, setup
clean()
setup(4)
you can use wildchar * to import everything in that module to your code
from util import *
clean()
setup(4)
How does a PreparedStatement avoid or prevent SQL injection?
The SQL used in a PreparedStatement is precompiled on the driver. From that point on, the parameters are sent to the driver as literal values and not executable portions of SQL; thus no SQL can be injected using a parameter. Another beneficial side effect of PreparedStatements (precompilation + sending only parameters) is improved performance when running the statement multiple times even with different values for the parameters (assuming that the driver supports PreparedStatements) as the driver does not have to perform SQL parsing and compilation each time the parameters change.
How to create a zip archive of a directory in Python?
Try the below one .it worked for me.
import zipfile, os
zipf = "compress.zip"
def main():
directory = r"Filepath"
toZip(directory)
def toZip(directory):
zippedHelp = zipfile.ZipFile(zipf, "w", compression=zipfile.ZIP_DEFLATED )
list = os.listdir(directory)
for file_list in list:
file_name = os.path.join(directory,file_list)
if os.path.isfile(file_name):
print file_name
zippedHelp.write(file_name)
else:
addFolderToZip(zippedHelp,file_list,directory)
print "---------------Directory Found-----------------------"
zippedHelp.close()
def addFolderToZip(zippedHelp,folder,directory):
path=os.path.join(directory,folder)
print path
file_list=os.listdir(path)
for file_name in file_list:
file_path=os.path.join(path,file_name)
if os.path.isfile(file_path):
zippedHelp.write(file_path)
elif os.path.isdir(file_name):
print "------------------sub directory found--------------------"
addFolderToZip(zippedHelp,file_name,path)
if __name__=="__main__":
main()
PHP remove commas from numeric strings
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
Selecting a row in DataGridView programmatically
Not tested, but I think you can do the following:
dataGrid.Rows[index].Selected = true;
or you could do the following (but again: not tested):
dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
if(YOUR CONDITION)
row.Selected = true;
}
How to fix div on scroll
(function($) {
var triggers = [];
$.fn.floatingFixed = function(options) {
options = $.extend({}, $.floatingFixed.defaults, options);
var r = $(this).each(function() {
var $this = $(this), pos = $this.position();
pos.position = $this.css("position");
$this.data("floatingFixedOrig", pos);
$this.data("floatingFixedOptions", options);
triggers.push($this);
});
windowScroll();
return r;
};
$.floatingFixed = $.fn.floatingFixed;
$.floatingFixed.defaults = {
padding: 0
};
var $window = $(window);
var windowScroll = function() {
if(triggers.length === 0) { return; }
var scrollY = $window.scrollTop();
for(var i = 0; i < triggers.length; i++) {
var t = triggers[i], opt = t.data("floatingFixedOptions");
if(!t.data("isFloating")) {
var off = t.offset();
t.data("floatingFixedTop", off.top);
t.data("floatingFixedLeft", off.left);
}
var top = top = t.data("floatingFixedTop");
if(top < scrollY + opt.padding && !t.data("isFloating")) {
t.css({position: 'fixed', top: opt.padding, left: t.data("floatingFixedLeft"), width: t.width() }).data("isFloating", true);
} else if(top >= scrollY + opt.padding && t.data("isFloating")) {
var pos = t.data("floatingFixedOrig");
t.css(pos).data("isFloating", false);
}
}
};
$window.scroll(windowScroll).resize(windowScroll);
})(jQuery);
and then make any div as floating fixed by calling
$('#id of the div').floatingFixed();
source: https://github.com/cheald/floatingFixed
UIWebView open links in Safari
The accepted answer does not work.
If your page loads URLs via Javascript, the navigationType
will be UIWebViewNavigationTypeOther
. Which, unfortunately, also includes background page loads such as analytics.
To detect page navigation, you need to compare the [request URL]
to the [request mainDocumentURL]
.
This solution will work in all cases:
- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type
{
if ([[request URL] isEqual:[request mainDocumentURL]])
{
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
else
{
return YES;
}
}
REST URI convention - Singular or plural name of resource while creating it
For me is better to have a schema that you can map directly to code (easy to automate), mainly because code is what is going to be at both ends.
GET /orders <---> orders
POST /orders <---> orders.push(data)
GET /orders/1 <---> orders[1]
PUT /orders/1 <---> orders[1] = data
GET /orders/1/lines <---> orders[1].lines
POST /orders/1/lines <---> orders[1].lines.push(data)
List all files in one directory PHP
You are looking for the command scandir.
$path = '/tmp';
$files = scandir($path);
Following code will remove .
and ..
from the returned array from scandir
:
$files = array_diff(scandir($path), array('.', '..'));
Determine if two rectangles overlap each other?
struct rect
{
int x;
int y;
int width;
int height;
};
bool valueInRange(int value, int min, int max)
{ return (value >= min) && (value <= max); }
bool rectOverlap(rect A, rect B)
{
bool xOverlap = valueInRange(A.x, B.x, B.x + B.width) ||
valueInRange(B.x, A.x, A.x + A.width);
bool yOverlap = valueInRange(A.y, B.y, B.y + B.height) ||
valueInRange(B.y, A.y, A.y + A.height);
return xOverlap && yOverlap;
}
What does it mean to have an index to scalar variable error? python
IndexError: invalid index to scalar variable
happens when you try to index a numpy
scalar such as numpy.int64
or numpy.float64
. It is very similar to TypeError: 'int' object has no attribute '__getitem__'
when you try to index an int
.
>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'
Can't compare naive and aware datetime.now() <= challenge.datetime_end
Just:
dt = datetimeObject.strftime(format) # format = your datetime format ex) '%Y %d %m'
dt = datetime.datetime.strptime(dt,format)
So do this:
start_time = challenge.datetime_start.strftime('%Y %d %m %H %M %S')
start_time = datetime.datetime.strptime(start_time,'%Y %d %m %H %M %S')
end_time = challenge.datetime_end.strftime('%Y %d %m %H %M %S')
end_time = datetime.datetime.strptime(end_time,'%Y %d %m %H %M %S')
and then use start_time
and end_time
What's the difference between Apache's Mesos and Google's Kubernetes
Mesos and Kubernetes can both be used to manage a cluster of machines and abstract away the hardware.
Mesos, by design, doesn't provide you with a scheduler (to decide where and when to run processes and what to do if the process fails), you can use something like Marathon or Chronos, or write your own.
Kubernetes will do scheduling for you out of the box, and can be used as a scheduler for Mesos (please correct me if I'm wrong here!) which is where you can use them together. Mesos can have multiple schedulers sharing the same cluster, so in theory you could run kubernetes and chronos together on the same hardware.
Super simplistically: if you want control over how your containers are scheduled, go for Mesos, otherwise Kubernetes rocks.
C++ template typedef
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
Simple Random Samples from a Sql database
Starting with the observation that we can retrieve the ids of a table (eg. count 5) based on a set:
select *
from table_name
where _id in (4, 1, 2, 5, 3)
we can come to the result that if we could generate the string "(4, 1, 2, 5, 3)"
, then we would have a more efficient way than RAND()
.
For example, in Java:
ArrayList<Integer> indices = new ArrayList<Integer>(rowsCount);
for (int i = 0; i < rowsCount; i++) {
indices.add(i);
}
Collections.shuffle(indices);
String inClause = indices.toString().replace('[', '(').replace(']', ')');
If ids have gaps, then the initial arraylist indices
is the result of an sql query on ids.
Make Adobe fonts work with CSS3 @font-face in IE9
It is true that IE9 requires TTF fonts to have the embedding bits set to Installable. The Generator does this automatically, but we are currently blocking Adobe fonts for other reasons. We may lift this restriction in the near future.
How to get the MD5 hash of a file in C++?
Using Crypto++, you could do the following:
#include <sha.h>
#include <iostream>
SHA256 sha;
while ( !f.eof() ) {
char buff[4096];
int numchars = f.read(...);
sha.Update(buff, numchars);
}
char hash[size];
sha.Final(hash);
cout << hash <<endl;
I have a need for something very similar, because I can't read in multi-gigabyte files just to compute a hash. In theory I could memory map them, but I have to support 32bit platforms - that's still problematic for large files.
Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell
In Excel 2010 it is easy, just takes a few more steps for each list items.
The following steps must be completed for each item within the validation list.
(Have the worksheet open to where the drop down was created)
1) Click on cell with drop down list.
2) Select which answer to apply format to.
3) Click on "Home" tab, then click the "Styles" tool button on the ribbon.
4) Click "Conditional Formatting", in drop down list click the "*New Rule" option.
5) Select a Rule Type: "Format only cells that contain"
6) Edit the Rule Description: "Cell Value", "equal to", click the cell formula icon in
the formula bar (far right), select which worksheet the validation list was created in,
select the cell within the list to which you wish to apply the formatting.
Formula should look something like: ='Workbook Data'!$A$2
7) Click the formula icon again to return to format menu.
8) Click on Format button beside preview pane.
9) Select all format options desired.
10) Press "OK" twice.
You are finished with only one item within list. Repeat steps 1 thru 10 until all drop down list items are finished.
ngrok command not found
Short answer: Put the executable file in /usr/local/bin
instead of applications. You should now be able to run commands like ngrok http 80
.
Long answer: When you type commands like ngrok
in the terminal, Macs (and other Unix OSs) look for these programs in the folders specified in your PATH
. The PATH
is a list of folders that's specified by each user. To check your path, open the terminal and type: echo $PATH
.
You'll see output that looks something like: /usr/local/bin:/usr/bin:/bin
. This is a :
separated list of folders.
So when you type ngrok
in the terminal, your Mac will look for this executable in the following folders: /usr/local/bin
, /usr/bin/
and /bin
.
Read this post if you are interested in learning about why you should prefer usr/local/bin
over other folders.
Adding rows to tbody of a table using jQuery
I have never ever come across such a strange problem like this! o.O
Do you know what the problem was? $ isn't working. I tried the same code with jQuery like jQuery("#tblEntAttributes tbody").append(newRowContent);
and it works like a charm!
No idea why this strange problem occurs!
Reordering Chart Data Series
Excel 2010 - if you're looking to reorder the series on a pivot chart:
- go to your underlying pivot table
- right-click on one of the Column Labels for the series you're looking to adjust (Note: you need to click on one of the series headings (i.e. 'Saturday' or 'Sunday' in the example shown below) not the 'Column Labels' text itself)
- in the pop-up menu, hover over 'Move' and then select an option from the resulting sub-menu to reposition the series variable.
- your pivot chart will update itself accordingly
Insert data into table with result from another select query
If table_2
is empty, then try the following insert statement:
insert into table_2 (itemid,location1)
select itemid,quantity from table_1 where locationid=1
If table_2
already contains the itemid
values, then try this update statement:
update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)
Is it a good practice to place C++ definitions in header files?
I think that it's absolutely absurd to put ALL of your function definitions into the header file. Why? Because the header file is used as the PUBLIC interface to your class. It's the outside of the "black box".
When you need to look at a class to reference how to use it, you should look at the header file. The header file should give a list of what it can do (commented to describe the details of how to use each function), and it should include a list of the member variables. It SHOULD NOT include HOW each individual function is implemented, because that's a boat load of unnecessary information and only clutters the header file.
Instagram API: How to get all user media?
What I had to do is (in Javascript) is go through all pages by using a recursive function. It's dangerouse as instagram users could have thousands of pictures i a part from that (so your have to controle it) I use this code: (count parameter I think , doesn't do much)
instagramLoadDashboard = function(hash)
{
code = hash.split('=')[1];
$('#instagram-pictures .images-list .container').html('').addClass('loading');
ts = Math.round((new Date()).getTime() / 1000);
url = 'https://api.instagram.com/v1/users/self/media/recent?count=200&min_timestamp=0&max_timestamp='+ts+'&access_token='+code;
instagramLoadMediaPage(url, function(){
galleryHTML = instagramLoadGallery(instagramData);
//console.log(galleryHTML);
$('#instagram-pictures .images-list .container').html(galleryHTML).removeClass('loading');
initImages('#instagram-pictures');
IGStatus = 'loaded';
});
};
instagramLoadMediaPage = function (url, callback)
{
$.ajax({
url : url,
dataType : 'jsonp',
cache : false,
success: function(response){
console.log(response);
if(response.code == '400')
{
alert(response.error_message);
return false;
}
if(response.pagination.next_url !== undefined) {
instagramData = instagramData.concat(response.data);
return instagramLoadMediaPage(response.pagination.next_url,callback);
}
instagramData = instagramData.concat(response.data);
callback.apply();
}
});
};
instagramLoadGallery = function(images)
{
galleryHTML ='<ul>';
for(var i=0;i<images.length;i++)
{
galleryHTML += '<li><img src="'+images[i].images.thumbnail.url+'" width="120" id="instagram-'+images[i].id+' data-type="instagram" data-source="'+images[i].images.standard_resolution.url+'" class="image"/></li>';
}
galleryHTML +='</ul>';
return galleryHTML;
};
There some stuff related to print out a gallery of picture.
How to add an element to Array and shift indexes?
Have a look at commons. It uses arrayCopy(), but has nicer syntax. To those answering with the element-by-element code: if this isn't homework, that's trivial and the interesting answer is the one that promotes reuse. To those who propose lists: probably readers know about that too and performance issues should be mentioned.
How to set Spinner Default by its Value instead of Position?
Compare string with value from index
private void selectSpinnerValue(Spinner spinner, String myString)
{
int index = 0;
for(int i = 0; i < spinner.getCount(); i++){
if(spinner.getItemAtPosition(i).toString().equals(myString)){
spinner.setSelection(i);
break;
}
}
}
Android read text raw resource file
Rather do it this way:
// reads resources regardless of their size
public byte[] getResource(int id, Context context) throws IOException {
Resources resources = context.getResources();
InputStream is = resources.openRawResource(id);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] readBuffer = new byte[4 * 1024];
try {
int read;
do {
read = is.read(readBuffer, 0, readBuffer.length);
if(read == -1) {
break;
}
bout.write(readBuffer, 0, read);
} while(true);
return bout.toByteArray();
} finally {
is.close();
}
}
// reads a string resource
public String getStringResource(int id, Charset encoding) throws IOException {
return new String(getResource(id, getContext()), encoding);
}
// reads an UTF-8 string resource
public String getStringResource(int id) throws IOException {
return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
}
From an Activity, add
public byte[] getResource(int id) throws IOException {
return getResource(id, this);
}
or from a test case, add
public byte[] getResource(int id) throws IOException {
return getResource(id, getContext());
}
And watch your error handling - don't catch and ignore exceptions when your resources must exist or something is (very?) wrong.
How do I enable C++11 in gcc?
As previously mentioned - in case of a project, Makefile
or otherwise, this is a project configuration issue, where you'll likely need to specify other flags too.
But what about one-off programs, where you would normally just write g++ file.cpp && ./a.out
?
Well, I would much like to have some #pragma
to turn in on at source level, or maybe a default extension - say .cxx
or .C11
or whatever, trigger it by default. But as of today, there is no such feature.
But, as you probably are working in a manual environment (i.e. shell), you can just have an alias in you .bashrc
(or whatever):
alias g++11="g++ -std=c++0x"
or, for newer G++ (and when you want to feel "real C++11")
alias g++11="g++ -std=c++11"
You can even alias to g++
itself, if you hate C++03 that much ;)
List of All Folders and Sub-folders
As well as find
listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh
for example...
ls -lad **/*(/)
...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...
find . -type d -exec ls -ld {} \;
(not quite as easy as the other answers suggest)
The benefit of find is that it's more independent of the shell - more portable, even for system()
calls from within a C/C++ program etc..
What is declarative programming?
I am sorry, but I must disagree with many of the other answers. I would like to stop this muddled misunderstanding of the definition of declarative programming.
Definition
Referential transparency (RT) of the sub-expressions is the only required attribute of a declarative programming expression, because it is the only attribute which is not shared with imperative programming.
Other cited attributes of declarative programming, derive from this RT. Please click the hyperlink above for the detailed explanation.
Spreadsheet example
Two answers mentioned spreadsheet programming. In the cases where the spreadsheet programming (a.k.a. formulas) does not access mutable global state, then it is declarative programming. This is because the mutable cell values are the monolithic input and output of the main()
(the entire program). The new values are not written to the cells after each formula is executed, thus they are not mutable for the life of the declarative program (execution of all the formulas in the spreadsheet). Thus relative to each other, the formulas view these mutable cells as immutable. An RT function is allowed to access immutable global state (and also mutable local state).
Thus the ability to mutate the values in the cells when the program terminates (as an output from main()
), does not make them mutable stored values in the context of the rules. The key distinction is the cell values are not updated after each spreadsheet formula is performed, thus the order of performing the formulas does not matter. The cell values are updated after all the declarative formulas have been performed.
How to throw std::exceptions with variable messages?
Here is my solution:
#include <stdexcept>
#include <sstream>
class Formatter
{
public:
Formatter() {}
~Formatter() {}
template <typename Type>
Formatter & operator << (const Type & value)
{
stream_ << value;
return *this;
}
std::string str() const { return stream_.str(); }
operator std::string () const { return stream_.str(); }
enum ConvertToString
{
to_str
};
std::string operator >> (ConvertToString) { return stream_.str(); }
private:
std::stringstream stream_;
Formatter(const Formatter &);
Formatter & operator = (Formatter &);
};
Example:
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData); // implicitly cast to std::string
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str); // explicitly cast to std::string
Best way to make WPF ListView/GridView sort on column-header clicking?
Solution that summarizes all working parts of existing answers and comments including column header templates:
View:
<ListView x:Class="MyNamspace.MyListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
ItemsSource="{Binding Items}"
GridViewColumnHeader.Click="ListViewColumnHeaderClick">
<ListView.Resources>
<Style TargetType="Grid" x:Key="HeaderGridStyle">
<Setter Property="Height" Value="20" />
</Style>
<Style TargetType="TextBlock" x:Key="HeaderTextBlockStyle">
<Setter Property="Margin" Value="5,0,0,0" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style TargetType="Path" x:Key="HeaderPathStyle">
<Setter Property="StrokeThickness" Value="1" />
<Setter Property="Fill" Value="Gray" />
<Setter Property="Width" Value="20" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="Margin" Value="5,0,5,0" />
<Setter Property="SnapsToDevicePixels" Value="True" />
</Style>
<DataTemplate x:Key="HeaderTemplateDefault">
<Grid Style="{StaticResource HeaderGridStyle}">
<TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplateArrowUp">
<Grid Style="{StaticResource HeaderGridStyle}">
<Path Data="M 7,3 L 13,3 L 10,0 L 7,3" Style="{StaticResource HeaderPathStyle}" />
<TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplateArrowDown">
<Grid Style="{StaticResource HeaderGridStyle}">
<Path Data="M 7,0 L 10,3 L 13,0 L 7,0" Style="{StaticResource HeaderPathStyle}" />
<TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
</Grid>
</DataTemplate>
</ListView.Resources>
<ListView.View>
<GridView ColumnHeaderTemplate="{StaticResource HeaderTemplateDefault}">
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding NameProperty}" />
<GridViewColumn Header="Type" Width="45" DisplayMemberBinding="{Binding TypeProperty}"/>
<!-- ... -->
</GridView>
</ListView.View>
</ListView>
Code Behinde:
public partial class MyListView : ListView
{
GridViewColumnHeader _lastHeaderClicked = null;
public MyListView()
{
InitializeComponent();
}
private void ListViewColumnHeaderClick(object sender, RoutedEventArgs e)
{
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
if (headerClicked == null)
return;
if (headerClicked.Role == GridViewColumnHeaderRole.Padding)
return;
var sortingColumn = (headerClicked.Column.DisplayMemberBinding as Binding)?.Path?.Path;
if (sortingColumn == null)
return;
var direction = ApplySort(Items, sortingColumn);
if (direction == ListSortDirection.Ascending)
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowUp"] as DataTemplate;
}
else
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowDown"] as DataTemplate;
}
// Remove arrow from previously sorted header
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
{
_lastHeaderClicked.Column.HeaderTemplate =
Resources["HeaderTemplateDefault"] as DataTemplate;
}
_lastHeaderClicked = headerClicked;
}
public static ListSortDirection ApplySort(ICollectionView view, string propertyName)
{
ListSortDirection direction = ListSortDirection.Ascending;
if (view.SortDescriptions.Count > 0)
{
SortDescription currentSort = view.SortDescriptions[0];
if (currentSort.PropertyName == propertyName)
{
if (currentSort.Direction == ListSortDirection.Ascending)
direction = ListSortDirection.Descending;
else
direction = ListSortDirection.Ascending;
}
view.SortDescriptions.Clear();
}
if (!string.IsNullOrEmpty(propertyName))
{
view.SortDescriptions.Add(new SortDescription(propertyName, direction));
}
return direction;
}
}
Confused by python file mode "w+"
Let's say you're opening the file with a with
statement like you should be. Then you'd do something like this to read from your file:
with open('somefile.txt', 'w+') as f:
# Note that f has now been truncated to 0 bytes, so you'll only
# be able to read data that you write after this point
f.write('somedata\n')
f.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
data = f.read() # Returns 'somedata\n'
Note the f.seek(0)
-- if you forget this, the f.read()
call will try to read from the end of the file, and will return an empty string.
Difference between `Optional.orElse()` and `Optional.orElseGet()`
Considering the following code:
import java.util.Optional;
// one class needs to have a main() method
public class Test
{
public String orelesMethod() {
System.out.println("in the Method");
return "hello";
}
public void test() {
String value;
value = Optional.<String>ofNullable("test").orElseGet(this::orelesMethod);
System.out.println(value);
value = Optional.<String>ofNullable("test").orElse(orelesMethod());
System.out.println(value);
}
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
Test test = new Test();
test.test();
}
}
if we get value
in this way: Optional.<String>ofNullable(null)
, there is no difference between orElseGet() and orElse(), but if we get value
in this way: Optional.<String>ofNullable("test")
, orelesMethod()
in orElseGet()
will not be called but in orElse()
it will be called
How to render an ASP.NET MVC view as a string?
Additional tip for ASP NET CORE:
Interface:
public interface IViewRenderer
{
Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model);
}
Implementation:
public class ViewRenderer : IViewRenderer
{
private readonly IRazorViewEngine viewEngine;
public ViewRenderer(IRazorViewEngine viewEngine) => this.viewEngine = viewEngine;
public async Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model)
{
ViewEngineResult viewEngineResult = this.viewEngine.FindView(controller.ControllerContext, name, false);
if (!viewEngineResult.Success)
{
throw new InvalidOperationException(string.Format("Could not find view: {0}", name));
}
IView view = viewEngineResult.View;
controller.ViewData.Model = model;
await using var writer = new StringWriter();
var viewContext = new ViewContext(
controller.ControllerContext,
view,
controller.ViewData,
controller.TempData,
writer,
new HtmlHelperOptions());
await view.RenderAsync(viewContext);
return writer.ToString();
}
}
Registration in Startup.cs
...
services.AddSingleton<IViewRenderer, ViewRenderer>();
...
And usage in controller:
public MyController: Controller
{
private readonly IViewRenderer renderer;
public MyController(IViewRendere renderer) => this.renderer = renderer;
public async Task<IActionResult> MyViewTest
{
var view = await this.renderer.RenderAsync(this, "MyView", model);
return new OkObjectResult(view);
}
}
How do I get the current date in JavaScript?
If you just want a date without time info, use:
_x000D_
_x000D_
var today = new Date();_x000D_
today.setHours(0, 0, 0, 0);_x000D_
_x000D_
document.write(today);
_x000D_
_x000D_
_x000D_
Tokenizing strings in C
You can simplify the code by introducing an extra variable.
#include <string.h>
#include <stdio.h>
int main()
{
char str[100], *s = str, *t = NULL;
strcpy(str, "a space delimited string");
while ((t = strtok(s, " ")) != NULL) {
s = NULL;
printf(":%s:\n", t);
}
return 0;
}
Importing class from another file
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
android: changing option menu items programmatically
In case you have a BottomBar:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (mBottomBar.getCurrentTabId() == R.id.tab_more) {
getMenuInflater().inflate(R.menu.more_menu, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.preferences:
startActivity(new Intent(this, PreferenceActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
Then you just need to call:
@Override
public void onBottomBarClick(int tabId) {
supportInvalidateOptionsMenu();
}
What is the size of a pointer?
Recently came upon a case where this was not true, TI C28x boards can have a sizeof pointer == 1, since a byte for those boards is 16-bits, and pointer size is 16 bits. To make matters more confusing, they also have far pointers which are 22-bits. I'm not really sure what sizeof far pointer would be.
In general, DSP boards can have weird integer sizes.
So pointer sizes can still be weird in 2020 if you are looking in weird places
Winforms TableLayoutPanel adding rows programmatically
This works perfectly for adding rows and controls in a TableLayoutPanel.
Define a blank Tablelayoutpanel with 3 columns in the design page
Dim TableLayoutPanel3 As New TableLayoutPanel()
TableLayoutPanel3.Name = "TableLayoutPanel3"
TableLayoutPanel3.Location = New System.Drawing.Point(32, 287)
TableLayoutPanel3.AutoSize = True
TableLayoutPanel3.Size = New System.Drawing.Size(620, 20)
TableLayoutPanel3.ColumnCount = 3
TableLayoutPanel3.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
TableLayoutPanel3.BackColor = System.Drawing.Color.Transparent
TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 26.34146!))
TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 73.65854!))
TableLayoutPanel3.ColumnStyles.Add(New ColumnStyle(SizeType.Absolute, 85.0!))
Controls.Add(TableLayoutPanel3)
Create a button btnAddRow to add rows on each click
Private Sub btnAddRow_Click(sender As System.Object, e As System.EventArgs) Handles btnAddRow.Click
TableLayoutPanel3.GrowStyle = TableLayoutPanelGrowStyle.AddRows
TableLayoutPanel3.RowStyles.Add(New RowStyle(SizeType.Absolute, 20))
TableLayoutPanel3.SuspendLayout()
TableLayoutPanel3.RowCount += 1
Dim tb1 As New TextBox()
Dim tb2 As New TextBox()
Dim tb3 As New TextBox()
TableLayoutPanel3.Controls.Add(tb1 , 0, TableLayoutPanel3.RowCount - 1)
TableLayoutPanel3.Controls.Add(tb2, 1, TableLayoutPanel3.RowCount - 1)
TableLayoutPanel3.Controls.Add(tb3, 2, TableLayoutPanel3.RowCount - 1)
TableLayoutPanel3.ResumeLayout()
tb1.Focus()
End Sub
Copy or rsync command
rsync is not necessarily more efficient, due to the more detailed inventory of files and blocks it performs. The algorithm is fantastic at what it does, but you need to understand your problem to know if it is really going to be the best choice.
On a very large file system (say many thousands or millions of files) where files tend to be added but not updated, "cp -u" will likely be more efficient. cp makes the decision to copy solely on metadata and can simply get to the business of copying.
Note that you might want some buffering, e.g. by using tar rather than straight cp, depending on the size of the files, network performance, other disk activity, etc. I find the following idea very useful:
tar cf - . | tar xCf directory -
Metadata itself may actually become a significant overhead on very large (cluster) file systems, but rsync and cp will share this problem.
rsync seems to frequently be the preferred tool (and in general purpose applications is my usual default choice), but there are probably many people who blindly use rsync without thinking it through.
jQuery set checkbox checked
Dude try below code :
$("div.row-form input[type='checkbox']").attr('checked','checked')
OR
$("div.row-form #estado_cat").attr("checked","checked");
OR
$("div.row-form #estado_cat").attr("checked",true);
How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install
since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:
npx mocha <args>
Note: the optional args are forwarded to the command being executed (mocha in this case)
this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).
Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.
You can read more on npx here
Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...
you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:
node node_modules/.bin/mocha
npm puts aliases to all the binaries in your dependencies on that special folder.
Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:
"scripts": {
"test": "mocha"
}
and invoke it with
npm test
Anchor links in Angularjs?
Works for me:
<a onclick='return false;' href="" class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" ng-href="#profile#collapse{{$index}}"> blalba </a>
Plain Old CLR Object vs Data Transfer Object
I think a DTO can be a POCO. DTO is more about the usage of the object while POCO is more of the style of the object (decoupled from architectural concepts).
One example where a POCO is something different than DTO is when you're talking about POCO's inside your domain model/business logic model, which is a nice OO representation of your problem domain. You could use the POCO's throughout the whole application, but this could have some undesirable side effect such a knowledge leaks. DTO's are for instance used from the Service Layer which the UI communicates with, the DTO's are flat representation of the data, and are only used for providing the UI with data, and communicating changes back to the service layer. The service layer is in charge of mapping the DTO's both ways to the POCO domain objects.
Update Martin Fowler said that this approach is a heavy road to take, and should only be taken if there is a significant mismatch between the domain layer and the user interface.
Open file in a relative location in Python
Python just passes the filename you give it to the operating system, which opens it. If your operating system supports relative paths like main/2091/data.txt
(hint: it does), then that will work fine.
You may find that the easiest way to answer a question like this is to try it and see what happens.
What does git push -u mean?
When you push a new branch the first time use:
>git push -u origin
After that, you can just type a shorter command:
>git push
The first-time -u option created a persistent upstream tracking branch with your local branch.
"End of script output before headers" error in Apache
Since no answer is accepted, I would like to provide one possible solution. If your script is written on Windows and uploaded to a Linux server(through FTP), then the problem will raise usually. The reason is that Windows uses CRLF
to end each line while Linux uses LF
. So you should convert it from CRLF
to LF
with the help of an editor, such Atom, as following
Create SQL script that create database and tables
In SQL Server Management Studio you can right click on the database you want to replicate, and select "Script Database as" to have the tool create the appropriate SQL file to replicate that database on another server. You can repeat this process for each table you want to create, and then merge the files into a single SQL file. Don't forget to add a using statement after you create your Database but prior to any table creation.
In more recent versions of SQL Server you can get this in one file in SSMS.
- Right click a database.
- Tasks
- Generate Scripts
This will launch a wizard where you can script the entire database or just portions. There does not appear to be a T-SQL way of doing this.
Javascript can't find element by id?
Script is called before element exists.
You should try one of the following:
- wrap code into a function and use a body onload event to call it.
- put script at the end of document
- use defer attribute into script tag declaration
A tool to convert MATLAB code to Python
There are several tools for converting Matlab to Python code.
The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).
Other options include:
- LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
- OMPC: Matlab to Python (a bit outdated).
Also, for those interested in an interface between the two languages and not conversion:
pymatlab
: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
- Python-Matlab wormholes: both directions of interaction supported.
- Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
- PyMat: Control Matlab session from Python.
pymat2
: continuation of the seemingly abandoned PyMat.
mlabwrap
, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
oct2py
: run GNU Octave commands from within Python.
pymex
: Embeds the Python Interpreter in Matlab, also on File Exchange.
matpy
: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
- MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.
Btw might be helpful to look here for other migration tips:
On a different note, though I'm not a fortran
fan at all, for people who might find it useful there is:
How to configure log4j with a properties file
When you use PropertyConfigurator.configure(String configFilename),
they are the following operation in the log4j library.
Properties props = new Properties();
FileInputStream istream = null;
try {
istream = new FileInputStream(configFileName);
props.load(istream);
istream.close();
}
catch (Exception e) {
...
It fails in reading because it looks for "Log4j.properties" from the current directory where the application is executed.
How about the way that it changes the reading part of the property file as follows, and puts "log4j.properties" on the directory to which the CLASSPATH is set.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource("log4j.properties");
PropertyConfigurator.configure(url);
Another method of putting "Log4j.properties" in the jar file exists.
jar xvf [YourApplication].jar log4j.properties
How to write trycatch in R
tryCatch
has a slightly complex syntax structure. However, once we understand the 4 parts which constitute a complete tryCatch call as shown below, it becomes easy to remember:
expr: [Required] R code(s) to be evaluated
error : [Optional] What should run if an error occured while evaluating the codes in expr
warning : [Optional] What should run if a warning occured while evaluating the codes in expr
finally : [Optional] What should run just before quitting the tryCatch call, irrespective of if expr ran successfully, with an error, or with a warning
tryCatch(
expr = {
# Your code...
# goes here...
# ...
},
error = function(e){
# (Optional)
# Do this if an error is caught...
},
warning = function(w){
# (Optional)
# Do this if an warning is caught...
},
finally = {
# (Optional)
# Do this at the end before quitting the tryCatch structure...
}
)
Thus, a toy example, to calculate the log of a value might look like:
log_calculator <- function(x){
tryCatch(
expr = {
message(log(x))
message("Successfully executed the log(x) call.")
},
error = function(e){
message('Caught an error!')
print(e)
},
warning = function(w){
message('Caught an warning!')
print(w)
},
finally = {
message('All done, quitting.')
}
)
}
Now, running three cases:
A valid case
log_calculator(10)
# 2.30258509299405
# Successfully executed the log(x) call.
# All done, quitting.
A "warning" case
log_calculator(-10)
# Caught an warning!
# <simpleWarning in log(x): NaNs produced>
# All done, quitting.
An "error" case
log_calculator("log_me")
# Caught an error!
# <simpleError in log(x): non-numeric argument to mathematical function>
# All done, quitting.
I've written about some useful use-cases which I use regularly. Find more details here: https://rsangole.netlify.com/post/try-catch/
Hope this is helpful.
How to multiply duration by integer?
For multiplication of variable to time.Second using following code
oneHr:=3600
addOneHrDuration :=time.Duration(oneHr)
addOneHrCurrTime := time.Now().Add(addOneHrDuration*time.Second)
When to favor ng-if vs. ng-show/ng-hide?
If you use ng-show or ng-hide
the content (eg. thumbnails from server) will be loaded irrespective of the value of expression but will be displayed based on the value of the expression.
If you use ng-if
the content will be loaded only if the expression of the ng-if evaluates to truthy.
Using ng-if is a good idea in a situation where you are going to load data or images from the server and show those only depending on users interaction. This way your page load will not be blocked by unnecessary nw intensive tasks.
How to query MongoDB with "like"?
That would have to be:
db.users.find({"name": /.*m.*/})
or, similar:
db.users.find({"name": /m/})
You're looking for something that contains "m" somewhere (SQL's '%
' operator is equivalent to Regexp's '.*
'), not something that has "m" anchored to the beginning of the string.
note: mongodb uses regular expressions which are more powerful than "LIKE" in sql. With regular expressions you can create any pattern that you imagine.
For more info on regular expressions refer to this link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Time complexity of Euclid's Algorithm
There's a great look at this on the wikipedia article.
It even has a nice plot of complexity for value pairs.
It is not O(a%b)
.
It is known (see article) that it will never take more steps than five times the number of digits in the smaller number. So the max number of steps grows as the number of digits (ln b)
. The cost of each step also grows as the number of digits, so the complexity is bound by O(ln^2 b)
where b is the smaller number. That's an upper limit, and the actual time is usually less.
Get restaurants near my location
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
How can I pass data from Flask to JavaScript in a template?
Using a data attribute on an HTML element avoids having to use inline scripting, which in turn means you can use stricter CSP rules for increased security.
Specify a data attribute like so:
<div id="mydiv" data-geocode='{{ geocode|tojson }}'>...</div>
Then access it in a static JavaScript file like so:
// Raw JavaScript
var geocode = JSON.parse(document.getElementById("mydiv").dataset.geocode);
// jQuery
var geocode = JSON.parse($("#mydiv").data("geocode"));
Fade In Fade Out Android Animation in Java
Another alternative:
No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.
So you can do this with Animation.REVERSE like this:
AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);
then onAnimationEnd:
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
//TODO: Run when animation start
}
@Override
public void onAnimationEnd(Animation animation) {
//TODO: Run when animation end
}
@Override
public void onAnimationRepeat(Animation animation) {
//TODO: Run when animation repeat
}
});
how to pass this element to javascript onclick function and add a class to that clicked element
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick(event)
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var target = event.target || event.srcElement; // IE
console.log(target);
console.log(target.src);
var img = document.createElement('img');
img.setAttribute('src', target.src);
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
<img src="sabaLogo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
</body>
</html>
RecyclerView inside ScrollView is not working
For ScrollView
, you could use fillViewport=true
and make layout_height="match_parent"
as below and put recycler view inside:
<ScrollView
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/llOptions">
<android.support.v7.widget.RecyclerView
android:id="@+id/rvList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
No further height adjustment needed through code.
HttpServletRequest get JSON POST data
Normaly you can GET and POST parameters in a servlet the same way:
request.getParameter("cmd");
But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.
If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:
BufferedReader reader = request.getReader();
Json post processing example (uses org.json package )
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
Failed to run sdkmanager --list with Java 9
When having java 11 in the system, the solutions provided are not valid.
This -XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee or
--add-modules java.xml.bind do not work with Java 11 on Mac OS.
For that reason you have to downgrade java version to version 8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
List Java versions installed
/usr/libexec/java_home -V
Java 11
export JAVA_HOME=$(/usr/libexec/java_home -v 11)
Java 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
Then go to
cd ~/Library/Android/sdk/tools/bin
and
./sdkmanager --licenses
Is there a way to delete created variables, functions, etc from the memory of the interpreter?
You can delete individual names with del
:
del x
or you can remove them from the globals()
object:
for name in dir():
if not name.startswith('_'):
del globals()[name]
This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.
Modules you've imported (import os
) are going to remain imported because they are referenced by sys.modules
; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.
How to show Snackbar when Activity starts?
call this method in onCreate
Snackbar snack = Snackbar.make(
(((Activity) context).findViewById(android.R.id.content)),
message + "", Snackbar.LENGTH_SHORT);
snack.setDuration(Snackbar.LENGTH_INDEFINITE);//change Duration as you need
//snack.setAction(actionButton, new View.OnClickListener());//add your own listener
View view = snack.getView();
TextView tv = (TextView) view
.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);//change textColor
TextView tvAction = (TextView) view
.findViewById(android.support.design.R.id.snackbar_action);
tvAction.setTextSize(16);
tvAction.setTextColor(Color.WHITE);
snack.show();
numpy matrix vector multiplication
Simplest solution
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Other Solutions
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
Rarer options for edge cases
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
How to use order by with union all in sql?
Select 'Shambhu' as ShambhuNewsFeed,Note as [News Fedd],NotificationId
from Notification with(nolock) where DesignationId=@Designation
Union All
Select 'Shambhu' as ShambhuNewsFeed,Note as [Notification],NotificationId
from Notification with(nolock)
where DesignationId=@Designation
order by NotificationId desc
Receiving "fatal: Not a git repository" when attempting to remote add a Git repo
NOTE: this does not answer to the common problem, which was OP’s problem, but to different problem where this error message may come up. I didn’t feel like doing new question just to write this answer down, tell me if I should do that instead :P
I got to situation, most likely due to some corruption of certain crash I had, that I got this error even when .git
did exist.
smar@aaeru ~/P/Nominatim> git status
fatal: Not a git repository (or any of the parent directories): .git
smar@aaeru ~/P/Nominatim [128]> ls .git
COMMIT_EDITMSG config* FETCH_HEAD HEAD index logs/ modules/ objects/ ORIG_HEAD packed-refs
Since I didn’t have anything that really needed preserving, I just went with dummy way, and did...
smar@aaeru ~/P/Nominatim [128]> git init
Reinitialized existing Git repository in /home/smar/Projektit/Nominatim/.git/
Still not working though, as for example git log
returns fatal: bad default revision 'HEAD'
. Remotes were there though, so I did git fetch --all
and then just git reset --hard origin/master
to get myself to the state the repo was previously.
Note that if there is some uncommitted changes, you can see them with git status
, git diff
and so on. Then just git diff yourfile > patch
before running the reset.
At least for me reflog (git reflog
) disappeared completely. Hence, if you do the reset, and there was some changes you wanted to prevent, I’m not sure you can get them back after reset anymore. So, make sure that you have all changes you can’t lose backed up, ultimately by just copying the clone before trying this.
php error: Class 'Imagick' not found
For all to those having problems with this i did this tutorial:
How to install Imagemagick and Php module Imagick on ubuntu?
i did this 7 simple steps:
Update libraries, and packages
apt-get update
Remove obsolete things
apt-get autoremove
For the libraries of ImageMagick
apt-get install libmagickwand-dev
for the core class Imagick
apt-get install imagemagick
For create the binaries, and conections in beetween
pecl install imagick
Append the extension to your php.ini
echo "extension=imagick.so" >> /etc/php5/apache2/php.ini
Restart Apache
service apache2 restart
I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.
What's the most efficient way to check if a record exists in Oracle?
select NVL ((select 'Y' from dual where exists
(select 1 from sales where sales_type = 'Accessories')),'N') as rec_exists
from dual
1.Dual table will return 'Y' if record exists in sales_type table
2.Dual table will return null if no record exists in sales_type table and NVL will convert that to 'N'
Structs in Javascript
It's more work to set up, but if maintainability beats one-time effort then this may be your case.
/**
* @class
*/
class Reference {
/**
* @constructs Reference
* @param {Object} p The properties.
* @param {String} p.class The class name.
* @param {String} p.field The field name.
*/
constructor(p={}) {
this.class = p.class;
this.field = p.field;
}
}
Advantages:
- not bound to argument order
- easily extendable
- type script support:
How to create windows service from java jar?
[2020 Update]
Actually, after spending some times trying the different option provided here which are quite old, I found that the easiest way to do it was to use a small paid tool built for that purpose : FireDaemon Pro. I was trying to run Selenium standalone server as a service and none of the free option worked instantly.
The tool is quite cheap (50 USD one-time-licence, 30 days trial) and it took me 5 minutes to set up the server service instead of a half a day of reading/troubleshooting. So far, it works like a charm.
I have absolutely no link with FusionPro, this is a pure disinterested advice, but feel free to delete if it violates forum rules.
Rails params explained?
As others have pointed out, params
values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.
As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params
. For example, if you have a route like this:
match 'products/:id', ...
Then a request to a URL like http://example.com/products/42
will set params[:id]
to 42
.