I generally need to diff codes from subversion repositories and so far eclipse has worked really nicely for me... I use KDiff3 for other works.
with bash:
shopt -s globstar nullglob
rename _dbg.txt .txt **/*dbg*
If you want to install Python 2.7 on Oracle Linux, you can proceed as follows:
Enable the Software Collection in /etc/yum.repos.d/public-yum-ol6.repo.
vim /etc/yum.repos.d/public-yum-ol6.repo
[public_ol6_software_collections]
name=Software Collection Library release 1.2 packages for Oracle Linux 6
(x86_64)
baseurl=[http://yum.oracle.com/repo/OracleLinux/OL6/SoftwareCollections12/x86_64/][1]
gpgkey=file:[///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle][2]
gpgcheck=1
enabled=1 <==============change from 0 to 1
After making this change to the yum repository you can simply run the yum command to install the Python:
yum install gcc libffi libffi-devel python27 python27-python-devel openssl-devel python27-MySQL-python
edit bash_profile with follow variables:
vim ~/.bash_profile
PATH=$PATH:$HOME/bin:/opt/rh/python27/root/usr/bin export PATH
LD_LIBRARY_PATH=/opt/rh/python27/root/usr/lib64 export LD_LIBRARY_PATH
PKG_CONFIG_PATH=/opt/rh/python27/root/usr/lib64/pkgconfig export PKG_CONFIG_PATH
Now you can use python2.7 and pip for install Python modules:
/opt/rh/python27/root/usr/bin/pip install pynacl
/opt/rh/python27/root/usr/bin/python2.7 --version
If the array element is not integer you can use something like below :
$skus = array('LDRES10','LDRES12','LDRES11'); //sample data
if(!empty($skus)){
$sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "
}
first you have to import: import javax.swing.JOptionPane; then you can call it using this:
JOptionPane.showMessageDialog(null,
"ALERT MESSAGE",
"TITLE",
JOptionPane.WARNING_MESSAGE);
the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE
. it works pretty well in a lot of ways mostly for errors.
Hit enter as there is no password. Enter the following commands:
mysql> SET PASSWORD for 'root'@'localhost' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'127.0.0.1' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'::1' = password('enteryourpassword');
That’s it, I keep the passwords the same to keep things simple. If you want to check the user’s table to see that the info has been updated just enter the additional commands as shown below. This is a good option to check that you have indeed entered the same password for all hosts.
As of NuGet 2.8, there is a feature to downgrade a package.
Example:
The following command entered into the Package Manager Console will downgrade the Couchbase client to version 1.3.1.0.
Update-Package CouchbaseNetClient -Version 1.3.1.0
Result:
Updating 'CouchbaseNetClient' from version '1.3.3' to '1.3.1.0' in project [project name].
Removing 'CouchbaseNetClient 1.3.3' from [project name].
Successfully removed 'CouchbaseNetClient 1.3.3' from [project name].
Something to note as per crimbo below:
This approach doesn't work for downgrading from one prerelease version to other prerelease version - it only works for downgrading to a release version
In Java7 you can use:
import static java.nio.charset.StandardCharsets.*;
byte[] ptext = myString.getBytes(ISO_8859_1);
String value = new String(ptext, UTF_8);
This has the advantage over getBytes(String)
that it does not declare throws UnsupportedEncodingException
.
If you're using an older Java version you can declare the charset constants yourself:
import java.nio.charset.Charset;
public class StandardCharsets {
public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
public static final Charset UTF_8 = Charset.forName("UTF-8");
//....
}
You can take advantage of the NilClass
provided #to_i
method, which will return zero for nil
values:
unless discount.to_i.zero?
# Code here
end
If discount
can be fractional numbers, you can use #to_f
instead, to prevent the number from being rounded to zero.
I have try to my code and got success try this
package com.mobeyosoft.latitudelongitude;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by 5943 6417 on 14-09-2016.
*/
public class LocationService extends Service
{
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 1;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
Context context;
Intent intent;
int counter = 0;
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
context=this;
}
@Override
public void onStart(Intent intent, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
}
@Override
public IBinder onBind(Intent intent){
return null;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public void onDestroy() {
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates(listener);
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
@Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
public class MyLocationListener implements LocationListener{
public void onLocationChanged(final Location loc)
{
Log.i("**********", "Location changed");
if(isBetterLocation(loc, previousBestLocation)) {
loc.getLatitude();
loc.getLongitude();
Toast.makeText(context, "Latitude" + loc.getLatitude() + "\nLongitude"+loc.getLongitude(),Toast.LENGTH_SHORT).show();
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
Forgive me if I don't understand your question well, but here's my answer:
You can create a private npm module and use npm's normal commands to install it. Most node.js users use git as their repository, but you can use whatever repository works for you.
Once your package is made, then use
npm install *tarball_url*
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
You need the Microsoft.AspNet.WebApi.Core package.
You can see it in the .csproj file:
<Reference Include="System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
I think the shortest way to do just throw-away single call (without altering existing modules or creating new ones) would be as follows:
Class.new.extend(UsefulThings).get_file
Package auto-indent exists to apply auto-indent to entire file with this shortcuts :
ctrl+shift+i
or
cmd+shift+i
Package url : https://atom.io/packages/auto-indent
Your code is passing a function as an argument to find
. That function takes an element
argument (of type Conversation
) and returns void
(meaning there is no return value). TypeScript describes this as (element: Conversation) => void'
What TypeScript is saying is that the find
function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations
, a number
and a Conversation
array, and that this function should return a boolean
.
So bottom line is that you either need to change your code to pass in the values to find
correctly, or else you need to provide an overload to the definition of find
in your definition file that accepts a Conversation
and returns void
.
mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+---------------+-----------+
| Variable_name | Value |
+---------------+-----------+
| hostname | karola-pc |
+---------------+-----------+
1 row in set (0.00 sec)
For Example in my case : karola-pc
is the host name of the box where my mysql is running. And it my local PC host name.
If it is romote box than you can ping that host directly if, If you are in network with that box you should be able to ping that host.
If it UNIX or Linux you can run "hostname" command
in terminal to check the host name.
if it is windows you can see same value in MyComputer-> right click -> properties ->Computer Name
you can see ( i.e System Properties)
Hope it will answer your Q.
It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).
Here is a nice CANCEL SIP Call Flow illustration.
Just put this blur view on the imageView. Here is an example in Objective-C:
UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
visualEffectView.frame = imageView.bounds;
[imageView addSubview:visualEffectView];
and Swift:
var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
visualEffectView.frame = imageView.bounds
imageView.addSubview(visualEffectView)
I could advise you to use Exp4j. It is easy to understand as you can see from the following example code:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
The other methods described assume a binary mask. If you want to use a real-valued single-channel grayscale image as a mask (e.g. from an alpha channel), you can expand it to three channels and then use it for interpolation:
assert len(mask.shape) == 2 and issubclass(mask.dtype.type, np.floating)
assert len(foreground_rgb.shape) == 3
assert len(background_rgb.shape) == 3
alpha3 = np.stack([mask]*3, axis=2)
blended = alpha3 * foreground_rgb + (1. - alpha3) * background_rgb
Note that mask
needs to be in range 0..1
for the operation to succeed. It is also assumed that 1.0
encodes keeping the foreground only, while 0.0
means keeping only the background.
If the mask may have the shape (h, w, 1)
, this helps:
alpha3 = np.squeeze(np.stack([np.atleast_3d(mask)]*3, axis=2))
Here np.atleast_3d(mask)
makes the mask (h, w, 1)
if it is (h, w)
and np.squeeze(...)
reshapes the result from (h, w, 3, 1)
to (h, w, 3)
.
Use jquery animate and give it a long duration say 2000
$("#Friends").animate({
top: "-=30px",
}, duration );
The -= means that the animation will be relative to the current top position.
Note that the Friends
element must have position set to relative in the css:
#Friends{position:relative;}
You can transpose the array if you want to get the length of the other dimension.
len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)
Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.
I checked and it worked for me.
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="margin-top:100px;"><!--style with margin-top according to your need-->
<ul class="nav navbar-nav navbar-right">
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
You could add your IEnumerable range to a list then set the ICollection = to the list.
IEnumerable<T> source;
List<item> list = new List<item>();
list.AddRange(source);
ICollection<item> destination = list;
It happens that /etc/hosts
file doesn't support wild card entries.
You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf
and add the following line:
address=/example.com/127.0.0.1
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous
function. Otherwise you will have to make a callback
.
So I just added async:false,
to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
h/H = 12/24 hours means you will write hh:mm = 12 hours format and HH:mm = 24 hours format
I don't understand why the other friends tell you use HH
, But after I test so many time, The correct 24 hour format is :
hh
.
I see it from : http://www.malot.fr/bootstrap-datetimepicker/
I don't know why they don't use the common type HH
for 24 hour.....
I hope anyone could tell me if I'm wrong.....
For my application, I use a HorizontalScrollView containing LinearLayout inside, which has orientation set to horizontal. In order to add images inside, I create ImageViews inside the activity and add them to my LinearLayout. For example:
<HorizontalScrollView
android:id="@+id/photo_scroll"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="horizontal"
android:visibility="gone">
<LinearLayout
android:id="@+id/imageview_holder"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="match_parent">
</LinearLayout>
</HorizontalScrollView>
An this works perfectly fine for me. In the activity all I have to do is something like the code below:
LinearLayout imgViewHolder = findViewById(R.id.imageview_holder);
ImageView img1 = new ImageView(getApplicationContext());
//set bitmap
//set img1 layout params
imgViewHolder.add(img1);
ImageView img2 = new ImageView(getApplicationContext());
//set bitmap
//set img2 layout params
imgViewHolder.add(img2);
As I said that works for me, and I hope it helps somebody looking to achieve this as well.
Luckily git stash pop
does not change the stash in the case of a conflict!
So nothing, to worry about, just clean up your code and try it again.
Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop
again and you get the same stash, that conflicted before.
Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.
How about this ? Example illusrated using a file:
f = open('abc.log','r')
content = f.readlines()
for line in content:
m = re.search(r"\[(.*?)\]", line)
print m.group(1)
Hope this helps:
Magic regex : \[(.*?)\]
Explanation:
\[
: [
is a meta char and needs to be escaped if you want to match it literally.
(.*?)
: match everything in a non-greedy way and capture it.
\]
: ]
is a meta char and needs to be escaped if you want to match it literally.
You could add the user to the Database Level Role db_datareader.
Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.
See Books Online for reference:
http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx
You can add a database user to a database role using the following query:
EXEC sp_addrolemember N'db_datareader', N'userName'
The accepted answer may solve the question, but if you want multiline if
conditions in the dockerfile, you can do that placing \
at the end of each line (similar to how you would do in a shell script) and ending each command with ;
. You can even define someting like set -eux
as the 1st command.
Example:
RUN set -eux; \
if [ -f /path/to/file ]; then \
mv /path/to/file /dest; \
fi; \
if [ -d /path/to/dir ]; then \
mv /path/to/dir /dest; \
fi
In your case:
FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
echo Argument not provided; \
else \
echo Argument is $arg; \
fi
Then build with:
docker build -t my_docker . --build-arg arg=42
While calling your sub functions from your main functions you can convert the variables into int and then call. Please refer the below code:
import sys
print("Welcome to Calculator\n")
print("Please find the options:\n" + "1. Addition\n" + "2. Subtraction\n" +
"3. Multiplication\n" + "4. Division\n" + "5. Exponential\n" + "6. Quit\n")
def calculator():
choice = input("Enter choice\n")
if int(choice) == 1:
a = input("Enter first number\n")
b = input("Enter second number\n")
add(int(a), int(b))
if int(choice) == 2:
a = input("Enter first number\n")
b = input("Enter second number\n")
diff(int(a), int(b))
if int(choice) == 3:
a = input("Enter first number\n")
b = input("Enter second number\n")
mult(int(a), int(b))
if int(choice) == 4:
a = input("Enter first number\n")
b = input("Enter second number\n")
div(float(a), float(b))
if int(choice) == 5:
a = input("Enter the base number\n")
b = input("Enter the exponential\n")
exp(int(a), int(b))
if int(choice) == 6:
print("Bye")
sys.exit(0)
def add(a, b):
c = a+b
print("Sum of {} and {} is {}".format(a, b, c))
def diff(a,b):
c = a-b
print("Difference between {} and {} is {}".format(a, b, c))
def mult(a, b):
c = a*b
print("The Product of {} and {} is {}".format(a, b, c))
def div(a, b):
c = a/b
print("The Quotient of {} and {} is {}".format(a, b, c))
def exp(a, b):
c = a**b
print("The result of {} to the power of {} is {}".format(a, b, c))
calculator()
Here what I did is I called each of the function while converting the parameters inputted to int. I hope this has been helpful.
In your case it could be changed like this:
if choice == "0":
numberA = raw_input("Enter your first number: ")
numberB = raw_input("Enter your second number: ")
print "Your result is:"
print addition(int(numberA), int(numberB))
You post JSON like this
$.ajax(url, {
data : JSON.stringify(myJSObject),
contentType : 'application/json',
type : 'POST',
...
if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want
there one more option that allows to get "select" size with joins, and table size as option too
-- 1
EXPLAIN PLAN
FOR
SELECT
Scheme.Table_name.table_column1 AS "column1",
Scheme.Table_name.table_column2 AS "column2",
Scheme.Table_name.table_column3 AS "column3",
FROM Scheme.Table_name
WHERE ;
SELECT * FROM TABLE (DBMS_XPLAN.display);
You can use Jinja's default
:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
Wow. Good grief. It's because I had an env value with a space in it, not surrounded by quotes
This
SITE_NAME=My website
Changed to this
SITE_NAME="My website"
Fixed it. I think this had to do with Laravel 5.2 now upgrading vlucas/phpdotenv from 1.1.1 to 2.1.0
The best solution I could find at present time to open a window maximized is (Internet Explorer 11, Chrome 49, Firefox 45):
var popup = window.open("your_url", "popup", "fullscreen");
if (popup.outerWidth < screen.availWidth || popup.outerHeight < screen.availHeight)
{
popup.moveTo(0,0);
popup.resizeTo(screen.availWidth, screen.availHeight);
}
see https://jsfiddle.net/8xwocrp6/7/
Note 1: It does not work on Edge (13.1058686). Not sure whether it's a bug or if it's as designed (I've filled a bug report, we'll see what they have to say about it). Here is a workaround:
if (navigator.userAgent.match(/Edge\/\d+/g))
{
return window.open("your_url", "popup", "width=" + screen.width + ",height=" + screen.height);
}
Note 2: moveTo
or resizeTo
will not work (Access denied) if the window you are opening is on another domain.
If still noting is working for you add the following styles on your page style sheet
.ui-widget-content .ui-state-default {
border: 0px solid #d3d3d3;
background: #00ACD6 50% 50% repeat-x;
font-weight: normal;
color: #fff;
}
It will change the background color of the dialog buttons.
Try this
in view:
<form name="formName" ng-submit="submitForm(formName)">
<!-- fields -->
</form>
in controller:
$scope.submitForm = function(form){
if(form.$valid) {
// Code here if valid
}
};
or
in view:
<form name="formName" ng-submit="submitForm(formName.$valid)">
<!-- fields -->
</form>
in controller:
$scope.submitForm = function(formValid){
if(formValid) {
// Code here if valid
}
};
You could use a regular expression replace:
str = str.replace(/ +(?= )/g,'');
Credit: The above regex was taken from Regex to replace multiple spaces with a single space
In python: help(my_list.append)
for example, will give you the docstring of the function.
>>> my_list = []
>>> help(my_list.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
Here is my solution:
<!-- jquery smooth scroll to id's -->
<script>
$(function() {
$('a[href*=\\#]:not([href=\\#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 500);
return false;
}
}
});
});
</script>
With just this snippet you can use an unlimited number of hash-links and corresponding ids without having to execute a new script for each.
I already explained how it works in another thread here: https://stackoverflow.com/a/28631803/4566435 (or here's a direct link to my blog post)
For clarifications, let me know. Hope it helps!
It's recommended to put the image to the resources, than you can use it like this:
imageView = new ImageView("/gui.img/img.jpg");
//Add the Framework in .h file
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
//Set the delegate methods
UIViewController<UINavigationControllerDelegate,MFMessageComposeViewControllerDelegate>
//add the below code in .m file
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
MFMessageComposeViewController *controller =
[[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
NSString *str= @"Hello";
controller.body = str;
controller.recipients = [NSArray arrayWithObjects:
@"", nil];
controller.delegate = self;
[self presentModalViewController:controller animated:YES];
}
}
- (void)messageComposeViewController:
(MFMessageComposeViewController *)controller
didFinishWithResult:(MessageComposeResult)result
{
switch (result)
{
case MessageComposeResultCancelled:
NSLog(@"Cancelled");
break;
case MessageComposeResultFailed:
NSLog(@"Failed");
break;
case MessageComposeResultSent:
break;
default:
break;
}
[self dismissModalViewControllerAnimated:YES];
}
Yes, from the moment on you establish a HTTPS connection everyting is secure. The query string (GET) as the POST is sent over SSL.
It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.
In 'Path Variables' create a variable for example ANALYTICS_VERSION
.
In a 'Run Configuration' under 'Environment Variables' add for example the following:
ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin
To answer the original question you would need to add an APP_HOME
environment variable to your run configuration which references the path variable:
APP_HOME=$APP_HOME$
Try
$ awk 'NF>1{print $NF}' file
example.
line.
file.
To get the result in one line as in your example, try:
{
sub(/\./, ",", $NF)
str = str$NF
}
END { print str }
output:
$ awk -f script.awk file
example, line, file,
Pure bash:
$ while read line; do [ -z "$line" ] && continue ;echo ${line##* }; done < file
example.
line.
file.
There are lots of good reasons for setting the size of a frame. One is to remember the last size the user set, and restore those settings. I have this code which seems to work for me:
package javatools.swing;
import java.util.prefs.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class FramePositionMemory {
public static final String WIDTH_PREF = "-width";
public static final String HEIGHT_PREF = "-height";
public static final String XPOS_PREF = "-xpos";
public static final String YPOS_PREF = "-ypos";
String prefix;
Window frame;
Class<?> cls;
public FramePositionMemory(String prefix, Window frame, Class<?> cls) {
this.prefix = prefix;
this.frame = frame;
this.cls = cls;
}
public void loadPosition() {
Preferences prefs = (Preferences)Preferences.userNodeForPackage(cls);
// Restore the most recent mainframe size and location
int width = prefs.getInt(prefix + WIDTH_PREF, frame.getWidth());
int height = prefs.getInt(prefix + HEIGHT_PREF, frame.getHeight());
System.out.println("WID: " + width + " HEI: " + height);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int xpos = (screenSize.width - width) / 2;
int ypos = (screenSize.height - height) / 2;
xpos = prefs.getInt(prefix + XPOS_PREF, xpos);
ypos = prefs.getInt(prefix + YPOS_PREF, ypos);
frame.setPreferredSize(new Dimension(width, height));
frame.setLocation(xpos, ypos);
frame.pack();
}
public void storePosition() {
Preferences prefs = (Preferences)Preferences.userNodeForPackage(cls);
prefs.putInt(prefix + WIDTH_PREF, frame.getWidth());
prefs.putInt(prefix + HEIGHT_PREF, frame.getHeight());
Point loc = frame.getLocation();
prefs.putInt(prefix + XPOS_PREF, (int)loc.getX());
prefs.putInt(prefix + YPOS_PREF, (int)loc.getY());
System.out.println("STORE: " + frame.getWidth() + " " + frame.getHeight() + " " + loc.getX() + " " + loc.getY());
}
}
public class Main {
void main(String[] args) {
JFrame frame = new Frame();
// SET UP YOUR FRAME HERE.
final FramePositionMemory fm = new FramePositionMemory("scannacs2", frame, Main.class);
frame.setSize(400, 400); // default size in the absence of previous setting
fm.loadPosition();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
fm.storePosition();
}
});
frame.setVisible(true);
}
}
}
You have not joined TableD, merely selected the TableD FIELD (dID
) from one of the tables.
I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.
I found a hint in the following question - Python: Histogram with area normalized to something other than 1
But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data
If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.
import matplotlib.pyplot as plt
# Let X be the array whose histogram needs to be plotted.
nx, xbins, ptchs = plt.hist(X, bins=20)
plt.clf() # Get rid of this histogram since not the one we want.
nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
width = xbins[1] - xbins[0] # Width of each bin.
x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
y = np.ravel(zip(nx_frac,nx_frac))
plt.plot(x,y,linestyle="dashed",label="MyLabel")
#... Further formatting.
This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.
Just thought I'd share my experience. Thank you.
To define the minimum value of the EditText, I used this:
if (message.trim().length() >= 1 && message.trim().length() <= 12) {
// do stuf
} else {
// Too short or too long
}
So, as an example...
First you need to create an ExifInterface:
ExifInterface exif = new ExifInterface(filename);
You can then grab the orientation of the image:
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Here's what the orientation values mean: http://sylvana.net/jpegcrop/exif_orientation.html
So, the most important values are 3, 6 and 8.
If the orientation is ExifInterface.ORIENTATION_ROTATE_90
(which is 6), for example, you can rotate the image like this:
Matrix matrix = new Matrix();
matrix.postRotate(90);
rotatedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, true);
That's just a quick example, though. I'm sure there are other ways of performing the actual rotation. But you will find those on StackOverflow as well.
You could always make a unique index, which causes MongoDB to reject a conflicting save. Consider the following done using the mongodb shell:
> db.getCollection("test").insert ({a:1, b:2, c:3})
> db.getCollection("test").find()
{ "_id" : ObjectId("50c8e35adde18a44f284e7ac"), "a" : 1, "b" : 2, "c" : 3 }
> db.getCollection("test").ensureIndex ({"a" : 1}, {unique: true})
> db.getCollection("test").insert({a:2, b:12, c:13}) # This works
> db.getCollection("test").insert({a:1, b:12, c:13}) # This fails
E11000 duplicate key error index: foo.test.$a_1 dup key: { : 1.0 }
Tried following code
$db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbuser, $dbpass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
Then
try {
$db->query('SET NAMES gbk');
$stmt = $db->prepare('SELECT * FROM 2_1_paidused WHERE NumberRenamed = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));
}
catch (PDOException $e){
echo "DataBase Errorz: " .$e->getMessage() .'<br>';
}
catch (Exception $e) {
echo "General Errorz: ".$e->getMessage() .'<br>';
}
And got
DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/*' LIMIT 1' at line 1
If added $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
after $db = ...
Then got blank page
If instead SELECT
tried DELETE
, then in both cases got error like
DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM 2_1_paidused WHERE NumberRenamed = '¿\' OR 1=1 /*' LIMIT 1' at line 1
So my conclusion that no injection possible...
I know this is an old post, but for anyone using Retrofit, this can be useful useful.
If you are using Retrofit + Jackson + Kotlin + Data classes, you need:
implement group: 'com.fasterxml.jackson.module', name: 'jackson-module-kotlin', version: '2.7.1-2'
to your dependencies, so that Jackson can de-serialize into Data classes val jsonMapper = com.fasterxml.jackson.module.kotlin.jacksonObjectMapper()
val retrofit = Retrofit.Builder()
...
.addConverterFactory(JacksonConverterFactory.create(jsonMapper))
.build()
Note: If Retrofit is not being used, @Jayson Minard has a more general approach answer.
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/
is the same as /../
, and that will get normalized away.
(This is a combination of an answer by bobince and a comment by slowpoison.)
It would work giving the #container div width:80%
(any width less than the main content and have given in %, so that it manages well from both left and right) and giving margin:0px auto;
or margin:0 auto;
(both work fine).
After reading your comment on my previous answer I thought I might put this as a separate answer.
Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.
That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with
WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/
This is the jQuery
$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();
$('.active').show();
$('#button-next').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':last-child')) {
$('.sp').first().addClass('active');
}
else{
$('.oldActive').next().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
$('#button-previous').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':first-child')) {
$('.sp').last().addClass('active');
}
else{
$('.oldActive').prev().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
});
So now the explanation.
Stage 1
1) Load the script on document ready.
2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.
3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;
Stage 2
Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.
2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.
3) We remove the class oldActive because it's no longer needed.
4) fadeOut all of the slides
5) fade In the active slides
Step 3
Same as in step two but using some reverse logic for traversing through the elements backwards.
It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.
Hidde:
BUTTON.setVisibility(View.GONE);
Show:
BUTTON.setVisibility(View.VISIBLE);
Here is another solution:
SELECT Isnull(Nullif(listing.offertext, ''), company.offertext) AS offer_text,
FROM tbl_directorylisting listing
INNER JOIN tbl_companymaster company
ON listing.company_id = company.company_id
For application/msword and application/vnd.ms-excel, when I deleted the size restriction:
($_FILES["file"]["size"] < 20000)
...it worked ok.
The settings which has been advised to change in @Diego's accepted answer might be good if you want to set this option permanently for all future query sessions that you open within SQL Server Management Studio(SSMS). This is usually not the case. Also, changing this setting requires restarting SQL Server Management Studio (SSMS) application. This is again a 'not-so-nice' experience if you've many unsaved open query session windows and you are in the middle of some debugging.
SQL Server gives a much slick option of changing it on per session basis which is very quick, handy and convenient. I'm detailing the steps below using query options window:
Query Options...
at the bottom of the context menu as shown below:Results
> Grid
in the left navigation pane. Check the Include column headers when copying or saving the results
check box in right pane as shown below:That's it. Your current session will honour your settings with immediate effect without restarting SSMS. Also, this setting won't be propagated to any future session. Effectively changing this setting on a per session basis is much less noisy.
here you can find an implementation :
def __uniqueid__():
"""
generate unique id with length 17 to 21.
ensure uniqueness even with daylight savings events (clocks adjusted one-hour backward).
if you generate 1 million ids per second during 100 years, you will generate
2*25 (approx sec per year) * 10**6 (1 million id per sec) * 100 (years) = 5 * 10**9 unique ids.
with 17 digits (radix 16) id, you can represent 16**17 = 295147905179352825856 ids (around 2.9 * 10**20).
In fact, as we need far less than that, we agree that the format used to represent id (seed + timestamp reversed)
do not cover all numbers that could be represented with 35 digits (radix 16).
if you generate 1 million id per second with this algorithm, it will increase the seed by less than 2**12 per hour
so if a DST occurs and backward one hour, we need to ensure to generate unique id for twice times for the same period.
the seed must be at least 1 to 2**13 range. if we want to ensure uniqueness for two hours (100% contingency), we need
a seed for 1 to 2**14 range. that's what we have with this algorithm. You have to increment seed_range_bits if you
move your machine by airplane to another time zone or if you have a glucky wallet and use a computer that can generate
more than 1 million ids per second.
one word about predictability : This algorithm is absolutely NOT designed to generate unpredictable unique id.
you can add a sha-1 or sha-256 digest step at the end of this algorithm but you will loose uniqueness and enter to collision probability world.
hash algorithms ensure that for same id generated here, you will have the same hash but for two differents id (a pair of ids), it is
possible to have the same hash with a very little probability. You would certainly take an option on a bijective function that maps
35 digits (or more) number to 35 digits (or more) number based on cipher block and secret key. read paper on breaking PRNG algorithms
in order to be convinced that problems could occur as soon as you use random library :)
1 million id per second ?... on a Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz, you get :
>>> timeit.timeit(uniqueid,number=40000)
1.0114529132843018
an average of 40000 id/second
"""
mynow=datetime.now
sft=datetime.strftime
# store old datetime each time in order to check if we generate during same microsecond (glucky wallet !)
# or if daylight savings event occurs (when clocks are adjusted backward) [rarely detected at this level]
old_time=mynow() # fake init - on very speed machine it could increase your seed to seed + 1... but we have our contingency :)
# manage seed
seed_range_bits=14 # max range for seed
seed_max_value=2**seed_range_bits - 1 # seed could not exceed 2**nbbits - 1
# get random seed
seed=random.getrandbits(seed_range_bits)
current_seed=str(seed)
# producing new ids
while True:
# get current time
current_time=mynow()
if current_time <= old_time:
# previous id generated in the same microsecond or Daylight saving time event occurs (when clocks are adjusted backward)
seed = max(1,(seed + 1) % seed_max_value)
current_seed=str(seed)
# generate new id (concatenate seed and timestamp as numbers)
#newid=hex(int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed])))[2:-1]
newid=int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed]))
# save current time
old_time=current_time
# return a new id
yield newid
""" you get a new id for each call of uniqueid() """
uniqueid=__uniqueid__().next
import unittest
class UniqueIdTest(unittest.TestCase):
def testGen(self):
for _ in range(3):
m=[uniqueid() for _ in range(10)]
self.assertEqual(len(m),len(set(m)),"duplicates found !")
hope it helps !
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
Yes! And another solution. My solution differs in the keys that are being checked.
In all other solutions we only look at the keys in dict_b
. But here we look in the union of both dictionaries.
Do with it as you please
def update_nested(dict_a, dict_b):
set_keys = set(dict_a.keys()).union(set(dict_b.keys()))
for k in set_keys:
v = dict_a.get(k)
if isinstance(v, dict):
new_dict = dict_b.get(k, None)
if new_dict:
update_nested(v, new_dict)
else:
new_value = dict_b.get(k, None)
if new_value:
dict_a[k] = new_value
When you create an object myObj
as you have, think of it more like a dictionary. In this case, it has two keys, name
, and age
.
You can access these dictionaries in two ways:
myObj[name]
); ormyObj.name
); do note that some properties are reserved, so the first method is preferred.You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name
is a variable, and since you haven't created a variable called name
, it won't be able to access the key you're expecting.
git checkout
modifies your working tree,git reset
modifies which reference the branch you're on points to,git revert
adds a commit undoing changes.As Doug Currie says use RunAsService.
From my past experience you must remember that the Service you generate will
not sure if the last one still applies ... it was one big night mare in a project I worked on some time ago.
Check the static Nullable.GetUnderlyingType
.
- If the underlying type is null, then the template parameter is not Nullable
, and we can use that type directly
- If the underlying type is not null, then use the underlying type in the conversion.
Seems to work for me:
public object Get( string _toparse, Type _t )
{
// Test for Nullable<T> and return the base type instead:
Type undertype = Nullable.GetUnderlyingType(_t);
Type basetype = undertype == null ? _t : undertype;
return Convert.ChangeType(_toparse, basetype);
}
public T Get<T>(string _key)
{
return (T)Get(_key, typeof(T));
}
public void test()
{
int x = Get<int>("14");
int? nx = Get<Nullable<int>>("14");
}
I would expect that the JVM gracefully interrupts (thread.interrupt()
) all the running threads created by the application, at least for signals SIGINT (kill -2)
and SIGTERM (kill -15)
.
This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.
But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
.
As other users commented, the usage of shutdown hooks seems mandatory.
So, how do I would handle it?
Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM
from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).
As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException
if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException
is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.
So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Interrupting threads");
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
for (Thread th : runningThreads) {
if (th != Thread.currentThread()
&& !th.isDaemon()
&& th.getClass().getName().startsWith("org.brutusin")) {
System.out.println("Interrupting '" + th.getClass() + "' termination");
th.interrupt();
}
}
for (Thread th : runningThreads) {
try {
if (th != Thread.currentThread()
&& !th.isDaemon()
&& th.isInterrupted()) {
System.out.println("Waiting '" + th.getName() + "' termination");
th.join();
}
} catch (InterruptedException ex) {
System.out.println("Shutdown interrupted");
}
}
System.out.println("Shutdown finished");
}
});
Complete test application at github: https://github.com/idelvall/kill-test
What I ended up doing was having the server map any request for an image at that directory to the source that I was trying to update. I then had my timer append a number onto the end of the name so the DOM would see it as a new image and load it.
E.g.
http://localhost/image.jpg
//and
http://localhost/image01.jpg
will request the same image generation code but it will look like different images to the browser.
var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
var count = 0;
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
newImage.src = "http://localhost/image/id/image" + count++ + ".jpg";
}
setTimeout(updateImage, 1000);
}
Use this:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
You have to create the myfile.json before you run the script.
This also works in Java 8 :
Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");
How about sourcing the profile before running the command?
ssh user@host "source /etc/profile; /path/script.sh"
You might find it best to change that to ~/.bash_profile
, ~/.bashrc
, or whatever.
I'm on Linux Mint 19 (Ubuntu 18 based). I wanted to have coredump
files in current folder. I had to do two things:
/proc/sys/kernel/core_pattern
(by # echo "core.%p.%s.%c.%d.%P > /proc/sys/kernel/core_pattern
or by # sysctl -w kernel.core_pattern=core.%p.%s.%c.%d.%P)
$ ulimit -c unlimited
That was written already in the answers, but I wrote to summarize succinctly. Interestingly changing limit did not require root privileges (as per https://askubuntu.com/questions/162229/how-do-i-increase-the-open-files-limit-for-a-non-root-user non-root can only lower the limit, so that was unexpected - comments about it are welcome).
I googled a bit, and found this code here:
File file = getJarFileToLoadFrom();
String lcStr = getNameOfClassToLoad();
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
Can anyone share opinions/comments/answers regarding this approach?
Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.
import pickle
class MyUser(object):
def __init__(self,name):
self.name = name
user = MyUser('Peter')
print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'
with open(filename,'wb') as file_object:
file_object.write(serialized)
with open(filename,'rb') as file_object:
raw_data = file_object.read()
deserialized = pickle.loads(raw_data)
print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array.
How about just plain old js ? example:
autoClick = () => {
if (something === something) {
var link = document.getElementById('dashboard-link');
link.click();
}
};
......
var clickIt = this.autoClick();
return (
<div>
<Link id="dashboard-link" to={'/dashboard'}>Dashboard</Link>
</div>
);
Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :
Dim Splitter() As String
Splitter = Split(AddrMail, ";")
For Each Dest In Splitter
.Recipients.Add (Trim(Dest))
Next
IMHO, He has merit ONLY if he's doing templates and/or metaprogramming. There's plenty of reasons already mentioned that you limit header files to just declarations. They're just that... headers. If you want to include code, you compile it as a library and link it up.
Try this:
Create a model called Profile
and reference the user with a OneToOneField
and provide an option of related_name
.
models.py
from django.db import models
from django.contrib.auth.models import *
from django.dispatch import receiver
from django.db.models.signals import post_save
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
try:
if created:
Profile.objects.create(user=instance).save()
except Exception as err:
print('Error creating user profile!')
Now to directly access the profile using a User
object you can use the related_name
.
views.py
from django.http import HttpResponse
def home(request):
profile = f'profile of {request.user.user_profile}'
return HttpResponse(profile)
You need to make a class library and not a Console Application. The console application is translated into an .exe
whereas the class library will then be compiled into a dll
which you can reference in your windows project.
along with below command line parameters ,
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
Sometimes in the linux servers , imx connection doesn't get succeeded. that is because , in cloud linux host, in /etc/hosts so that the hostname resolves to the host address.
the best way to fix it is, ping the particular linux server from other machine in network and use that host IP address in the
-Djava.rmi.server.hostname=IP address that obtained when you ping that linux server.
But never rely on the ipaddress that you get from linux server using ifconfig.me. the ip that you get there is masked one which is present in the host file.
#include <iostream>
using namespace std;
int main()
{
int n1 ;
cout <<"Please enter five digits number: ";
cin >> n1;
cout << n1 / 10000 % 10 << " ";
cout << n1 / 1000 % 10 << " ";
cout << n1 / 100 % 10 << " ";
cout << n1 / 10 % 10 << " ";
cout << n1 % 10 << " :)";
cout << endl;
return 0;
}
I encapsulated the logic in the following helper method.
public class JpaResultHelper {
public static Object getSingleResultOrNull(Query query){
List results = query.getResultList();
if (results.isEmpty()) return null;
else if (results.size() == 1) return results.get(0);
throw new NonUniqueResultException();
}
}
If you are just looking for a lightweight way to save some or all of your current working copy changes and then reapply them later at will, consider a patch file:
# save your working copy changes
git diff > some.patch
# re-apply it later
git apply some.patch
Every now and then I wonder if I should be using stashes for this and then I see things like the insanity above and I'm content with what I'm doing :)
FirebaseInstanceIdService
This class is deprecated. In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.
The new way to do this would be to override the onNewToken
method from FirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
}
Also dont forget to add the service in the Manifest.xml
<service
android:name=".MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Created Pipe for sorting. Accepts both string and array of strings, sorting by multiple values. Works for Angular (not AngularJS). Supports both sort for string and numbers.
@Pipe({name: 'orderBy'})
export class OrderBy implements PipeTransform {
transform(array: any[], filter: any): any[] {
if(typeof filter === 'string') {
return this.sortAray(array, filter)
} else {
for (var i = filter.length -1; i >= 0; i--) {
array = this.sortAray(array, filter[i]);
}
return array;
}
}
private sortAray(array, field) {
return array.sort((a, b) => {
if(typeof a[field] !== 'string') {
a[field] !== b[field] ? a[field] < b[field] ? -1 : 1 : 0
} else {
a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0
}
});
}
}
It's still valid to use IE=edge,chrome=1.
But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.
I use the following for correctness nowadays
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete
This is using dataframes from the pandas
package. The "index" part can be either a single index, a list of indices, or a list of booleans. This can be read about in the documentation: https://pandas.pydata.org/pandas-docs/stable/indexing.html
So the index
part specifies a subset of the rows to pull out, and the (optional) column_name
specifies the column you want to work with from that subset of the dataframe. So if you want to update the 'class' column but only in rows where the class is currently set as 'versicolor', you might do something like what you list in the question:
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
first delete all tables of the database in the localhost
Change Laravel default database (utf8mb4) properties in file config/database.php to:
'charset' => 'utf8', 'collation' => 'utf8_unicode_ci',
after then Changing my local database properties utf8_unicode_ci. php artisan migrate it is ok.
In this code we define a method and then we can simply call it. we give it two parameters. first one is text and the second one should be count of characters that you wanna display.
function the_excerpt(string $text,int $length){
if(strlen($text) > $length){$text = substr($text,0,$length);}
return $text;
}
you have to tell angular
that you updated the content after ngAfterContentChecked
you can import ChangeDetectorRef
from @angular/core
and call detectChanges
import {ChangeDetectorRef } from '@angular/core';
constructor( private cdref: ChangeDetectorRef ) {}
ngAfterContentChecked() {
this.sampleViewModel.DataContext = this.DataContext;
this.sampleViewModel.Position = this.Position;
this.cdref.detectChanges();
}
$dateString = '08/04/2010 22:15:00';
$dateObject = new DateTime($dateString);
echo $dateObject->format('h:i A');
I had this problem and tried various solutions to solve it including many of those listed above (config file, debug ssh etc). In the end, I resolved it by including the -u switch in the git push, per the github instructions when creating a new repository onsite - Github new Repository
Spinner sp = (Spinner)findViewById(R.id.spinner);
sp.setSelection(pos);
here pos is integer (your array item position)
array is like below then pos = 0;
String str[] = new String{"Select Gender","male", "female" };
then in onItemSelected
@Override
public void onItemSelected(AdapterView<?> main, View view, int position,
long Id) {
if(position > 0){
// get spinner value
}else{
// show toast select gender
}
}
Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).
If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.
For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.
For example:
Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
For the listed three conditions only, these expressions might work also:
^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$
If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:
123451234
12345 1234
12345 1234
this expression for instance would be a secondary option with less constraints:
^\d{5}([-]|\s*)?(\d{4})?$
jex.im visualizes regular expressions:
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345 1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
You can just do it like this:
#content {
position: relative;
}
#content img {
position: absolute;
top: 0px;
right: 0px;
}
<div id="content">
<img src="images/ribbon.png" class="ribbon"/>
<div>some text...</div>
</div>
read
is a shell builtin command that prints to stderr, and can be used like echo without performing redirection tricks:
read -t 0.1 -p "This will be sent to stderr"
The -t 0.1
is a timeout that disables read's main functionality, storing one line of stdin into a variable.
Clearly you're passing in d.keys()
to your shuffle
function. Probably this was written with python2.x (when d.keys()
returned a list). With python3.x, d.keys()
returns a dict_keys
object which behaves a lot more like a set
than a list
. As such, it can't be indexed.
The solution is to pass list(d.keys())
(or simply list(d)
) to shuffle
.
The error message is correct (if not very helpful): the file we're trying to load is not a file on the filesystem, but a chunk of bytes in a ZIP inside a ZIP.
Through experimentation (Java 11, Spring Boot 2.3.x), I found this to work without changing any config or even a wildcard:
var resource = ResourceUtils.getURL("classpath:some/resource/in/a/dependency");
new BufferedReader(
new InputStreamReader(resource.openStream())
).lines().forEach(System.out::println);
Avoiding Select
and Activate
is the move that makes you a bit better VBA developer. In general, Select
and Activate
are used when a macro is recorded, thus the Parent
worksheet or range is always considered the active one.
This is how you may avoid Select
and Activate
in the following cases:
From (code generated with macro recorder):
Sub Makro2()
Range("B2").Select
Sheets.Add After:=ActiveSheet
Sheets("Tabelle1").Select
Sheets("Tabelle1").Name = "NewName"
ActiveCell.FormulaR1C1 = "12"
Range("B2").Select
Selection.Copy
Range("B3").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
To:
Sub TestMe()
Dim ws As Worksheet
Set ws = Worksheets.Add
With ws
.Name = "NewName"
.Range("B2") = 12
.Range("B2").Copy Destination:=.Range("B3")
End With
End Sub
From:
Sheets("Source").Select
Columns("A:D").Select
Selection.Copy
Sheets("Target").Select
Columns("A:D").Select
ActiveSheet.Paste
To:
Worksheets("Source").Columns("A:D").Copy Destination:=Worksheets("Target").Range("a1")
You may access them with []
, which is really beautiful, compared to the other way. Check yourself:
Dim Months As Range
Dim MonthlySales As Range
Set Months = Range("Months")
Set MonthlySales = Range("MonthlySales")
Set Months =[Months]
Set MonthlySales = [MonthlySales]
The example from above would look like this:
Worksheets("Source").Columns("A:D").Copy Destination:=Worksheets("Target").[A1]
Usually, if you are willing to select
, most probably you are copying something. If you are only interested in the values, this is a good option to avoid select:
Range("B1:B6").Value = Range("A1:A6").Value
This is probably the most common mistake in vba. Whenever you copy ranges, sometimes the worksheet is not referenced and thus VBA considers the wrong sheet the ActiveWorksheet.
'This will work only if the 2. Worksheet is selected!
Public Sub TestMe()
Dim rng As Range
Set rng = Worksheets(2).Range(Cells(1, 1), Cells(2, 2)).Copy
End Sub
'This works always!
Public Sub TestMe2()
Dim rng As Range
With Worksheets(2)
.Range(.Cells(1, 1), .Cells(2, 2)).Copy
End With
End Sub
.Select
or .Activate
for anything?.Activate
and .Select
is when you want make sure that a specific Worksheet is selected for visual reasons. E.g., that your Excel would always open with the cover worksheet selected first, disregarding which which was the ActiveSheet when the file was closed.Thus, something like the code below is absolutely OK:
Private Sub Workbook_Open()
Worksheets("Cover").Activate
End Sub
Another good example is when you need to export all sheets into one PDF file, as mentioned in this case - How to avoid select/active statements in VBA in this example?
When a command only works with ActiveWindow
like ActiveWindow.Zoom or ActiveWindow.FreezePanes
You cannot check window.history.length
as it contains the amount of pages in you visited in total in a given session:
window.history.length
(Integer)Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1
Lets say a user visits your page, clicks on some links and goes back:
www.mysite.com/index.html <-- first page and now current page <----+ www.mysite.com/about.html | www.mysite.com/about.html#privacy | www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back
Now window.history.length
is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.
You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:
window.goBack = function (e){
var defaultLocation = "http://www.mysite.com";
var oldHash = window.location.hash;
history.back(); // Try to go back
var newHash = window.location.hash;
/* If the previous page hasn't been loaded in a given time (in this case
* 1000ms) the user is redirected to the default location given above.
* This enables you to redirect the user to another page.
*
* However, you should check whether there was a referrer to the current
* site. This is a good indicator for a previous entry in the history
* session.
*
* Also you should check whether the old location differs only in the hash,
* e.g. /index.html#top --> /index.html# shouldn't redirect to the default
* location.
*/
if(
newHash === oldHash &&
(typeof(document.referrer) !== "string" || document.referrer === "")
){
window.setTimeout(function(){
// redirect to default location
window.location.href = defaultLocation;
},1000); // set timeout in ms
}
if(e){
if(e.preventDefault)
e.preventDefault();
if(e.preventPropagation)
e.preventPropagation();
}
return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>
Note that typeof(document.referrer) !== "string"
is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.
EDIT: Don't use <a href='#'>...</a>
, as this will add another entry to the session history. It's better to use a <span>
or some other element. Note that typeof document.referrer
is always "string"
and not empty if your page is inside of a (i)frame.
See also:
In Laravel 5+, to set a variable just once and access it 'globally', I find it easiest to just add it as an attribute to the Request:
$request->attributes->add(['myVar' => $myVar]);
Then you can access it from any of your controllers using:
$myVar = $request->get('myVar');
and from any of your blades using:
{{ Request::get('myVar') }}
You can use html and be a boss with simple things :
<embed src="music.mp3" width="3000" height="200" controls>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Data.SqlClient;
public partial class ExcuteScript : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";
string script = File.ReadAllText(@"E:\Project Docs\MX462-PD\MX756_ModMappings1.sql");
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
I came across the same problem and solved it as following for VB.NET. It's the .NET Framework so you should be possible to adapt. Wanted to compare my solution and now I see that nobody seems to solve it my way.
Make a field declaration.
Private _currentDataView as DataView
So looping through all the rows and searching for a cell containing a value that I know is next to the cell I want to change works for me.
Public Sub SetCellValue(ByVal value As String)
Dim dataView As DataView = _currentDataView
For i As Integer = 0 To dataView.Count - 1
If dataView(i).Row.Item("projID").ToString.Equals("139") Then
dataView(i).Row.Item("Comment") = value
Exit For ' Exit early to save performance
End If
Next
End Sub
So that you can better understand it. I know that ColumnName "projID" is 139. I loop until I find it and then I can change the value of "ColumnNameofCell" in my case "Comment". I use this for comments added on runtime.
Maintain a set
and remove a randomly picked-up element (with choice
) until the list is empty:
s = set(range(1, 6))
import random
while len(s) > 0:
s.remove(random.choice(list(s)))
print(s)
Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
$("#foo > div").length
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.
Even better: use the inspect.isclass
function.
>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
>>> x = X()
>>> isinstance(x, X)
True
>>> y = 25
>>> isinstance(y, X)
False
The first one catches all subclasses of Throwable
(this includes Exception
and Error
), the second one catches all subclasses of Exception
.
Error
is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception
is programmatically recoverable. Its subclass RuntimeException
indicates a programming error and is usually not to be caught as well.
Here it was caused by avast antivirus. You can disable the avast firewall and let only windows firewall active.
I wrote a blog post about it: http://blogs.msdn.com/kirillosenkov/archive/2009/01/31/foreach.aspx
You can vote here if you'd like to see this method in .NET 4.0: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=279093
You just need to change directories to your app, THEN run bundle install
:)
Split is slow, but not as slow as Scanner. StringTokenizer is faster than split. However, I found that I could obtain double the speed, by trading some flexibility, to get a speed-boost, which I did at JFastParser https://github.com/hughperkins/jfastparser
Testing on a string containing one million doubles:
Scanner: 10642 ms
Split: 715 ms
StringTokenizer: 544ms
JFastParser: 290ms
Using the example posted by Brock, I modified it so that it is a category of UIView instead UIViewController and made it recursive so that any subview can (hopefully) find the parent UIViewController.
@interface UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController;
- (id) traverseResponderChainForUIViewController;
@end
@implementation UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController {
// convenience function for casting and to "mask" the recursive function
return (UIViewController *)[self traverseResponderChainForUIViewController];
}
- (id) traverseResponderChainForUIViewController {
id nextResponder = [self nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return nextResponder;
} else if ([nextResponder isKindOfClass:[UIView class]]) {
return [nextResponder traverseResponderChainForUIViewController];
} else {
return nil;
}
}
@end
To use this code, add it into an new class file (I named mine "UIKitCategories") and remove the class data... copy the @interface into the header, and the @implementation into the .m file. Then in your project, #import "UIKitCategories.h" and use within the UIView code:
// from a UIView subclass... returns nil if UIViewController not available
UIViewController * myController = [self firstAvailableUIViewController];
In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)
Use the code below. It works every time.
<button onclick="self.close()">Close</button>
It works every time in Chrome and also works on Firefox.
You need to create new Book
objects then put those in a new List
:
List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList();
Update: Slightly simpler... List<T>
has a method called ConvertAll
that returns a new list:
List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));
This continues to frequently gather additional votes, even several years later, and so I need to update it for modern versions of Sql Server. For Sql Server 2008 and later, it's simple:
cast(getDate() As Date)
Note that the last three paragraphs near the bottom still apply, and you often need to take a step back and find a way to avoid the cast in the first place.
But there are other ways to accomplish this, too. Here are the most common.
The correct way (new since Sql Server 2008):
cast(getdate() As Date)
The correct way (old):
dateadd(dd, datediff(dd,0, getDate()), 0)
This is older now, but it's still worth knowing because it can also easily adapt for other time points, like the first moment of the month, minute, hour, or year.
This correct way uses documented functions that are part of the ansi standard and are guaranteed to work, but it can be somewhat slower. It works by finding how many days there are from day 0 to the current day, and adding that many days back to day 0. It will work no matter how your datetime is stored and no matter what your locale is.
The fast way:
cast(floor(cast(getdate() as float)) as datetime)
This works because datetime columns are stored as 8-byte binary values. Cast them to float, floor them to remove the fraction, and the time portion of the values are gone when you cast them back to datetime. It's all just bit shifting with no complicated logic and it's very fast.
Be aware this relies on an implementation detail Microsoft is free to change at any time, even in an automatic service update. It's also not very portable. In practice, it's very unlikely this implementation will change any time soon, but it's still important to be aware of the danger if you choose to use it. And now that we have the option to cast as a date, it's rarely necessary.
The wrong way:
cast(convert(char(11), getdate(), 113) as datetime)
The wrong way works by converting to a string, truncating the string, and converting back to a datetime. It's wrong, for two reasons: 1)it might not work across all locales and 2) it's about the slowest possible way to do this... and not just a little; it's like an order of magnitude or two slower than the other options.
Update This has been getting some votes lately, and so I want to add to it that since I posted this I've seen some pretty solid evidence that Sql Server will optimize away the performance difference between "correct" way and the "fast" way, meaning you should now favor the former.
In either case, you want to write your queries to avoid the need to do this in the first place. It's very rare that you should do this work on the database.
In most places, the database is already your bottleneck. It's generally the server that's the most expensive to add hardware to for performance improvements and the hardest one to get those additions right (you have to balance disks with memory, for example). It's also the hardest to scale outward, both technically and from a business standpoint; it's much easier technically to add a web or application server than a database server and even if that were false you don't pay $20,000+ per server license for IIS or apache.
The point I'm trying to make is that whenever possible you should do this work at the application level. The only time you should ever find yourself truncating a datetime on Sql Server is when you need to group by the day, and even then you should probably have an extra column set up as a computed column, maintained at insert/update time, or maintained in application logic. Get this index-breaking, cpu-heavy work off your database.
Another reason that it's a good idea to write both declarations and definitions in header files is for readability. Suppose there's such a template function in Utility.h:
template <class T>
T min(T const& one, T const& theOther);
And in the Utility.cpp:
#include "Utility.h"
template <class T>
T min(T const& one, T const& other)
{
return one < other ? one : other;
}
This requires every T class here to implement the less than operator (<). It will throw a compiler error when you compare two class instances that haven't implemented the "<".
Therefore if you separate the template declaration and definition, you won't be able to only read the header file to see the ins and outs of this template in order to use this API on your own classes, though the compiler will tell you in this case about which operator needs to be overridden.
A rough description of how a system takes any recursive function and executes it using a stack:
This intended to show the idea without details. Consider this function that would print out nodes of a graph:
function show(node)
0. if isleaf(node):
1. print node.name
2. else:
3. show(node.left)
4. show(node)
5. show(node.right)
For example graph: A->B A->C show(A) would print B, A, C
Function calls mean save the local state and the continuation point so you can come back, and then jump the the function you want to call.
For example, suppose show(A) begins to run. The function call on line 3. show(B) means - Add item to the stack meaning "you'll need to continue at line 2 with local variable state node=A" - Goto line 0 with node=B.
To execute code, the system runs through the instructions. When a function call is encountered, the system pushes information it needs to come back to where it was, runs the function code, and when the function completes, pops the information about where it needs to go to continue.
you can only make circle from square using border-radius.
border-radius doesn't increase or reduce heights nor widths.
Your request is to use only image tag , it is basicly not possible if tag is not a square.
If you want to use a blank image and set another in bg, it is going to be painfull , one background for each image to set.
Cropping can only be done if a wrapper is there to do so. inthat case , you have many ways to do it
Sets are faster, morover you get more functions with sets, such as lets say you have two sets :
set1 = {"Harry Potter", "James Bond", "Iron Man"}
set2 = {"Captain America", "Black Widow", "Hulk", "Harry Potter", "James Bond"}
We can easily join two sets:
set3 = set1.union(set2)
Find out what is common in both:
set3 = set1.intersection(set2)
Find out what is different in both:
set3 = set1.difference(set2)
And much more! Just try them out, they are fun! Moreover if you have to work on the different values within 2 list or common values within 2 lists, I prefer to convert your lists to sets, and many programmers do in that way. Hope it helps you :-)
Apparently no one has come up with a multi-platform* solution for over a decade since [the] year 2008, so I shall append mine . Plz upvote. (Joking. I don’t care.)
lltoa()
How to use:
#include <stdlib.h> /* lltoa() */
// ...
char dummy[255];
printf("Over 4 bytes: %s\n", lltoa(5555555555, dummy, 10));
printf("Another one: %s\n", lltoa(15555555555, dummy, 10));
OP’s example:
#include <stdio.h>
#include <stdlib.h> /* lltoa() */
int main() {
unsigned long long int num = 285212672; // fits in 29 bits
char dummy[255];
int normalInt = 5;
printf("My number is %d bytes wide and its value is %s. "
"A normal number is %d.\n",
sizeof(num), lltoa(num, dummy, 10), normalInt);
return 0;
}
Unlike the %lld
print format string, this one works for me under 32-bit GCC on Windows.
*) Well, almost multi-platform. In MSVC, you apparently need _ui64toa()
instead of lltoa()
.
If it's a CLOB why can't we to_char the column and then search normally ?
Create a table
CREATE TABLE MY_TABLE(Id integer PRIMARY KEY, Name varchar2(20), message clob);
Create few records in this table
INSERT INTO MY_TABLE VALUES(1,'Tom','Hi This is Row one');
INSERT INTO MY_TABLE VALUES(2,'Lucy', 'Hi This is Row two');
INSERT INTO MY_TABLE VALUES(3,'Frank', 'Hi This is Row three');
INSERT INTO MY_TABLE VALUES(4,'Jane', 'Hi This is Row four');
INSERT INTO MY_TABLE VALUES(5,'Robert', 'Hi This is Row five');
COMMIT;
Search in the clob column
SELECT * FROM MY_TABLE where to_char(message) like '%e%';
Results
ID NAME MESSAGE
===============================
1 Tom Hi This is Row one
3 Frank Hi This is Row three
5 Robert Hi This is Row five
If you're using it in several different places, you should turn it into a plugin.
jQuery.fn.fadeOutAndRemove = function(speed){
$(this).fadeOut(speed,function(){
$(this).remove();
})
}
And then:
// Somewhere in the program code.
$('div').fadeOutAndRemove('fast');
Bit-shifts are only defined up to a shift-amount of 31 (on a 32 bit integer)..
What do you do if you want to have a computed shift that need to work with higher shift-values as well? Here is how the Theora vide-codec does it:
unsigned int shiftmystuff (unsigned int a, unsigned int v)
{
return (a>>(v>>1))>>((v+1)>>1);
}
Or much more readable:
unsigned int shiftmystuff (unsigned int a, unsigned int v)
{
unsigned int halfshift = v>>1;
unsigned int otherhalf = (v+1)>>1;
return (a >> halfshift) >> otherhalf;
}
Performing the task the way shown above is a good deal faster than using a branch like this:
unsigned int shiftmystuff (unsigned int a, unsigned int v)
{
if (v<=31)
return a>>v;
else
return 0;
}
Here are two examples of how to generate graphs in separate windows (frames), and, an example of how to generate graphs and save them into separate graphics files.
Okay, first the on-screen example. Notice that we use a separate instance of plt.figure(), for each graph, with plt.plot(). At the end, we have to call plt.show() to put it all on the screen.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.show()
Another way to do this, is to use plt.show(block=False) inside the loop:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.show( block=False )
Now, let's generate the graphs and instead, write them each to a file. Here we replace plt.show(), with plt.savefig( filename ). The difference from the previous example is that we don't have to account for ''blocking'' at each graph. Note also, that we number the file names. Here we use %03d so that we can conveniently have them in number order afterwards.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.savefig('myfilename%03d.png'%(n))
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
pip install django-truncate
settings.py
file:INSTALLED_APPS = [
...
'django_truncate',
]
python manage.py truncate --apps app_name --models table_name
Sample 1: This works and produces Exit code = 0. That is Good. Note the "." , directly after echo.
C:\Users\phife.dog\gitrepos\1\repo_abc\scripts #
@echo.| set /p JUNK_VAR=This is a message displayed like Linux echo -n would display it ... & echo %ERRORLEVEL%
This is a message displayed like Linux echo -n would display it ... 0
Sample 2: This works but produces Exit code = 1. That is Bad. Please note the lack of ".", after echo. That appears to be the difference.
C:\Users\phife.dog\gitrepos\1\repo_abc\scripts #
@echo | set /p JUNK_VAR=This is a message displayed like Linux echo -n would display it ... & echo %ERRORLEVEL%
This is a message displayed like Linux echo -n would display it ... 1
Try this
<script>
$().ready(function(){
$('.coupon_question').live('click',function()
{
if ($('.coupon_question').is(':checked')) {
$(".answer").show();
} else {
$(".answer").hide();
}
});
});
</script>
Technically, Node.js isn't proper JavaScript as we know it, since there isn't a Document Object Model (DOM). For instance, JavaScript scripts that run in the browser will not work. At all. The solution would be to run JavaScript with a headless browser. Fortunately there is a project still active: Mozilla Firefox has a headless mode.
https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode
$ /Applications/Firefox.app/Contents/MacOS/firefox -headless index.html
*** You are running in headless mode.
Try the following I found Here's a link
If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.
EasyImage.openCamera(Activity activity, int type);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
@Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
//Some error handling
}
@Override
public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
//Handle the images
onPhotosReturned(imagesFiles);
}
});
}
For Mysql please see the LOAD XML
SyntaxDocs.
It should work without any additional XML transformation for the XML you've provided, just specify the format and define the table inside the database firsthand with matching column names:
LOAD XML LOCAL INFILE 'table1.xml'
INTO TABLE table1
ROWS IDENTIFIED BY '<table1>';
There is also a related question:
For Postgresql I do not know.
Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.
This worked for me:
char yyy[6];
String xxx;
yyy[0]='h';
yyy[1]='e';
yyy[2]='l';
yyy[3]='l';
yyy[4]='o';
yyy[5]='\0';
xxx=String(yyy);
You have to use parseInt() to convert
For eg.
var z = parseInt(x) + parseInt(y);
use parseFloat() if you want to handle float value.
You can also use f
or x
to focus or exclude a test. For example
fit('only this test will run', () => {
expect(true).toBe(false);
});
it('this test will not run', () => {
expect(true).toBe(false);
});
xit('this test will be ignored', () => {
expect(true).toBe(false);
});
I think you can use function htonl()
. Network byte order is big endian.
For Linux and OSX
Step 1: Download chromedriver
# You can find more recent/older versions at http://chromedriver.storage.googleapis.com/
# Also make sure to pick the right driver, based on your Operating System
wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip
For debian: wget https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip
Step 2: Add chromedriver to /usr/local/bin
unzip chromedriver_mac64.zip
sudo mv chromedriver /usr/local/bin
sudo chown root:root /usr/local/bin/chromedriver
sudo chmod +x /usr/local/bin/chromedriver
You should now be able to run
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://localhost:8000')
without any issues
If the logic for choosing the files is not trivial, I would trigger script execution on each change and then write a script to check if indeed a build is required, then triggering a build if it is.
Several definitions of the same name
<C-w>g<C-]>
open the definition in a split, but also do :tjump
which either goes to the definition or, if there are several definitions, presents you with a list of definitions to choose from.
When you create a StreamWriter
it always create a file from scratch, you will have to create a third file and copy from target and replace what you need, and then replace the old one.
But as I can see what you need is XML manipulation, you might want to use XmlDocument
and modify your file using Xpath.
It has 2 possible solutions:
1) You can set it in the view by javascript... (not recomended)
<input class="form-control"
type="text"
id="tbFormControll"
th:field="*{clientName}"/>
<script type="text/javascript">
document.getElementById("tbFormControll").value = "default";
</script>
2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.
public class FormControllModel {
...
private String clientName = "default";
public String getClientName () {
return clientName;
}
public void setClientName (String value) {
clientName = value;
}
...
}
I hope it helps.
Arrays in PHP can have Key Value structure.
There's obviously more than one way to do it, but I would suggest using the more standard:
ErrorDocument 404 /index.php?page=404
// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};
// First position
double firstNum = array_doubles[0]; // 2.5
// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6
This is the same in any array.
In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at
It's the second file input; the first with information in it.
If it's not clear, [redacted]
should be replaced with the local file path to your .m2 folder.
If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.
If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
</settings>
You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository
. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.
Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>
. See Maven — Settings Reference for more information.
Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.
If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings
and <localRepository>
should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.
I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.
Why use LEN so you have 2 string functions? All you need is character 5 on...
...SUBSTRING (Code1, 5, 8000)...
The Go blog: Go maps in action has an excellent explanation.
When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. If you require a stable iteration order you must maintain a separate data structure that specifies that order.
Here's my modified version of example code: http://play.golang.org/p/dvqcGPYy3-
package main
import (
"fmt"
"sort"
)
func main() {
// To create a map as input
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"
// To store the keys in slice in sorted order
keys := make([]int, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Ints(keys)
// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}
Output:
Key: 0 Value: b
Key: 1 Value: a
Key: 2 Value: c
Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.
Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:
num_list[-9:]
When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")
The full notation is
sequence[start:stop:step]
But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is
list_copy = sequence[:]
And clearing them is with:
del my_list[:]
(Lists get list.copy
and list.clear
in Python 3.)
You may find it useful to separate forming the slice from passing it to the list.__getitem__
method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.
However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:
last_nine_slice = slice(-9, None)
The second argument, None
, is required, so that the first argument is interpreted as the start
argument otherwise it would be the stop
argument.
You can then pass the slice object to your sequence:
>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]
islice
islice
from the itertools module is another possibly performant way to get this. islice
doesn't take negative arguments, so ideally your iterable has a __reversed__
special method - which list does have - so you must first pass your list (or iterable with __reversed__
) to reversed
.
>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>
islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list
):
>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]
Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:
public function up()
{
Schema::create('trip_table', function (Blueprint $table) {
$table->increments('trip_id')->unsigned();
$table->time('est_start');
$table->time('est_end');
$table->time('act_start')->nullable();
$table->time('act_end')->nullable();
$table->date('Trip_Date');
$table->integer('Starting_Miles')->nullable();
$table->integer('Ending_Miles')->nullable();
$table->string('Bus_id')->nullable();
$table->string('Event');
$table->string('Desc')->nullable();
$table->string('Destination');
$table->string('Departure_location');
$table->text('Drivers_Comment')->nullable();
$table->string('Requester')->nullable();
$table->integer('driver_id')->nullable();
$table->timestamps();
});
}
The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!
I don't think there is anything built-in, but you can do it by leaving more space above your axes and using figtext
:
axes([.1,.1,.8,.7])
figtext(.5,.9,'Foo Bar', fontsize=18, ha='center')
figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center')
ha
is short for horizontalalignment
.
you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
Yes it's Immutable
sum.add(BigInteger.valueOf(i));
so the method add() of BigInteger class does not add new BigIntger value to its own value ,but creates and returns a new BigInteger reference without changing the current BigInteger and this is what done even in the case of Strings
In case you want a nice no dependencies copy-paste solution. Grab the code below.
MyObject myObject = ...
byte[] bytes = SerializeUtils.serialize(myObject);
myObject = SerializeUtils.deserialize(bytes);
import java.io.*;
public class SerializeUtils {
public static byte[] serialize(Serializable value) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try(ObjectOutputStream outputStream = new ObjectOutputStream(out)) {
outputStream.writeObject(value);
}
return out.toByteArray();
}
public static <T extends Serializable> T deserialize(byte[] data) throws IOException, ClassNotFoundException {
try(ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
//noinspection unchecked
return (T) new ObjectInputStream(bis).readObject();
}
}
}
Your getAll()
method does not get all. It returns the first car.
The return
statement terminates the loop.
If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:
CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);
At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345"
) instead of a fractional value (e.g. "12345.0"
). Note that setCellType
is available in interface Cell
(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase
. Obviously, it would be nicer either to have getRawValue
in the Cell
interface or at least to be able use getStringCellValue
on non STRING cell types. Unfortunately, all replacements of setCellType
mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).
A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.
For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).
EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.
I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:
This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.
Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".
So in your case the JSTL code should look like the following, note the capital 'P':
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
If number
could be None
or a number, and you wanted to include 0
, filter on None
instead:
if number is not None:
If number
can be any number of types, test for the type; you can test for just int
or a combination of types with a tuple:
if isinstance(number, int): # it is an integer
if isinstance(number, (int, float)): # it is an integer or a float
or perhaps:
from numbers import Number
if isinstance(number, Number):
to allow for integers, floats, complex numbers, Decimal
and Fraction
objects.
I have written a java example for this case:
Use json.org library to retrieve JSONObjects and JSONArrays. The example below uses blockchain.info's data which can be obtained as JSONObject.
public class main
{
public static void main(String[] args) throws MalformedURLException, IOException
{
JSONObject data = getJSONfromURL("https://blockchain.info/charts/market-price?format=json");
JSONArray data_array = data.getJSONArray("values");
for (int i = 0; i < data_array.length(); i++)
{
JSONObject price_point = data_array.getJSONObject(i);
// Unix time
int x = price_point.getInt("x");
// Bitcoin price at that time
double y = price_point.getDouble("y");
// Do something with x and y.
}
}
public static JSONObject getJSONfromURL(String URL)
{
try
{
URLConnection uc;
URL url = new URL(URL);
uc = url.openConnection();
uc.setConnectTimeout(10000);
uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
uc.connect();
BufferedReader rd = new BufferedReader(
new InputStreamReader(uc.getInputStream(),
Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1)
{
sb.append((char)cp);
}
String jsonText = (sb.toString());
return new JSONObject(jsonText.toString());
} catch (IOException ex)
{
return null;
}
}
}
I had this issue with npm v1.1.4
(and node v0.6.12
), which are the Ubuntu 12.04
repository versions.
It looks like that version of npm
isn't supported any more, updating node (and npm with it) resolved the issue.
First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).
sudo apt-get purge nodejs npm
Then enable nodesource's repo and install:
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs
Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:
From: here
For 3-D visualization pythreejs is the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless.
A more advanced library is bqplot which is a d3-based interactive viz library for the iPython notebook, but it only does 2D
I tried the first few solutions and didn't work for me. Mainly the problem with attributes being removed like the other have already mentioned. I would say my approach is very similar to Jimmy by using the XElement constructors that taking object as parameters.
public static XElement RemoveAllNamespaces(this XElement element)
{
return new XElement(element.Name.LocalName,
element.HasAttributes ? element.Attributes().Select(a => new XAttribute(a.Name.LocalName, a.Value)) : null,
element.HasElements ? element.Elements().Select(e => RemoveAllNamespaces(e)) : null,
element.Value);
}
First, your success()
handler just returns the data, but that's not returned to the caller of getData()
since it's already in a callback. $http
is an asynchronous call that returns a $promise
, so you have to register a callback for when the data is available.
I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.
For simplicity, here's your same code re-written with a function callback provided by the calling controller:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
Now, $http
actually already returns a $promise, so this can be re-written:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
Finally, there's better ways to configure the $http
service to handle the headers for you using config()
to setup the $httpProvider
. Checkout the $http documentation for examples.
Use the vectorised str
method replace
:
In [30]:
df['range'] = df['range'].str.replace(',','-')
df
Out[30]:
range
0 (2-30)
1 (50-290)
EDIT
So if we look at what you tried and why it didn't work:
df['range'].replace(',','-',inplace=True)
from the docs we see this desc:
str or regex: str: string exactly matching to_replace will be replaced with value
So because the str values do not match, no replacement occurs, compare with the following:
In [43]:
df = pd.DataFrame({'range':['(2,30)',',']})
df['range'].replace(',','-', inplace=True)
df['range']
Out[43]:
0 (2,30)
1 -
Name: range, dtype: object
here we get an exact match on the second row and the replacement occurs.
Yes you can do it using the JsonConvert.DeserializeObject. To do that, just simple do:
dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);
Paint DOES have set color function.
/**
* Set the paint's color. Note that the color is an int containing alpha
* as well as r,g,b. This 32bit value is not premultiplied, meaning that
* its alpha can be any value, regardless of the values of r,g,b.
* See the Color class for more details.
*
* @param color The new color (including alpha) to set in the paint.
*/
public native void setColor(@ColorInt int color);
As an Android developer, I set paint color like this...
paint.setColor(getResources().getColor(R.color.xxx));
I define the color value on color.xml something like...
<color name="xxx">#008fd2</color>
By the way if you want to the hex RGB value of specific color value, then you can check website like this: http://www.rapidtables.com/web/color/RGB_Color.htm
I hope this helps ! Enjoy coding!
I'm created RunApp to do such a job and also using it in my production env, hope it's helps.
The config like below:
file: config.arg
:style:hidden
MyBatchFile.bat
arg1
arg2
And launch runapp.exe
instead.
Code:
function textToBin(text) {
var length = text.length,
output = [];
for (var i = 0;i < length; i++) {
var bin = text[i].charCodeAt().toString(2);
output.push(Array(8-bin.length+1).join("0") + bin);
}
return output.join(" ");
}
textToBin("!a") => "00100001 01100001"
Another way
function textToBin(text) {
return (
Array
.from(text)
.reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
.map(bin => '0'.repeat(8 - bin.length) + bin )
.join(' ')
);
}
You need to escape the .
as "0\.49"
.
A .
is a regex meta-character to match any character(except newline). To match a literal period, you need to escape it.
I prefer using filter (https://docs.python.org/2/library/functions.html#filter), but this is just a matter of taste.
d='.'
filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d))
Use the timeIntervalSinceDate
method
NSTimeInterval secondsElapsed = [secondDate timeIntervalSinceDate:firstDate];
NSTimeInterval
is just a double
, define in NSDate
like this:
typedef double NSTimeInterval;
if you want to kill a specific node process , you can go to command line route and type:
ps aux | grep node
to get a list of all node process ids. now you can get your process id(pid), then do:
kill -9 PID
and if you want to kill all node processes then do:
killall -9 node
-9 switch is like end task on windows. it will force the process to end. you can do:
kill -l
to see all switches of kill command and their comments.
Please try:
declare @var nvarchar(max)='Balance1000sheet'
SELECT LEFT(Val,PATINDEX('%[^0-9]%', Val+'a')-1) from(
SELECT SUBSTRING(@var, PATINDEX('%[0-9]%', @var), LEN(@var)) Val
)x
Using the AWS Management Console
you can add an invisible TextView to the FrameLayout.
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:visibility="invisible"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<Button
android:id="@+id/daily_delete_btn"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="DELETE"
android:layout_gravity="center"/>
<Button
android:id="@+id/daily_save_btn"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="SAVE"
android:layout_gravity="center"/>
</LinearLayout>
The origin of this error lies in the fact that each and every promise is expected to handle promise rejection i.e. have a .catch(...) . you can avoid the same by adding .catch(...) to a promise in the code as given below.
for example, the function PTest() will either resolve or reject a promise based on the value of a global variable somevar
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
}).catch(function () {
console.log("Promise Rejected");
});
In some cases, the "unhandled promise rejection" message comes even if we have .catch(..) written for promises. It's all about how you write your code. The following code will generate "unhandled promise rejection" even though we are handling catch
.
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
});
// See the Difference here
myfunc.catch(function () {
console.log("Promise Rejected");
});
The difference is that you don't handle .catch(...)
as chain but as separate. For some reason JavaScript engine treats it as promise without un-handled promise rejection.
These two style of filtering are equivalent in most cases, but when query on objects base on ForeignKey or ManyToManyField, they are slightly different.
Examples from the documentation.
model
Blog to Entry is a one-to-many relation.
from django.db import models
class Blog(models.Model):
...
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
pub_date = models.DateField()
...
objects
Assuming there are some blog and entry objects here.
queries
Blog.objects.filter(entry__headline_contains='Lennon',
entry__pub_date__year=2008)
Blog.objects.filter(entry__headline_contains='Lennon').filter(
entry__pub_date__year=2008)
For the 1st query (single filter one), it match only blog1.
For the 2nd query (chained filters one), it filters out blog1 and blog2.
The first filter restricts the queryset to blog1, blog2 and blog5; the second filter restricts the set of blogs further to blog1 and blog2.
And you should realize that
We are filtering the Blog items with each filter statement, not the Entry items.
So, it's not the same, because Blog and Entry are multi-valued relationships.
Reference: https://docs.djangoproject.com/en/1.8/topics/db/queries/#spanning-multi-valued-relationships
If there is something wrong, please correct me.
Edit: Changed v1.6 to v1.8 since the 1.6 links are no longer available.
For win7 chrome can be found at:
C:\Users\[UserName]\AppData\Local\Google\Chrome\Application\chrome.exe
For VS2017 click the little down arrow next to the run in debug/release mode button to find the "browse with..." option.
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100"
to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).
ISO_8859_1 Worked for me! I was reading text file with comma separated values
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])
x*y
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit x*y
1000000 loops, best of 3: 421 ns per loop
np.multiply(x,y)
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop
Both np.multiply
and *
would yield element wise multiplication known as the Hadamard Product
%timeit
is ipython magic
Use Thread.Sleep
when you want to block the current thread.
Use Task.Delay
when you want a logical delay without blocking the current thread.
Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.
Only 3 commands will make it work
git fetch origin
git reset --hard origin/HEAD
git clean -f
Or use the FileInfo as suggested in In C# check that filename is possibly valid (not that it exists).