Excel column number from column name
Write and run the following code in the Immediate Window
?cells(,"type the column name here").column
For example ?cells(,"BYL").column
will return 2014. The code is case-insensitive, hence you may write ?cells(,"byl").column
and the output will still be the same.
ArrayBuffer to base64 encoded string
The OP did not specify the Running Enviroment but if you are using Node.JS there is a very simple way to do such thing.
Accordig with the official Node.JS docs
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
// This step is only necessary if you don't already have a Buffer Object
const buffer = Buffer.from(yourArrayBuffer);
const base64String = buffer.toString('base64');
Also, If you are running under Angular for example, the Buffer Class will also be made available in a Browser Environment.
Vuejs: v-model array in multiple input
Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11
_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
},_x000D_
methods: {_x000D_
addUser: function () {_x000D_
this.users.push({ name: '',email:'' });_x000D_
},_x000D_
deleteUser: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.users.splice(index, 1);_x000D_
if(index===0)_x000D_
this.addUser()_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Add user</h1>_x000D_
<div v-for="(user, index) in users">_x000D_
<input v-model="user.name">_x000D_
<input v-model="user.email">_x000D_
<button @click="deleteUser(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addUser">_x000D_
New User_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Xcopy Command excluding files and folders
Just give full path to exclusion file: eg..
-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt
In this example the file would be located " C:\list-of-excluded-files.txt "
or...
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt
In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "
Full path fixes syntax error.
MessageBox Buttons?
If you actually want Yes and No buttons (and assuming WinForms):
void button_Click(object sender, EventArgs e)
{
var message = "Yes or No?";
var title = "Hey!";
var result = MessageBox.Show(
message, // the message to show
title, // the title for the dialog box
MessageBoxButtons.YesNo, // show two buttons: Yes and No
MessageBoxIcon.Question); // show a question mark icon
// the following can be handled as if/else statements as well
switch (result)
{
case DialogResult.Yes: // Yes button pressed
MessageBox.Show("You pressed Yes!");
break;
case DialogResult.No: // No button pressed
MessageBox.Show("You pressed No!");
break;
default: // Neither Yes nor No pressed (just in case)
MessageBox.Show("What did you press?");
break;
}
}
JavaScript Infinitely Looping slideshow with delays?
You are calling setTimeout()
ten times in a row, so they all expire almost at the same time. What you actually want is this:
window.onload = function start() {
slide(10);
}
function slide(repeats) {
if (repeats > 0) {
document.getElementById('container').style.marginLeft='-600px';
document.getElementById('container').style.marginLeft='-1200px';
document.getElementById('container').style.marginLeft='-1800px';
document.getElementById('container').style.marginLeft='0px';
window.setTimeout(
function(){
slide(repeats - 1)
},
3000
);
}
}
This will call slide(10), which will then set the 3-second timeout to call slide(9), which will set timeout to call slide(8), etc. When slide(0) is called, no more timeouts will be set up.
How do I read the file content from the Internal storage - Android App
String path = Environment.getExternalStorageDirectory().toString();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: " + file.length);
for (int i = 0; i < file.length; i++) {
//here populate your listview
Log.d("Files", "FileName:" + file[i].getName());
}
How can I compare strings in C using a `switch` statement?
I think the best way to do this is separate the 'recognition' from the functionality:
struct stringcase { char* string; void (*func)(void); };
void funcB1();
void funcAzA();
stringcase cases [] =
{ { "B1", funcB1 }
, { "AzA", funcAzA }
};
void myswitch( char* token ) {
for( stringcases* pCase = cases
; pCase != cases + sizeof( cases ) / sizeof( cases[0] )
; pCase++ )
{
if( 0 == strcmp( pCase->string, token ) ) {
(*pCase->func)();
break;
}
}
}
What is difference between png8 and png24
You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.
This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"
You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png
extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.
The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include
- PNG8 or PNG-8 (indexed-color with 8-bit samples, usually means opaque or with GIF-like, binary transparency, but sometimes includes translucency)
- PNG24 or PNG-24 (RGB with 8-bit samples, may have GIF-like transparency via tRNS)
- PNG32 (RGBA with 8-bit samples, opaque, transparent, or translucent)
- PNG48 (Like PNG24 but with 16-bit R,G,B samples)
- PNG64 (like PNG32 but with 16-bit R,G,B,A samples)
There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.
Calendar date to yyyy-MM-dd format in java
java.util.Date
object can't represent date in custom format instead you've to use SimpleDateFormat.format
method that returns string
.
String myString=format1.format(date);
Pass Multiple Parameters to jQuery ajax call
DO not use the below method to send the data using ajax call
data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}'
If by mistake user enter special character like single quote or double quote
the ajax call fails due to wrong string.
Use below method to call the Web service without any issue
var parameter = {
jewellerId: filter,
locale : locale
};
data: JSON.stringify(parameter)
In above parameter is the name of javascript object and stringify it when passing it to the data attribute of the ajax call.
Finding current executable's path without /proc/self/exe
An alternative on Linux to using either /proc/self/exe
or argv[0]
is using the information passed by the ELF interpreter, made available by glibc as such:
#include <stdio.h>
#include <sys/auxv.h>
int main(int argc, char **argv)
{
printf("%s\n", (char *)getauxval(AT_EXECFN));
return(0);
}
Note that getauxval
is a glibc extension, and to be robust you should check so that it doesn't return NULL
(indicating that the ELF interpreter hasn't provided the AT_EXECFN
parameter), but I don't think this is ever actually a problem on Linux.
How do I convert a calendar week into a date in Excel?
If A1 has the week number and year as a 3 or 4 digit integer in the format wwYY then the formula would be:
=INT(A1/100)*7+DATE(MOD([A1,100),1,1)-WEEKDAY(DATE(MOD(A1,100),1,1))-5
the subtraction of the weekday ensures you return a consistent start day of the week. Use the final subtraction to adjust the start day.
How to find a Java Memory Leak
Most of the time, in enterprise applications the Java heap given is larger than the ideal size of max 12 to 16 GB. I have found it hard to make the NetBeans profiler work directly on these big java apps.
But usually this is not needed. You can use the jmap utility that comes with the jdk to take a "live" heap dump , that is jmap will dump the heap after running GC. Do some operation on the application, wait till the operation is completed, then take another "live" heap dump. Use tools like Eclipse MAT to load the heapdumps, sort on the histogram, see which objects have increased, or which are the highest, This would give a clue.
su proceeuser
/bin/jmap -dump:live,format=b,file=/tmp/2930javaheap.hrpof 2930(pid of process)
There is only one problem with this approach; Huge heap dumps, even with the live option, may be too big to transfer out to development lap, and may need a machine with enough memory/RAM to open.
That is where the class histogram comes into picture. You can dump a live class histogram with the jmap tool. This will give only the class histogram of memory usage.Basically it won't have the information to chain the reference. For example it may put char array at the top. And String class somewhere below. You have to draw the connection yourself.
jdk/jdk1.6.0_38/bin/jmap -histo:live 60030 > /tmp/60030istolive1330.txt
Instead of taking two heap dumps, take two class histograms, like as described above; Then compare the class histograms and see the classes that are increasing. See if you can relate the Java classes to your application classes. This will give a pretty good hint. Here is a pythons script that can help you compare two jmap histogram dumps. histogramparser.py
Finally tools like JConolse and VisualVm are essential to see the memory growth over time, and see if there is a memory leak. Finally sometimes your problem may not be a memory leak , but high memory usage.For this enable GC logging;use a more advanced and new compacting GC like G1GC; and you can use jdk tools like jstat to see the GC behaviour live
jstat -gccause pid <optional time interval>
Other referecences to google for -jhat, jmap, Full GC, Humongous allocation, G1GC
jackson deserialization json to java-objects
You have to change the line
product userFromJSON = mapper.readValue(userDataJSON, product.class);
to
product[] userFromJSON = mapper.readValue(userDataJSON, product[].class);
since you are deserializing an array (btw: you should start your class names with upper case letters as mentioned earlier). Additionally you have to create setter methods for your fields or mark them as public in order to make this work.
Edit: You can also go with Steven Schlansker's suggestion and use
List<product> userFromJSON =
mapper.readValue(userDataJSON, new TypeReference<List<product>>() {});
instead if you want to avoid arrays.
How to update a claim in ASP.NET Identity?
I created a Extension method to Add/Update/Read Claims based on a given ClaimsIdentity
namespace Foobar.Common.Extensions
{
public static class Extensions
{
public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return;
// check for existing claim and remove it
var existingClaim = identity.FindFirst(key);
if (existingClaim != null)
identity.RemoveClaim(existingClaim);
// add new claim
identity.AddClaim(new Claim(key, value));
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
}
public static string GetClaimValue(this IPrincipal currentPrincipal, string key)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return null;
var claim = identity.Claims.FirstOrDefault(c => c.Type == key);
return claim.Value;
}
}
}
and then to use it
using Foobar.Common.Extensions;
namespace Foobar.Web.Main.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// add/updating claims
User.AddUpdateClaim("key1", "value1");
User.AddUpdateClaim("key2", "value2");
User.AddUpdateClaim("key3", "value3");
}
public ActionResult Details()
{
// reading a claim
var key2 = User.GetClaimValue("key2");
}
}
}
How to check if a map contains a key in Go?
One line answer:
if val, ok := dict["foo"]; ok {
//do something here
}
Explanation:
if
statements in Go can include both a condition and an initialization statement. The example above uses both:
initializes two variables - val
will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and ok
will receive a bool that will be set to true
if "foo" was actually present in the map
evaluates ok
, which will be true
if "foo" was in the map
If "foo" is indeed present in the map, the body of the if
statement will be executed and val
will be local to that scope.
Convert String[] to comma separated string in java
You may also want not to spawn StringBuilder for such simple operation. Please note that I've changed name of your array from name to names for sake of content conformity:
String[] names = {"amit", "rahul", "surya"};
String namesString = "";
int delimeters = (names.size() - 1);
for (String name : names)
namesString += (delimeters-- > 0) ? "'" + name + "'," : "'" + name + "'";
pandas: best way to select all columns whose names start with X
Just perform a list comprehension to create your columns:
In [28]:
filter_col = [col for col in df if col.startswith('foo')]
filter_col
Out[28]:
['foo.aa', 'foo.bars', 'foo.fighters', 'foo.fox', 'foo.manchu']
In [29]:
df[filter_col]
Out[29]:
foo.aa foo.bars foo.fighters foo.fox foo.manchu
0 1.0 0 0 2 NA
1 2.1 0 1 4 0
2 NaN 0 NaN 1 0
3 4.7 0 0 0 0
4 5.6 0 0 0 0
5 6.8 1 0 5 0
Another method is to create a series from the columns and use the vectorised str method startswith
:
In [33]:
df[df.columns[pd.Series(df.columns).str.startswith('foo')]]
Out[33]:
foo.aa foo.bars foo.fighters foo.fox foo.manchu
0 1.0 0 0 2 NA
1 2.1 0 1 4 0
2 NaN 0 NaN 1 0
3 4.7 0 0 0 0
4 5.6 0 0 0 0
5 6.8 1 0 5 0
In order to achieve what you want you need to add the following to filter the values that don't meet your ==1
criteria:
In [36]:
df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]]==1]
Out[36]:
bar.baz foo.aa foo.bars foo.fighters foo.fox foo.manchu nas.foo
0 NaN 1 NaN NaN NaN NaN NaN
1 NaN NaN NaN 1 NaN NaN NaN
2 NaN NaN NaN NaN 1 NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN
5 NaN NaN 1 NaN NaN NaN NaN
EDIT
OK after seeing what you want the convoluted answer is this:
In [72]:
df.loc[df[df[df.columns[pd.Series(df.columns).str.startswith('foo')]] == 1].dropna(how='all', axis=0).index]
Out[72]:
bar.baz foo.aa foo.bars foo.fighters foo.fox foo.manchu nas.foo
0 5.0 1.0 0 0 2 NA NA
1 5.0 2.1 0 1 4 0 0
2 6.0 NaN 0 NaN 1 0 1
5 6.8 6.8 1 0 5 0 0
MySQL: can't access root account
This worked for me:
https://blog.dotkam.com/2007/04/10/mysql-reset-lost-root-password/
Step 1: Stop MySQL daemon if it is currently running
ps -ef | grep mysql - checks if mysql/mysqld is one of the running processes.
pkill mysqld - kills the daemon, if it is running.
Step 2: Run MySQL safe daemon with skipping grant tables
mysqld_safe --skip-grant-tables &
mysql -u root mysql
Step 3: Login to MySQL as root with no password
mysql -u root mysql
Step 4: Run UPDATE query to reset the root password
UPDATE user SET password=PASSWORD("value=42") WHERE user="root";
FLUSH PRIVILEGES;
In MySQL 5.7, the 'password' field was removed, now the field name is 'authentication_string':
UPDATE user SET authentication_string=PASSWORD("42") WHERE
user="root";
FLUSH PRIVILEGES;
Step 5: Stop MySQL safe daemon
Step 6: Start MySQL daemon
How to check if element is visible after scrolling?
Update: use IntersectionObserver
The best method I have found so far is the jQuery appear plugin. Works like a charm.
Mimics a custom "appear" event, which fires when an element scrolls into view or otherwise becomes visible to the user.
$('#foo').appear(function() {
$(this).text('Hello world');
});
This plugin can be used to prevent unnecessary requests for content that's hidden or outside the viewable area.
What is the best way to prevent session hijacking?
Have you considered reading a book on PHP security? Highly recommended.
I have had much success with the following method for non SSL certified sites.
Dis-allow multiple sessions under the same account, making sure you aren't checking this solely by IP address. Rather check by token generated upon login which is stored with the users session in the database, as well as IP address, HTTP_USER_AGENT and so forth
Using Relation based hyperlinks
Generates a link ( eg. http://example.com/secure.php?token=2349df98sdf98a9asdf8fas98df8 )
The link is appended with a x-BYTE ( preferred size ) random salted MD5 string, upon page redirection the randomly generated token corresponds to a requested page.
- Upon reload, several checks are done.
- Originating IP Address
- HTTP_USER_AGENT
- Session Token
- you get the point.
Short Life-span session authentication cookie.
as posted above, a cookie containing a secure string, which is one of the direct references to the sessions validity is a good idea. Make it expire every x Minutes, reissuing that token, and re-syncing the session with the new Data. If any mis-matches in the data, either log the user out, or having them re-authenticate their session.
I am in no means an expert on the subject, I'v had a bit of experience in this particular topic, hope some of this helps anyone out there.
PHP foreach with Nested Array?
foreach ($tmpArray as $innerArray) {
// Check type
if (is_array($innerArray)){
// Scan through inner loop
foreach ($innerArray as $value) {
echo $value;
}
}else{
// one, two, three
echo $innerArray;
}
}
How to install MinGW-w64 and MSYS2?
MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw
and cygwin fork
package.
To install the MinGW-w64 toolchain (Reference):
- Open MSYS2 shell from start menu
- Run
pacman -Sy pacman
to update the package database
- Re-open the shell, run
pacman -Syu
to update the package database and core system packages
- Re-open the shell, run
pacman -Su
to update the rest
- Install compiler:
- For 32-bit target, run
pacman -S mingw-w64-i686-toolchain
- For 64-bit target, run
pacman -S mingw-w64-x86_64-toolchain
- Select which package to install, default is all
- You may also need
make
, run pacman -S make
Convert SVG to PNG in Python
A little extension on the answer of jsbueno:
#!/usr/bin/env python
import cairo
import rsvg
from xml.dom import minidom
def convert_svg_to_png(svg_file, output_file):
# Get the svg files content
with open(svg_file) as f:
svg_data = f.read()
# Get the width / height inside of the SVG
doc = minidom.parse(svg_file)
width = int([path.getAttribute('width') for path
in doc.getElementsByTagName('svg')][0])
height = int([path.getAttribute('height') for path
in doc.getElementsByTagName('svg')][0])
doc.unlink()
# create the png
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(img)
handler = rsvg.Handle(None, str(svg_data))
handler.render_cairo(ctx)
img.write_to_png(output_file)
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="svg_file",
help="SVG input file", metavar="FILE")
parser.add_argument("-o", "--output", dest="output", default="svg.png",
help="PNG output file", metavar="FILE")
args = parser.parse_args()
convert_svg_to_png(args.svg_file, args.output)
Java swing application, close one window and open another when button is clicked
This is obviously the scenario where you should be using CardLayout. Here instead of opening two JFrame, what you can do is simply change the JPanels using CardLayout.
And the code that is responsible for creating and displaying your GUI should be inside the SwingUtilities.invokeLater(...); method for it to be Thread Safe. For More Info you have to read about Concurrency in Swing.
But if you want to stick to your approach, here is a Sample Code for your Help.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private JFrame frame1, frame2;
private ActionListener action;
private JButton showButton, hideButton;
public void createAndDisplayGUI()
{
frame1 = new JFrame("FRAME 1");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLocationByPlatform(true);
JPanel contentPane1 = new JPanel();
contentPane1.setBackground(Color.BLUE);
showButton = new JButton("OPEN FRAME 2");
hideButton = new JButton("HIDE FRAME 2");
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
/*
* If this button is clicked, we will create a new JFrame,
* and hide the previous one.
*/
if (button == showButton)
{
frame2 = new JFrame("FRAME 2");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setLocationByPlatform(true);
JPanel contentPane2 = new JPanel();
contentPane2.setBackground(Color.DARK_GRAY);
contentPane2.add(hideButton);
frame2.getContentPane().add(contentPane2);
frame2.setSize(300, 300);
frame2.setVisible(true);
frame1.setVisible(false);
}
/*
* Here we will dispose the previous frame,
* show the previous JFrame.
*/
else if (button == hideButton)
{
frame1.setVisible(true);
frame2.setVisible(false);
frame2.dispose();
}
}
};
showButton.addActionListener(action);
hideButton.addActionListener(action);
contentPane1.add(showButton);
frame1.getContentPane().add(contentPane1);
frame1.setSize(300, 300);
frame1.setVisible(true);
}
public static void main(String... args)
{
/*
* Here we are Scheduling a JOB for Event Dispatcher
* Thread. The code which is responsible for creating
* and displaying our GUI or call to the method which
* is responsible for creating and displaying your GUI
* goes into this SwingUtilities.invokeLater(...) thingy.
*/
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
And the output will be :
and
How can I connect to Android with ADB over TCP?
If you want to be able to do it on a button click then:
- In Android Studio -> Settings/Preferences -> Plugins -> Browse Repositories
- Search 'ADB wifi'
- Install and restart android studio
- Connect your device (with USB Debugging enabled) to your computer with USB (you will need to do this just once per session)
- Tools -> Android -> ADB WIFI -> ADB USB TO WIFI (Or use the key combination mentioned. For MacOS: ctrl + shift + w)
Note: If it did not work:
- Your wifi router firewall may be blocking the connection.
- ABD may not be installed on your computer.
Python truncate a long string
With regex:
re.sub(r'^(.{75}).*$', '\g<1>...', data)
Long strings are truncated:
>>> data="11111111112222222222333333333344444444445555555555666666666677777777778888888888"
>>> re.sub(r'^(.{75}).*$', '\g<1>...', data)
'111111111122222222223333333333444444444455555555556666666666777777777788888...'
Shorter strings never get truncated:
>>> data="11111111112222222222333333"
>>> re.sub(r'^(.{75}).*$', '\g<1>...', data)
'11111111112222222222333333'
This way, you can also "cut" the middle part of the string, which is nicer in some cases:
re.sub(r'^(.{5}).*(.{5})$', '\g<1>...\g<2>', data)
>>> data="11111111112222222222333333333344444444445555555555666666666677777777778888888888"
>>> re.sub(r'^(.{5}).*(.{5})$', '\g<1>...\g<2>', data)
'11111...88888'
Relative imports in Python 3
For PyCharm users:
I also was getting ImportError: attempted relative import with no known parent package
because I was adding the .
notation to silence a PyCharm parsing error. PyCharm innaccurately reports not being able to find:
lib.thing import function
If you change it to:
.lib.thing import function
it silences the error but then you get the aforementioned ImportError: attempted relative import with no known parent package
. Just ignore PyCharm's parser. It's wrong and the code runs fine despite what it says.
How can I add an item to a IEnumerable<T> collection?
I just come here to say that, aside from Enumerable.Concat
extension method, there seems to be another method named Enumerable.Append
in .NET Core 1.1.1. The latter allows you to concatenate a single item to an existing sequence. So Aamol's answer can also be written as
IEnumerable<T> items = new T[]{new T("msg")};
items = items.Append(new T("msg2"));
Still, please note that this function will not change the input sequence, it just return a wrapper that put the given sequence and the appended item together.
What is the string length of a GUID?
36, and the GUID will only use 0-9A-F (hexidecimal!).
12345678-1234-1234-1234-123456789012
That's 36 characters in any GUID--they are of constant length. You can read a bit more about the intricacies of GUIDs here.
You will need two more in length if you want to store the braces.
Note: 36 is the string length with the dashes in between. They are actually 16-byte numbers.
Why should I use a pointer rather than the object itself?
There are many excellent answers already, but let me give you one example:
I have an simple Item class:
class Item
{
public:
std::string name;
int weight;
int price;
};
I make a vector to hold a bunch of them.
std::vector<Item> inventory;
I create one million Item objects, and push them back onto the vector. I sort the vector by name, and then do a simple iterative binary search for a particular item name. I test the program, and it takes over 8 minutes to finish executing. Then I change my inventory vector like so:
std::vector<Item *> inventory;
...and create my million Item objects via new. The ONLY changes I make to my code are to use the pointers to Items, excepting a loop I add for memory cleanup at the end. That program runs in under 40 seconds, or better than a 10x speed increase.
EDIT: The code is at http://pastebin.com/DK24SPeW
With compiler optimizations it shows only a 3.4x increase on the machine I just tested it on, which is still considerable.
Open file dialog and select a file using WPF controls and C#
var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"};
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;
How to make a round button?
You can use a MaterialButton
:
<com.google.android.material.button.MaterialButton
android:layout_width="48dp"
android:layout_height="48dp"
android:insetTop="0dp"
android:insetBottom="0dp"
android:text="A"
app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.App.Rounded"
/>
and apply a circular ShapeAppearanceOverlay
with:
<style name="ShapeAppearanceOverlay.App.rounded" parent="">
<item name="cornerSize">50%</item>
</style>
Split output of command by columns using Bash?
Similar to brianegge's awk solution, here is the Perl equivalent:
ps | egrep 11383 | perl -lane 'print $F[3]'
-a
enables autosplit mode, which populates the @F
array with the column data.
Use -F,
if your data is comma-delimited, rather than space-delimited.
Field 3 is printed since Perl starts counting from 0 rather than 1
"Auth Failed" error with EGit and GitHub
I discovered that if I set up the two-step authentication in github, Eclipse isn't able to connect to Github - which makes sense because the two-step authentication in github requires you to input a number from an SMS (and Eclipse wouldn't have this information).
If this is your scenario, you might consider de-activating your two-step authentication in github, and see if that helps.
How to request Google to re-crawl my website?
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
- Go to: https://www.google.com/webmasters/tools/ and log in
- If you haven't already, add and verify the site with the "Add a Site" button
- Click on the site name for the one you want to manage
- Click Crawl -> Fetch as Google
- Optional: if you want to do a specific page only, type in the URL
- Click Fetch
- Click Submit to Index
- Select either "URL" or "URL and its direct links"
- Click OK and you're done.
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
- Login to - Google Search Console
- Add a site and verify it with the available methods.
- After verification from the console, click on URL Inspection.
- In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
- After Inspection, it'll show an option to Request Indexing
- Click on it and GoogleBot will add your website in a Queue for crawling.
How to prevent long words from breaking my div?
This is a complex issue, as we know, and not supported in any common way between browsers. Most browsers don't support this feature natively at all.
In some work done with HTML emails, where user content was being used, but script is not available (and even CSS is not supported very well) the following bit of CSS in a wrapper around your unspaced content block should at least help somewhat:
.word-break {
/* The following styles prevent unbroken strings from breaking the layout */
width: 300px; /* set to whatever width you need */
overflow: auto;
white-space: -moz-pre-wrap; /* Mozilla */
white-space: -hp-pre-wrap; /* HP printers */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
word-wrap: break-word; /* IE */
-moz-binding: url('xbl.xml#wordwrap'); /* Firefox (using XBL) */
}
In the case of Mozilla-based browsers, the XBL file mentioned above contains:
<?xml version="1.0" encoding="utf-8"?>
<bindings xmlns="http://www.mozilla.org/xbl"
xmlns:html="http://www.w3.org/1999/xhtml">
<!--
More information on XBL:
http://developer.mozilla.org/en/docs/XBL:XBL_1.0_Reference
Example of implementing the CSS 'word-wrap' feature:
http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/
-->
<binding id="wordwrap" applyauthorstyles="false">
<implementation>
<constructor>
//<![CDATA[
var elem = this;
doWrap();
elem.addEventListener('overflow', doWrap, false);
function doWrap() {
var walker = document.createTreeWalker(elem, NodeFilter.SHOW_TEXT, null, false);
while (walker.nextNode()) {
var node = walker.currentNode;
node.nodeValue = node.nodeValue.split('').join(String.fromCharCode('8203'));
}
}
//]]>
</constructor>
</implementation>
</binding>
</bindings>
Unfortunately, Opera 8+ don't seem to like any of the above solutions, so JavaScript will have to be the solution for those browsers (like Mozilla/Firefox.) Another cross-browser solution (JavaScript) that includes the later editions of Opera would be to use Hedger Wang's script found here:
http://www.hedgerwow.com/360/dhtml/css-word-break.html
Other useful links/thoughts:
Incoherent Babble » Blog Archive » Emulating CSS word-wrap for Mozilla/Firefox
http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/
[OU] No word wrap in Opera, displays fine in IE
http://list.opera.com/pipermail/opera-users/2004-November/024467.html
http://list.opera.com/pipermail/opera-users/2004-November/024468.html
How do I get the key at a specific index from a Dictionary in Swift?
SWIFT 4
Slightly off-topic: But here is if you have an
Array of Dictionaries i.e: [ [String : String] ]
var array_has_dictionary = [ // Start of array
// Dictionary 1
[
"name" : "xxxx",
"age" : "xxxx",
"last_name":"xxx"
],
// Dictionary 2
[
"name" : "yyy",
"age" : "yyy",
"last_name":"yyy"
],
] // end of array
cell.textLabel?.text = Array(array_has_dictionary[1])[1].key
// Output: age -> yyy
How to use the divide function in the query?
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
How do I display a wordpress page content?
You can achieve this by adding this simple php code block
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
the_content();
endwhile; else: ?>
<p>!Sorry no posts here</p>
<?php endif; ?>
Capture Image from Camera and Display in Activity
Here you can open camera or gallery and set the selected image into imageview
private static final String IMAGE_DIRECTORY = "/YourDirectName";
private Context mContext;
private CircleImageView circleImageView; // imageview
private int GALLERY = 1, CAMERA = 2;
Add permissions in manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />
In onCreate()
requestMultiplePermissions(); // check permission
circleImageView = findViewById(R.id.profile_image);
circleImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showPictureDialog();
}
});
Show options dialog box (to select image from camera or gallery)
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
Get photo from Gallery
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
Get photo from Camera
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
Once the image is get selected or captured then ,
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
circleImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
circleImageView.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
Now its time to store the picture
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!wallpaperDirectory.exists()) { // have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
Request permission
private void requestMultiplePermissions() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) { // check if all permissions are granted
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
if (report.isAnyPermissionPermanentlyDenied()) { // check for permanent denial of any permission
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
@Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
How do you use MySQL's source command to import large files in windows
Hello I had the same problem but I tried many different states and I came to it:
SOURCE doesn't work with ; at the end in my case:
SOURCE D:\Barname-Narmafzar\computer programming's languages\SQL\MySQL\dataAug-12-2019\dataAug-12-2019.sql;
and the error was:
ERROR: Unknown command '\B'.
'>
it also didn't work with a quotation for the address.
But it works without ; at the end:
SOURCE D:\Barname-Narmafzar\computer programming's languages\SQL\MySQL\dataAug-12-2019\dataAug-12-2019.sql
But remember to use USE database_name; before that.
I think it's so because the SOURCE or USE or HELP are for the Mysql itself and they are not such query codes although when you write HELP it says:
"Note that all text commands must be first on line and end with ; ".
but here doesn't work.
I should say that I have done it in CMD and I didn't try it in Mysql Workbench.
That was it
This is the result
C++ inheritance - inaccessible base?
You have to do this:
class Bar : public Foo
{
// ...
}
The default inheritance type of a class
in C++ is private
, so any public
and protected
members from the base class are limited to private
. struct
inheritance on the other hand is public
by default.
How to validate an OAuth 2.0 access token for a resource server?
OAuth 2.0 spec doesn't define the part. But there could be couple of options:
When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.
Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.
Is either GET or POST more secure than the other?
Disclaimer: Following points are only applicable for API calls and not the website URLs.
Security over the network: You must use HTTPS. GET and POST are equally safe in this case.
Browser History: For front-end applications like, Angular JS, React JS etc API calls are AJAX calls made by front-end. These does not become part of browser history. Hence, POST and GET are equally secure.
Server side logs: With using write set of data-masking and access logs format it is possible to hide all or only sensitive data from request-URL.
Data visibility in browser console: For someone with mallicious intent, it's almost the same efforts to view POST data as much as GET.
Hence, with right logging practices, GET API is as secure as POST API. Following POST everywhere, forces poor API definitions and should be avoided.
Removing leading zeroes from a field in a SQL statement
If you want the query to return a 0 instead of a string of zeroes or any other value for that matter you can turn this into a case statement like this:
select CASE
WHEN ColumnName = substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
THEN '0'
ELSE substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
END
How to use delimiter for csv in python
CSV Files with Custom Delimiters
By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are |
and \t
.
import csv
data_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='|')
writer.writerows(data_list)
output:
SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming
Write CSV files with quotes
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
writer.writerows(row_list)
output:
"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"
As you can see, we have passed csv.QUOTE_NONNUMERIC
to the quoting
parameter. It is a constant defined by the csv
module.
csv.QUOTE_NONNUMERIC
specifies the writer
object that quotes should be added around the non-numeric entries.
There are 3 other predefined constants you can pass to the quoting
parameter:
csv.QUOTE_ALL
- Specifies the writer
object to write CSV file with quotes around all the entries.
csv.QUOTE_MINIMAL
- Specifies the writer
object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)
csv.QUOTE_NONE
- Specifies the writer
object that none of the entries should be quoted. It is the default value.
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
delimiter=';', quotechar='*')
writer.writerows(row_list)
output:
*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*
Here, we can see that quotechar='*'
parameter instructs the writer
object to use *
as quote for all non-numeric values.
How to call shell commands from Ruby
If you really need Bash, per the note in the "best" answer.
First, note that when Ruby calls out to a shell, it typically calls /bin/sh
, not Bash. Some Bash syntax is not supported by /bin/sh
on all systems.
If you need to use Bash, insert bash -c "your Bash-only command"
inside of your desired calling method:
quick_output = system("ls -la")
quick_bash = system("bash -c 'ls -la'")
To test:
system("echo $SHELL")
system('bash -c "echo $SHELL"')
Or if you are running an existing script file like
script_output = system("./my_script.sh")
Ruby should honor the shebang, but you could always use
system("bash ./my_script.sh")
to make sure, though there may be a slight overhead from /bin/sh
running /bin/bash
, you probably won't notice.
android.view.InflateException: Binary XML file: Error inflating class fragment
I had the same problem, issue, tried all the answers in this thread to no avail. My solution was, I hadn't added an ID in the Activity XML. I didn't think it would matter, but it did.
So in the Activity XML I had:
<fragment
android:name="com.covle.hellocarson.SomeFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
But should've had:
<fragment
android:id="@+id/some_fragment"
android:name="com.covle.hellocarson.SomeFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
If someone would be happy to comment on why this is, I'm all ears, to other, I hope this helps.
Git diff against a stash
Depending on what you want to compare the stash with (local working tree / parent commit / head commit), there are actually several commands available, amongst which the good old git diff
, and the more specific git stash show
:
+--------------------------------------------------------------------------+
¦ Compare stash with ? ¦ git diff ¦ git stash show ¦
¦----------------------+-------------------------------+-------------------¦
¦ Local working tree ¦ git diff stash@{0} ¦ git stash show -l ¦
¦----------------------¦-------------------------------¦-------------------¦
¦ Parent commit ¦ git diff stash@{0}^ stash@{0} ¦ git stash show -p ¦
¦----------------------¦-------------------------------¦-------------------¦
¦ HEAD commit ¦ git diff stash@{0} HEAD ¦ / ¦
+--------------------------------------------------------------------------+
While git stash show
looks more user friendly on first sight, git diff
is actually more powerful in that it allows specifying filenames for a more focused diff. I've personally set up aliases for all of these commands in my zsh git plugin.
Shuffle DataFrame rows
(I don't have enough reputation to comment this on the top post, so I hope someone else can do that for me.) There was a concern raised that the first method:
df.sample(frac=1)
made a deep copy or just changed the dataframe. I ran the following code:
print(hex(id(df)))
print(hex(id(df.sample(frac=1))))
print(hex(id(df.sample(frac=1).reset_index(drop=True))))
and my results were:
0x1f8a784d400
0x1f8b9d65e10
0x1f8b9d65b70
which means the method is not returning the same object, as was suggested in the last comment. So this method does indeed make a shuffled copy.
Visual C++: How to disable specific linker warnings?
The PDB file is typically used to store debug information. This warning is caused probably because the file vc80.pdb
is not found when linking the target object file. Read the MSDN entry on LNK4099 here.
Alternatively, you can turn off debug information generation from the Project Properties > Linker > Debugging > Generate Debug Info field.
What does the question mark operator mean in Ruby?
In your example
product.valid?
Is actually a function call and calls a function named valid?
. Certain types of "test for condition"/boolean functions have a question mark as part of the function name by convention.
Display a angular variable in my html page
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
How to get the number of characters in a string
I should point out that none of the answers provided so far give you the number of characters as you would expect, especially when you're dealing with emojis (but also some languages like Thai, Korean, or Arabic). VonC's suggestions will output the following:
fmt.Println(utf8.RuneCountInString("??")) // Outputs "6".
fmt.Println(len([]rune("??"))) // Outputs "6".
That's because these methods only count Unicode code points. There are many characters which can be composed of multiple code points.
Same for using the Normalization package:
var ia norm.Iter
ia.InitString(norm.NFKD, "??")
nc := 0
for !ia.Done() {
nc = nc + 1
ia.Next()
}
fmt.Println(nc) // Outputs "6".
Normalization is not really the same as counting characters and many characters cannot be normalized into a one-code-point equivalent.
masakielastic's answer comes close but only handles modifiers (the rainbow flag contains a modifier which is thus not counted as its own code point):
fmt.Println(GraphemeCountInString("??")) // Outputs "5".
fmt.Println(GraphemeCountInString2("??")) // Outputs "5".
The correct way to split Unicode strings into (user-perceived) characters, i.e. grapheme clusters, is defined in the Unicode Standard Annex #29. The rules can be found in Section 3.1.1. The github.com/rivo/uniseg package implements these rules so you can determine the correct number of characters in a string:
fmt.Println(uniseg.GraphemeClusterCount("??")) // Outputs "2".
Python virtualenv questions
on Windows I have python 3.7 installed and I still couldn't activate virtualenv
from Gitbash with ./Scripts/activate
although it worked from Powershell after running Set-ExecutionPolicy Unrestricted
in Powershell and changing the setting to "Yes To All".
I don't like Powershell and I like to use Gitbash, so to activate virtualenv
in Gitbash first navigate to your project folder, use ls
to list the contents of the folder and be sure you see "Scripts". Change directory to "Scripts" using cd Scripts
, once you're in the "Scripts" path use . activate
to activate virtualenv
. Don't forget the space after the dot.
'if' statement in jinja2 template
Why the loop?
You could simply do this:
{% if 'priority' in data %}
<p>Priority: {{ data['priority'] }}</p>
{% endif %}
When you were originally doing your string comparison, you should have used ==
instead.
Passing parameter to controller action from a Html.ActionLink
Addition to the accepted answer:
if you are going to use
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)
this will create actionlink where you can't create new custom attribute or style for the link.
However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })
How to find longest string in the table column data
You can:
SELECT CR
FROM table1
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)
Having just recieved an upvote more than a year after posting this, I'd like to add some information.
- This query gives all values with the maximum length. With a TOP 1 query you get only one of these, which is usually not desired.
- This query must probably read the table twice: a full table scan to get the maximum length and another full table scan to get all values of that length. These operations, however, are very simple operations and hence rather fast. With a TOP 1 query a DBMS reads all records from the table and then sorts them. So the table is read only once, but a sort operation on a whole table is quite some task and can be very slow on large tables.
- One would usually add
DISTINCT
to my query (SELECT DISTINCT CR FROM ...
), so as to get every value just once. That would be a sort operation, but only on the few records already found. Again, no big deal.
- If the string lengths have to be dealt with quite often, one might think of creating a computed column (calculated field) for it. This is available as of Ms Access 2010. But reading up on this shows that you cannot index calculated fields in MS Access. As long as this holds true, there is hardly any benefit from them. Applying
LEN
on the strings is usually not what makes such queries slow.
How to get the type of T from a member of a generic class or method?
With the following extension method you can get away without reflection:
public static Type GetListType<T>(this List<T> _)
{
return typeof(T);
}
Or more general:
public static Type GetEnumeratedType<T>(this IEnumerable<T> _)
{
return typeof(T);
}
Usage:
List<string> list = new List<string> { "a", "b", "c" };
IEnumerable<string> strings = list;
IEnumerable<object> objects = list;
Type listType = list.GetListType(); // string
Type stringsType = strings.GetEnumeratedType(); // string
Type objectsType = objects.GetEnumeratedType(); // BEWARE: object
SQL sum with condition
Try moving ValueDate
:
select sum(CASE
WHEN ValueDate > @startMonthDate THEN cash
ELSE 0
END)
from Table a
where a.branch = p.branch
and a.transID = p.transID
(reformatted for clarity)
You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.
Create a file if it doesn't exist
Using input()
implies Python 3, recent Python 3 versions have made the IOError
exception deprecated (it is now an alias for OSError
). So assuming you are using Python 3.3 or later:
fn = input('Enter file name: ')
try:
file = open(fn, 'r')
except FileNotFoundError:
file = open(fn, 'w')
TSQL PIVOT MULTIPLE COLUMNS
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
Take the content of a list and append it to another list
You can also combine two lists (say a,b) using the '+' operator.
For example,
a = [1,2,3,4]
b = [4,5,6,7]
c = a + b
Output:
>>> c
[1, 2, 3, 4, 4, 5, 6, 7]
React.js: How to append a component on click?
As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.
In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field
class HealthConditions extends React.Component {
constructor(props) {
super(props);
this.state = {
inputLinkClicked: false
}
}
handleAddSecondInput() {
this.setState({
inputLinkClicked: true
})
}
render() {
return(
<main id="wrapper" className="" data-reset-cookie-tab>
<div id="content" role="main">
<div className="inner-block">
<H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>
<InputField label="Name of condition"
InputType="text"
InputId="id-condition"
InputName="condition"
/>
{
this.state.inputLinkClicked?
<InputField label=""
InputType="text"
InputId="id-condition2"
InputName="condition2"
/>
:
<div></div>
}
<button
type="button"
className="make-button-link"
data-add-button=""
href="#"
onClick={this.handleAddSecondInput}
>
Add a condition
</button>
<FormButton buttonLabel="Next"
handleSubmit={this.handleSubmit}
linkto={
this.state.illnessOrDisability === 'true' ?
"/404"
:
"/add-your-details"
}
/>
<BackLink backLink="/add-your-details" />
</div>
</div>
</main>
);
}
}
Find the host name and port using PSQL commands
This command will give you postgres port number
\conninfo
If postgres is running on Linux server, you can also use the following command
sudo netstat -plunt |grep postgres
OR (if it comes as postmaster)
sudo netstat -plunt |grep postmaster
and you will see something similar as this
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 140/postgres
tcp6 0 0 ::1:5432 :::* LISTEN 140/postgres
in this case, port number is 5432 which is also default port number
credits link
How to use Google fonts in React.js?
It could be the self-closing tag of link at the end, try:
<link href="https://fonts.googleapis.com/css?family=Bungee+Inline" rel="stylesheet"/>
and in your main.css file try:
body,div {
font-family: 'Bungee Inline', cursive;
}
What does `dword ptr` mean?
The dword ptr
part is called a size directive. This page explains them, but it wasn't possible to direct-link to the correct section.
Basically, it means "the size of the target operand is 32 bits", so this will bitwise-AND the 32-bit value at the address computed by taking the contents of the ebp
register and subtracting four with 0.
In C++, what is a virtual base class?
It means a call to a virtual function will be forwarded to the "right" class.
C++ FAQ Lite FTW.
In short, it is often used in multiple-inheritance scenarios, where a "diamond" hierarchy is formed. Virtual inheritance will then break the ambiguity created in the bottom class, when you call function in that class and the function needs to be resolved to either class D1 or D2 above that bottom class. See the FAQ item for a diagram and details.
It is also used in sister delegation, a powerful feature (though not for the faint of heart). See this FAQ.
Also see Item 40 in Effective C++ 3rd edition (43 in 2nd edition).
How do I measure separate CPU core usage for a process?
You can use:
mpstat -P ALL 1
It shows how much each core is busy and it updates automatically each second. The output would be something like this (on a quad-core processor):
10:54:41 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle
10:54:42 PM all 8.20 0.12 0.75 0.00 0.00 0.00 0.00 0.00 90.93
10:54:42 PM 0 24.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 74.00
10:54:42 PM 1 22.00 0.00 2.00 0.00 0.00 0.00 0.00 0.00 76.00
10:54:42 PM 2 2.02 1.01 0.00 0.00 0.00 0.00 0.00 0.00 96.97
10:54:42 PM 3 2.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 98.00
10:54:42 PM 4 14.15 0.00 1.89 0.00 0.00 0.00 0.00 0.00 83.96
10:54:42 PM 5 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 99.00
10:54:42 PM 6 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
10:54:42 PM 7 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00
This command doesn't answer original question though i.e. it does not show CPU core usage for a specific process.
JUnit 5: How to assert an exception is thrown?
They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:
@Test
public void wrongInput() {
Throwable exception = assertThrows(InvalidArgumentException.class,
()->{objectName.yourMethod("WRONG");} );
}
Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?
Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so.
EDIT:
I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
/* Try to dis-comment this:
$('#a').click(function () {
alert('jQuery.click()');
return true;
});
*/
});
function button_onClick() {
$('#a').click();
}
function a_onClick() {
alert('a_onClick');
}
</script>
</head>
<body>
<input type="button" onclick="button_onClick()">
<br>
<a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a>
</body>
</html>
It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly.
I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.
PDO get the last ID inserted
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId()
.
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
Regular expression to detect semi-colon terminated C++ for & while loops
Greg is absolutely correct. This kind of parsing cannot be done with regular expressions. I suppose it is possible to build some horrendous monstrosity that would work for many cases, but then you'll just run across something that does.
You really need to use more traditional parsing techniques. For example, its pretty simple to write a recursive decent parser to do what you need.
Get list of certificates from the certificate store in C#
The simplest way to do that is by opening the certificate store you want and then using X509Certificate2UI
.
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var selectedCertificate = X509Certificate2UI.SelectFromCollection(
store.Certificates,
"Title",
"MSG",
X509SelectionFlag.SingleSelection);
More information in X509Certificate2UI
on MSDN.
Best way to find os name and version in Unix/Linux platform
With perl and Linux::Distribution, the cleanest solution for an old problem :
#!/bin/sh
perl -e '
use Linux::Distribution qw(distribution_name distribution_version);
my $linux = Linux::Distribution->new;
if(my $distro = $linux->distribution_name()) {
my $version = $linux->distribution_version();
print "you are running $distro";
print " version $version" if $version;
print "\n";
} else {
print "distribution unknown\n";
}
'
How to SSH into Docker?
Notice: this answer promotes a tool I've written.
The selected answer here suggests to install an SSH server into every image. Conceptually this is not the right approach (https://docs.docker.com/articles/dockerfile_best-practices/).
I've created a containerized SSH server that you can 'stick' to any running container. This way you can create compositions with every container. The only requirement is that the container has bash.
The following example would start an SSH server exposed on port 2222 of the local machine.
$ docker run -d -p 2222:22 \
-v /var/run/docker.sock:/var/run/docker.sock \
-e CONTAINER=my-container -e AUTH_MECHANISM=noAuth \
jeroenpeeters/docker-ssh
$ ssh -p 2222 localhost
For more pointers and documentation see: https://github.com/jeroenpeeters/docker-ssh
Not only does this defeat the idea of one process per container, it is also a cumbersome approach when using images from the Docker Hub since they often don't (and shouldn't) contain an SSH server.
Implementing a HashMap in C
The best approach depends on the expected key distribution and number
of collisions. If relatively few collisions are expected, it really
doesn't matter which method is used. If lots of collisions are
expected, then which to use depends on the cost of rehashing or
probing vs. manipulating the extensible bucket data structure.
But here is source code example of An Hashmap Implementation in C
Uninstalling an MSI file from the command line without using msiexec
The msi
file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt
file handler to display the file).
Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.
sorting a List of Map<String, String>
try {
java.util.Collections.sort(data,
new Comparator<Map<String, String>>() {
SimpleDateFormat sdf = new SimpleDateFormat(
"MM/dd/yyyy");
public int compare(final Map<String, String> map1,
final Map<String, String> map2) {
Date date1 = null, date2 = null;
try {
date1 = sdf.parse(map1.get("Date"));
date2 = sdf.parse(map2.get("Date"));
} catch (ParseException e) {
e.printStackTrace();
}
if (date1.compareTo(date2) > 0) {
return +1;
} else if (date1.compareTo(date2) == 0) {
return 0;
} else {
return -1;
}
}
});
} catch (Exception e) {
}
What's sizeof(size_t) on 32-bit vs the various 64-bit data models?
EDIT: Thanks for the comments - I looked it up in the C99 standard, which says in section 6.5.3.4:
The value of the result is
implementation-defined, and its type
(an unsigned integer type) is size_t
,
defined in <stddef.h>
(and other
headers)
So, the size of size_t
is not specified, only that it has to be an unsigned integer type. However, an interesting specification can be found in chapter 7.18.3 of the standard:
limit of size_t
SIZE_MAX 65535
Which basically means that, irrespective of the size of size_t
, the allowed value range is from 0-65535, the rest is implementation dependent.
How to get jQuery dropdown value onchange event
If you have simple dropdown like:
<select name="status" id="status">
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
Then you can use this code for getting value:
$(function(){
$("#status").change(function(){
var status = this.value;
alert(status);
if(status=="1")
$("#icon_class, #background_class").hide();// hide multiple sections
});
});
Format certain floating dataframe columns into percentage in pandas
replace the values using the round function, and format the string representation of the percentage numbers:
df['var2'] = pd.Series([round(val, 2) for val in df['var2']], index = df.index)
df['var3'] = pd.Series(["{0:.2f}%".format(val * 100) for val in df['var3']], index = df.index)
The round function rounds a floating point number to the number of decimal places provided as second argument to the function.
String formatting allows you to represent the numbers as you wish. You can change the number of decimal places shown by changing the number before the f
.
p.s. I was not sure if your 'percentage' numbers had already been multiplied by 100. If they have then clearly you will want to change the number of decimals displayed, and remove the hundred multiplication.
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
What are static factory methods?
NOTE! "The static factory method is NOT the same as the Factory Method pattern" (c) Effective Java, Joshua Bloch.
Factory Method: "Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" (c) GoF.
"Static factory method is simply a static method that returns an instance of a class." (c) Effective Java, Joshua Bloch. Usually this method is inside a particular class.
The difference:
The key idea of static factory method is to gain control over object creation and delegate it from constructor to static method. The decision of object to be created is like in Abstract Factory made outside the method (in common case, but not always). While the key (!) idea of Factory Method is to delegate decision of what instance of class to create inside Factory Method. E.g. classic Singleton implementation is a special case of static factory method. Example of commonly used static factory methods:
- valueOf
- getInstance
- newInstance
What is a Python egg?
Note: Egg packaging has been superseded by Wheel packaging.
Same concept as a .jar
file in Java, it is a .zip
file with some metadata files renamed .egg
, for distributing code as bundles.
Specifically: The Internal Structure of Python Eggs
A "Python egg" is a logical structure embodying the release of a
specific version of a Python project, comprising its code, resources,
and metadata. There are multiple formats that can be used to
physically encode a Python egg, and others can be developed. However,
a key principle of Python eggs is that they should be discoverable and
importable. That is, it should be possible for a Python application to
easily and efficiently find out what eggs are present on a system, and
to ensure that the desired eggs' contents are importable.
The .egg
format is well-suited to distribution and the easy
uninstallation or upgrades of code, since the project is essentially
self-contained within a single directory or file, unmingled with any
other projects' code or resources. It also makes it possible to have
multiple versions of a project simultaneously installed, such that
individual programs can select the versions they wish to use.
HQL ERROR: Path expected for join
select u from UserGroup ug inner join ug.user u
where ug.group_id = :groupId
order by u.lastname
As a named query:
@NamedQuery(
name = "User.findByGroupId",
query =
"SELECT u FROM UserGroup ug " +
"INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)
Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.
How to compress an image via Javascript in the browser?
@PsychoWoods' answer is good. I would like to offer my own solution. This Javascript function takes an image data URL and a width, scales it to the new width, and returns a new data URL.
// Take an image URL, downscale it to the given width, and return a new image URL.
function downscaleImage(dataUrl, newWidth, imageType, imageArguments) {
"use strict";
var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;
// Provide default values
imageType = imageType || "image/jpeg";
imageArguments = imageArguments || 0.7;
// Create a temporary image so that we can compute the height of the downscaled image.
image = new Image();
image.src = dataUrl;
oldWidth = image.width;
oldHeight = image.height;
newHeight = Math.floor(oldHeight / oldWidth * newWidth)
// Create a temporary canvas to draw the downscaled image on.
canvas = document.createElement("canvas");
canvas.width = newWidth;
canvas.height = newHeight;
// Draw the downscaled image on the canvas and return the new data URL.
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, newWidth, newHeight);
newDataUrl = canvas.toDataURL(imageType, imageArguments);
return newDataUrl;
}
This code can be used anywhere you have a data URL and want a data URL for a downscaled image.
How to pass a callback as a parameter into another function
Yup. Function references are just like any other object reference, you can pass them around to your heart's content.
Here's a more concrete example:
_x000D_
_x000D_
function foo() {
console.log("Hello from foo!");
}
function caller(f) {
// Call the given function
f();
}
function indirectCaller(f) {
// Call `caller`, who will in turn call `f`
caller(f);
}
// Do it
indirectCaller(foo); // logs "Hello from foo!"
_x000D_
_x000D_
_x000D_
You can also pass in arguments for foo
:
_x000D_
_x000D_
function foo(a, b) {
console.log(a + " + " + b + " = " + (a + b));
}
function caller(f, v1, v2) {
// Call the given function
f(v1, v2);
}
function indirectCaller(f, v1, v2) {
// Call `caller`, who will in turn call `f`
caller(f, v1, v2);
}
// Do it
indirectCaller(foo, 1, 2); // logs "1 + 2 = 3"
_x000D_
_x000D_
_x000D_
How to create a numpy array of arbitrary length strings?
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
Error: unmappable character for encoding UTF8 during maven compilation
I came across this problem just now and ended up resolving it like so: I opened up the offending .java file in Notepad++ and from the Encoding menu I selected "Convert to UTF-8 without BOM". Saved. Re-ran maven, all went through ok.
If the offending resource was not encoded in UTF-8 - as you have configured for your maven compiler plugin - you would see in the Encoding menu of Np++ a bullet mark next to the file's current encoding (in my case I saw it was set to "Encode in ANSI").
So your maven compiler plugin invoked the Java compiler with the -encoding option set to UTF-8, but the compiler encountered a ANSI-encoded source file and reported this as an error. This used to be a warning previously in Java 5 but is treated as an error in Java 6+
mysql datatype for telephone number and address
i would use a varchar for telephone numbers. that way you can also store + and (), which is sometimes seen in tel numbers (as you mentioned yourself). and you don't have to worry about using up all bits in integers.
"Automatic" vs "Automatic (Delayed start)"
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.
HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.
How to return JSON with ASP.NET & jQuery
Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.
Of course, it's then up to you to do what you need to do on the client side.
I would be thinking something like this:
[WebMethod]
public static List GetProducts()
{
var products = context.GetProducts().ToList();
return products;
}
There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data
How do I parse a string into a number with Dart?
You can parse a string into an integer with int.parse()
. For example:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
Note that int.parse()
accepts 0x
prefixed strings. Otherwise the input is treated as base-10.
You can parse a string into a double with double.parse()
. For example:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse()
will throw FormatException if it cannot parse the input.
Dynamic classname inside ngClass in angular 2
i want to mention some important point to bare in mind while implementing class binding.
[ngClass] = "{
'badge-secondary': somevariable === value1,
'badge-danger': somevariable === value1,
'badge-warning': somevariable === value1,
'badge-warning': somevariable === value1,
'badge-success': somevariable === value1 }"
class here is not binding correctly because one condition is to be met, whereas you have two identical classes 'badge-warning' that may have two different condition.
To correct this
[ngClass] = "{
'badge-secondary': somevariable === value1,
'badge-danger': somevariable === value1,
'badge-warning': somevariable === value1 || somevariable === value1,
'badge-success': somevariable === value1 }"
Iterating over a numpy array
I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one.
According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.
I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.
def cal_mse(y_actual, y_predicted):
""" this function will return mean squared error
args:
y_actual (ndarray): np array containing target variable
y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
returns:
mse (integer)
"""
sq_error = 0
for i in np.nditer(np.arange(y_pred.shape[0])):
sq_error += (y_actual[i] - y_predicted[i])**2
mse = 1/y_actual.shape[0] * sq_error
return mse
Hope this helps :). for further explaination visit
Change color of bootstrap navbar on hover link?
If you Navbar code as like as follow:
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../navbar/">Default</a></li>
<li><a href="../navbar-static-top/">Static top</a></li>
<li class="active"><a href="./">Fixed top</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
Then just use the following CSS style to change hover color of your navbar-brand
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: white;
}
So your navbad-brand
hover color will be changed to white. I just tested it and it's working for me correctly.
Spring boot - configure EntityManager
Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample
@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = {
ServiceMarker.class,
RepositoryMarker.class }
)
public class AppConfig {
}
PersistenceConfig
@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
@Autowired
private Environment env;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
private HibernateJpaVendorAdapter vendorAdaptor() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
return entityManagerFactoryBean;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
return properties;
}
}
Main
public static void main(String[] args) {
try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
MyService myService = springContext.getBean(MyServiceImpl.class);
try {
myService.handleProcess(fromDate, toDate);
} catch (Exception e) {
logger.error("Exception occurs", e);
myService.handleException(fromDate, toDate, e);
}
} catch (Exception e) {
logger.error("Exception occurs in loading Spring context: ", e);
}
}
MyService
@Service
public class MyServiceImpl implements MyService {
@Inject
private MyDao myDao;
@Override
public void handleProcess(String fromDate, String toDate) {
List<Student> myList = myDao.select(fromDate, toDate);
}
}
MyDaoImpl
@Repository
@Transactional
public class MyDaoImpl implements MyDao {
@PersistenceContext
private EntityManager entityManager;
public Student select(String fromDate, String toDate){
TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Student> list = query.getResultList();
return CollectionUtils.isEmpty(list) ? null : list;
}
}
Assuming maven project:
Properties file should be in src/main/resources/database
folder
jdbc.properties file
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password
hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true
ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.
Let's say you have package name a.b.c.service.impl
. MyServiceImpl is in this package and so is ServiceMarker.
public interface ServiceMarker {
}
Same for repository marker. Let's say you have a.b.c.repository.impl
or a.b.c.dao.impl
package name. Then MyDaoImpl is in this this package and also Repositorymarker
public interface RepositoryMarker {
}
a.b.c.entities.Student
//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {
private LocalDateTime fromDate;
private LocalDateTime toDate;
//getters setters
}
a.b.c.converters
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Timestamp.valueOf(dateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
}
pom.xml
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.1.RELEASE</org.springframework-version>
<hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<mysql-connector-java.version>5.1.36</mysql-connector-java.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
Hope it helps. Thanks
Mysql - How to quit/exit from stored procedure
This works for me :
CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int ,
IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
OUT o_number INT )
BEGIN
DECLARE v_pkg_name varchar(50) ;
DECLARE v_pkg_temp_id int(10) ;
DECLARE v_workflow_count INT(10);
-- checking if workflow created for package
select count(*) INTO v_workflow_count from workflow w where w.package_id =
package_id ;
this_proc:BEGIN -- this_proc block start here
IF v_workflow_count = 0 THEN
select 'no work flow ' as 'workflow_status' ;
SET o_message ='Work flow is not created for this package.';
SET o_number = -2 ;
LEAVE this_proc;
END IF;
select 'work flow created ' as 'workflow_status' ;
-- To send some message
SET o_message ='SUCCESSFUL';
SET o_number = 1 ;
END ;-- this_proc block end here
END
cocoapods - 'pod install' takes forever
Possible solutions:
- Updating Cocoa Pods may solve this issue
- Clean and fresh install pods again
Updating CocoaPods
Open terminal and type:
$ sudo gem update cocoapods
Reinstall Pods
Step 1
Remove all the pods from your project (tricky part):
Manually
- Remove all Pods records on Build Phases of your project (Marked Red)
- Remove libPods.a under Frameworks folder
- Now head to project directory and remove Podfile.lock*, **Pods folder and Workspace (Remove from Trash too).
Automatically using CocoaPods De-Integrate
Install
$ [sudo] gem install cocoapods-deintegrate
Run
$ pod deintegrate
Step 2
Here we are going through at installing the Pods again
Change your location your directory
$ cd yourprojectdirectory
Edit podfile by adding lines you need to it
$ open -a Xcode podfile
or
$ nano podfile
FINALLY install the pod again
$ pod install
Hope this helps
Is it good practice to use the xor operator for boolean checks?
If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?
The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.
public static boolean xor(boolean a, boolean b) {
return (a && !b) || (b && !a);
}
Most efficient way to convert an HTMLCollection to an Array
I saw a more concise method of getting Array.prototype
methods in general that works just as well. Converting an HTMLCollection
object into an Array
object is demonstrated below:
[].slice.call( yourHTMLCollectionObject );
And, as mentioned in the comments, for old browsers such as IE7 and earlier, you simply have to use a compatibility function, like:
function toArray(x) {
for(var i = 0, a = []; i < x.length; i++)
a.push(x[i]);
return a
}
I know this is an old question, but I felt the accepted answer was a little incomplete; so I thought I'd throw this out there FWIW.
Double.TryParse or Convert.ToDouble - which is faster and safer?
I generally try to avoid the Convert
class (meaning: I don't use it) because I find it very confusing: the code gives too few hints on what exactly happens here since Convert
allows a lot of semantically very different conversions to occur with the same code. This makes it hard to control for the programmer what exactly is happening.
My advice, therefore, is never to use this class. It's not really necessary either (except for binary formatting of a number, because the normal ToString
method of number classes doesn't offer an appropriate method to do this).
Mercurial stuck "waiting for lock"
I do not expect this to be a winning answer, but it is a fairly unusual situation.
Mentioning in case someone other than me runs into it.
Today I got the "waiting for lock on repository" on an hg push command.
When I killed the hung hg command I could see no .hg/store/lock
When I looked for .hg/store/lock while the command was hung, it existed. But the lockfile was deleted when the hg command was killed.
When I went to the target of the push, and executed hg pull, no problem.
Eventually I realized that the process ID on the hg push was lock waiting message was changing each time. It turns out that the "hg push" was hanging waiting for a lock held by itself (or possibly a subprocess, I did not investigate further).
It turns out that the two workspaces, let's call them A and B, had .hg trees shared by symlink:
A/.hg --symlinked-to--> B/.hg
This is NOT a good thing to do with Mercurial. Mercurial does not understand the concept of two workspaces sharing the same repository. I do understand, however, how somebody coming to Mercurial from another VCS might want this (Perforce does, although not a DVCS; the Bazaar DVCS reportedly can do so). I am surprised that a symlinked REP-ROOT/.hg works at all, although it seems to except for this push.
Can I catch multiple Java exceptions in the same catch clause?
Catch the exception that happens to be a parent class in the exception hierarchy. This is of course, bad practice. In your case, the common parent exception happens to be the Exception class, and catching any exception that is an instance of Exception, is indeed bad practice - exceptions like NullPointerException are usually programming errors and should usually be resolved by checking for null values.
How to Flatten a Multidimensional Array?
I needed to represent PHP multidimensional array in HTML input format.
$test = [
'a' => [
'b' => [
'c' => ['a', 'b']
]
],
'b' => 'c',
'c' => [
'd' => 'e'
]
];
$flatten = function ($input, $parent = []) use (&$flatten) {
$return = [];
foreach ($input as $k => $v) {
if (is_array($v)) {
$return = array_merge($return, $flatten($v, array_merge($parent, [$k])));
} else {
if ($parent) {
$key = implode('][', $parent) . '][' . $k . ']';
if (substr_count($key, ']') != substr_count($key, '[')) {
$key = preg_replace('/\]/', '', $key, 1);
}
} else {
$key = $k;
}
$return[$key] = $v;
}
}
return $return;
};
die(var_dump( $flatten($test) ));
array(4) {
["a[b][c][0]"]=>
string(1) "a"
["a[b][c][1]"]=>
string(1) "b"
["b"]=>
string(1) "c"
["c[d]"]=>
string(1) "e"
}
MongoDB: Combine data from multiple collections into one..how?
Although you can't do this real-time, you can run map-reduce multiple times to merge data together by using the "reduce" out option in MongoDB 1.8+ map/reduce (see http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Outputoptions). You need to have some key in both collections that you can use as an _id.
For example, let's say you have a users
collection and a comments
collection and you want to have a new collection that has some user demographic info for each comment.
Let's say the users
collection has the following fields:
- _id
- firstName
- lastName
- country
- gender
- age
And then the comments
collection has the following fields:
- _id
- userId
- comment
- created
You would do this map/reduce:
var mapUsers, mapComments, reduce;
db.users_comments.remove();
// setup sample data - wouldn't actually use this in production
db.users.remove();
db.comments.remove();
db.users.save({firstName:"Rich",lastName:"S",gender:"M",country:"CA",age:"18"});
db.users.save({firstName:"Rob",lastName:"M",gender:"M",country:"US",age:"25"});
db.users.save({firstName:"Sarah",lastName:"T",gender:"F",country:"US",age:"13"});
var users = db.users.find();
db.comments.save({userId: users[0]._id, "comment": "Hey, what's up?", created: new ISODate()});
db.comments.save({userId: users[1]._id, "comment": "Not much", created: new ISODate()});
db.comments.save({userId: users[0]._id, "comment": "Cool", created: new ISODate()});
// end sample data setup
mapUsers = function() {
var values = {
country: this.country,
gender: this.gender,
age: this.age
};
emit(this._id, values);
};
mapComments = function() {
var values = {
commentId: this._id,
comment: this.comment,
created: this.created
};
emit(this.userId, values);
};
reduce = function(k, values) {
var result = {}, commentFields = {
"commentId": '',
"comment": '',
"created": ''
};
values.forEach(function(value) {
var field;
if ("comment" in value) {
if (!("comments" in result)) {
result.comments = [];
}
result.comments.push(value);
} else if ("comments" in value) {
if (!("comments" in result)) {
result.comments = [];
}
result.comments.push.apply(result.comments, value.comments);
}
for (field in value) {
if (value.hasOwnProperty(field) && !(field in commentFields)) {
result[field] = value[field];
}
}
});
return result;
};
db.users.mapReduce(mapUsers, reduce, {"out": {"reduce": "users_comments"}});
db.comments.mapReduce(mapComments, reduce, {"out": {"reduce": "users_comments"}});
db.users_comments.find().pretty(); // see the resulting collection
At this point, you will have a new collection called users_comments
that contains the merged data and you can now use that. These reduced collections all have _id
which is the key you were emitting in your map functions and then all of the values are a sub-object inside the value
key - the values aren't at the top level of these reduced documents.
This is a somewhat simple example. You can repeat this with more collections as much as you want to keep building up the reduced collection. You could also do summaries and aggregations of data in the process. Likely you would define more than one reduce function as the logic for aggregating and preserving existing fields gets more complex.
You'll also note that there is now one document for each user with all of that user's comments in an array. If we were merging data that has a one-to-one relationship rather than one-to-many, it would be flat and you could simply use a reduce function like this:
reduce = function(k, values) {
var result = {};
values.forEach(function(value) {
var field;
for (field in value) {
if (value.hasOwnProperty(field)) {
result[field] = value[field];
}
}
});
return result;
};
If you want to flatten the users_comments
collection so it's one document per comment, additionally run this:
var map, reduce;
map = function() {
var debug = function(value) {
var field;
for (field in value) {
print(field + ": " + value[field]);
}
};
debug(this);
var that = this;
if ("comments" in this.value) {
this.value.comments.forEach(function(value) {
emit(value.commentId, {
userId: that._id,
country: that.value.country,
age: that.value.age,
comment: value.comment,
created: value.created,
});
});
}
};
reduce = function(k, values) {
var result = {};
values.forEach(function(value) {
var field;
for (field in value) {
if (value.hasOwnProperty(field)) {
result[field] = value[field];
}
}
});
return result;
};
db.users_comments.mapReduce(map, reduce, {"out": "comments_with_demographics"});
This technique should definitely not be performed on the fly. It's suited for a cron job or something like that which updates the merged data periodically. You'll probably want to run ensureIndex
on the new collection to make sure queries you perform against it run quickly (keep in mind that your data is still inside a value
key, so if you were to index comments_with_demographics
on the comment created
time, it would be db.comments_with_demographics.ensureIndex({"value.created": 1});
Is there a way to specify which pytest tests to run from a file?
My answer provides a ways to run a subset of test in different scenarios.
Run all tests in a project
pytest
Run tests in a Single Directory
To run all the tests from one directory, use the directory as a parameter to
pytest
:
pytest tests/my-directory
Run tests in a Single Test File/Module
To run a file full of tests, list the file with the relative path as a parameter to pytest
:
pytest tests/my-directory/test_demo.py
Run a Single Test Function
To run a single test function, add ::
and the test function name:
pytest -v tests/my-directory/test_demo.py::test_specific_function
-v
is used so you can see which function was run.
Run a Single Test Class
To run just a class, do like we did with functions and add ::
, then the class name to the file parameter:
pytest -v tests/my-directory/test_demo.py::TestClassName
Run a Single Test Method of a Test Class
If you don't want to run all of a test class, just one method, just add
another ::
and the method name:
pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method
Run a Set of Tests Based on Test Name
The -k
option enables you to pass in an expression to run tests that have
certain names specified by the expression as a substring of the test name.
It is possible to use and, or, and not to create complex expressions.
For example, to run all of the functions that have _raises in their name:
pytest -v -k _raises
Scala: write string to file in one statement
Through the magic of the semicolon, you can make anything you like a one-liner.
import java.io.PrintWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
val outfile = java.io.File.createTempFile("", "").getPath
val outstream = new PrintWriter(Files.newBufferedWriter(Paths.get(outfile)
, StandardCharsets.UTF_8
, StandardOpenOption.WRITE)); outstream.println("content"); outstream.flush(); outstream.close()
2 "style" inline css img tags?
You don't need 2 style attributes - just use one:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
style="height:100px;width:100px;" alt="25"/>
Consider, however, using a CSS class instead:
CSS:
.100pxSquare
{
width: 100px;
height: 100px;
}
HTML:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
class="100pxSquare" alt="25"/>
@RequestParam vs @PathVariable
@PathVariable - must be placed in the endpoint uri and access the query parameter value from the request
@RequestParam - must be passed as method parameter (optional based on the required property)
http://localhost:8080/employee/call/7865467
@RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
public List<Calls> getAgentCallById(
@PathVariable(“callId") int callId,
@RequestParam(value = “status", required = false) String callStatus) {
}
http://localhost:8080/app/call/7865467?status=Cancelled
@RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
public List<Calls> getAgentCallById(
@PathVariable(“callId") int callId,
@RequestParam(value = “status", required = true) String callStatus) {
}
remove kernel on jupyter notebook
Just for completeness, you can get a list of kernels with jupyter kernelspec list
, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel
. If you do not see everything in this list when you run jupyter kernelspec list
, try looking in common Jupyter folders:
ls ~/.local/share/jupyter/kernels # usually where local kernels go
ls /usr/local/share/jupyter/kernels # usually where system-wide kernels go
ls /usr/share/jupyter/kernels # also where system-wide kernels can go
Also, you can delete a kernel with jupyter kernelspec remove
or jupyter kernelspec uninstall
. The latter is an alias for remove
. From the in-line help text for the command:
uninstall
Alias for remove
remove
Remove one or more Jupyter kernelspecs by name.
Use String.split() with multiple delimiters
The string you give split
is the string form of a regular expression, so:
private void getId(String pdfName){
String[]tokens = pdfName.split("[\\-.]");
}
That means to split on any character in the []
(we have to escape -
with a backslash because it's special inside []
; and of course we have to escape the backslash because this is a string). (Conversely, .
is normally special but isn't special inside []
.)
Iterate keys in a C++ map
Below the more general templated solution to which Ian referred...
#include <map>
template<typename Key, typename Value>
using Map = std::map<Key, Value>;
template<typename Key, typename Value>
using MapIterator = typename Map<Key, Value>::iterator;
template<typename Key, typename Value>
class MapKeyIterator : public MapIterator<Key, Value> {
public:
MapKeyIterator ( ) : MapIterator<Key, Value> ( ) { };
MapKeyIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };
Key *operator -> ( ) { return ( Key * const ) &( MapIterator<Key, Value>::operator -> ( )->first ); }
Key operator * ( ) { return MapIterator<Key, Value>::operator * ( ).first; }
};
template<typename Key, typename Value>
class MapValueIterator : public MapIterator<Key, Value> {
public:
MapValueIterator ( ) : MapIterator<Key, Value> ( ) { };
MapValueIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };
Value *operator -> ( ) { return ( Value * const ) &( MapIterator<Key, Value>::operator -> ( )->second ); }
Value operator * ( ) { return MapIterator<Key, Value>::operator * ( ).second; }
};
All credits go to Ian... Thanks Ian.
Focus Next Element In Tab Index
I created a simple jQuery plugin which does just this. It uses the ':tabbable' selector of jQuery UI to find the next 'tabbable' element and selects it.
Example usage:
// Simulate tab key when element is clicked
$('.myElement').bind('click', function(event){
$.tabNext();
return false;
});
Convert XML String to Object
I have gone through all the answers as at this date (2020-07-24), and there has to be a simpler more familiar way to solve this problem, which is the following.
Two scenarios... One is if the XML string is well-formed, i.e. it begins with something like <?xml version="1.0" encoding="utf-16"?>
or its likes, before encountering the root element, which is <msg>
in the question. The other is if it is NOT well-formed, i.e. just the root element (e.g. <msg>
in the question) and its child nodes only.
Firstly, just a simple class that contains the properties that match, in case-insensitive names, the child nodes of the root node in the XML. So, from the question, it would be something like...
public class TheModel
{
public int Id { get; set; }
public string Action { get; set; }
}
The following is the rest of the code...
// These are the key using statements to add.
using Newtonsoft.Json;
using System.Xml;
bool isWellFormed = false;
string xml = = @"
<msg>
<id>1</id>
<action>stop</action>
</msg>
";
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
if (isWellFormed)
{
xmlDocument.RemoveChild(xmlDocument.FirstChild);
/* i.e. removing the first node, which is the declaration part.
Also, if there are other unwanted parts in the XML,
write another similar code to locate the nodes
and remove them to only leave the desired root node
(and its child nodes).*/
}
var serializedXmlNode = JsonConvert.SerializeXmlNode(
xmlDocument,
Newtonsoft.Json.Formatting.Indented,
true
);
var theDesiredObject = JsonConvert.DeserializeObject<TheModel>(serializedXmlNode);
Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token
If you want to avoid using an extra Class
and List<Object> genomes
you could simply use a Map
.
The data structure translates into Map<String, List<Country>>
String resourceEndpoint = "http://api.geonames.org/countryInfoJSON?username=volodiaL";
Map<String, List<Country>> geonames = restTemplate.getForObject(resourceEndpoint, Map.class);
List<Country> countries = geonames.get("geonames");
How to handle notification when app in background in Firebase
you want to work onMessageReceived(RemoteMessage remoteMessage) in background send only data part notification part this:
"data": "image": "", "message": "Firebase Push Message Using API",
"AnotherActivity": "True", "to" : "device id Or Device token"
By this onMessageRecivied is call background and foreground no need to handle notification using notification tray on your launcher activity.
Handle data payload in using this:
public void onMessageReceived(RemoteMessage remoteMessage)
if (remoteMessage.getData().size() > 0)
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
How do I print colored output to the terminal in Python?
Color_Console library is comparatively easier to use. Install this library and the following code would help you.
from Color_Console import *
ctext("This will be printed" , "white" , "blue")
The first argument is the string to be printed, The second argument is the color of
the text and the last one is the background color.
The latest version of Color_Console allows you to pass a list or dictionary of colors which would change after a specified delay time.
Also, they have good documentation on all of their functions.
Visit https://pypi.org/project/Color-Console/ to know more.
Compilation error - missing zlib.h
I also had the same problem. Then I installed the zlib, still the problem remained the same. Then I added the following lines in my .bashrc and it worked. You should replace the path with your zlib installation path. (I didn't have root privileges).
export PATH =$PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/
export LIBRARY_PATH=$LIBRARY_PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/
export C_INCLUDE_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/include/
export CPLUS_INCLUDE_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/include/
export PKG_CONFIG_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/pkgconfig
How to get the size of a JavaScript object?
I use Chrome dev tools' Timeline tab, instantiate increasingly large amounts of objects, and get good estimates like that. You can use html like this one below, as boilerplate, and modify it to better simulate the characteristics of your objects (number and types of properties, etc...). You may want to click the trash bit icon at the bottom of that dev tools tab, before and after a run.
<html>
<script>
var size = 1000*100
window.onload = function() {
document.getElementById("quantifier").value = size
}
function scaffold()
{
console.log("processing Scaffold...");
a = new Array
}
function start()
{
size = document.getElementById("quantifier").value
console.log("Starting... quantifier is " + size);
console.log("starting test")
for (i=0; i<size; i++){
a[i]={"some" : "thing"}
}
console.log("done...")
}
function tearDown()
{
console.log("processing teardown");
a.length=0
}
</script>
<body>
<span style="color:green;">Quantifier:</span>
<input id="quantifier" style="color:green;" type="text"></input>
<button onclick="scaffold()">Scaffold</button>
<button onclick="start()">Start</button>
<button onclick="tearDown()">Clean</button>
<br/>
</body>
</html>
Instantiating 2 million objects of just one property each (as in this code above) leads to a rough calculation of 50 bytes per object, on my Chromium, right now. Changing the code to create a random string per object adds some 30 bytes per object, etc.
Hope this helps.
How to add multiple font files for the same font?
/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
src:
local('DejaVu Sans'),
local('DejaVu-Sans'), /* Duplicated name with hyphen */
url('dejavu/DejaVuSans.ttf')
format('truetype');
}
/*bold version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-Bold.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-Bold.ttf')
format('truetype');
font-weight: bold;
}
/*italic version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-Oblique.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-Oblique.ttf')
format('truetype');
font-style: italic;
}
/*bold italic version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-BoldOblique.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-BoldOblique.ttf')
format('truetype');
font-weight: bold;
font-style: italic;
}
C++ "Access violation reading location" Error
You haven't posted the findvertex
method, but Access Reading Violation with an offset like 0x00000048
means that the Vertex* f;
in your getCost function is receiving null, and when trying to access the member adj
in the null
Vertex pointer (that is, in f
), it is offsetting to adj
(in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0
or null
memory address.
Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex
isn't returning null, or do a comparisong for null on f
before using it to keep yourself sane (or use an assert):
assert( f != null ); // A good sanity check
EDIT:
If you have a map
for doing something like a find, you can just use the map's find
method to make sure the vertex exists:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.find( s );
if ( itr == map1.end() )
{
return NULL;
}
return itr->second;
}
Just make sure you're still careful to handle the error case where it does return NULL
. Otherwise, you'll keep getting this access violation.
Android SQLite: Update Statement
You can try:
db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");
Or
ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");
db.update("YOUR_TABLE", newValues, "id=6", null);
Or
ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");
String[] args = new String[]{"user1", "user2"};
db.update("YOUR_TABLE", newValues, "name=? OR name=?", args);
Is there an advantage to use a Synchronized Method instead of a Synchronized Block?
TLDR; Neither use the synchronized
modifier nor the synchronized(this){...}
expression but synchronized(myLock){...}
where myLock
is a final instance field holding a private object.
The difference between using the synchronized
modifier on the method declaration and the synchronized(..){ }
expression in the method body are this:
- The
synchronized
modifier specified on the method's signature
- is visible in the generated JavaDoc,
- is programmatically determinable via reflection when testing a method's modifier for Modifier.SYNCHRONIZED,
- requires less typing and indention compared to
synchronized(this) { .... }
, and
- (depending on your IDE) is visible in the class outline and code completion,
- uses the
this
object as lock when declared on non-static method or the enclosing class when declared on a static method.
- The
synchronized(...){...}
expression allows you
- to only synchronize the execution of parts of a method's body,
- to be used within a constructor or a (static) initialization block,
- to choose the lock object which controls the synchronized access.
However, using the synchronized
modifier or synchronized(...) {...}
with this
as the lock object (as in synchronized(this) {...}
), have the same disadvantage. Both use it's own instance as the lock object to synchronize on. This is dangerous because not only the object itself but any other external object/code that holds a reference to that object can also use it as a synchronization lock with potentially severe side effects (performance degradation and deadlocks).
Therefore best practice is to neither use the synchronized
modifier nor the synchronized(...)
expression in conjunction with this
as lock object but a lock object private to this object. For example:
public class MyService {
private final lock = new Object();
public void doThis() {
synchronized(lock) {
// do code that requires synchronous execution
}
}
public void doThat() {
synchronized(lock) {
// do code that requires synchronous execution
}
}
}
You can also use multiple lock objects but special care needs to be taken to ensure this does not result in deadlocks when used nested.
public class MyService {
private final lock1 = new Object();
private final lock2 = new Object();
public void doThis() {
synchronized(lock1) {
synchronized(lock2) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThat() and doMore().
}
}
public void doThat() {
synchronized(lock1) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThis().
// doMore() may execute concurrently
}
}
public void doMore() {
synchronized(lock2) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThis().
// doThat() may execute concurrently
}
}
}
Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional
In my case the Data provider entry for MySQL was "simply" missing in the machine.config file described above (though I had installed the MySQL connector properly)
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
Don't forget to put the right Version of your MySQL on the Entry
Input type=password, don't let browser remember the password
In the case of most major browsers, having an input outside of and not connected to any forms whatsoever tricks the browser into thinking there was no submission. In this case, you would have to use pure JS validation for your login and encryption of your passwords would be necessary as well.
Before:
<form action="..."><input type="password"/></form>
After:
<input type="password"/>
How to make PDF file downloadable in HTML link?
This can be achieved using HTML.
<a href="myfile.pdf">Download Brochure</a>
Add download attribute to it:
Here the file name will be myfile.pdf
<a href="myfile.pdf" download>Download Brochure</a>
Specify a value for the download attribute:
<a href="myfile.pdf" download="Brochure">Download Brochure</a>
Here the file name will be Brochure.pdf
Create dynamic variable name
Variable names should be known at compile time. If you intend to populate those names dynamically at runtime you could use a List<T>
var variables = List<Variable>();
variables.Add(new Variable { Name = inputStr1 });
variables.Add(new Variable { Name = inputStr2 });
here input string maybe any text or any list
Java/ JUnit - AssertTrue vs AssertFalse
Your first reaction to these methods is quite interesting to me. I will use it in future arguments that both assertTrue and assertFalse are not the most friendly tools. If you would use
assertThat(thisOrThat, is(false));
it is much more readable, and it prints a better error message too.
Create a one to many relationship using SQL Server
This is how I usually do it (sql server).
Create Table Master (
MasterID int identity(1,1) primary key,
Stuff varchar(10)
)
GO
Create Table Detail (
DetailID int identity(1,1) primary key,
MasterID int references Master, --use 'references'
Stuff varchar(10))
GO
Insert into Master values('value')
--(1 row(s) affected)
GO
Insert into Detail values (1, 'Value1') -- Works
--(1 row(s) affected)
insert into Detail values (2, 'Value2') -- Fails
--Msg 547, Level 16, State 0, Line 2
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Detail__MasterID__0C70CFB4".
--The conflict occurred in database "Play", table "dbo.Master", column 'MasterID'.
--The statement has been terminated.
As you can see the second insert into the detail fails because of the foreign key.
Here's a good weblink that shows various syntax for defining FK during table creation or after.
http://www.1keydata.com/sql/sql-foreign-key.html
Replace characters from a column of a data frame R
You can use the stringr
library:
library('stringr')
a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A_C
# 6 0.55313288 f A_C
# 7 0.31264280 g A_C
# 8 0.33759921 h A_C
# 9 0.72322599 i A_C
# 10 0.25223075 j A_C
data$c <- str_replace_all(data$c, '_', '-')
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A-C
# 6 0.55313288 f A-C
# 7 0.31264280 g A-C
# 8 0.33759921 h A-C
# 9 0.72322599 i A-C
# 10 0.25223075 j A-C
Note that this does change factored variables into character.
Quotation marks inside a string
You can do this using Escape Sequence.
\"
So you will have to write something like this :
String name = "\"john\"";
You can learn about Escape Sequences from here.
How to convert string values from a dictionary, into int/float datatypes?
If you'd decide for a solution acting "in place" you could take a look at this one:
>>> d = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
>>> [dt.update({k: int(v)}) for dt in d for k, v in dt.iteritems()]
[None, None, None, None, None, None]
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'e': 5, 'd': 4, 'f': 6}]
Btw, key order is not preserved because that's the way standard dictionaries work, ie without the concept of order.
Is it possible to have a multi-line comments in R?
Unfortunately, there is still no multi-line commenting in R.
If your text editor supports column-mode, then use it to add a bunch of #s at once. If you use UltraEdit, Alt+c will put you in column mode.
Open Source Javascript PDF viewer
You can use the Google Docs PDF-viewing widget, if you don't mind having them host the "application" itself.
I had more suggestions, but stack overflow only lets me post one hyperlink as a new user, sorry.
Resize iframe height according to content height in it
Below is my onload
event handler.
I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments.
This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5.
It might need some extra tweaking, but the general idea should be clear.
function onLoadDialog(frame) {
try {
var body = frame.contentDocument.body;
var $body = $(body);
var $frame = $(frame);
var contentDiv = frame.parentNode;
var $contentDiv = $(contentDiv);
var savedShow = $contentDiv.dialog('option', 'show');
var position = $contentDiv.dialog('option', 'position');
// disable show effect to enable re-positioning (UI bug?)
$contentDiv.dialog('option', 'show', null);
// show dialog, otherwise sizing won't work
$contentDiv.dialog('open');
// Maximize frame width in order to determine minimal scrollHeight
$frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
contentDiv.offsetWidth + frame.offsetWidth);
var minScrollHeight = body.scrollHeight;
var maxWidth = body.offsetWidth;
var minWidth = 0;
// decrease frame width until scrollHeight starts to grow (wrapping)
while (Math.abs(maxWidth - minWidth) > 10) {
var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
$body.css('width', width);
if (body.scrollHeight > minScrollHeight) {
minWidth = width;
} else {
maxWidth = width;
}
}
$frame.css('width', maxWidth);
// use maximum height to avoid vertical scrollbar (if possible)
var maxHeight = $contentDiv.dialog('option', 'maxHeight')
$frame.css('height', maxHeight);
$body.css('width', '');
// correct for vertical scrollbar (if necessary)
while (body.clientWidth < maxWidth) {
$frame.css('width', maxWidth + (maxWidth - body.clientWidth));
}
var minScrollWidth = body.scrollWidth;
var minHeight = Math.min(minScrollHeight, maxHeight);
// descrease frame height until scrollWidth decreases (wrapping)
while (Math.abs(maxHeight - minHeight) > 10) {
var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
$body.css('height', height);
if (body.scrollWidth < minScrollWidth) {
minHeight = height;
} else {
maxHeight = height;
}
}
$frame.css('height', maxHeight);
$body.css('height', '');
// reset widths to 'auto' where possible
$contentDiv.css('width', 'auto');
$contentDiv.css('height', 'auto');
$contentDiv.dialog('option', 'width', 'auto');
// re-position the dialog
$contentDiv.dialog('option', 'position', position);
// hide dialog
$contentDiv.dialog('close');
// restore show effect
$contentDiv.dialog('option', 'show', savedShow);
// open using show effect
$contentDiv.dialog('open');
// remove show effect for consecutive requests
$contentDiv.dialog('option', 'show', null);
return;
}
//An error is raised if the IFrame domain != its container's domain
catch (e) {
window.status = 'Error: ' + e.number + '; ' + e.description;
alert('Error: ' + e.number + '; ' + e.description);
}
};
Git: Remove committed file after push
You can revert only one file to a specified revision.
First you can check on which commits the file was changed.
git log path/to/file.txt
Then you can checkout the file with the revision number.
git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt
After that you can commit and push it again.
twitter bootstrap typeahead ajax example
Edit: typeahead is no longer bundled in Bootstrap 3. Check out:
As of Bootstrap 2.1.0 up to 2.3.2, you can do this:
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('/typeahead', { query: query }, function (data) {
return process(data.options);
});
}
});
To consume JSON data like this:
{
"options": [
"Option 1",
"Option 2",
"Option 3",
"Option 4",
"Option 5"
]
}
Note that the JSON data must be of the right mime type (application/json) so jQuery recognizes it as JSON.
How to flush output of print function?
How to flush output of Python print?
I suggest five ways of doing this:
- In Python 3, call
print(..., flush=True)
(the flush argument is not available in Python 2's print function, and there is no analogue for the print statement).
- Call
file.flush()
on the output file (we can wrap python 2's print function to do this), for example, sys.stdout
- apply this to every print function call in the module with a partial function,
print = partial(print, flush=True)
applied to the module global.
- apply this to the process with a flag (
-u
) passed to the interpreter command
- apply this to every python process in your environment with
PYTHONUNBUFFERED=TRUE
(and unset the variable to undo this).
Python 3.3+
Using Python 3.3 or higher, you can just provide flush=True
as a keyword argument to the print
function:
print('foo', flush=True)
Python 2 (or < 3.3)
They did not backport the flush
argument to Python 2.7 So if you're using Python 2 (or less than 3.3), and want code that's compatible with both 2 and 3, may I suggest the following compatibility code. (Note the __future__
import must be at/very "near the top of your module"):
from __future__ import print_function
import sys
if sys.version_info[:2] < (3, 3):
old_print = print
def print(*args, **kwargs):
flush = kwargs.pop('flush', False)
old_print(*args, **kwargs)
if flush:
file = kwargs.get('file', sys.stdout)
# Why might file=None? IDK, but it works for print(i, file=None)
file.flush() if file is not None else sys.stdout.flush()
The above compatibility code will cover most uses, but for a much more thorough treatment, see the six
module.
Alternatively, you can just call file.flush()
after printing, for example, with the print statement in Python 2:
import sys
print 'delayed output'
sys.stdout.flush()
Changing the default in one module to flush=True
You can change the default for the print function by using functools.partial on the global scope of a module:
import functools
print = functools.partial(print, flush=True)
if you look at our new partial function, at least in Python 3:
>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(<built-in function print>, flush=True)
We can see it works just like normal:
>>> print('foo')
foo
And we can actually override the new default:
>>> print('foo', flush=False)
foo
Note again, this only changes the current global scope, because the print name on the current global scope will overshadow the builtin print
function (or unreference the compatibility function, if using one in Python 2, in that current global scope).
If you want to do this inside a function instead of on a module's global scope, you should give it a different name, e.g.:
def foo():
printf = functools.partial(print, flush=True)
printf('print stuff like this')
If you declare it a global in a function, you're changing it on the module's global namespace, so you should just put it in the global namespace, unless that specific behavior is exactly what you want.
Changing the default for the process
I think the best option here is to use the -u
flag to get unbuffered output.
$ python -u script.py
or
$ python -um package.module
From the docs:
Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.
Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.
Changing the default for the shell operating environment
You can get this behavior for all python processes in the environment or environments that inherit from the environment if you set the environment variable to a nonempty string:
e.g., in Linux or OSX:
$ export PYTHONUNBUFFERED=TRUE
or Windows:
C:\SET PYTHONUNBUFFERED=TRUE
from the docs:
PYTHONUNBUFFERED
If this is set to a non-empty string it is equivalent to specifying the -u option.
Addendum
Here's the help on the print function from Python 2.7.12 - note that there is no flush
argument:
>>> from __future__ import print_function
>>> help(print)
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
unix sort descending order
The presence of the n
option attached to the -k5
causes the global -r
option to be ignored for that field. You have to specify both n
and r
at the same level (globally or locally).
sort -t $'\t' -k5,5rn
or
sort -rn -t $'\t' -k5,5
library not found for -lPods
I ran into an issue where I had created my own .xcworkspace
which kept pods form createing it's own (where is where it attaches it's library).
solution
I moved the .xcworkspace
I had created, ran pod install
again and then manually merged my .xcworkspace
with the one pods created by openeing both workspaces and dragging files from one workspace to the other.
Save each sheet in a workbook to separate CSV files
Here is one that will give you a visual file chooser to pick the folder you want to save the files to and also lets you choose the CSV delimiter (I use pipes '|' because my fields contain commas and I don't want to deal with quotes):
' ---------------------- Directory Choosing Helper Functions -----------------------
' Excel and VBA do not provide any convenient directory chooser or file chooser
' dialogs, but these functions will provide a reference to a system DLL
' with the necessary capabilities
Private Type BROWSEINFO ' used by the function GetFolderName
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Function GetFolderName(Msg As String) As String
' returns the name of the folder selected by the user
Dim bInfo As BROWSEINFO, path As String, r As Long
Dim X As Long, pos As Integer
bInfo.pidlRoot = 0& ' Root folder = Desktop
If IsMissing(Msg) Then
bInfo.lpszTitle = "Select a folder."
' the dialog title
Else
bInfo.lpszTitle = Msg ' the dialog title
End If
bInfo.ulFlags = &H1 ' Type of directory to return
X = SHBrowseForFolder(bInfo) ' display the dialog
' Parse the result
path = Space$(512)
r = SHGetPathFromIDList(ByVal X, ByVal path)
If r Then
pos = InStr(path, Chr$(0))
GetFolderName = Left(path, pos - 1)
Else
GetFolderName = ""
End If
End Function
'---------------------- END Directory Chooser Helper Functions ----------------------
Public Sub DoTheExport()
Dim FName As Variant
Dim Sep As String
Dim wsSheet As Worksheet
Dim nFileNum As Integer
Dim csvPath As String
Sep = InputBox("Enter a single delimiter character (e.g., comma or semi-colon)", _
"Export To Text File")
'csvPath = InputBox("Enter the full path to export CSV files to: ")
csvPath = GetFolderName("Choose the folder to export CSV files to:")
If csvPath = "" Then
MsgBox ("You didn't choose an export directory. Nothing will be exported.")
Exit Sub
End If
For Each wsSheet In Worksheets
wsSheet.Activate
nFileNum = FreeFile
Open csvPath & "\" & _
wsSheet.Name & ".csv" For Output As #nFileNum
ExportToTextFile CStr(nFileNum), Sep, False
Close nFileNum
Next wsSheet
End Sub
Public Sub ExportToTextFile(nFileNum As Integer, _
Sep As String, SelectionOnly As Boolean)
Dim WholeLine As String
Dim RowNdx As Long
Dim ColNdx As Integer
Dim StartRow As Long
Dim EndRow As Long
Dim StartCol As Integer
Dim EndCol As Integer
Dim CellValue As String
Application.ScreenUpdating = False
On Error GoTo EndMacro:
If SelectionOnly = True Then
With Selection
StartRow = .Cells(1).Row
StartCol = .Cells(1).Column
EndRow = .Cells(.Cells.Count).Row
EndCol = .Cells(.Cells.Count).Column
End With
Else
With ActiveSheet.UsedRange
StartRow = .Cells(1).Row
StartCol = .Cells(1).Column
EndRow = .Cells(.Cells.Count).Row
EndCol = .Cells(.Cells.Count).Column
End With
End If
For RowNdx = StartRow To EndRow
WholeLine = ""
For ColNdx = StartCol To EndCol
If Cells(RowNdx, ColNdx).Value = "" Then
CellValue = ""
Else
CellValue = Cells(RowNdx, ColNdx).Value
End If
WholeLine = WholeLine & CellValue & Sep
Next ColNdx
WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))
Print #nFileNum, WholeLine
Next RowNdx
EndMacro:
On Error GoTo 0
Application.ScreenUpdating = True
End Sub
Best approach to converting Boolean object to string in java
I don't think there would be any significant performance difference between them, but I would prefer the 1st way.
If you have a Boolean
reference, Boolean.toString(boolean)
will throw NullPointerException
if your reference is null
. As the reference is unboxed to boolean
before being passed to the method.
While, String.valueOf()
method as the source code shows, does the explicit null
check:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Just test this code:
Boolean b = null;
System.out.println(String.valueOf(b)); // Prints null
System.out.println(Boolean.toString(b)); // Throws NPE
For primitive boolean, there is no difference.
AngularJS passing data to $http.get request
Solution for those who are interested in sending params and headers in GET request
$http.get('https://www.your-website.com/api/users.json', {
params: {page: 1, limit: 100, sort: 'name', direction: 'desc'},
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
});
Complete service example will look like this
var mainApp = angular.module("mainApp", []);
mainApp.service('UserService', function($http, $q){
this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {
var dfrd = $q.defer();
$http.get('https://www.your-website.com/api/users.json',
{
params:{page: page, limit: limit, sort: sort, direction: direction},
headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
if ( response.data.success == true ) {
} else {
}
}, function(x) {
dfrd.reject(true);
});
return dfrd.promise;
}
});
How to sort a Pandas DataFrame by index?
Dataframes have a sort_index
method which returns a copy by default. Pass inplace=True
to operate in place.
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())
Gives me:
A
1 4
29 2
100 1
150 5
234 3
select count(*) from select
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
Bootstrap get div to align in the center
In bootstrap you can use .text-center
to align center. also add .row
and .col-md-*
to your code.
align=
is deprecated,
Added .col-xs-*
for demo
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
<div class="container">
<div class="row">
<div class="col-xs-4">
<p>Hello there</p>
</div>
<div class="col-xs-4 text-center">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="col-xs-4 text-right">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
</div>
_x000D_
_x000D_
_x000D_
UPDATE(OCT 2017)
For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
<div class="d-flex justify-content-between">
<div class="p-1">
<p>Hello there</p>
</div>
<div class="p-1">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="p-1">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
_x000D_
_x000D_
_x000D_
Read and write to binary files in C?
This is an example to read and write binary jjpg or wmv video file.
FILE *fout;
FILE *fin;
Int ch;
char *s;
fin=fopen("D:\\pic.jpg","rb");
if(fin==NULL)
{ printf("\n Unable to open the file ");
exit(1);
}
fout=fopen("D:\\ newpic.jpg","wb");
ch=fgetc(fin);
while (ch!=EOF)
{
s=(char *)ch;
printf("%c",s);
ch=fgetc (fin):
fputc(s,fout);
s++;
}
printf("data read and copied");
fclose(fin);
fclose(fout);
What is WebKit and how is it related to CSS?
Webkit is the html/css rendering engine used in Apple's Safari browser, and in Google's Chrome.
css values prefixes with -webkit- are webkit-specific, they're usually CSS3 or other non-standardised features.
to answer update 2
w3c is the body that tries to standardize these things, they write the rules, then programmers write their rendering engine to interpret those rules. So basically w3c says DIVs should work "This way" the engine-writer then uses that rule to write their code, any bugs or mis-interpretations of the rules cause the compatibility issues.
Add and remove attribute with jquery
If you want to do this, you need to save it in a variable first. So you don't need to use id to query this element every time.
var el = $("#page_navigation1");
$("#add").click(function(){
el.attr("id","page_navigation1");
});
$("#remove").click(function(){
el.removeAttr("id");
});
Add/remove HTML inside div using JavaScript
To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient insertAdjacentHTML
on MDN (see CanIUse?insertAdjacentHTML for a pretty green compatibility table).
So using it you would write
_x000D_
_x000D_
function addRow () {_x000D_
document.querySelector('#content').insertAdjacentHTML(_x000D_
'afterbegin',_x000D_
`<div class="row">_x000D_
<input type="text" name="name" value="" />_x000D_
<input type="text" name="value" value="" />_x000D_
<label><input type="checkbox" name="check" value="1" />Checked?</label>_x000D_
<input type="button" value="-" onclick="removeRow(this)">_x000D_
</div>` _x000D_
)_x000D_
}_x000D_
_x000D_
function removeRow (input) {_x000D_
input.parentNode.remove()_x000D_
}
_x000D_
<input type="button" value="+" onclick="addRow()">_x000D_
_x000D_
<div id="content">_x000D_
</div>
_x000D_
_x000D_
_x000D_
How do I split an int into its digits?
You can just use a sequence of x/10.0f and std::floor operations to have "math approach".
Or you can also use boost::lexical_cast(the_number) to obtain a string and then you can simply do the_string.c_str()[i] to access the individual characters (the "string approach").
SQL permissions for roles
Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:
GRANT ALL ON table1 TO doctor
Users in that role will have no permissions whatsoever to other tables (not even read).
How to close Android application?
Android has a mechanism in place to close an application safely per its documentation. In the last Activity that is exited (usually the main Activity that first came up when the application started) just place a couple of lines in the onDestroy() method. The call to System.runFinalizersOnExit(true) ensures that all objects will be finalized and garbage collected when the the application exits. You can also kill an application quickly via android.os.Process.killProcess(android.os.Process.myPid()) if you prefer. The best way to do this is put a method like the following in a helper class and then call it whenever the app needs to be killed. For example in the destroy method of the root activity (assuming that the app never kills this activity):
Also Android will not notify an application of the HOME key event, so you cannot close the application when the HOME key is pressed. Android reserves the HOME key event to itself so that a developer cannot prevent users from leaving their application. However you can determine with the HOME key is pressed by setting a flag to true in a helper class that assumes that the HOME key has been pressed, then changing the flag to false when an event occurs that shows the HOME key was not pressed and then checking to see of the HOME key pressed in the onStop() method of the activity.
Don't forget to handle the HOME key for any menus and in the activities that are started by the menus. The same goes for the SEARCH key. Below is some example classes to illustrate:
Here's an example of a root activity that kills the application when it is destroyed:
package android.example;
/**
* @author Danny Remington - MacroSolve
*/
public class HomeKey extends CustomActivity {
public void onDestroy() {
super.onDestroy();
/*
* Kill application when the root activity is killed.
*/
UIHelper.killApp(true);
}
}
Here's an abstract activity that can be extended to handle the HOME key for all activities that extend it:
package android.example;
/**
* @author Danny Remington - MacroSolve
*/
import android.app.Activity;
import android.view.Menu;
import android.view.MenuInflater;
/**
* Activity that includes custom behavior shared across the application. For
* example, bringing up a menu with the settings icon when the menu button is
* pressed by the user and then starting the settings activity when the user
* clicks on the settings icon.
*/
public abstract class CustomActivity extends Activity {
public void onStart() {
super.onStart();
/*
* Check if the app was just launched. If the app was just launched then
* assume that the HOME key will be pressed next unless a navigation
* event by the user or the app occurs. Otherwise the user or the app
* navigated to this activity so the HOME key was not pressed.
*/
UIHelper.checkJustLaunced();
}
public void finish() {
/*
* This can only invoked by the user or the app finishing the activity
* by navigating from the activity so the HOME key was not pressed.
*/
UIHelper.homeKeyPressed = false;
super.finish();
}
public void onStop() {
super.onStop();
/*
* Check if the HOME key was pressed. If the HOME key was pressed then
* the app will be killed. Otherwise the user or the app is navigating
* away from this activity so assume that the HOME key will be pressed
* next unless a navigation event by the user or the app occurs.
*/
UIHelper.checkHomeKeyPressed(true);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings_menu, menu);
/*
* Assume that the HOME key will be pressed next unless a navigation
* event by the user or the app occurs.
*/
UIHelper.homeKeyPressed = true;
return true;
}
public boolean onSearchRequested() {
/*
* Disable the SEARCH key.
*/
return false;
}
}
Here's an example of a menu screen that handles the HOME key:
/**
* @author Danny Remington - MacroSolve
*/
package android.example;
import android.os.Bundle;
import android.preference.PreferenceActivity;
/**
* PreferenceActivity for the settings screen.
*
* @see PreferenceActivity
*
*/
public class SettingsScreen extends PreferenceActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.settings_screen);
}
public void onStart() {
super.onStart();
/*
* This can only invoked by the user or the app starting the activity by
* navigating to the activity so the HOME key was not pressed.
*/
UIHelper.homeKeyPressed = false;
}
public void finish() {
/*
* This can only invoked by the user or the app finishing the activity
* by navigating from the activity so the HOME key was not pressed.
*/
UIHelper.homeKeyPressed = false;
super.finish();
}
public void onStop() {
super.onStop();
/*
* Check if the HOME key was pressed. If the HOME key was pressed then
* the app will be killed either safely or quickly. Otherwise the user
* or the app is navigating away from the activity so assume that the
* HOME key will be pressed next unless a navigation event by the user
* or the app occurs.
*/
UIHelper.checkHomeKeyPressed(true);
}
public boolean onSearchRequested() {
/*
* Disable the SEARCH key.
*/
return false;
}
}
Here's an example of a helper class that handles the HOME key across the app:
package android.example;
/**
* @author Danny Remington - MacroSolve
*
*/
/**
* Helper class to help handling of UI.
*/
public class UIHelper {
public static boolean homeKeyPressed;
private static boolean justLaunched = true;
/**
* Check if the app was just launched. If the app was just launched then
* assume that the HOME key will be pressed next unless a navigation event
* by the user or the app occurs. Otherwise the user or the app navigated to
* the activity so the HOME key was not pressed.
*/
public static void checkJustLaunced() {
if (justLaunched) {
homeKeyPressed = true;
justLaunched = false;
} else {
homeKeyPressed = false;
}
}
/**
* Check if the HOME key was pressed. If the HOME key was pressed then the
* app will be killed either safely or quickly. Otherwise the user or the
* app is navigating away from the activity so assume that the HOME key will
* be pressed next unless a navigation event by the user or the app occurs.
*
* @param killSafely
* Primitive boolean which indicates whether the app should be
* killed safely or quickly when the HOME key is pressed.
*
* @see {@link UIHelper.killApp}
*/
public static void checkHomeKeyPressed(boolean killSafely) {
if (homeKeyPressed) {
killApp(true);
} else {
homeKeyPressed = true;
}
}
/**
* Kill the app either safely or quickly. The app is killed safely by
* killing the virtual machine that the app runs in after finalizing all
* {@link Object}s created by the app. The app is killed quickly by abruptly
* killing the process that the virtual machine that runs the app runs in
* without finalizing all {@link Object}s created by the app. Whether the
* app is killed safely or quickly the app will be completely created as a
* new app in a new virtual machine running in a new process if the user
* starts the app again.
*
* <P>
* <B>NOTE:</B> The app will not be killed until all of its threads have
* closed if it is killed safely.
* </P>
*
* <P>
* <B>NOTE:</B> All threads running under the process will be abruptly
* killed when the app is killed quickly. This can lead to various issues
* related to threading. For example, if one of those threads was making
* multiple related changes to the database, then it may have committed some
* of those changes but not all of those changes when it was abruptly
* killed.
* </P>
*
* @param killSafely
* Primitive boolean which indicates whether the app should be
* killed safely or quickly. If true then the app will be killed
* safely. Otherwise it will be killed quickly.
*/
public static void killApp(boolean killSafely) {
if (killSafely) {
/*
* Notify the system to finalize and collect all objects of the app
* on exit so that the virtual machine running the app can be killed
* by the system without causing issues. NOTE: If this is set to
* true then the virtual machine will not be killed until all of its
* threads have closed.
*/
System.runFinalizersOnExit(true);
/*
* Force the system to close the app down completely instead of
* retaining it in the background. The virtual machine that runs the
* app will be killed. The app will be completely created as a new
* app in a new virtual machine running in a new process if the user
* starts the app again.
*/
System.exit(0);
} else {
/*
* Alternatively the process that runs the virtual machine could be
* abruptly killed. This is the quickest way to remove the app from
* the device but it could cause problems since resources will not
* be finalized first. For example, all threads running under the
* process will be abruptly killed when the process is abruptly
* killed. If one of those threads was making multiple related
* changes to the database, then it may have committed some of those
* changes but not all of those changes when it was abruptly killed.
*/
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
list all files in the folder and also sub folders
Using you current code, make this tweak:
public void listf(String directoryName, List<File> files) {
File directory = new File(directoryName);
// Get all files from a directory.
File[] fList = directory.listFiles();
if(fList != null)
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
}
}
How can I count the occurrences of a list item?
I had this problem today and rolled my own solution before I thought to check SO. This:
dict((i,a.count(i)) for i in a)
is really, really slow for large lists. My solution
def occurDict(items):
d = {}
for i in items:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
return d
is actually a bit faster than the Counter solution, at least for Python 2.7.
Remove end of line characters from Java string
You can either directly pass line terminator e.g. \n, if you know the line terminator in Windows, Mac or UNIX. Alternatively you can use following code to replace line breaks in either of three major operating system.
str = str.replaceAll("\\r\\n|\\r|\\n", " ");
Above code line will replace line breaks with space in Mac, Windows and Linux.
Also you can use line-separator. It will work for all OS. Below is the code snippet for line-separator.
String lineSeparator=System.lineSeparator();
String newString=yourString.replace(lineSeparator, "");