How to make a Generic Type Cast function
While probably not as clean looking as the IConvertible
approach, you could always use the straightforward checking typeof(T)
to return a T
:
public static T ReturnType<T>(string stringValue)
{
if (typeof(T) == typeof(int))
return (T)(object)1;
else if (typeof(T) == typeof(FooBar))
return (T)(object)new FooBar(stringValue);
else
return default(T);
}
public class FooBar
{
public FooBar(string something)
{}
}
What's the fastest way in Python to calculate cosine similarity given sparse matrix data?
You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output:
from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse
A = np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]])
A_sparse = sparse.csr_matrix(A)
similarities = cosine_similarity(A_sparse)
print('pairwise dense output:\n {}\n'.format(similarities))
#also can output sparse matrices
similarities_sparse = cosine_similarity(A_sparse,dense_output=False)
print('pairwise sparse output:\n {}\n'.format(similarities_sparse))
Results:
pairwise dense output:
[[ 1. 0.40824829 0.40824829]
[ 0.40824829 1. 0.33333333]
[ 0.40824829 0.33333333 1. ]]
pairwise sparse output:
(0, 1) 0.408248290464
(0, 2) 0.408248290464
(0, 0) 1.0
(1, 0) 0.408248290464
(1, 2) 0.333333333333
(1, 1) 1.0
(2, 1) 0.333333333333
(2, 0) 0.408248290464
(2, 2) 1.0
If you want column-wise cosine similarities simply transpose your input matrix beforehand:
A_sparse.transpose()
How do operator.itemgetter() and sort() work?
You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter
returns a callable:
>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8
To do it in a different way, you can use lambda
:
a.sort(key=lambda x: x[1])
And reverse it:
a.sort(key=operator.itemgetter(1), reverse=True)
Sort by more than one column:
a.sort(key=operator.itemgetter(1,2))
See the sorting How To.
cartesian product in pandas
You could start by taking the Cartesian product of df1.col1
and df2.col3
, then merge back to df1
to get col2
.
Here's a general Cartesian product function which takes a dictionary of lists:
def cartesian_product(d):
index = pd.MultiIndex.from_product(d.values(), names=d.keys())
return pd.DataFrame(index=index).reset_index()
Apply as:
res = cartesian_product({'col1': df1.col1, 'col3': df2.col3})
pd.merge(res, df1, on='col1')
# col1 col3 col2
# 0 1 5 3
# 1 1 6 3
# 2 2 5 4
# 3 2 6 4
HTML encoding issues - "Â" character showing up instead of " "
If any one had the same problem as me and the charset was already correct, simply do this:
- Copy all the code inside the .html file.
- Open notepad (or any basic text editor) and paste the code.
- Go "File -> Save As"
- Enter you file name "example.html" (Select "Save as type: All Files (.)")
- Select Encoding as UTF-8
- Hit Save and you can now delete your old .html file and the encoding should be fixed
How to get the next auto-increment id in mysql
The top answer uses PHP MySQL_ for a solution, thought I would share an updated PHP MySQLi_ solution for achieving this. There is no error output in this exmaple!
$db = new mysqli('localhost', 'user', 'pass', 'database');
$sql = "SHOW TABLE STATUS LIKE 'table'";
$result=$db->query($sql);
$row = $result->fetch_assoc();
echo $row['Auto_increment'];
Kicks out the next Auto increment coming up in a table.
"google is not defined" when using Google Maps V3 in Firefox remotely
You can try the following:
First, add async defer
. This specifies that the script will be executed asynchronously as soon as it is available and when the page has finished parsing.
Second, add the initMap()
function as a callback in a script tag inside your html. In this way the map will be initialized before the document.ready and window.onload:
<script async defer src="{{ 'https://maps.googleapis.com/maps/api/js?key=$key&language='.$language.'®ion='.$country.'&callback=initMap' }}"></script>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 4,
disableDefaultUI: false,
scrollwheel: false,
styles: [{ ... }]
});
}
</script>
Finally, you can use the map object inside your js files.
Show Current Location and Update Location in MKMapView in Swift
100% working, easy steps and tested
Import libraries:
import MapKit
import CoreLocation
set delegates:
CLLocationManagerDelegate,MKMapViewDelegate
Take variable:
let locationManager = CLLocationManager()
write this code on viewDidLoad():
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.delegate = self
mapView.mapType = .standard
mapView.isZoomEnabled = true
mapView.isScrollEnabled = true
if let coor = mapView.userLocation.location?.coordinate{
mapView.setCenter(coor, animated: true)
}
Write delegate method for location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
mapView.mapType = MKMapType.standard
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: locValue, span: span)
mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = locValue
annotation.title = "Javed Multani"
annotation.subtitle = "current location"
mapView.addAnnotation(annotation)
//centerMap(locValue)
}
Do not forgot to set permission in info.plist
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>
It's look like:
How to import a module given its name as string?
With Python older than 2.7/3.1, that's pretty much how you do it.
For newer versions, see importlib.import_module
for Python 2 and and Python 3.
You can use exec
if you want to as well.
Or using __import__
you can import a list of modules by doing this:
>>> moduleNames = ['sys', 'os', 're', 'unittest']
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
Ripped straight from Dive Into Python.
Cannot refer to a non-final variable inside an inner class defined in a different method
Good explanations for why you can't do what you're trying to do already provided. As a solution, maybe consider:
public class foo
{
static class priceInfo
{
public double lastPrice = 0;
public double price = 0;
public Price priceObject = new Price ();
}
public static void main ( String args[] )
{
int period = 2000;
int delay = 2000;
final priceInfo pi = new priceInfo ();
Timer timer = new Timer ();
timer.scheduleAtFixedRate ( new TimerTask ()
{
public void run ()
{
pi.price = pi.priceObject.getNextPrice ( pi.lastPrice );
System.out.println ();
pi.lastPrice = pi.price;
}
}, delay, period );
}
}
Seems like probably you could do a better design than that, but the idea is that you could group the updated variables inside a class reference that doesn't change.
Changing the git user inside Visual Studio Code
I had the same problem as Daniel, setting the commit address and unsetting the credentials helper also worked for me.
git config --global user.email '<git-commit-address>'
git config --global --unset credential.helper
Where can I find the Java SDK in Linux after installing it?
This question still seems relevant, and the answer seems to be a moving target.
On my debian system (buster):
> update-java-alternatives -l
java-1.11.0-openjdk-amd64 1111 /usr/lib/jvm/java-1.11.0-openjdk-amd64
However, if you actually go look there, you'll see there are multiple directories and symbolic links placed there by the package system to simplify future maintenance.
The actual directory is java-11-openjdk-amd64
, with another symlink of default-java
. There is also an openjdk-11
directory, but it appears to only contain a source.zip file.
Given this, for Debian ONLY, I would guess the best value to use is /usr/lib/jvm/default-java
, as this should always be valid, even if you decide to install a totally different version of java, or even switch vendors.
The normal reason to want to know the path is because some application wants it, and you probably don't want that app to break because you did an upgrade that changed version numbers.
How can I recover the return value of a function passed to multiprocessing.Process?
You can use the exit
built-in to set the exit code of a process. It can be obtained from the exitcode
attribute of the process:
import multiprocessing
def worker(procnum):
print str(procnum) + ' represent!'
exit(procnum)
if __name__ == '__main__':
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p)
p.start()
result = []
for proc in jobs:
proc.join()
result.append(proc.exitcode)
print result
Output:
0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
[0, 1, 2, 3, 4]
Using Page_Load and Page_PreRender in ASP.Net
The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing.
Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.
How to replace plain URLs with links?
Try Below Solution
function replaceLinkClickableLink(url = '') {
let pattern = new RegExp('^(https?:\\/\\/)?'+
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+
'((\\d{1,3}\\.){3}\\d{1,3}))'+
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+
'(\\?[;&a-z\\d%_.~+=-]*)?'+
'(\\#[-a-z\\d_]*)?$','i');
let isUrl = pattern.test(url);
if (isUrl) {
return `<a href="${url}" target="_blank">${url}</a>`;
}
return url;
}
How to create a stacked bar chart for my DataFrame using seaborn?
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
Calculate last day of month in JavaScript
const today = new Date();
let beginDate = new Date();
let endDate = new Date();
// fist date of montg
beginDate = new Date(
`${today.getFullYear()}-${today.getMonth() + 1}-01 00:00:00`
);
// end date of month
// set next Month first Date
endDate = new Date(
`${today.getFullYear()}-${today.getMonth() + 2}-01 :23:59:59`
);
// deducting 1 day
endDate.setDate(0);
MAC addresses in JavaScript
If this is for an intranet application and all of the clients use DHCP, you can query the DHCP server for the MAC address for a given IP address.
UIAlertController custom font, size, color
A Swift translation of the @dupuis2387 answer. Worked out the syntax to set the UIAlertController
title's color and font via KVC using the attributedTitle
key.
let message = "Some message goes here."
let alertController = UIAlertController(
title: "", // This gets overridden below.
message: message,
preferredStyle: .Alert
)
let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ -> Void in
}
alertController.addAction(okAction)
let fontAwesomeHeart = "\u{f004}"
let fontAwesomeFont = UIFont(name: "FontAwesome", size: 17)!
let customTitle:NSString = "I \(fontAwesomeHeart) Swift" // Use NSString, which lets you call rangeOfString()
let systemBoldAttributes:[String : AnyObject] = [
// setting the attributed title wipes out the default bold font,
// so we need to reconstruct it.
NSFontAttributeName : UIFont.boldSystemFontOfSize(17)
]
let attributedString = NSMutableAttributedString(string: customTitle as String, attributes:systemBoldAttributes)
let fontAwesomeAttributes = [
NSFontAttributeName: fontAwesomeFont,
NSForegroundColorAttributeName : UIColor.redColor()
]
let matchRange = customTitle.rangeOfString(fontAwesomeHeart)
attributedString.addAttributes(fontAwesomeAttributes, range: matchRange)
alertController.setValue(attributedString, forKey: "attributedTitle")
self.presentViewController(alertController, animated: true, completion: nil)
How to open a specific port such as 9090 in Google Compute Engine
Creating firewall rules
Please review the firewall rule components [1] if you are unfamiliar with firewall rules in GCP. Firewall rules are defined at the network level, and only apply to the network where they are created; however, the name you choose for each of them must be unique to the project.
For Cloud Console:
- Go to the Firewall rules page in the Google Cloud Platform Console.
- Click Create firewall rule.
- Enter a Name for the firewall rule.
This name must be unique for the project.
- Specify the Network where the firewall rule will be implemented.
- Specify the Priority of the rule.
The lower the number, the higher the priority.
- For the Direction of traffic, choose ingress or egress.
- For the Action on match, choose allow or deny.
Specify the Targets of the rule.
- If you want the rule to apply to all instances in the network, choose All instances in the network.
- If you want the rule to apply to select instances by network (target) tags, choose Specified target tags, then type the tags to which the rule should apply into the Target tags field.
- If you want the rule to apply to select instances by associated service account, choose Specified service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Target service account field.
For an ingress rule, specify the Source filter:
- Choose IP ranges and type the CIDR blocks into the Source IP ranges field to define the source for incoming traffic by IP address ranges. Use 0.0.0.0/0 for a source from any network.
- Choose Subnets then mark the ones you need from the Subnets pop-up button to define the source for incoming traffic by subnet name.
- To limit source by network tag, choose Source tags, then type the network tags in to the Source tags field. For the limit on the number of source tags, see VPC Quotas and Limits. Filtering by source tag is only available if the target is not specified by service account. For more information, see filtering by service account vs.network tag.
- To limit source by service account, choose Service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Source service account field. Filtering by source service account is only available if the target is not specified by network tag. For more information, see filtering by service account vs. network tag.
- Specify a Second source filter if desired. Secondary source filters cannot use the same filter criteria as the primary one.
For an egress rule, specify the Destination filter:
- Choose IP ranges and type the CIDR blocks into the Destination IP ranges field to define the destination for outgoing traffic by IP address ranges. Use 0.0.0.0/0 to mean everywhere.
- Choose Subnets then mark the ones you need from the Subnets pop-up button to define the destination for outgoing traffic by subnet name.
Define the Protocols and ports to which the rule will apply:
Select Allow all or Deny all, depending on the action, to have the rule apply to all protocols and ports.
Define specific protocols and ports:
- Select tcp to include the TCP protocol and ports. Enter all or a comma delimited list of ports, such as 20-22, 80, 8080.
- Select udp to include the UDP protocol and ports. Enter all or a comma delimited list of ports, such as 67-69, 123.
- Select Other protocols to include protocols such as icmp or sctp.
(Optional) You can create the firewall rule but not enforce it by setting its enforcement state to disabled. Click Disable rule, then select Disabled.
(Optional) You can enable firewall rules logging:
- Click Logs > On.
- Click Turn on.
Click Create.
Link:
[1] https://cloud.google.com/vpc/docs/firewalls#firewall_rule_components
Sending HTTP POST with System.Net.WebClient
WebClient
doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:
Using client as new WebClient
result = client.UploadString(someurl, "param1=somevalue¶m2=othervalue")
End Using
Algorithm to calculate the number of divisors of a given number
This is the most basic way of computing the number divissors:
class PrintDivisors
{
public static void main(String args[])
{
System.out.println("Enter the number");
// Create Scanner object for taking input
Scanner s=new Scanner(System.in);
// Read an int
int n=s.nextInt();
// Loop from 1 to 'n'
for(int i=1;i<=n;i++)
{
// If remainder is 0 when 'n' is divided by 'i',
if(n%i==0)
{
System.out.print(i+", ");
}
}
// Print [not necessary]
System.out.print("are divisors of "+n);
}
}
Access parent DataContext from DataTemplate
You can use RelativeSource
to find the parent element, like this -
Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified,
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"
See this SO question for more details about RelativeSource
.
cmd line rename file with date and time
I took the above but had to add one more piece because it was putting a space after the hour which gave a syntax error with the rename command.
I used:
set HR=%time:~0,2%
set HR=%Hr: =0%
set HR=%HR: =%
rename c:\ops\logs\copyinvoices.log copyinvoices_results_%date:~10,4%-%date:~4,2%-%date:~7,2%_%HR%%time:~3,2%.log
This gave me my format I needed:
copyinvoices_results_2013-09-13_0845.log
Classpath including JAR within a JAR
If you are building with ant (I am using ant from eclipse), you can just add the extra jar files
by saying to ant to add them...
Not necessarily the best method if you have a project maintained by multiple people but it works for one person project and is easy.
for example my target that was building the .jar file was:
<jar destfile="${plugin.jar}" basedir="${plugin.build.dir}">
<manifest>
<attribute name="Author" value="ntg"/>
................................
<attribute name="Plugin-Version" value="${version.entry.commit.revision}"/>
</manifest>
</jar>
I just added one line to make it:
<jar ....">
<zipgroupfileset dir="${external-lib-dir}" includes="*.jar"/>
<manifest>
................................
</manifest>
</jar>
where
<property name="external-lib-dir"
value="C:\...\eclipseWorkspace\Filter\external\...\lib" />
was the dir with the external jars.
And that's it...
How do you make a HTTP request with C++?
I had the same problem. libcurl is really complete. There is a C++ wrapper curlpp that might interest you as you ask for a C++ library. neon is another interesting C library that also support WebDAV.
curlpp seems natural if you use C++. There are many examples provided in the source distribution.
To get the content of an URL you do something like that (extracted from examples) :
// Edit : rewritten for cURLpp 0.7.3
// Note : namespace changed, was cURLpp in 0.7.2 ...
#include <curlpp/cURLpp.hpp>
#include <curlpp/Options.hpp>
// RAII cleanup
curlpp::Cleanup myCleanup;
// Send request and get a result.
// Here I use a shortcut to get it in a string stream ...
std::ostringstream os;
os << curlpp::options::Url(std::string("http://www.wikipedia.org"));
string asAskedInQuestion = os.str();
See the examples
directory in curlpp source distribution, there is a lot of more complex cases, as well as a simple complete minimal one using curlpp.
my 2 cents ...
form confirm before submit
$('#myForm').submit(function() {
var c = confirm("Click OK to continue?");
return c; //you can just return c because it will be true or false
});
YAML: Do I need quotes for strings in YAML?
I had this concern when working on a Rails application with Docker.
My most preferred approach is to generally not use quotes. This includes not using quotes for:
- variables like
${RAILS_ENV}
- values separated by a colon (:) like
postgres-log:/var/log/postgresql
- other strings values
I, however, use double-quotes for integer
values that need to be converted to strings like:
- docker-compose version like
version: "3.8"
- port numbers like
"8080:8080"
However, for special cases like booleans
, floats
, integers
, and other cases, where using double-quotes for the entry values could be interpreted as strings
, please do not use double-quotes.
Here's a sample docker-compose.yml
file to explain this concept:
version: "3"
services:
traefik:
image: traefik:v2.2.1
command:
- --api.insecure=true # Don't do that in production
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
That's all.
I hope this helps
android.app.Application cannot be cast to android.app.Activity
You can also try this one.
override fun registerWith( registry: PluginRegistry) {
GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)
//registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
}
I think this one is far better solution than creating a new class.
How to Git stash pop specific stash in 1.8.3?
git stash apply n
works as of git version 2.11
Original answer, possibly helping to debug issues with the older syntax involving shell escapes:
As pointed out previously, the curly braces may require escaping or quoting depending on your OS, shell, etc.
See "stash@{1} is ambiguous?" for some detailed hints of what may be going wrong, and how to work around it in various shells and platforms.
git stash list
git stash apply stash@{n}
git stash apply version
Get element inside element by class and ID - JavaScript
You should not used document.getElementByID because its work only for client side controls which ids are fixed . You should use jquery instead like below example.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="foo">
<div class="bar">
Hello world!
</div>
</div>
use this :
$("[id^='foo']").find("[class^='bar']")
// do not forget to add script tags as above
if you want any remove edit any operation then just add "." behind and do the operations
How to read line by line of a text area HTML tag
This would give you all valid numeric values in lines
. You can change the loop to validate, strip out invalid characters, etc - whichever you want.
var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
if (parseInt($(this) != 'NaN')
lines[] = parseInt($(this));
}
How to check whether Kafka Server is running?
I found an event OnError
in confluent Kafka:
consumer.OnError += Consumer_OnError;
private void Consumer_OnError(object sender, Error e)
{
Debug.Log("connection error: "+ e.Reason);
ConsumerConnectionError(e);
}
And its documentation in code:
//
// Summary:
// Raised on critical errors, e.g. connection failures or all brokers down. Note
// that the client will try to automatically recover from errors - these errors
// should be seen as informational rather than catastrophic
//
// Remarks:
// Executes on the same thread as every other Consumer event handler (except OnLog
// which may be called from an arbitrary thread).
public event EventHandler<Error> OnError;
PHP class: Global variable as property in class
Try to avoid globals, instead you can use something like this
class myClass() {
private $myNumber;
public function setNumber($number) {
$this->myNumber = $number;
}
}
Now you can call
$class = new myClass();
$class->setNumber('1234');
Conditional replacement of values in a data.frame
Since you are conditionally indexing df$est
, you also need to conditionally index the replacement vector df$a
:
index <- df$b == 0
df$est[index] <- (df$a[index] - 5)/2.533
Of course, the variable index
is just temporary, and I use it to make the code a bit more readible. You can write it in one step:
df$est[df$b == 0] <- (df$a[df$b == 0] - 5)/2.533
For even better readibility, you can use within
:
df <- within(df, est[b==0] <- (a[b==0]-5)/2.533)
The results, regardless of which method you choose:
df
a b est
1 11.77000 2 0.000000
2 10.90000 3 0.000000
3 10.32000 2 0.000000
4 10.96000 0 2.352941
5 9.90600 0 1.936834
6 10.70000 0 2.250296
7 11.43000 1 0.000000
8 11.41000 2 0.000000
9 10.48512 4 0.000000
10 11.19000 0 2.443743
As others have pointed out, an alternative solution in your example is to use ifelse
.
Generating random, unique values C#
I'm calling NewNumber() regularly, but the problem is I often get
repeated numbers.
Random.Next
doesn't guarantee the number to be unique. Also your range is from 0 to 10 and chances are you will get duplicate values. May be you can setup a list of int
and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like:
public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode());
// Since similar code is done in default constructor internally
public List<int> randomList = new List<int>();
int MyNumber = 0;
private void NewNumber()
{
MyNumber = a.Next(0, 10);
if (!randomList.Contains(MyNumber))
randomList.Add(MyNumber);
}
Populating a ComboBox using C#
but do you not just get your combo box name and then items.add("")
?
For instance
Language.Items.Add("Italian");
Language.Items.Add("English");
Language.Items.Add("Spanish");
Hope this helped :D
SQL ROWNUM how to return rows between a specific range
I know this is an old question, however, it is useful to mention the new features in the latest version.
From Oracle 12c onwards, you could use the new Top-n Row limiting feature. No need to write a subquery, no dependency on ROWNUM.
For example, the below query would return the employees between 4th highest till 7th highest salaries in ascending order:
SQL> SELECT empno, sal
2 FROM emp
3 ORDER BY sal
4 OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;
EMPNO SAL
---------- ----------
7654 1250
7934 1300
7844 1500
7499 1600
SQL>
Fatal error: Call to undefined function: ldap_connect()
If you are a Windows user, this is a common error when you use XAMPP
since LDAP
is not enabled by default.
You can follow this steps to make sure LDAP
works in your XAMPP
:
[Your Drive]:\xampp\php\php.ini
: In this file uncomment the following line:
extension=php_ldap.dll
Move the file: libsasl.dll
, from [Your Drive]:\xampp\php
to [Your Drive]:\xampp\apache\bin
(Note: moving the file is needed only for XAMPP prior to version: 5.6.28
)
Restart Apache.
You can now use functions of the LDAP Module!
If you use Linux:
For php5:
sudo apt-get install php5-ldap
For php7:
sudo apt-get install php7.0-ldap
If you are using the latest version of PHP you can do
sudo apt-get install php-ldap
running the above command should do the trick.
if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap
to uncomment, save and restart Apache
Eclipse can't find / load main class
Removing the Run Configuration
Sometimes I have a similar problems in some pre-release versions of eclipse. For fix the error, I delete the Run Configuration. You can find that in menu Run, Run Configurations...
Then I launch the app with Alt+Shift+X, then J. If this don't work, Ctrl+F11.
Deleting the .metadata
directory
In another way, the configuration settings for your current workspace may are corrupted. Those settings are in the .metadata
directory in your current workspace 1. In that case, there is no other choice than delete the directory:
- Close eclipse.
- Delete the
.metadata
directory.
- Start eclipse.
- Import the projects.
- Run the project again.
Notes
- You will see that directory with File > Switch Workspace > Other...
Test only if variable is not null in if statement
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
How can I temporarily disable a foreign key constraint in MySQL?
If the key field is nullable, then you can also set the value to null before attempting to delete it:
cursor.execute("UPDATE myapp_item SET myapp_style_id = NULL WHERE n = %s", n)
transaction.commit_unless_managed()
cursor.execute("UPDATE myapp_style SET myapp_item_id = NULL WHERE n = %s", n)
transaction.commit_unless_managed()
cursor.execute("DELETE FROM myapp_item WHERE n = %s", n)
transaction.commit_unless_managed()
cursor.execute("DELETE FROM myapp_style WHERE n = %s", n)
transaction.commit_unless_managed()
Get file version in PowerShell
As EBGreen said, [System.Diagnostics.FileVersionInfo]::GetVersionInfo(path) will work, but remember that you can also get all the members of FileVersionInfo, for example:
[System.Diagnostics.FileVersionInfo]::GetVersionInfo(path).CompanyName
You should be able to use every member of FileVersionInfo documented here, which will get you basically anything you could ever want about the file.
Parsing query strings on Android
this method takes the uri and return map of par name and par value
public static Map<String, String> getQueryMap(String uri) {
String queryParms[] = uri.split("\\?");
Map<String, String> map = new HashMap<>();//
if (queryParms == null || queryParms.length == 0) return map;
String[] params = queryParms[1].split("&");
for (String param : params) {
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
ExpressionChangedAfterItHasBeenCheckedError Explained
I had this sort of error in Ionic3 (which uses Angular 4 as part of it's technology stack).
For me it was doing this:
<ion-icon [name]="getFavIconName()"></ion-icon>
So I was trying to conditionally change the type of an ion-icon from a pin
to a remove-circle
, per a mode a screen was operating on.
I'm guessing I'll have to add an *ngIf
instead.
When does System.gc() do something?
we can never force garbage collection. System.gc is only suggesting vm for garbage collection, however, really what time the mechanism runs, nobody knows, this is as stated by JSR specifications.
How to display custom view in ActionBar?
There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .
The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.
Here're the themes:
styles.xml
<style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowShowWallpaper">true</item>
</style>
<style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
</style>
<style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
<item name="android:displayOptions">showCustom</item>
<item name="android:background">#88000000</item>
</style>
value-v19/styles.xml
<style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
<style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:
getSupportActionBar().setDisplayShowCustomEnabled(true);
Test process.env with Jest
In test file:
const APP_PORT = process.env.APP_PORT || 8080;
In the test script of ./package.json
:
"scripts": {
"test": "jest --setupFiles dotenv/config",
}
In ./env
:
APP_PORT=8080
CSS Box Shadow - Top and Bottom Only
So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.
HTML
<div class="shadow-block">
<div class="shadow"></div>
<div class="overlay">
<div class="overlay-inner">
content here
</div>
</div>
</div>
CSS
.overlay {
background: #f7f7f4;
height: 185px;
overflow: hidden;
position: relative;
width: 100%;
}
.overlay:before {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
content: " ";
display: block;
margin: 0 auto;
width: 80%;
}
.overlay:after {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
content: "-";
display: block;
margin: 0 auto;
position: absolute;
bottom: -65px;
left: -50%;
right: -50%;
width: 80%;
}
.shadow {
position: relative;
width:100%;
height:8px;
margin: 0 0 -22px 0;
-webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
border-radius: 50%;
}
assigning column names to a pandas series
You can also use the .to_frame()
method.
If it is a Series, I assume 'Gene' is already the index, and will remain the index after converting it to a DataFrame. The name
argument of .to_frame()
will name the column.
x = x.to_frame('count')
If you want them both as columns, you can reset the index:
x = x.to_frame('count').reset_index()
How to Install Windows Phone 8 SDK on Windows 7
You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.
How do I get the name of a Ruby class?
Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...
If you use Rails (ActiveSupport):
result.class.name.demodulize
If you use POR (plain-ol-Ruby):
result.class.name.split('::').last
Passing $_POST values with cURL
Ross has the right idea for POSTing the usual parameter/value format to a url.
I recently ran into a situation where I needed to POST some XML as Content-Type "text/xml" without any parameter pairs so here's how you do that:
$xml = '<?xml version="1.0"?><stuff><child>foo</child><child>bar</child></stuff>';
$httpRequest = curl_init();
curl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($httpRequest, CURLOPT_POST, 1);
curl_setopt($httpRequest, CURLOPT_HEADER, 1);
curl_setopt($httpRequest, CURLOPT_URL, $url);
curl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml);
$returnHeader = curl_exec($httpRequest);
curl_close($httpRequest);
In my case, I needed to parse some values out of the HTTP response header so you may not necessarily need to set CURLOPT_RETURNTRANSFER
or CURLOPT_HEADER
.
How to do Base64 encoding in node.js?
I have created a ultimate small js npm library for the base64 encode/decode conversion in Node.js.
Installation
npm install nodejs-base64-converter --save
Usage
var nodeBase64 = require('nodejs-base64-converter');
console.log(nodeBase64.encode("test text")); //dGVzdCB0ZXh0
console.log(nodeBase64.decode("dGVzdCB0ZXh0")); //test text
python: how to send mail with TO, CC and BCC?
As of Python 3.2, released Nov 2011, the smtplib has a new function send_message
instead of just sendmail
, which makes dealing with To/CC/BCC easier. Pulling from the Python official email examples, with some slight modifications, we get:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
# them == the cc's email address
# they == the bcc's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
msg['Cc'] = them
msg['Bcc'] = they
# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
Using the headers work fine, because send_message respects BCC as outlined in the documentation:
send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg
With sendmail
it was common to add the CC headers to the message, doing something such as:
msg['Bcc'] = [email protected]
Or
msg = "From: [email protected]" +
"To: [email protected]" +
"BCC: [email protected]" +
"Subject: You've got mail!" +
"This is the message body"
The problem is, the sendmail function treats all those headers the same, meaning they'll get sent (visibly) to all To: and BCC: users, defeating the purposes of BCC. The solution, as shown in many of the other answers here, was to not include BCC in the headers, and instead only in the list of emails passed to sendmail
.
The caveat is that send_message
requires a Message object, meaning you'll need to import a class from email.message
instead of merely passing strings into sendmail
.
Why doesn't Java allow overriding of static methods?
overriding is reserved for instance members to support polymorphic behaviour. static class members do not belong to a particular instance. instead, static members belong to the class and as a result overriding is not supported because subclasses only inherit protected and public instance members and not static members. You may want to define an inerface and research factory and/or strategy design patterns to evaluate an alternate approach.
How to access your website through LAN in ASP.NET
You may also need to enable the World Wide Web Service inbound firewall rule.
On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules
Find World Wide Web Services (HTTP Traffic-In)
in the list and select to enable the rule. Change is pretty much immediate.
Programmatically scroll to a specific position in an Android ListView
For a SmoothScroll with Scroll duration:
getListView().smoothScrollToPositionFromTop(position,offset,duration);
Parameters
position -> Position to scroll to
offset ---->Desired distance in pixels of position from the top of the view when scrolling is finished
duration-> Number of milliseconds to use for the scroll
Note: From API 11.
HandlerExploit's answer was what I was looking for, but My listview is quite lengthy and also with alphabet scroller. Then I found that the same function can take other parameters as well :)
Edit:(From AFDs suggestion)
To position the current selection:
int h1 = mListView.getHeight();
int h2 = listViewRow.getHeight();
mListView.smoothScrollToPositionFromTop(position, h1/2 - h2/2, duration);
When to use std::size_t?
size_t
is a very readable way to specify the size dimension of an item - length of a string, amount of bytes a pointer takes, etc.
It's also portable across platforms - you'll find that 64bit and 32bit both behave nicely with system functions and size_t
- something that unsigned int
might not do (e.g. when should you use unsigned long
Compare two DataFrames and output their differences side-by-side
With pandas 1.1, you could essentially replicate Ted Petrou's output with a single function call. Example taken from the docs:
pd.__version__
# '1.1.0'
df1.compare(df2)
score isEnrolled Comment
self other self other self other
1 1.11 1.21 NaN NaN NaN NaN
2 NaN NaN 1.0 0.0 NaN On vacation
Here, "self" refers to the LHS dataFrame, while "other" is the RHS DataFrame. By default, equal values are replaced with NaNs so you can focus on just the diffs. If you want to show values that are equal as well, use
df1.compare(df2, keep_equal=True, keep_shape=True)
score isEnrolled Comment
self other self other self other
1 1.11 1.21 False False Graduated Graduated
2 4.12 4.12 True False NaN On vacation
You can also change the axis of comparison using align_axis
:
df1.compare(df2, align_axis='index')
score isEnrolled Comment
1 self 1.11 NaN NaN
other 1.21 NaN NaN
2 self NaN 1.0 NaN
other NaN 0.0 On vacation
This compares values row-wise, instead of column-wise.
How to set default text for a Tkinter Entry widget
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
The condition has length > 1 and only the first element will be used
You get the error because if
can only evaluate a logical
vector of length 1.
Maybe you miss the difference between &
(|
) and &&
(||
). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:
c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE
# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE
You don't need the if
statement at all:
mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"
How to center a Window in Java?
Actually frame.getHeight()
and getwidth()
doesnt return values , check it by System.out.println(frame.getHeight());
directly put the values for width and height ,then it will work fine in center. eg: as below
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)((dimension.getWidth() - 450)/2);
int y=(int)((dimension.getHeight() - 450)/2);
jf.setLocation(x, y);
both 450 is my frame width n height
Compare two Byte Arrays? (Java)
In your example, you have:
if (new BigInteger("1111000011110001", 2).toByteArray() == array)
When dealing with objects, ==
in java compares reference values. You're checking to see if the reference to the array returned by toByteArray()
is the same as the reference held in array
, which of course can never be true. In addition, array classes don't override .equals()
so the behavior is that of Object.equals()
which also only compares the reference values.
To compare the contents of two arrays, static array comparison methods are provided by the Arrays class
byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();
if (Arrays.equals(array, secondArray))
{
System.out.println("Yup, they're the same!");
}
Bootstrap Element 100% Width
Though people have mentioned that you will need to use .container-fluid in this case but you will also have to remove the padding from bootstrap.
Auto increment primary key in SQL Server Management Studio 2012
When you're using Data Type: int you can select the row which you want to get autoincremented and go to the column properties tag. There you can set the identity to 'yes'. The starting value for autoincrement can also be edited there. Hope I could help ;)
How to add elements to a list in R (loop)
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
What is the difference between tree depth and height?
Another way to understand those concept is as follow:
Depth: Draw a horizontal line at the root position and treat this line as ground. So the depth of the root is 0, and all its children are grow downward so each level of nodes has the current depth + 1.
Height: Same horizontal line but this time the ground position is external nodes, which is the leaf of tree and count upward.
How do you remove columns from a data.frame?
rm
in within
can be quite useful.
within(mtcars, rm(mpg, cyl, disp, hp))
# drat wt qsec vs am gear carb
# Mazda RX4 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 3.90 2.875 17.02 0 1 4 4
# Datsun 710 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 3.15 3.440 17.02 0 0 3 2
# Valiant 2.76 3.460 20.22 1 0 3 1
# ...
May be combined with other operations.
within(mtcars, {
mpg2=mpg^2
cyl2=cyl^2
rm(mpg, cyl, disp, hp)
})
# drat wt qsec vs am gear carb cyl2 mpg2
# Mazda RX4 3.90 2.620 16.46 0 1 4 4 36 441.00
# Mazda RX4 Wag 3.90 2.875 17.02 0 1 4 4 36 441.00
# Datsun 710 3.85 2.320 18.61 1 1 4 1 16 519.84
# Hornet 4 Drive 3.08 3.215 19.44 1 0 3 1 36 457.96
# Hornet Sportabout 3.15 3.440 17.02 0 0 3 2 64 349.69
# Valiant 2.76 3.460 20.22 1 0 3 1 36 327.61
# ...
Is there a way to 'uniq' by column?
awk -F"," '!_[$1]++' file
-F
sets the field separator.
$1
is the first field.
_[val]
looks up val
in the hash _
(a regular variable).
++
increment, and return old value.
!
returns logical not.
- there is an implicit print at the end.
Marker content (infoWindow) Google Maps
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
Cannot get a text value from a numeric cell “Poi”
Cell cell = sheet.getRow(i).getCell(0);
cell.setCellType ( Cell.CELL_TYPE_STRING );
String j_username = cell.getStringCellValue();
UPDATE
Ok, as have been said in comments, despite this works it isn't correct method of retrieving data from an Excel's cell.
According to the manual here:
If what you want to do is get a String value for your numeric cell,
stop!. This is not the way to do it. Instead, for fetching the string
value of a numeric or boolean or date cell, use DataFormatter instead.
And according to the DataFormatter API
DataFormatter contains methods for formatting the value stored in an
Cell. This can be useful for reports and GUI presentations when you
need to display data exactly as it appears in Excel. Supported formats
include currency, SSN, percentages, decimals, dates, phone numbers,
zip codes, etc.
So, right way to show numeric cell's value is as following:
DataFormatter formatter = new DataFormatter(); //creating formatter using the default locale
Cell cell = sheet.getRow(i).getCell(0);
String j_username = formatter.formatCellValue(cell); //Returns the formatted value of a cell as a String regardless of the cell type.
What is the role of the bias in neural networks?
The bias helps to get a better equation
Imagine the input and output like a function y = ax + b
and you need to put the right line between the input(x) and output(y) to minimise the global error between each point and the line , if you keep the equation like this y = ax
, you will have one parameter for adaptation only , even if you find the best a
minimising the global error it will be kind of far from the wanted value
You can say the bias makes the equation more flexible to adapt to the best values
MySQL, update multiple tables with one query
Let's say I have Table1
with primary key _id
and a boolean column doc_availability
; Table2
with foreign key _id
and DateTime column last_update
and I want to change the availability of a document with _id
14 in Table1
to 0 i.e unavailable and update Table2
with the timestamp when the document was last updated. The following query would do the task:
UPDATE Table1, Table2
SET doc_availability = 0, last_update = NOW()
WHERE Table1._id = Table2._id AND Table1._id = 14
How to suppress binary file matching results in grep
This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:
bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$
Render HTML in React Native
<WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />
This worked for me :) I have html text aboutus file.
Split / Explode a column of dictionaries into separate columns with pandas
>>> df
Station ID Pollutants
0 8809 {"a": "46", "b": "3", "c": "12"}
1 8810 {"a": "36", "b": "5", "c": "8"}
2 8811 {"b": "2", "c": "7"}
3 8812 {"c": "11"}
4 8813 {"a": "82", "c": "15"}
speed comparison for a large dataset of 10 million rows
>>> df = pd.concat([df]*100000).reset_index(drop=True)
>>> df = pd.concat([df]*20).reset_index(drop=True)
>>> print(df.shape)
(10000000, 2)
def apply_drop(df):
return df.join(df['Pollutants'].apply(pd.Series)).drop('Pollutants', axis=1)
def json_normalise_drop(df):
return df.join(pd.json_normalize(df.Pollutants)).drop('Pollutants', axis=1)
def tolist_drop(df):
return df.join(pd.DataFrame(df['Pollutants'].tolist())).drop('Pollutants', axis=1)
def vlues_tolist_drop(df):
return df.join(pd.DataFrame(df['Pollutants'].values.tolist())).drop('Pollutants', axis=1)
def pop_tolist(df):
return df.join(pd.DataFrame(df.pop('Pollutants').tolist()))
def pop_values_tolist(df):
return df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
>>> %timeit apply_drop(df.copy())
1 loop, best of 3: 53min 20s per loop
>>> %timeit json_normalise_drop(df.copy())
1 loop, best of 3: 54.9 s per loop
>>> %timeit tolist_drop(df.copy())
1 loop, best of 3: 6.62 s per loop
>>> %timeit vlues_tolist_drop(df.copy())
1 loop, best of 3: 6.63 s per loop
>>> %timeit pop_tolist(df.copy())
1 loop, best of 3: 5.99 s per loop
>>> %timeit pop_values_tolist(df.copy())
1 loop, best of 3: 5.94 s per loop
+---------------------+-----------+
| apply_drop | 53min 20s |
| json_normalise_drop | 54.9 s |
| tolist_drop | 6.62 s |
| vlues_tolist_drop | 6.63 s |
| pop_tolist | 5.99 s |
| pop_values_tolist | 5.94 s |
+---------------------+-----------+
df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
is the fastest
CSS Resize/Zoom-In effect on Image while keeping Dimensions
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
WORKING DEMO.
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
UPDATED DEMO.
Testing if value is a function
I think the source of confusion is the distinction between a node's attribute and the corresponding property.
You're using:
$("a.button").parents("form").attr("onsubmit")
You're directly reading the onsubmit
attribute's value (which must be a string). Instead, you should access the onsubmit
property of the node:
$("a.button").parents("form").prop("onsubmit")
Here's a quick test:
<form id="form1" action="foo1.htm" onsubmit="return valid()"></form>
<script>
window.onload = function () {
var form1 = document.getElementById("form1");
function log(s) {
document.write("<div>" + s + "</div>");
}
function info(v) {
return "(" + typeof v + ") " + v;
}
log("form1 onsubmit property: " + info(form1.onsubmit));
log("form1 onsubmit attribute: " + info(form1.getAttribute("onsubmit")));
};
</script>
This yields:
form1 onsubmit property: (function) function onsubmit(event) { return valid(); }
form1 onsubmit attribute: (string) return valid()
Initializing a struct to 0
If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;
If the data is a local variable or a heap-allocated zone, clear it with memset
like:
memset(&m, 0, sizeof(myStruct));
Current compilers (e.g. recent versions of gcc
) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).
You could perhaps code myStruct m = {};
or myStruct m = {0};
(even if the first member of myStruct
is not a scalar).
My feeling is that using memset
for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).
Android: How do bluetooth UUIDs work?
The UUID stands for Universally Unique Identifier. UUID is an simple 128 bit digit which uniquely distributed across the world.
Bluetooth sends data over air and all nearby device can receive it. Let's suppose, sometimes you have to send some important files via Bluetooth and all near by devices can access it in range. So when you pair with the other devices, they simply share the UUID number and match before sharing the files. When you send any file then your device encrypt that file with appropriate device UUID and share over the network. Now all Bluetooth devices in the range can access the encrypt file but they required right UUID number. So Only right UUID devices have access to encrypt the file and others will reject cause of wrong UUID.
In short, you can use UUID as a secret password for sharing files between any two Bluetooth devices.
Convert Go map to json
Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal
would work as expected.
package main
import (
"encoding/json"
"fmt"
"strconv"
)
// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler
type Num int
func (n *Num) UnmarshalText(text []byte) error {
i, err := strconv.Atoi(string(text))
if err != nil {
return err
}
*n = Num(i)
return nil
}
func (n Num) MarshalText() (text []byte, err error) {
return []byte(strconv.Itoa(int(n))), nil
}
type Foo struct {
Number Num `json:"number"`
Title string `json:"title"`
}
func main() {
datas := make(map[Num]Foo)
for i := 0; i < 10; i++ {
datas[Num(i)] = Foo{Number: 1, Title: "test"}
}
jsonString, err := json.Marshal(datas)
if err != nil {
panic(err)
}
fmt.Println(datas)
fmt.Println(jsonString)
m := make(map[Num]Foo)
err = json.Unmarshal(jsonString, &m)
if err != nil {
panic(err)
}
fmt.Println(m)
}
Output:
map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]
Inner Joining three tables
Just do the same thing agin but then for TableC
SELECT *
FROM dbo.tableA A
INNER JOIN dbo.TableB B ON A.common = B.common
INNER JOIN dbo.TableC C ON A.common = C.common
How to add fixed button to the bottom right of page
This will be helpful for the right bottom rounded button
HTML :
<a class="fixedButton" href>
<div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
</a>
CSS:
.fixedButton{
position: fixed;
bottom: 0px;
right: 0px;
padding: 20px;
}
.roundedFixedBtn{
height: 60px;
line-height: 80px;
width: 60px;
font-size: 2em;
font-weight: bold;
border-radius: 50%;
background-color: #4CAF50;
color: white;
text-align: center;
cursor: pointer;
}
Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/
Git checkout: updating paths is incompatible with switching branches
After having tried most of what I could read in this thread without success, I stumbled across this one:
Remote branch not showing up in "git branch -r"
It turned out that my .git/config file was incorrect. After doing a simple fix all branches showed up.
Going from
[remote "origin"]
url = http://stash.server.com/scm/EX/project.git
fetch = +refs/heads/master:refs/remotes/origin/master
to
[remote "origin"]
url = http://stash.server.com/scm/EX/project.git
fetch = +refs/heads/*:refs/remotes/origin/*
Did the trick
Using group by on multiple columns
Group By X
means put all those with the same value for X in the one group.
Group By X, Y
means put all those with the same values for both X and Y in the one group.
To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:
Table: Subject_Selection
+---------+----------+----------+
| Subject | Semester | Attendee |
+---------+----------+----------+
| ITB001 | 1 | John |
| ITB001 | 1 | Bob |
| ITB001 | 1 | Mickey |
| ITB001 | 2 | Jenny |
| ITB001 | 2 | James |
| MKB114 | 1 | John |
| MKB114 | 1 | Erica |
+---------+----------+----------+
When you use a group by
on the subject column only; say:
select Subject, Count(*)
from Subject_Selection
group by Subject
You will get something like:
+---------+-------+
| Subject | Count |
+---------+-------+
| ITB001 | 5 |
| MKB114 | 2 |
+---------+-------+
...because there are 5 entries for ITB001, and 2 for MKB114
If we were to group by
two columns:
select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester
we would get this:
+---------+----------+-------+
| Subject | Semester | Count |
+---------+----------+-------+
| ITB001 | 1 | 3 |
| ITB001 | 2 | 2 |
| MKB114 | 1 | 2 |
+---------+----------+-------+
This is because, when we group by two columns, it is saying "Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions (Count, Sum, Average, etc.) for each of those groups". In this example, this is demonstrated by the fact that, when we count them, there are three people doing ITB001 in semester 1, and two doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")
Hopefully that makes sense.
How can I use UserDefaults in Swift?
//Save
NSUserDefaults.standardUserDefaults().setObject("yourString", forKey: "YourStringKey")
//retrive
let yourStr : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("YourStringKey")
Most efficient way to find smallest of 3 numbers Java?
No, it's seriously not worth changing. The sort of improvements you're going to get when fiddling with micro-optimisations like this will not be worth it. Even the method call cost will be removed if the min
function is called enough.
If you have a problem with your algorithm, your best bet is to look into macro-optimisations ("big picture" stuff like algorithm selection or tuning) - you'll generally get much better performance improvements there.
And your comment that removing Math.pow
gave improvements may well be correct but that's because it's a relatively expensive operation. Math.min
will not even be close to that in terms of cost.
How do I loop through a date range?
@jacob-sobus and @mquander and @Yogurt not exactly correct.. If I need the next day I wait 00:00 time mostly
public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.NextDay())
yield return day;
}
public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
for (var month = from.Date; month.Date <= thru.Date || month.Year == thru.Year && month.Month == thru.Month; month = month.NextMonth())
yield return month;
}
public static IEnumerable<DateTime> EachYear(DateTime from, DateTime thru)
{
for (var year = from.Date; year.Date <= thru.Date || year.Year == thru.Year; year = year.NextYear())
yield return year;
}
public static DateTime NextDay(this DateTime date)
{
return date.AddTicks(TimeSpan.TicksPerDay - date.TimeOfDay.Ticks);
}
public static DateTime NextMonth(this DateTime date)
{
return date.AddTicks(TimeSpan.TicksPerDay * DateTime.DaysInMonth(date.Year, date.Month) - (date.TimeOfDay.Ticks + TimeSpan.TicksPerDay * (date.Day - 1)));
}
public static DateTime NextYear(this DateTime date)
{
var yearTicks = (new DateTime(date.Year + 1, 1, 1) - new DateTime(date.Year, 1, 1)).Ticks;
var ticks = (date - new DateTime(date.Year, 1, 1)).Ticks;
return date.AddTicks(yearTicks - ticks);
}
public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
{
return EachDay(dateFrom, dateTo);
}
public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
{
return EachMonth(dateFrom, dateTo);
}
public static IEnumerable<DateTime> EachYearTo(this DateTime dateFrom, DateTime dateTo)
{
return EachYear(dateFrom, dateTo);
}
Find the max of two or more columns with pandas
@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy()
(or .values
for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.
For example, you can use ndarray.max()
along the first axis.
# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
A B
0 1 -2
1 2 8
2 3 1
df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns,
# df['C'] = df.values.max(1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If your data has NaN
s, you will need numpy.nanmax
:
df['C'] = np.nanmax(df.values, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
You can also use numpy.maximum.reduce
. numpy.maximum
is a ufunc (Universal Function), and every ufunc has a reduce
:
df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
np.maximum.reduce
and np.max
appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max
. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).
The graph was generated using perfplot. Benchmarking code, for reference:
import pandas as pd
import perfplot
np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))
perfplot.show(
setup=lambda n: pd.concat([df_] * n, ignore_index=True),
kernels=[
lambda df: df.assign(new=df.max(axis=1)),
lambda df: df.assign(new=df.values.max(1)),
lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
],
labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
n_range=[2**k for k in range(0, 15)],
xlabel='N (* len(df))',
logx=True,
logy=True)
Can I prevent text in a div block from overflowing?
Recommendations for how to catch which part of your CSS is causing the issue:
1) set style="height:auto;"
on all the <div>
elements and retry again.
2) Set style="border: 3px solid red;"
on all the <div>
elements to see how wide of an area your <div>
's box is taking up.
3) Take away all the css height:#px;
properties from your CSS and start over.
So for example:
<div id="I" style="height:auto;border: 3px solid red;">I
<div id="A" style="height:auto;border: 3px solid purple;">A
<div id="1A" style="height:auto;border: 3px solid green;">1A
</div>
<div id="2A" style="height:auto;border: 3px solid green;">2A
</div>
</div>
<div id="B" style="height:auto;border: 3px solid purple;">B
<div id="1B" style="height:auto;border: 3px solid green;">1B
</div>
<div id="2B" style="height:auto;border: 3px solid green;">2B
</div>
</div>
</div>
How to echo out table rows from the db (php)
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name
($key) and value
($field) for each field, as iterate over the fields of a row.
Wrapped in <table>
so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
calculating execution time in c++
This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.
Depending on what problem you're trying to solve, there might be a faster algorithm.
Issue with virtualenv - cannot activate
If some beginner, like me, has followed multiple Python tutorials now possible has multiple Python versions and/or multiple versions of pip/virtualenv/pipenv...
In that case, answers listed, while many correct, might not help.
The first thing I would try in your place is uninstall and reinstall Python and go from there.
android.widget.Switch - on/off event listener?
For those using Kotlin, you can set a listener for a switch (in this case having the ID mySwitch
) as follows:
mySwitch.setOnCheckedChangeListener { _, isChecked ->
// do whatever you need to do when the switch is toggled here
}
isChecked
is true if the switch is currently checked (ON), and false otherwise.
Determine if $.ajax error is a timeout
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second
argument (besides null) are "timeout",
"error", "notmodified" and
"parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
gradlew command not found?
Linux / MacOS
As noted in the comments, just running
./gradlew
worked for me. Adding the ./
tells it to look in the current directory since it isn't in the path.
Windows PowerShell
.\gradlew
Get most recent file in a directory on Linux
If you want to get the most recent changed file also including any subdirectories you can do it with this little oneliner:
find . -type f -exec stat -c '%Y %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done
If you want to do the same not for changed files, but for accessed files you simple have to change the
%Y parameter from the stat command to %X. And your command for most recent accessed files looks like this:
find . -type f -exec stat -c '%X %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done
For both commands you also can change the var="1" parameter if you want to list more than just one file.
Class has no objects member
I installed PyLint but I was having the error Missing module docstringpylint(missing-module-docstring)
. So I found this answer with this config for pylint :
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--disable=C0111", // missing docstring
"--load-plugins=pylint_django,pylint_celery",
],
And now it works
Logcat not displaying my log calls
Best solution for me was restart adb server (while I have Enabled ADB integration in Android studio - Tools - Android - checked). To do this quickly I created adbr.bat
file inside android-sdk\platform-tools
directory (where is adb.exe
located) with this inside:
adb kill-server
adb start-server
Because I have this folder in PATH system variable, always when I need restart adb
from Android studio, I can write only into terminal adbr
and it is done.
Another option to do this is through Android Device Monitor in Devices tab - Menu after click on small arrow right - Reset adb.
Using HTTPS with REST in Java
When you say "is there an easier way to... trust this cert", that's exactly what you're doing by adding the cert to your Java trust store. And this is very, very easy to do, and there's nothing you need to do within your client app to get that trust store recognized or utilized.
On your client machine, find where your cacerts file is (that's your default Java trust store, and is, by default, located at <java-home>/lib/security/certs/cacerts.
Then, type the following:
keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to cacerts>
That will import the cert into your trust store, and after this, your client app will be able to connect to your Grizzly HTTPS server without issue.
If you don't want to import the cert into your default trust store -- i.e., you just want it to be available to this one client app, but not to anything else you run on your JVM on that machine -- then you can create a new trust store just for your app. Instead of passing keytool the path to the existing, default cacerts file, pass keytool the path to your new trust store file:
keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to new trust store>
You'll be asked to set and verify a new password for the trust store file. Then, when you start your client app, start it with the following parameters:
java -Djavax.net.ssl.trustStore=<path to new trust store> -Djavax.net.ssl.trustStorePassword=<trust store password>
Easy cheesy, really.
C# generic list <T> how to get the type of T?
Marc's answer is the approach I use for this, but for simplicity (and a friendlier API?) you can define a property in the collection base class if you have one such as:
public abstract class CollectionBase<T> : IList<T>
{
...
public Type ElementType
{
get
{
return typeof(T);
}
}
}
I have found this approach useful, and is easy to understand for any newcomers to generics.
Node.js - Maximum call stack size exceeded
Regarding increasing the max stack size, on 32 bit and 64 bit machines V8's memory allocation defaults are, respectively, 700 MB and 1400 MB. In newer versions of V8, memory limits on 64 bit systems are no longer set by V8, theoretically indicating no limit. However, the OS (Operating System) on which Node is running can always limit the amount of memory V8 can take, so the true limit of any given process cannot be generally stated.
Though V8 makes available the --max_old_space_size
option, which allows control over the amount of memory available to a process, accepting a value in MB. Should you need to increase memory allocation, simply pass this option the desired value when spawning a Node process.
It is often an excellent strategy to reduce the available memory allocation for a given Node instance, especially when running many instances. As with stack limits, consider whether massive memory needs are better delegated to a dedicated storage layer, such as an in-memory database or similar.
Rmi connection refused with localhost
You need to have a rmiregistry
running before attempting to connect (register) a RMI service with it.
The LocateRegistry.createRegistry(2020)
method call creates and exports a registry on the specified port number.
See the documentation for LocateRegistry
How to add "required" attribute to mvc razor viewmodel text input editor
@Erik's answer didn't fly for me.
Following did:
@Html.TextBoxFor(m => m.ShortName, new { data_val_required = "You need me" })
plus doing this manually under field I had to add error message container
@Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })
Hope this saves you some time.
How to update PATH variable permanently from Windows command line?
In a corporate network, where the user has only limited access and uses portable apps, there are these command line tricks:
- Query the user env variables:
reg query "HKEY_CURRENT_USER\Environment"
. Use "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
for LOCAL_MACHINE.
- Add new user env variable:
reg add "HKEY_CURRENT_USER\Environment" /v shared_dir /d "c:\shared" /t REG_SZ
. Use REG_EXPAND_SZ
for paths containing other %% variables.
- Delete existing env variable:
reg delete "HKEY_CURRENT_USER\Environment" /v shared_dir
.
What is the difference between rb and r+b modes in file objects
r
opens for reading, whereas r+
opens for reading and writing. The b
is for binary.
This is spelled out in the documentation:
The most commonly-used values of mode are 'r'
for reading, 'w'
for writing (truncating the file if it already exists), and 'a'
for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'
. The default is to use text mode, which may convert '\n'
characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b'
to the mode value to open the file in binary mode, which will improve portability. (Appending 'b'
is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.
Modes 'r+'
, 'w+'
and 'a+'
open the file for updating (note that 'w+'
truncates the file). Append 'b'
to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b'
has no effect.
How to present UIActionSheet iOS Swift?
Your Approach is fine, but you can add UIActionSheet
with other way with ease.
You can add UIActionSheetDelegate
in UIViewController` like
class ViewController: UIViewController ,UIActionSheetDelegate
Set you method like,
@IBAction func downloadSheet(sender: AnyObject)
{
let actionSheet = UIActionSheet(title: "Choose Option", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Save", "Delete")
actionSheet.showInView(self.view)
}
You can get your button index when it clicked like
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
{
println("\(buttonIndex)")
switch (buttonIndex){
case 0:
println("Cancel")
case 1:
println("Save")
case 2:
println("Delete")
default:
println("Default")
//Some code here..
}
}
Update 1: for iOS8+
//Create the AlertController and add Its action like button in Actionsheet
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .ActionSheet)
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Cancel")
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Save", style: .default)
{ _ in
print("Save")
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Delete", style: .default)
{ _ in
print("Delete")
}
actionSheetControllerIOS8.addAction(deleteActionButton)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
How to use _CRT_SECURE_NO_WARNINGS
Adding _CRT_SECURE_NO_WARNINGS
to Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions didn't work for me, don't know why.
The following hint works:
In stdafx.h file, please add
#define _CRT_SECURE_NO_DEPRECATE
before include other header files.
Error:Conflict with dependency 'com.google.code.findbugs:jsr305'
The problem, as stated in your logs, is 2 dependencies trying to use different versions of 3rd dependency.
Add one of the following to the app-gradle file:
androidTestCompile 'com.google.code.findbugs:jsr305:2.0.1'
androidTestCompile 'com.google.code.findbugs:jsr305:1.3.9'
Getting the client's time zone (and offset) in JavaScript
It's already been answered how to get offset in minutes as an integer, but in case anyone wants the local GMT offset as a string e.g. "+1130"
:
function pad(number, length){
var str = "" + number
while (str.length < length) {
str = '0'+str
}
return str
}
var offset = new Date().getTimezoneOffset()
offset = ((offset<0? '+':'-')+ // Note the reversed sign!
pad(parseInt(Math.abs(offset/60)), 2)+
pad(Math.abs(offset%60), 2))
How to echo in PHP, HTML tags
You need to escape the "
so that PHP doesn't recognise them as part of your PHP code. You do this by using the \
escape character.
So, your code would look like this:
echo
"<div>
<h3><a href=\"#\">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
<div>"
IF Statement multiple conditions, same statement
if (checkbox.checked && columnname != a && columnname != b && columnname != c)
{
"statement 1"
}
else if (columnname != a && columnname != b && columnname != c
&& columnname != A2)
{
"statement 1"
}
is one way to simplify a little.
Update query with PDO and MySQL
- Your
UPDATE
syntax is wrong
- You probably meant to update a row not all of them so you have to use
WHERE
clause to target your specific row
Change
UPDATE `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :telephone, :email)
to
UPDATE `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
WHERE `user_id` = :user_id -- you probably have some sort of id
Creating an instance of class
/* 1 */ Foo* foo1 = new Foo ();
Creates an object of type Foo
in dynamic memory. foo1
points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo
was a POD-type, this would perform value-initialization (it doesn't apply here).
/* 2 */ Foo* foo2 = new Foo;
Identical to before, because Foo
is not a POD type.
/* 3 */ Foo foo3;
Creates a Foo
object called foo3
in automatic storage.
/* 4 */ Foo foo4 = Foo::Foo();
Uses copy-initialization to create a Foo
object called foo4
in automatic storage.
/* 5 */ Bar* bar1 = new Bar ( *new Foo() );
Uses Bar
's conversion constructor to create an object of type Bar
in dynamic storage. bar1
is a pointer to it.
/* 6 */ Bar* bar2 = new Bar ( *new Foo );
Same as before.
/* 7 */ Bar* bar3 = new Bar ( Foo foo5 );
This is just invalid syntax. You can't declare a variable there.
/* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );
Would work and work by the same principle to 5 and 6 if bar3
wasn't declared on in 7.
5 & 6 contain memory leaks.
Syntax like new Bar ( Foo::Foo() );
is not usual. It's usually new Bar ( (Foo()) );
- extra parenthesis account for most-vexing parse. (corrected)
Write string to text file and ensure it always overwrites the existing content.
If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?
I'm assuming your using a streams here, there are other ways to write a file.
Complex numbers usage in python
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex
, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath
has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
How to get the caret column (not pixels) position in a textarea, in characters, from the start?
I modified the above function to account for carriage returns in IE. It's untested but I did something similar with it in my code so it should be workable.
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
var add_newlines = 0;
for (var i=0; i<rc.text.length; i++) {
if (rc.text.substr(i, 2) == '\r\n') {
add_newlines += 2;
i++;
}
}
//return rc.text.length + add_newlines;
//We need to substract the no. of lines
return rc.text.length - add_newlines;
}
return 0;
}
Change bullets color of an HTML list without using span
::marker
You can use the ::marker
CSS pseudo-element to select the marker box of a list item (i.e. bullets or numbers).
ul li::marker {
color: red;
}
Note: At the time of posting this answer, this is considered experimental technology and has only been implemented in Firefox and Safari (so far).
Java enum - why use toString instead of name
You can also use something like the code below. I used lombok to avoid writing some of the boilerplate codes for getters and constructor.
@AllArgsConstructor
@Getter
public enum RetroDeviceStatus {
DELIVERED(0,"Delivered"),
ACCEPTED(1, "Accepted"),
REJECTED(2, "Rejected"),
REPAIRED(3, "Repaired");
private final Integer value;
private final String stringValue;
@Override
public String toString() {
return this.stringValue;
}
}
Example of AES using Crypto++
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
SSIS Text was truncated with status value 4
I suspect the
or one or more characters had no match in the target code page
part of the error.
If you remove the rows with values in that column, does it load?
Can you identify, in other words, the rows which cause the package to fail?
It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.
Finding whether a point lies inside a rectangle or not
Assuming the rectangle is represented by three points A,B,C, with AB and BC perpendicular, you only need to check the projections of the query point M on AB and BC:
0 <= dot(AB,AM) <= dot(AB,AB) &&
0 <= dot(BC,BM) <= dot(BC,BC)
AB
is vector AB, with coordinates (Bx-Ax,By-Ay), and dot(U,V)
is the dot product of vectors U and V: Ux*Vx+Uy*Vy
.
Update. Let's take an example to illustrate this: A(5,0) B(0,2) C(1,5) and D(6,3).
From the point coordinates, we get AB=(-5,2), BC=(1,3), dot(AB,AB)=29, dot(BC,BC)=10.
For query point M(4,2), we have AM=(-1,2), BM=(4,0), dot(AB,AM)=9, dot(BC,BM)=4. M is inside the rectangle.
For query point P(6,1), we have AP=(1,1), BP=(6,-1), dot(AB,AP)=-3, dot(BC,BP)=3. P is not inside the rectangle, because its projection on side AB is not inside segment AB.
Property [title] does not exist on this collection instance
When you're using get()
you get a collection. In this case you need to iterate over it to get properties:
@foreach ($collection as $object)
{{ $object->title }}
@endforeach
Or you could just get one of objects by it's index:
{{ $collection[0]->title }}
Or get first object from collection:
{{ $collection->first() }}
When you're using find()
or first()
you get an object, so you can get properties with simple:
{{ $object->title }}
Laravel Eloquent - Get one Row
You can do this too
Before you use this you must declare the DB facade in the controller
Simply put this line for that
use Illuminate\Support\Facades\DB;
Now you can get a row using this
$getUserByEmail = DB::table('users')->where('email', $email)->first();
or by this too
$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);
This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.
Hope this helps.
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 :)
Load CSV data into MySQL in Python
If it is a pandas data frame you could do:
Sending the data
csv_data.to_sql=(con=mydb, name='<the name of your table>',
if_exists='replace', flavor='mysql')
to avoid the use of the for
.
How do I calculate r-squared using Python and Numpy?
You can execute this code directly, this will find you the polynomial, and will find you the R-value you can put a comment down below if you need more explanation.
from scipy.stats import linregress
import numpy as np
x = np.array([1,2,3,4,5,6])
y = np.array([2,3,5,6,7,8])
p3 = np.polyfit(x,y,3) # 3rd degree polynomial, you can change it to any degree you want
xp = np.linspace(1,6,6) # 6 means the length of the line
poly_arr = np.polyval(p3,xp)
poly_list = [round(num, 3) for num in list(poly_arr)]
slope, intercept, r_value, p_value, std_err = linregress(x, poly_list)
print(r_value**2)
Why is vertical-align: middle not working on my span or div?
Since vertical-align
works as expected on a td
, you could put a single celled table
in the div
to align its content.
<div>
<table style="width: 100%; height: 100%;"><tr><td style="vertical-align: middle; text-align: center">
Aligned content here...
</td></tr></table>
</div>
Clunky, but works as far as I can tell. It might not have the drawbacks of the other workarounds.
Search a string in a file and delete it from this file by Shell Script
sed -i '/pattern/d' file
Use 'd' to delete a line. This works at least with GNU-Sed.
If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:
sed '/pattern/d' file > tmpfile && mv tmpfile file
Writing directly to the source usually doesn't work: sed '/pattern/d' file > file
so make a copy before trying out, if you doubt it.
Android file chooser
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
How to sort with lambda in Python
You're trying to use key functions with lambda functions.
Python and other languages like C# or F# use lambda functions.
Also, when it comes to key functions and according to the documentation
Both list.sort() and sorted() have a key parameter to
specify a function to be called on each list element prior to making
comparisons.
...
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
So, key functions have a parameter key and it can indeed receive a lambda function.
In Real Python there's a nice example of its usage. Let's say you have the following list
ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']
and want to sort through its "integers". Then, you'd do something like
sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort
and printing it would give
['id1', 'id2', 'id3', 'id22', 'id30', 'id100']
In your particular case, you're only missing to write key=
before lambda. So, you'd want to use the following
a = sorted(a, key=lambda x: x.modified, reverse=True)
How to use a BackgroundWorker?
I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; //Tell the user how the process went
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}
//Start Process
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
//Check if background worker is doing anything and send a cancellation if it is
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
//Check if there is a request to cancel the process
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
//If the process exits the loop, ensure that progress is set to 100%
//Remember in the loop we set i < 100 so in theory the process will complete at 99%
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Process was cancelled";
}
else if (e.Error != null)
{
lblStatus.Text = "There was an error running the process. The thread aborted";
}
else
{
lblStatus.Text = "Process was completed";
}
}
How do I properly 'printf' an integer and a string in C?
You're on the right track. Here's a corrected version:
char str[10];
int n;
printf("type a string: ");
scanf("%s %d", str, &n);
printf("%s\n", str);
printf("%d\n", n);
Let's talk through the changes:
- allocate an int (
n
) to store your number in
- tell
scanf
to read in first a string and then a number (%d
means number, as you already knew from your printf
That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str
and start trampling your stack.
How to add row of data to Jtable from values received from jtextfield and comboboxes
you can use this code as template please customize it as per your requirement.
DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();
list.add(textField.getText());
list.add(comboBox.getSelectedItem());
model.addRow(list.toArray());
table.setModel(model);
here DefaultTableModel
is used to add rows in JTable
,
you can get more info here.
How to write header row with csv.DictWriter?
Edit:
In 2.7 / 3.2 there is a new writeheader()
method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader()
method now available in 2.7 / 3.2:
from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
dw.writeheader()
# continue on to write data
Instantiating DictWriter requires a fieldnames argument.
From the documentation:
The fieldnames parameter identifies
the order in which values in the
dictionary passed to the writerow()
method are written to the csvfile.
Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with
statement was added in 2.6. If using 2.5: from __future__ import with_statement
with open(infile,'rb') as fin:
dr = csv.DictReader(fin, delimiter='\t')
# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
headers = {}
for n in dw.fieldnames:
headers[n] = n
dw.writerow(headers)
for row in dr:
dw.writerow(row)
As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
for row in dr:
dw.writerow(row)
Fill DataTable from SQL Server database
If the variable table
contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
How do I set response headers in Flask?
Use make_response
of Flask something like
@app.route("/")
def home():
resp = make_response("hello") #here you could use make_response(render_template(...)) too
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
From flask docs,
flask.make_response(*args)
Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.
JavaScript get clipboard data on paste event (Cross browser)
For cleaning the pasted text and replacing the currently selected text with the pasted text the matter is pretty trivial:
<div id='div' contenteditable='true' onpaste='handlepaste(this, event)'>Paste</div>
JS:
function handlepaste(el, e) {
document.execCommand('insertText', false, e.clipboardData.getData('text/plain'));
e.preventDefault();
}
How to filter an array of objects based on values in an inner array with jq?
Very close! In your select
expression, you have to use a pipe (|
) before contains
.
This filter produces the expected output.
. - map(select(.Names[] | contains ("data"))) | .[] .Id
The jq Cookbook has an example of the syntax.
Filter objects based on the contents of a key
E.g., I only want objects whose genre key contains "house".
$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}
Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.
The simplest way is to wrap the whole expression in an array constructor:
$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]
You can also use the map function:
$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]
map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f)
is equivalent to [.[]|f]
.
My httpd.conf is empty
The /etc/apache2/httpd.conf
is empty in Ubuntu, because the Apache configuration resides in /etc/apache2/apache2.conf
!
“httpd.conf is for user options.” No it isn't, it's there for historic reasons.
Using Apache server, all user options should go into a new *.conf
-file inside /etc/apache2/conf.d/
. This method should be "update-safe", as httpd.conf
or apache2.conf
may get overwritten on the next server update.
Inside /etc/apache2/apache2.conf
, you will find the following line, which includes those files:
# Include generic snippets of statements
Include conf.d/
As of Apache 2.4+ the user configuration directory is /etc/apache2/conf-available/
. Use a2enconf FILENAME_WITHOUT_SUFFIX
to enable the new configuration file or manually create a symlink in /etc/apache2/conf-enabled/
. Be aware that as of Apache 2.4 the configuration files must have the suffix .conf
(e.g. conf-available/my-settings.conf
);