You still have access to StreamWriter
:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\hereIam.txt"))
{
file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}
From the MSDN documentation: Writing to a Text File (Visual C#).
For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText
method.
System.IO.File.WriteAllText(@"C:\TextFile.txt", stringBuilder.ToString());
Don't detect mobile devices, go for stationary ones instead.
Nowadays (2016) there is a way to detect dots per inch/cm/px that seems to work in most modern browsers (see http://caniuse.com/#feat=css-media-resolution). I needed a method to distinguish between a relatively small screen, orientation didn't matter, and a stationary computer monitor.
Because many mobile browsers don't support this, one can write the general css code for all cases and use this exception for large screens:
@media (max-resolution: 1dppx) {
/* ... */
}
Both Windows XP and 7 have the default setting of 1 dot per pixel (or 96dpi). I don't know about other operating systems, but this works really well for my needs.
Edit: dppx doesn't seem to work in Internet Explorer.. use (96)dpi instead.
I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).
As of Chrome 48+, you can access the print preview via the following steps:
Open dev tools – Ctrl/Cmd + Shift + I or right click on the page and choose 'Inspect'.
Hit Esc to open the additional drawer.
If 'Rendering' isn't already being show, click the 3 dot kebab and choose 'rendering'.
Check the 'Emulate print media' checkbox.
From there Chrome will show you a print version of your page and you can inspect element and troubleshoot like you would the browser version.
This is how I handle iPhone (and similar) devices [not iPad]:
In my CSS file:
@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
/* CSS overrides for mobile here */
}
In the head of my HTML document:
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
How about mobiledetect.net?
Other solutions seem too basic. This is a lightweight PHP class. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment. You can also benefit from Mobile Detect by using any of the 3rd party plugins available for: WordPress, Drupal, Joomla, Magento, etc.
This makes sure you are getting the latest version from of the css or js file from the server.
And later you can append "?v=2"
if you have a newer version and "?v=3", "?v=4"
and so on.
Note that you can use any querystring
, 'v' is not a must for example:
"?blah=1
" will work as well.
And
"?xyz=1002"
will work.
And this is a common technique because browsers are now caching js and css files better and longer.
I was also getting exact same error and using AsyncTask :
`java.lang.IllegalStateException:` The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131296334, class android.widget.ListView) with Adapter... etc
I solved it by puttingadapter.notifyDataSetChanged();
at the bottom of my UI thread, that is my AsyncTask onPostExecute method. Like this :
protected void onPostExecute(Void aVoid) {
all my other stuff etc...
all my other stuff etc...
adapter.notifyDataSetChanged();
}
});
}
Now my app works.
EDIT : In fact, my app still crashed about every 1 in 10 times, giving the same error.
Eventually I came across runOnUiThread
on a previous post, which I thought could be useful. So I put it in my doInBackground method, like this :
@Override
protected Void doInBackground(Void... voids) {
runOnUiThread(new Runnable() {
public void run() { etc... etc...
And I removed the adapter.notifyDataSetChanged();
method. Now, my app never crashes.
I often have this problem with sequences (as opposed to discrete values). If I have a sequence of ints, and I want to SUM them, when the list is empty I'll receive the error "InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.".
I find I can solve this by casting the sequence to a nullable type. SUM and the other aggregate operators don't throw this error if a sequence of nullable types is empty.
So for example something like this
MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => x.AnIntegerValue);
becomes
MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => (int?) x.AnIntegerValue);
The second one will return 0 when no rows match the where clause. (the first one throws an exception when no rows match).
You can use Drawable instead of Uri.
ImageView iv=(ImageView)findViewById(R.id.imageView1);
String pathName = "/external/images/media/470939";
Drawable image = Drawable.createFromPath(pathName);
iv.setImageDrawable(image);
This would work.
This was an eye-opener for me, what Christopher Kramer wrote in 2014 on https://www.php.net/manual/en/session.configuration.php#115842
On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime). [...]
The scope <scope>provided</scope>
gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.
Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.
Change groupId
to <groupId>net.sourceforge.ant4x</groupId>
to get the latest jar.
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
Another solution for this problem is:
Where http://localhost/repo is your local repo URL:
<repositories>
<repository>
<id>wmc-central</id>
<url>http://localhost/repo</url>
</repository>
<-- Other repository config ... -->
</repositories>
Easy way to iterate over fragments in fragment manager. Find viewpager, that has section position argument, placed in public static PlaceholderFragment newInstance(int sectionNumber).
public PlaceholderFragment getFragmentByPosition(Integer pos){
for(Fragment f:getChildFragmentManager().getFragments()){
if(f.getId()==R.id.viewpager && f.getArguments().getInt("SECTNUM") - 1 == pos) {
return (PlaceholderFragment) f;
}
}
return null;
}
It's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:
<input type="radio" ng-checked="false">
which is a lot more sane, if you need to make it unchecked.
Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.
It's possible to get this done using seaborn.lineplot()
but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:
# imports
import seaborn as sns
import numpy as np
import pandas as pd
# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])
# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)
# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>
And we get the following plot:
For more info on
yield sleep(2000);
you should check Redux-Saga. But it is specific to your choice of Redux as your model framework (although strictly not necessary).
Why not to try simple (but powerful) html()
method:
iElement.html('<svg width="600" height="100" class="svg"></svg>');
Or append
as an alternative:
iElement.append('<svg width="600" height="100" class="svg"></svg>');
And , of course , more cleaner way:
var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
iElement.append(svg);
Based on the answer which is already in the question and on this article: https://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/ I am presenting my solution to this problem:
public static class PropertyNameHelper
{
/// <summary>
/// A static method to get the Propertyname String of a Property
/// It eliminates the need for "Magic Strings" and assures type safety when renaming properties.
/// See: http://stackoverflow.com/questions/2820660/get-name-of-property-as-a-string
/// </summary>
/// <example>
/// // Static Property
/// string name = PropertyNameHelper.GetPropertyName(() => SomeClass.SomeProperty);
/// // Instance Property
/// string name = PropertyNameHelper.GetPropertyName(() => someObject.SomeProperty);
/// </example>
/// <typeparam name="T"></typeparam>
/// <param name="propertyLambda"></param>
/// <returns></returns>
public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
var me = propertyLambda.Body as MemberExpression;
if (me == null)
{
throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
}
return me.Member.Name;
}
/// <summary>
/// Another way to get Instance Property names as strings.
/// With this method you don't need to create a instance first.
/// See the example.
/// See: https://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/
/// </summary>
/// <example>
/// string name = PropertyNameHelper((Firma f) => f.Firmenumsatz_Waehrung);
/// </example>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="expression"></param>
/// <returns></returns>
public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name;
}
}
And a Test which also shows the usage for instance and static properties:
[TestClass]
public class PropertyNameHelperTest
{
private class TestClass
{
public static string StaticString { get; set; }
public string InstanceString { get; set; }
}
[TestMethod]
public void TestGetPropertyName()
{
Assert.AreEqual("StaticString", PropertyNameHelper.GetPropertyName(() => TestClass.StaticString));
Assert.AreEqual("InstanceString", PropertyNameHelper.GetPropertyName((TestClass t) => t.InstanceString));
}
}
i dont know how to diable home button. as long as my knowledge i got folowing link.
refer the link:- http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_HOME
Key code constant: Home key. This key is handled by the framework and is never delivered to applications.
But,we can diable back button. hope following code helps you out.
@Override
public void onBackPressed() {
//return nothing
return;
}
Also posted here: "background-size: cover" does not cover mobile screen
This works on Android 4.1.2 and iOS 6.1.3 (iPhone 4) and switches for desktop. Written for responsive sites.
Just in case, in your HTML head, something like this:
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
HTML:
<div class="html-mobile-background"></div>
CSS:
html {
/* Whatever you want */
}
.html-mobile-background {
position: fixed;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 125%; /* To compensate for mobile browser address bar space */
background: url(/images/bg.jpg) no-repeat;
background-size: 100% 100%;
}
@media (min-width: 600px) {
html {
background: url(/images/bg.jpg) no-repeat center center fixed;
background-size: cover;
}
.html-mobile-background {
display: none;
}
}
Your results will not be helpful unless the arrays are first sorted. To sort an array, run it through Sort-Object.
$x = @(5,1,4,2,3)
$y = @(2,4,6,1,3,5)
Compare-Object -ReferenceObject ($x | Sort-Object) -DifferenceObject ($y | Sort-Object)
Have the same issue. Resolved it by installing ca-certificate bundle from Mozilla:
$ zypper in ca-certificates-mozilla
The following NEW package is going to be installed:
ca-certificates-mozilla
1 new package to install.
Retrieving package ca-certificates-mozilla-1.85-8.8.1.noarch
(1/1), 143.7 KiB (239.1 KiB unpacked)
Retrieving: ca-certificates-mozilla-1.85-8.8.1.noarch.rpm.....................[done]
Installing: ca-certificates-mozilla-1.85-8.8.1 ...............................[done]
Additional rpm output:
Updating certificates in /etc/ssl/certs...
144 added, 0 removed.
creating /var/lib/ca-certificates/ca-bundle.pem ...
creating /var/lib/ca-certificates/java-cacerts ...
144 added, 0 removed.
$ ll /var/lib/ca-certificates/
total 392
drwxr-xr-x 2 root root 4096 Apr 26 07:25 ./
drwxr-xr-x 30 root root 4096 Apr 25 15:00 ../
-rw-r--r-- 1 root root 220196 Apr 26 07:25 ca-bundle.pem
-rw-r--r-- 1 root root 161555 Apr 26 07:25 java-cacerts
P.S.
$ cat /etc/SuSE-release
openSUSE 12.2 (x86_64)
VERSION = 12.2
CODENAME = Mantis
$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
This should do the trick.
<activity ... android:launchMode="singleTop" />
When you create an intent to start the app use:
Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
This is that should be needed.
This should work
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()
Beginning with C# 7.3, you can use closer approximation - the unmanaged constraint to specify that a type parameter is a non-pointer, non-nullable unmanaged type.
class SomeGeneric<T> where T : unmanaged
{
//...
}
The unmanaged constraint implies the struct constraint and can't be combined with either the struct or new() constraints.
A type is an unmanaged type if it's any of the following types:
To restrict further and eliminate pointer and user-defined types that do not implement IComparable add IComparable (but enum is still derived from IComparable, so restrict enum by adding IEquatable < T >, you can go further depending on your circumstances and add additional interfaces. unmanaged allows to keep this list shorter):
class SomeGeneric<T> where T : unmanaged, IComparable, IEquatable<T>
{
//...
}
But this doesn't prevent from DateTime instantiation.
Like so
DECLARE @t INT=1
SELECT CASE
WHEN @t>0 THEN
CASE
WHEN @t=1 THEN 'one'
ELSE 'not one'
END
ELSE 'less than one'
END
EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.
Just Add a primary key to the table. That's it. Problem solved.
ALTER TABLE <TABLE_NAME>
ADD CONSTRAINT <CONSTRAINT_NAME> PRIMARY KEY(<COLUMN_NAME>)
After having looked at various versions of itoa for gcc, the most flexible version I have found that is capable of handling conversions to binary, decimal and hexadecimal, both positive and negative is the fourth version found at http://www.strudel.org.uk/itoa/. While sprintf
/snprintf
have advantages, they will not handle negative numbers for anything other than decimal conversion. Since the link above is either off-line or no longer active, I've included their 4th version below:
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
A good way to do it without getting the view involved may be:
$.ajax({
type: "POST",
url: '/Controller/Search',
data: { queryString: searchVal },
success: function (data) {
alert("here" + data.d.toString());
}
});
This will try to POST to the URL:
"http://domain/Controller/Search (which is the correct URL for the action you want to use)"
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
On iOS 8/9/10 to make background location update every 5 minutes do the following:
Go to Project -> Capabilities -> Background Modes -> select Location updates
Go to Project -> Info -> add a key NSLocationAlwaysUsageDescription with empty value (or optionally any text)
To make location working when your app is in the background and send coordinates to web service or do anything with them every 5 minutes implement it like in the code below.
I'm not using any background tasks or timers. I've tested this code with my device with iOS 8.1 which was lying on my desk for few hours with my app running in the background. Device was locked and the code was running properly all the time.
@interface LocationManager () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSDate *lastTimestamp;
@end
@implementation LocationManager
+ (instancetype)sharedInstance
{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
LocationManager *instance = sharedInstance;
instance.locationManager = [CLLocationManager new];
instance.locationManager.delegate = instance;
instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // you can use kCLLocationAccuracyHundredMeters to get better battery life
instance.locationManager.pausesLocationUpdatesAutomatically = NO; // this is important
});
return sharedInstance;
}
- (void)startUpdatingLocation
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusDenied)
{
NSLog(@"Location services are disabled in settings.");
}
else
{
// for iOS 8
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization];
}
// for iOS 9
if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
{
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
[self.locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *mostRecentLocation = locations.lastObject;
NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));
NSDate *now = [NSDate date];
NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;
if (!self.lastTimestamp || interval >= 5 * 60)
{
self.lastTimestamp = now;
NSLog(@"Sending current location to web service.");
}
}
@end
OK I found it.
=LARGE($E$4:$E$9;A12)
=large(array, k)
Array Required. The array or range of data for which you want to determine the k-th largest value.
K Required. The position (from the largest) in the array or cell range of data to return.
In the CMakeLists.txt file, create a cache variable, as documented here:
SET(FAB "po" CACHE STRING "Some user-specified option")
Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set
Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:
cmake -DFAB:STRING=po
Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue
Modify your cache variable to a boolean if, in fact, your option is boolean.
A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).
C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).
private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;
public string Name{ // This is a readonly property.
get {
return _name;
}
}
public bool Enabled{ // This is a read- and writeable property.
get{
return _enabled;
}
set{
_enabled = value;
}
}
Software & Database is usually not in the Standard edition of Visio, only the Pro version.
Try looking here for some templates that will work in standard edition
For laravel 5 and onwards using only DB::getQueryLog() , will not do. BY default in this the value of
protected $loggingQueries = false;
change it to
protected $loggingQueries = true;
in the below file for logging query.
/vendor/laravel/framework/src/illuminate/Database/Connection.php
And then we can use the DB::getQueryLog()
where you want to print the query.
The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring
Would be better to use a regex here then:
textTitle.replace(/ /g, '%20');
As the "GNU C Library Reference Manual" says
off_t
This is a signed integer type used to represent file sizes.
In the GNU C Library, this type is no narrower than int.
If the source is compiled with _FILE_OFFSET_BITS == 64 this
type is transparently replaced by off64_t.
and
off64_t
This type is used similar to off_t. The difference is that
even on 32 bit machines, where the off_t type would have 32 bits,
off64_t has 64 bits and so is able to address files up to 2^63 bytes
in length. When compiling with _FILE_OFFSET_BITS == 64 this type
is available under the name off_t.
Thus if you want reliable way of representing file size between client and server, you can:
off64_t
type and stat64()
function accordingly (as it fills structure stat64
, which contains off64_t
type itself). Type off64_t
guaranties the same size on 32 and 64 bit machines.-D_FILE_OFFSET_BITS == 64
and use usual off_t
and stat()
.off_t
to type int64_t
with fixed size (C99 standard).
Note: (my book 'C in a Nutshell' says that it is C99 standard, but optional in implementation). The newest C11 standard says:7.20.1.1 Exact-width integer types
1 The typedef name intN_t designates a signed integer type with width N ,
no padding bits, and a two’s complement representation. Thus, int8_t
denotes such a signed integer type with a width of exactly 8 bits.
without mentioning.
And about implementation:
7.20 Integer types <stdint.h>
... An implementation shall provide those types described as ‘‘required’’,
but need not provide any of the others (described as ‘‘optional’’).
...
The following types are required:
int_least8_t uint_least8_t
int_least16_t uint_least16_t
int_least32_t uint_least32_t
int_least64_t uint_least64_t
All other types of this form are optional.
Thus, in general, C standard can't guarantee types with fixed sizes. But most compilers (including gcc) support this feature.
One solution that may helpful if you want to use the command line emulator cmder. You can install the package installer chocately. First we install chocately in windows command prompt using the following line:
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
refreshenv
After chocolatey is installed the choco command can be used to install make. Once installed, you will need add an alias to /cmder/config/user_aliases.cmd. The following line should be added:
make="path_to_chocolatey\chocolatey\bin\make.exe" $*
Make will then operate in the cmder environment.
You can use intl package, first import
import 'package:intl/intl.dart';
And then
int timeInMillis = 1586348737122;
var date = DateTime.fromMillisecondsSinceEpoch(timeInMillis);
var formattedDate = DateFormat.yMMMd().format(date); // Apr 8, 2020
In Java x ^ y
is an XOR
operation.
My below code solve this issue, but i suggest First of all you need to understand what causing this issue and try the solution which you can find by changing code
I can give another way to solve this issue but better solution is to check your coding structure and try to analyse what makes this happen,if you do not find any solution then you can go with this code below
try{
Start:
///Put your file access code here
}catch (Exception ex)
{
//by anyway you need to handle this error with below code
if (ex.Message.StartsWith("The process cannot access the file"))
{
//Wait for 5 seconds to free that file and then start execution again
Thread.Sleep(5000);
goto Start;
}
}
Here's a simple latex-based example.
---
header-includes:
- \usepackage[most]{tcolorbox}
- \definecolor{light-yellow}{rgb}{1, 0.95, 0.7}
- \newtcolorbox{myquote}{colback=light-yellow,grow to right by=-10mm,grow to left by=-10mm, boxrule=0pt,boxsep=0pt,breakable}
- \newcommand{\todo}[1]{\begin{myquote} \textbf{TODO:} \emph{#1} \end{myquote}}
---
blah blah
\todo{something}
blah
Unfortunately because this is latex, you can no-longer include markdown inside the TODO box (which is not a huge problem, usually), and it won't work when converting to formats other than PDF (e.g. html).
There's my solution cleaning up the unnecesary null values
DECLARE @cols AS NVARCHAR(MAX),
@maxcols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(CodigoFormaPago)
from PO_FormasPago
order by CodigoFormaPago
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @maxcols = STUFF((SELECT ',MAX(' + QUOTENAME(CodigoFormaPago) + ') as ' + QUOTENAME(CodigoFormaPago)
from PO_FormasPago
order by CodigoFormaPago
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT CodigoProducto, DenominacionProducto, ' + @maxcols + '
FROM
(
SELECT
CodigoProducto, DenominacionProducto,
' + @cols + ' from
(
SELECT
p.CodigoProducto as CodigoProducto,
p.DenominacionProducto as DenominacionProducto,
fpp.CantidadCuotas as CantidadCuotas,
fpp.IdFormaPago as IdFormaPago,
fp.CodigoFormaPago as CodigoFormaPago
FROM
PR_Producto p
LEFT JOIN PR_FormasPagoProducto fpp
ON fpp.IdProducto = p.IdProducto
LEFT JOIN PO_FormasPago fp
ON fpp.IdFormaPago = fp.IdFormaPago
) xp
pivot
(
MAX(CantidadCuotas)
for CodigoFormaPago in (' + @cols + ')
) p
) xx
GROUP BY CodigoProducto, DenominacionProducto'
t @query;
execute(@query);
If a method doesn't return anything, it's either one of the following
Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.
void DeductFromBalance( dAmount )
can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount
Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.
void OnAccountDebit( dAmount ) // emails account holder with info
can be tested by verifying if the email is being sent
Post more details about your actual method and people will be able to answer better.
Update: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested.
string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );
String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check this thread for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.
In the code it would be used like
InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) );
The solutions that involve setting this.state
directly aren't working for me in React 16, so here is what I did to reset each key:
const initialState = { example: 'example' }
...
constructor() {
super()
this.state = initialState
}
...
reset() {
const keys = Object.keys(this.state)
const stateReset = keys.reduce((acc, v) => ({ ...acc, [v]: undefined }), {})
this.setState({ ...stateReset, ...initialState })
}
use labelpad parameter:
pl.xlabel("...", labelpad=20)
or set it after:
ax.xaxis.labelpad = 20
Make sure you pass a proxy attribute in your command forexample - pip install --proxy=http://proxyhost:proxyport pixiedust
Use a proxy port which has direct connection (with / without password). Speak with your corporate IT administrator. Quick way is find out network settings used in eclipse which will have direct connection.
You will encouter this issue often if you work behind a corporate firewall. You will have to check your internet explorer - InternetOptions -LAN Connection - Settings
Uncheck - Use automatic configuration script Check - Use a proxy server for your LAN. Ensure you have given the right address and port.
Click Ok Come back to anaconda terminal and you can try install commands
I think you can do that with:
window.location = "your_url";
Actually, this too works great.
input[type=submit]{
width: 15px;
position: absolute;
right: 20px;
bottom: 20px;
background: #09c;
color: #fff;
font-family: tahoma,geneva,algerian;
height: 30px;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
border: 1px solid #999;
}
<property attribute="attributeValue">proopertyValue</property>
would be one way to look at it.
In C#
[Attribute]
public class Entity
{
private int Property{get; set;};
For me it worked like that in Kotlin:
my string.xml
<string name="price" formatted="false">Price:U$ %.2f%n</string>
my class.kt
var formatPrice: CharSequence? = null
var unitPrice = 9990
formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
Log.d("Double_CharSequence", "$formatPrice")
D/Double_CharSequence: Price :U$ 99,90
For an even better result, we can do so
<string name="price_to_string">Price:U$ %1$s</string>
var formatPrice: CharSequence? = null
var unitPrice = 199990
val numberFormat = (unitPrice/100.0).toString()
formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))
fun formatValue(value: String) :String{
val mDecimalFormat = DecimalFormat("###,###,##0.00")
val s1 = value.toDouble()
return mDecimalFormat.format(s1)
}
Log.d("Double_CharSequence", "$formatPrice")
D/Double_CharSequence: Price :U$ 1.999,90
This is a biased answer, but I wrote a library that may simplify the usage of Android Services, if they run locally in the same process as the app: https://github.com/germnix/acacia
Basically you define an interface annotated with @Service and its implementing class, and the library creates and binds the service, handles the connection and the background worker thread:
@Service(ServiceImpl.class)
public interface MyService {
void doProcessing(Foo aComplexParam);
}
public class ServiceImpl implements MyService {
// your implementation
}
MyService service = Acacia.createService(context, MyService.class);
service.doProcessing(foo);
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
...
<service android:name="com.gmr.acacia.AcaciaService"/>
...
</application>
You can get an instance of the associated android.app.Service to hide/show persistent notifications, use your own android.app.Service and manually handle threading if you wish.
In most cases without adding the !important
to the CSS code, it won't work.
!important
a, a:active, a:focus{
outline: none !important; /* Works in Firefox, Chrome, IE8 and above */
}
Or any other code:
button::-moz-focus-inner {
border: 0 !important;
}
str = "aaaaabbbb"
newstr = str[-4:]
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div>
<input id="fieldName" name="fieldName" type="text" class="text_box" value="Firstname" />
</div>
</body>
<script type="text/javascript">
$(function()
{
$('#fieldName').attr('disabled', 'disabled');
});
</script>
</html>
In my case I was following the documentation for react-fontawesome
package, but they aren't clear about how to call the icon when setting the icons into the library
this is was what I was doing:
App.js file
import {faCoffee} from "@fortawesome/pro-light-svg-icons";
library.add(faSearch, faFileSearch, faCoffee);
Component file
<FontAwesomeIcon icon={"coffee"} />
But I was getting this error
Then I added the alias when passing the icon prop like:
<FontAwesomeIcon icon={["fal", "coffee"]} />
And it is working, you can find the prefix value in the icon.js file, in my case was: faCoffee.js
Yes, %d
means decimal, but it means decimal number system, not decimal point.
Further, as a complement to the former post, you can also control the number of decimal points to show. Try this,
System.out.printf("%.2f %.1f",d,f); // prints 1.20 1.2
For more please refer to the API docs.
OK, what you can try is
Cntrl+H (Find and Replace), leave Find What blank and change Replace With to NULL.
That should replace all blank cells in the USED range with NULL
Solved my problem based on TommySM answer (see previous). But I didn't need to make login, I used Retrofit2 for testing https GraphQL API like this:
Defined my BaseResponse class with the help of json annotations (import jackson.annotation.JsonProperty).
public class MyRequest {
@JsonProperty("query")
private String query;
@JsonProperty("operationName")
private String operationName;
@JsonProperty("variables")
private String variables;
public void setQuery(String query) {
this.query = query;
}
public void setOperationName(String operationName) {
this.operationName = operationName;
}
public void setVariables(String variables) {
this.variables = variables;
}
}
Defined the call procedure in the interface:
@POST("/api/apiname")
Call<BaseResponse> apicall(@Body RequestBody params);
Called apicall in the body of test: Create a variable of MyRequest type (for example "myLittleRequest").
Map<String, Object> jsonParams = convertObjectToMap(myLittleRequest);
RequestBody body =
RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
(new JSONObject(jsonParams)).toString());
response = hereIsYourInterfaceName().apicall(body).execute();
Update:
This linked answer describes a cleaner, simpler way of doing the same thing with C# syntax.
Original post
This is Microsoft's recommended way to handle WCF client calls:
For more detail see: Expected Exceptions
try
{
...
double result = client.Add(value1, value2);
...
client.Close();
}
catch (TimeoutException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
catch (CommunicationException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
Additional information
So many people seem to be asking this question on WCF that Microsoft even created a dedicated sample to demonstrate how to handle exceptions:
c:\WF_WCF_Samples\WCF\Basic\Client\ExpectedExceptions\CS\client
Considering that there are so many issues involving the using statement, (heated?) Internal discussions and threads on this issue, I'm not going to waste my time trying to become a code cowboy and find a cleaner way. I'll just suck it up, and implement WCF clients this verbose (yet trusted) way for my server applications.
The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.
The jquery each
runs the inner loop; I needed the regular JavaScript for
on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.
This is only 5 main lines of code but wrapped onto multiple lines for display:
$.get("data.php", function(data){
for (var propTitle in data) {
$('<div></div>')
.addClass('heading')
.insertBefore('#contentHere')
.text(propTitle);
$(data[propTitle]).each(function(iRec, oRec) {
$('<div></div>')
.addClass(oRec.textType)
.attr('id', 'T'+oRec.textId)
.insertBefore('#contentHere')
.text(oRec.text);
});
}
});
Produces the output
(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")
<div class="heading">
justIn
</div>
<div id="T123" class="Greeting">
1Hello
</div>
<div id="T514" class="Question">
1What's up?
</div>
<div id="T122" class="Order">
1Come over here
</div>
<div class="heading">
recent
</div>
<div id="T1255" class="Greeting">
2Hello
</div>
<div id="T6564" class="Question">
2What's up?
</div>
<div id="T0192" class="Order">
2Come over here
</div>
<div class="heading">
old
</div>
<div id="T5213" class="Greeting">
3Hello
</div>
<div id="T9758" class="Question">
3What's up?
</div>
<div id="T7655" class="Order">
3Come over here
</div>
<div id="contentHere"></div>
Apply a style sheet
<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>
to get a "beautiful" looking set of data
More Info
The JSON data was used in the following way:
for each category (key name the array is held under):
for each object held inside an array:
If you are targeting evergreen browsers (Chrome, Firefox, Edge, but also works in Safari 9+) or you can afford a polyfill, you can turn the FileList into an array by using Array.from()
like this:
let fileArray = Array.from(fileList);
Then it's easy to handle the array of File
s like any other array.
Nowadays you can also use lazy_eval
function from lazyeval
package.
> lazyeval::lazy_eval("5+5")
[1] 10
WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.
The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).
Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.
To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).
Question states 'I want to drop all the columns whose name contains the word "Test".'
test_columns = [col for col in df if 'Test' in col]
df.drop(columns=test_columns, inplace=True)
Create a Virtual Machine with Windows running on it and download the file to a shared folder. :-D
it is not possible to pragmatically get the permission... but ill suggest you to put that line of code in try{} catch{} which make your app unfortunately stop... and in catch body make a dialog box which will navigate the user to small tutorial to enable the draw over other apps permission... then on yes button click put this code...
Intent callSettingIntent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivity(callSettingIntent);
this intent is to directly open the list of draw over other apps to manage permissions and then from here it is one click to the draw over other apps Permissions ... i know this is Not the answer you're looking for... but Im doing this in my apps...
var values = {};
$('td input').each(function(){
values[$(this).attr('name')] = $(this).val();
}
Haven't tested, but that should do it...
And if you are using python 3.X, you may apply the sorted
function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.
# using *sort method*
mylist.sort(lambda x: x[1])
# using *sorted function*
sorted(mylist, key = lambda x: x[1])
I fixed this error by inserting these lines of code:
<dependency>
<groupId>junit</groupId> <!-- NOT org.junit here -->
<artifactId>junit-dep</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
into <dependencies> node.
more details refer to: http://mvnrepository.com/artifact/junit/junit-dep/4.8.2
As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:
TSKILL processName
or
TSKILL PID
Have on mind that processName
should not have the .exe
suffix and is limited to 18 characters.
Another option is WMIC
:
wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate
wmic offer even more flexibility than taskkill .With wmic Path win32_process get
you can see the available fileds you can filter.
String one = object.getdata();
Log.d(one,"");
Additional-> To clear the Child Controls The below function would clear the nested(Child) controls also, wrap up in a class.
public static void ClearControl(Control control)
{
if (control is TextBox)
{
TextBox txtbox = (TextBox)control;
txtbox.Text = string.Empty;
}
else if (control is CheckBox)
{
CheckBox chkbox = (CheckBox)control;
chkbox.Checked = false;
}
else if (control is RadioButton)
{
RadioButton rdbtn = (RadioButton)control;
rdbtn.Checked = false;
}
else if (control is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)control;
dtp.Value = DateTime.Now;
}
else if (control is ComboBox)
{
ComboBox cmb = (ComboBox)control;
if (cmb.DataSource != null)
{
cmb.SelectedItem = string.Empty;
cmb.SelectedValue = 0;
}
}
ClearErrors(control);
// repeat for combobox, listbox, checkbox and any other controls you want to clear
if (control.HasChildren)
{
foreach (Control child in control.Controls)
{
ClearControl(child);
}
}
}
keep using the id
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserVerification extends Model
{
protected $table = 'user_verification';
protected $fillable = [
'id',
'email',
'verification_token'
];
//$timestamps = false;
protected $primaryKey = 'verification_token';
}
and get the email :
$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);
text()
and node()
are node tests, in XPath terminology (compare).
Node tests operate on a set (on an axis, to be exact) of nodes and return the ones that are of a certain type. When no axis is mentioned, the child
axis is assumed by default.
There are all kinds of node tests:
node()
matches any node (the least specific node test of them all)text()
matches text nodes onlycomment()
matches comment nodes*
matches any element nodefoo
matches any element node named "foo"
processing-instruction()
matches PI nodes (they look like <?name value?>
).*
also matches attribute nodes, but only along the attribute
axis. @*
is a shorthand for attribute::*
. Attributes are not part of the child
axis, that's why a normal *
does not select them.This XML document:
<produce>
<item>apple</item>
<item>banana</item>
<item>pepper</item>
</produce>
represents the following DOM (simplified):
root node element node (name="produce") text node (value="\n ") element node (name="item") text node (value="apple") text node (value="\n ") element node (name="item") text node (value="banana") text node (value="\n ") element node (name="item") text node (value="pepper") text node (value="\n")
So with XPath:
/
selects the root node/produce
selects a child element of the root node if it has the name "produce"
(This is called the document element; it represents the document itself. Document element and root node are often confused, but they are not the same thing.) /produce/node()
selects any type of child node beneath /produce/
(i.e. all 7 children)/produce/text()
selects the 4 (!) whitespace-only text nodes/produce/item[1]
selects the first child element named "item"
/produce/item[1]/text()
selects all child text nodes (there's only one - "apple" - in this case)And so on.
So, your questions
/produce/item/text()
(3 nodes selected)//department/manager
(1 node selected)Notes
child
axis. You can change the axis by prefixing a different axis name. For example: //item/ancestor::produce
/produce/item[1]/text()
and string(/produce/item[1])
will be the same.Another (probably not secure) way to pass password is using input redirection i.e. calling
pg_dump [params] < [path to file containing password]
If you have a valid integer value and your requirement is to compare values, you can simply go ahead with the comparison as seen below.
Sub t()
Dim i As Integer
Dim s As String
' pass
i = 65
s = "65"
If i = s Then
MsgBox i
End If
' fail - Type Mismatch
i = 65
s = "A"
If i = s Then
MsgBox i
End If
End Sub
Try this code.
For showing Softkeyboard:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
For Hiding SoftKeyboard -
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
This is the one that i've tried & it works pretty well for me
$('.mybutton').on('click', function() {
if (!$(this).data('clicked')) {
//do your stuff here if the button is not clicked
$(this).data('clicked', true);
} else {
//do your stuff here if the button is clicked
$(this).data('clicked', false);
}
});
for more reference check this link JQuery toggle click
If you don't need it to be human-readable/editable, the easiest solution is to just use pickle
.
To write:
with open(the_filename, 'wb') as f:
pickle.dump(my_list, f)
To read:
with open(the_filename, 'rb') as f:
my_list = pickle.load(f)
If you do need them to be human-readable, we need more information.
If my_list
is guaranteed to be a list of strings with no embedded newlines, just write them one per line:
with open(the_filename, 'w') as f:
for s in my_list:
f.write(s + '\n')
with open(the_filename, 'r') as f:
my_list = [line.rstrip('\n') for line in f]
If they're Unicode strings rather than byte strings, you'll want to encode
them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)
If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.
Let's use unicode-escape
here to solve both of the above problems at once:
with open(the_filename, 'w') as f:
for s in my_list:
f.write((s + u'\n').encode('unicode-escape'))
with open(the_filename, 'r') as f:
my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]
You can also use the 3.x-style solution in 2.x, with either the codecs
module or the io
module:*
import io
with io.open(the_filename, 'w', encoding='unicode-escape') as f:
f.writelines(line + u'\n' for line in my_list)
with open(the_filename, 'r') as f:
my_list = [line.rstrip(u'\n') for line in f]
* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs
; if not, use io
.
You can also use shift()
.
var streetaddress = addy.split(',').shift();
According to MDN Web Docs:
The
shift()
method removes the first element from an array and returns that removed element. This method changes the length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
You can truncate the date part:
select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')
The trouble with this approach is that any index on field1
wouldn't be used due to the function call.
Alternatively (and more index friendly)
select * from table1
where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD')
and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')
Now that Google Play locations services are here, I recommend that developers start using the new fused location provider. You will find it easier to use and more accurate. Please watch the Google I/O video Beyond the Blue Dot: New Features in Android Location by the two guys who created the new Google Play location services API.
I've been working with location APIs on a number of mobile platforms, and I think what these two guys have done is really revolutionary. It's gotten rid of a huge amount of the complexities of using the various providers. Stack Overflow is littered with questions about which provider to use, whether to use last known location, how to set other properties on the LocationManager, etc. This new API that they have built removes most of those uncertainties and makes the location services a pleasure to use.
I've written an Android app that periodically gets the location using Google Play location services and sends the location to a web server where it is stored in a database and can be viewed on Google Maps. I've written both the client software (for Android, iOS, Windows Phone and Java ME) and the server software (for ASP.NET and SQL Server or PHP and MySQL). The software is written in the native language on each platform and works properly in the background on each. Lastly, the software has the MIT License. You can find the Android client here:
https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android
Coming long after, but none of the answers here are entirely correct.
When drawn on a canvas, the passed image is uncompressed + all pre-multiplied.
When exported, its uncompressed or recompressed with a different algorithm, and un-multiplied.
All browsers and devices will have different rounding errors happening in this process
(see Canvas fingerprinting).
So if one wants a base64 version of an image file, they have to request it again (most of the time it will come from cache) but this time as a Blob.
Then you can use a FileReader to read it either as an ArrayBuffer, or as a dataURL.
function toDataURL(url, callback){_x000D_
var xhr = new XMLHttpRequest();_x000D_
xhr.open('get', url);_x000D_
xhr.responseType = 'blob';_x000D_
xhr.onload = function(){_x000D_
var fr = new FileReader();_x000D_
_x000D_
fr.onload = function(){_x000D_
callback(this.result);_x000D_
};_x000D_
_x000D_
fr.readAsDataURL(xhr.response); // async call_x000D_
};_x000D_
_x000D_
xhr.send();_x000D_
}_x000D_
_x000D_
toDataURL(myImage.src, function(dataURL){_x000D_
result.src = dataURL;_x000D_
_x000D_
// now just to show that passing to a canvas doesn't hold the same results_x000D_
var canvas = document.createElement('canvas');_x000D_
canvas.width = myImage.naturalWidth;_x000D_
canvas.height = myImage.naturalHeight;_x000D_
canvas.getContext('2d').drawImage(myImage, 0,0);_x000D_
_x000D_
console.log(canvas.toDataURL() === dataURL); // false - not same data_x000D_
});
_x000D_
<img id="myImage" src="https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png" crossOrigin="anonymous">_x000D_
<img id="result">
_x000D_
To call a specific exception such as FileNotFoundException use this format
if (-not (Test-Path $file))
{
throw [System.IO.FileNotFoundException] "$file not found."
}
To throw a general exception use the throw command followed by a string.
throw "Error trying to do a task"
When used inside a catch, you can provide additional information about what triggered the error
Alternatively, you can use Inner Queries to do so.
SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);
Hope this helps!
This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.
FileStream fileStream = File.Open(<path>, FileMode.Open);
/*
* Set the length of filestream to 0 and flush it to the physical file.
*
* Flushing the stream is important because this ensures that
* the changes to the stream trickle down to the physical file.
*
*/
fileStream.SetLength(0);
fileStream.Close(); // This flushes the content, too.
You could conceivably set up a git hook that when say a commit is made to say the "stable" branch it will pull the changes and apply them to the PHP site. The big downside is you won't have much control if something goes wrong and it will add time to your testing - but you can get an idea of how much work will be involved when you merge say your trunk branch into the stable branch to know how many conflicts you may run into. It will be important to keep an eye on any files that are site specific (eg. configuration files) unless you solely intend to only run the one site.
Alternatively have you looked into pushing the change to the site instead?
For information on git hooks see the githooks documentation.
You need to create new file and copy contents from InputStream
to that file:
File file = //...
try(OutputStream outputStream = new FileOutputStream(file)){
IOUtils.copy(inputStream, outputStream);
} catch (FileNotFoundException e) {
// handle exception here
} catch (IOException e) {
// handle exception here
}
I am using convenient IOUtils.copy()
to avoid manual copying of streams. Also it has built-in buffering.
Just to add more to comment
Mainly about how to do performance testing.
I did testing with following code:
import (
"testing"
)
var ss = []string{"Hello", "", "bar", " ", "baz", "ewrqlosakdjhf12934c r39yfashk fjkashkfashds fsdakjh-", "", "123"}
func BenchmarkStringCheckEq(b *testing.B) {
c := 0
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, s := range ss {
if s == "" {
c++
}
}
}
t := 2 * b.N
if c != t {
b.Fatalf("did not catch empty strings: %d != %d", c, t)
}
}
func BenchmarkStringCheckLen(b *testing.B) {
c := 0
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, s := range ss {
if len(s) == 0 {
c++
}
}
}
t := 2 * b.N
if c != t {
b.Fatalf("did not catch empty strings: %d != %d", c, t)
}
}
func BenchmarkStringCheckLenGt(b *testing.B) {
c := 0
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, s := range ss {
if len(s) > 0 {
c++
}
}
}
t := 6 * b.N
if c != t {
b.Fatalf("did not catch empty strings: %d != %d", c, t)
}
}
func BenchmarkStringCheckNe(b *testing.B) {
c := 0
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, s := range ss {
if s != "" {
c++
}
}
}
t := 6 * b.N
if c != t {
b.Fatalf("did not catch empty strings: %d != %d", c, t)
}
}
And results were:
% for a in $(seq 50);do go test -run=^$ -bench=. --benchtime=1s ./...|grep Bench;done | tee -a log
% sort -k 3n log | head -10
BenchmarkStringCheckEq-4 150149937 8.06 ns/op
BenchmarkStringCheckLenGt-4 147926752 8.06 ns/op
BenchmarkStringCheckLenGt-4 148045771 8.06 ns/op
BenchmarkStringCheckNe-4 145506912 8.06 ns/op
BenchmarkStringCheckLen-4 145942450 8.07 ns/op
BenchmarkStringCheckEq-4 146990384 8.08 ns/op
BenchmarkStringCheckLenGt-4 149351529 8.08 ns/op
BenchmarkStringCheckNe-4 148212032 8.08 ns/op
BenchmarkStringCheckEq-4 145122193 8.09 ns/op
BenchmarkStringCheckEq-4 146277885 8.09 ns/op
Effectively variants usually do not reach fastest time and there is only minimal difference (about 0.01ns/op) between variant top speed.
And if I look full log, difference between tries is greater than difference between benchmark functions.
Also there does not seem to be any measurable difference between BenchmarkStringCheckEq and BenchmarkStringCheckNe or BenchmarkStringCheckLen and BenchmarkStringCheckLenGt even if latter variants should inc c 6 times instead of 2 times.
You can try to get some confidence about equal performance by adding tests with modified test or inner loop. This is faster:
func BenchmarkStringCheckNone4(b *testing.B) {
c := 0
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, _ = range ss {
c++
}
}
t := len(ss) * b.N
if c != t {
b.Fatalf("did not catch empty strings: %d != %d", c, t)
}
}
This is not faster:
func BenchmarkStringCheckEq3(b *testing.B) {
ss2 := make([]string, len(ss))
prefix := "a"
for i, _ := range ss {
ss2[i] = prefix + ss[i]
}
c := 0
b.ResetTimer()
for n := 0; n < b.N; n++ {
for _, s := range ss2 {
if s == prefix {
c++
}
}
}
t := 2 * b.N
if c != t {
b.Fatalf("did not catch empty strings: %d != %d", c, t)
}
}
Both variants are usually faster or slower than difference between main tests.
It would also good to generate test strings (ss) using string generator with relevant distribution. And have variable lengths too.
So I don't have any confidence of performance difference between main methods to test empty string in go.
And I can state with some confidence, it is faster not to test empty string at all than test empty string. And also it is faster to test empty string than to test 1 char string (prefix variant).
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
For CentOS users (at least), one will also get a 404 error trying to access the server on port 8080 on a fresh install if the tomcat-webapps
package is not installed.
I had the similar issue. its resolved for me with a simple command.
lsnrctl start
The Network Adapter exception is caused because:
lsnrctl
utility.Try to start the listener using the command prompt:
cmd
in the search field, and when cmd
shows up in the list of options, right click it and select ‘Run as Administrator’.lsnrctl start
without the quotes and press Enter.Exit
and press Enter.Hope it helps.
Try this way. make a loop inside java script function to wait until the ajax call finished.
function getLabelById(id)
{
var label = '';
var done = false;
$.ajax({
cache: false,
url: "YourMvcActionUrl",
type: "GET",
dataType: "json",
async: false,
error: function (result) {
label='undefined';
done = true;
},
success: function (result) {
label = result.Message;
done = true;
}
});
//A loop to check done if ajax call is done.
while (!done)
{
setTimeout(function(){ },500); // take a sleep.
}
return label;
}
I faced the same problem and seems that there have been many changes by google.
I can tell you the steps for installing purely via command line from scratch. I tested it on Ubuntu on 22 Feb 2021.
export ANDROID_SDK_ROOT=/usr/lib/android-sdk
sudo mkdir -p $ANDROID_SDK_ROOT
sudo apt-get install openjdk-8-jdk
Go to https://developer.android.com/studio/index.html Then down to Command line tools only Click on Linux link, accept the agreement and instead of downloading right click and copy link address
cd $ANDROID_SDK_ROOT
sudo wget https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip
sudo unzip commandlinetools-linux-6858069_latest.zip
Rename the unpacked directory from cmdline-tools to tools, and place it under $ANDROID_SDK_ROOT/cmdline-tools, so now it should look like: $ANDROID_SDK_ROOT/cmdline-tools/tools. And inside it, you should have: NOTICE.txt bin lib source.properties.
PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin
This had no effect for me, hence the next step
cd $ANDROID_SDK_ROOT/cmdline-tools/tools/bin
yes | sudo sdkmanager --licenses
Finally, run this inside your project
sudo ./gradlew assembleDebug
This creates an APK named -debug.apk at //build/outputs/apk/debug The file is already signed with the debug key and aligned with zipalign, so you can immediately install it on a device.
https://gist.github.com/guipmourao/3e7edc951b043f6de30ca15a5cc2be40
Android Command line tools sdkmanager always shows: Warning: Could not create settings
"Failed to install the following Android SDK packages as some licences have not been accepted" error
https://developer.android.com/studio/build/building-cmdline#sign_cmdline
Just adding in for JupyterLab users. Ctrl, (advanced settings) and pasting the below in User References under keyboard shortcuts does the trick for me.
{
"shortcuts": [
{
"command": "notebook:hide-cell-outputs",
"keys": [
"H"
],
"selector": ".jp-Notebook:focus"
},
{
"command": "notebook:show-cell-outputs",
"keys": [
"Shift H"
],
"selector": ".jp-Notebook:focus"
}
]
}
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.
On Error Resume Next
DoStep1
If Err.Number <> 0 Then
WScript.Echo "Error in DoStep1: " & Err.Description
Err.Clear
End If
DoStep2
If Err.Number <> 0 Then
WScript.Echo "Error in DoStop2:" & Err.Description
Err.Clear
End If
'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0
The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
We had this problem having tag <button>
in the form, that was supposed to send ajax request from js. But this request was canceled, due to browser, that sends form automatically on any click on button
inside the form.
So if you realy want to use button
instead of regular div
or span
on the page, and you want to send form throw js - you should setup a listener with preventDefault
function.
e.g.
$('button').on('click', function(e){
e.preventDefault();
//do ajax
$.ajax({
...
});
})
How (and why) to use display: table-cell (CSS)
I just wanted to mention, since I don't think any of the other answers did directly, that the answer to "why" is: there is no good reason, and you should probably never do this.
In my over a decade of experience in web development, I can't think of a single time I would have been better served to have a bunch of <div>
s with display
styles than to just have table elements.
The only hypothetical I could come up with is if you have tabular data stored in some sort of non-HTML-table format (eg. a CSV file). In a very specific version of this case it might be easier to just add <div>
tags around everything and then add descendent-based styles, instead of adding actual table tags.
But that's an extremely contrived example, and in all real cases I know of simply using table tags would be better.
You can also do like this :
$("#table-filters li").parent().find('li').removeClass("active");
This should help.
To sum it up: a generic Pair
class doesn't have any special semantics and you could as well need a Tripplet
class etc. The developers of Java thus didn't include a generic Pair
but suggest to write special classes (which isn't that hard) like Point(x,y)
, Range(start, end)
or Map.Entry(key, value)
.
-- Access:
SELECT CHR(13) & CHR(10)
-- SQL Server:
SELECT CHAR(13) + CHAR(10)
I got same error because I was trying to run on
XXX-Macmini:Python-Project XXX.XXX$ from classDemo import MyClass
from: can't read /var/mail/classDemo
To solve this, type command python and when you get these >>> then run any python commands
>>>from classDemo import MyClass
>>>f = MyClass()
Have a look at here this link and their roadmap. They have RO|C on the way, and that can connect to their web services, which probably includes SOAP (I use the VCL version which definitely includes it).
Arrays are effectively passed by reference by default. Actually the value of the pointer to the first element is passed. Therefore the function or method receiving this can modify the values in the array.
void SomeMethod(Coordinate Coordinates[]){Coordinates[0].x++;};
int main(){
Coordinate tenCoordinates[10];
tenCoordinates[0].x=0;
SomeMethod(tenCoordinates[]);
SomeMethod(&tenCoordinates[0]);
if(0==tenCoordinates[0].x - 2;){
exit(0);
}
exit(-1);
}
The two calls are equivalent, and the exit value should be 0;
Quick version which uses vector
as the base class, giving full access to all of its operators:
// Split string into parts.
class Split : public std::vector<std::string>
{
public:
Split(const std::string& str, char* delimList)
{
size_t lastPos = 0;
size_t pos = str.find_first_of(delimList);
while (pos != std::string::npos)
{
if (pos != lastPos)
push_back(str.substr(lastPos, pos-lastPos));
lastPos = pos + 1;
pos = str.find_first_of(delimList, lastPos);
}
if (lastPos < str.length())
push_back(str.substr(lastPos, pos-lastPos));
}
};
Example used to populate an STL set:
std::set<std::string> words;
Split split("Hello,World", ",");
words.insert(split.begin(), split.end());
cast (
case
when FC.CourseId is not null then 1 else 0
end
as bit)
The CAST spec is "CAST (expression AS type)". The CASE is an expression in this context.
If you have multiple such expressions, I'd declare bit vars @true and @false and use them. Or use UDFs if you really wanted...
DECLARE @True bit, @False bit;
SELECT @True = 1, @False = 0; --can be combined with declare in SQL 2008
SELECT
case when FC.CourseId is not null then @True ELSE @False END AS ...
I prefer the lambda form of the DropDownList helper - see MVC 3 Layout Page, Razor Template, and DropdownList
If you want to use the SelectList, then I think this bug report might assist - http://aspnet.codeplex.com/workitem/4932
This is pretty easy to do using LINQ:
var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
// Element doesn't exist
}
To fix this solution i followed: this
1.Click Start and then type Run
2.Type services.msc and click OK
3.Scroll down the list and locate that the VMware Authorization service.
4.Click Start the service, unless the service is showing a status of Started.
Change Column Name/Type/Position/Comment:
ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]
Example:
CREATE TABLE test_change (a int, b int, c int);
// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention.
Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
.
So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
Use the following methods
1: Method one
var count = 123;
var message = $"Rows count is: {count}";
2: Method two
var count = 123;
var message = "Rows count is:" + count;
3: Method three
var count = 123;
var message = string.Format("Rows count is:{0}", count);
4: Method four
var count = 123;
var message = @"Rows
count
is:{0}" + count;
5: Method five
var count = 123;
var message = $@"Rows
count
is: {count}";
event.key
and modern JS!No number codes anymore. You can use "Enter"
, "ArrowLeft"
, "r"
, or any key name directly, making your code far more readable.
NOTE: The old alternatives (
.keyCode
and.which
) are Deprecated.
document.addEventListener("keypress", function onEvent(event) {
if (event.key === "ArrowLeft") {
// Move Left
}
else if (event.key === "Enter") {
// Open Menu...
}
});
Back to Jonathan002's original question about
"... what version supports the new ES6 import statements?"
based on the article by Dr. Axel Rauschmayer, there is a plan to have it supported by default (without the experimental command line flag) in Node.js 10.x LTS. According to node.js's release plan as it is on 3/29, 2018, it's likely to become available after Apr 2018, while LTS of it will begin on October 2018.
JPG doesn't support transparency
Since you have updated your label client side, you'll need a post-back in order for you're server side code to reflect the changes.
If you do not know how to do this, here is how I've gone about it in the past.
Create a hidden field:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
Create a button that has both client side and server side functions attached to it. You're client side function will populate your hidden field, and the server side will read it. Be sure you're client side is being called first.
<asp:Button ID="_Submit" runat="server" Text="Submit Button" OnClientClick="TestSubmit();" OnClick="_Submit_Click" />
Javascript Client Side Function:
function TestSubmit() {
try {
var message = "Message to Pass";
document.getElementById('__EVENTTARGET').value = message;
} catch (err) {
alert(err.message);
}
}
C# Server Side Function
protected void _Submit_Click(object sender, EventArgs e)
{
// Hidden Value after postback
string hiddenVal= Request.Form["__EVENTTARGET"];
}
Hope this helps!
public void AnalyseArray(ArrayList<Integer> array) {
// Do something
}
...
ArrayList<Integer> A = new ArrayList<Integer>();
AnalyseArray(A);
One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.
In your Partial calling side
@Html.Partial("ParitalAction", "String data to pass to partial")
And then binding the model with Partial View like this
@model string
and the using its value in Partial View like this
@Model
You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.
Hope it helps,
First off, you're not dealing with a "JSON object." You're dealing with a JavaScript object. JSON is a textual notation, but if your example code works ([0].amount
), you've already deserialized that notation into a JavaScript object graph. (What you've quoted isn't valid JSON at all; in JSON, the keys must be in double quotes. What you've quoted is a JavaScript object literal, which is a superset of JSON.)
Here, length of this array is 2.
No, it's 3.
So, i need to get the name (like amount or job... totally four name) and also to count how many names are there?
If you're using an environment that has full ECMAScript5 support, you can use Object.keys
(spec | MDN) to get the enumerable keys for one of the objects as an array. If not (or if you just want to loop through them rather than getting an array of them), you can use for..in
:
var entry;
var name;
entry = array[0];
for (name in entry) {
// here, `name` will be "amount", "job", "month", then "year" (in no defined order)
}
Full working example:
(function() {_x000D_
_x000D_
var array = [_x000D_
{_x000D_
amount: 12185,_x000D_
job: "GAPA",_x000D_
month: "JANUARY",_x000D_
year: "2010"_x000D_
},_x000D_
{_x000D_
amount: 147421,_x000D_
job: "GAPA",_x000D_
month: "MAY",_x000D_
year: "2010"_x000D_
},_x000D_
{_x000D_
amount: 2347,_x000D_
job: "GAPA",_x000D_
month: "AUGUST",_x000D_
year: "2010"_x000D_
}_x000D_
];_x000D_
_x000D_
var entry;_x000D_
var name;_x000D_
var count;_x000D_
_x000D_
entry = array[0];_x000D_
_x000D_
display("Keys for entry 0:");_x000D_
count = 0;_x000D_
for (name in entry) {_x000D_
display(name);_x000D_
++count;_x000D_
}_x000D_
display("Total enumerable keys: " + count);_x000D_
_x000D_
// === Basic utility functions_x000D_
_x000D_
function display(msg) {_x000D_
var p = document.createElement('p');_x000D_
p.innerHTML = msg;_x000D_
document.body.appendChild(p);_x000D_
}_x000D_
_x000D_
})();
_x000D_
Since you're dealing with raw objects, the above for..in
loop is fine (unless someone has committed the sin of mucking about with Object.prototype
, but let's assume not). But if the object you want the keys from may also inherit enumerable properties from its prototype, you can restrict the loop to only the object's own keys (and not the keys of its prototype) by adding a hasOwnProperty
call in there:
for (name in entry) {
if (entry.hasOwnProperty(name)) {
display(name);
++count;
}
}
You should \usepackage{longtable}
.
So, I've found a solution for what I'm looking for, which is:
print open('f2').read().decode('string-escape').decode("utf-8")
There are some unusual codecs that are useful here. This particular reading allows one to take UTF-8 representations from within Python, copy them into an ASCII file, and have them be read in to Unicode. Under the "string-escape" decode, the slashes won't be doubled.
This allows for the sort of round trip that I was imagining.
@praneeth-nidarshan has covered mostly all the steps, except some:
$ sudo apt-get install php-pear
sh: phpize: not found
ERROR: `phpize’ failed
$ sudo apt-get install php7.2-dev
$ sudo pecl install mcrypt-1.0.1
extension=mcrypt.so
to your php.ini configuration file; if you don't know where it is, search with:$ sudo php -i | grep 'Configuration File'
parser.add_argument
also has a switch required. You can use required=False
.
Here is a sample snippet with Python 2.7:
parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()
This doesn't sound intuitive but select the column you're having the issue with and use "text to column" and just press finish. This is the suggested answer from Excel help as well. For some reason in converts text to numbers.
If this need to be done in UIBarButtonItem, additional wrapping in view should be used
This will work
let view = UIView()
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)
This won't work
let button = UIButton()
button.setTitle("Skip", for: .normal)
button.setImage(#imageLiteral(resourceName:"forward_button"), for: .normal)
button.semanticContentAttribute = .forceRightToLeft
button.sizeToFit()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
If your subplots also have titles, you may need to adjust the main title size:
plt.suptitle("Main Title", size=16)
There are two sets of characters you need to watch out for: reserved and unsafe.
The reserved characters are:
The characters generally considered unsafe are:
I may have forgotten one or more, which leads to me echoing Carl V's answer. In the long run you are probably better off using a "white list" of allowed characters and then encoding the string rather than trying to stay abreast of characters that are disallowed by servers and systems.
You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website
If you are going to use it in a class, and if you prefer it to be functional (and work in all browsers):
inArray: function(needle, haystack)
{
var result = false;
for (var i in haystack) {
if (haystack[i] === needle) {
result = true;
break;
}
}
return result;
}
Hope it helps someone :-)
IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.
A minimal in-python solution that colors json data supplied via the command line:
import sys
import json
from pygments import highlight, lexers, formatters
formatted_json = json.dumps(json.loads(sys.argv[1]), indent=4)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)
Inspired by pjson
mentioned above. This code needs pygments
to be installed.
Output example:
I'm writing logs to the files, which are generate on daily basis (per day one log file is getting generated). This approach is working fine for me :
var (
serverLogger *log.Logger
)
func init() {
// set location of log file
date := time.Now().Format("2006-01-02")
var logpath = os.Getenv(constant.XDirectoryPath) + constant.LogFilePath + date + constant.LogFileExtension
os.MkdirAll(os.Getenv(constant.XDirectoryPath)+constant.LogFilePath, os.ModePerm)
flag.Parse()
var file, err1 = os.OpenFile(logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err1 != nil {
panic(err1)
}
mw := io.MultiWriter(os.Stdout, file)
serverLogger = log.New(mw, constant.Empty, log.LstdFlags)
serverLogger.Println("LogFile : " + logpath)
}
// LogServer logs to server's log file
func LogServer(logLevel enum.LogLevel, message string) {
_, file, no, ok := runtime.Caller(1)
logLineData := "logger_server.go"
if ok {
file = shortenFilePath(file)
logLineData = fmt.Sprintf(file + constant.ColonWithSpace + strconv.Itoa(no) + constant.HyphenWithSpace)
}
serverLogger.Println(logLineData + logLevel.String() + constant.HyphenWithSpace + message)
}
// ShortenFilePath Shortens file path to a/b/c/d.go tp d.go
func shortenFilePath(file string) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == constant.ForwardSlash {
short = file[i+1:]
break
}
}
file = short
return file
}
"shortenFilePath()" method used to get the name of the file from full path of file. and "LogServer()" method is used to create a formatted log statement (contains : filename, line number, log level, error statement etc...)
They are stored in the CGI fieldstorage object.
import cgi
form = cgi.FieldStorage()
print "The user entered %s" % form.getvalue("uservalue")
Based on the syntax provided
Select * Where Amount = min(Amount)
You could do using:
library(sqldf)
Using @Kara Woo's example df
sqldf("select * from df where Amount in (select min(Amount) from df)")
#Name Amount
#1 B 120
#2 E 120
As the character (-) is referred to as "hyphen" or "dash", it seems more natural to name this "dash-case", or "hyphen-case" (less frequently used).
As mentioned in Wikipedia, "kebab-case" is also used. Apparently (see answer) this is because the character would look like a skewer... It needs some imagination though.
Used in lodash lib for example.
Recently, "dash-case" was used by
When we use Django:
Server ===> Client(Browser)
Send a page
When you click button and send the form,
----------------------------
Server <=== Client(Browser)
Give data back. (data in form will be lost)
Server ===> Client(Browser)
Send a page after doing sth with these data
----------------------------
If you want to keep old data, you can do it without Ajax. (Page will be refreshed)
Server ===> Client(Browser)
Send a page
Server <=== Client(Browser)
Give data back. (data in form will be lost)
Server ===> Client(Browser)
1. Send a page after doing sth with data
2. Insert data into form and make it like before.
After these thing, server will send a html page to client. It means that server do more work, however, the way to work is same.
Or you can do with Ajax (Page will be not refreshed)
--------------------------
<Initialization>
Server ===> Client(Browser) [from URL1]
Give a page
--------------------------
<Communication>
Server <=== Client(Browser)
Give data struct back but not to refresh the page.
Server ===> Client(Browser) [from URL2]
Give a data struct(such as JSON)
---------------------------------
If you use Ajax, you must do these:
Django is different from Ajax. The reason for this is as follows:
In my opinion, if you would like to use ajax everywhere. when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template.
If you don't think Ajax is the best practice. you can use Django template to do everything, like anime.
(My English is not good)
You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).
Here's what worked for me. My Python and Oracle versions are slightly different from yours, but the same approach should apply. Just make sure the cx_Oracle binary installer version matches your Oracle client and Python versions.
My versions:
Steps:
Source: oracle_python.bat
@echo off
set ORACLE_HOME=C:\your\path\to\instantclient_11_2
set PATH=%ORACLE_HOME%;%PATH%
Source: oracle_test.py
import cx_Oracle
conn_str = u'user/password@host:port/service'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute(u'select your_col_1, your_col_2 from your_table')
for row in c:
print row[0], "-", row[1]
conn.close()
Possible Issues:
So, is that a behavior to expect, a bug
Truth be told I am not sure. It looks like parser is interpreting count
not as a column name but a function and expects following parentheses. Looks like a bug or at least a serious limitation of the parser.
is there a canonical way to go around?
Some options have been already mentioned by Herman and mattinbits so here more SQLish approach from me:
import org.apache.spark.sql.functions.count
df.groupBy("x").agg(count("*").alias("cnt")).where($"cnt" > 2)
Add "name" attribute and keep the name same for all the radio buttons in a form.
i.e.,
<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3
Hope that would help.
.container {_x000D_
border: 3px solid #eee;_x000D_
margin: 10px;_x000D_
padding: 10px;_x000D_
float: left;_x000D_
text-align: center;_x000D_
max-width: 20%_x000D_
}_x000D_
_x000D_
input[type=range].range {_x000D_
cursor: pointer;_x000D_
width: 100px !important;_x000D_
-webkit-appearance: none;_x000D_
z-index: 200;_x000D_
width: 50px;_x000D_
border: 1px solid #e6e6e6;_x000D_
background-color: #e6e6e6;_x000D_
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#e6e6e6), to(#d2d2d2));_x000D_
background-image: -webkit-linear-gradient(right, #e6e6e6, #d2d2d2);_x000D_
background-image: -moz-linear-gradient(right, #e6e6e6, #d2d2d2);_x000D_
background-image: -ms-linear-gradient(right, #e6e6e6, #d2d2d2);_x000D_
background-image: -o-linear-gradient(right, #e6e6e6, #d2d2d2)_x000D_
}_x000D_
_x000D_
input[type=range].range:focus {_x000D_
border: 0 !important;_x000D_
outline: 0 !important_x000D_
}_x000D_
_x000D_
input[type=range].range::-webkit-slider-thumb {_x000D_
-webkit-appearance: none;_x000D_
width: 10px;_x000D_
height: 10px;_x000D_
background-color: #555;_x000D_
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#4ddbff), to(#0cf));_x000D_
background-image: -webkit-linear-gradient(right, #4ddbff, #0cf);_x000D_
background-image: -moz-linear-gradient(right, #4ddbff, #0cf);_x000D_
background-image: -ms-linear-gradient(right, #4ddbff, #0cf);_x000D_
background-image: -o-linear-gradient(right, #4ddbff, #0cf)_x000D_
}_x000D_
_x000D_
input[type=range].round {_x000D_
-webkit-border-radius: 20px;_x000D_
-moz-border-radius: 20px;_x000D_
border-radius: 20px_x000D_
}_x000D_
_x000D_
input[type=range].round::-webkit-slider-thumb {_x000D_
-webkit-border-radius: 5px;_x000D_
-moz-border-radius: 5px;_x000D_
-o-border-radius: 5px_x000D_
}_x000D_
_x000D_
.vertical-lowest-first {_x000D_
-webkit-transform: rotate(90deg);_x000D_
-moz-transform: rotate(90deg);_x000D_
-o-transform: rotate(90deg);_x000D_
-ms-transform: rotate(90deg);_x000D_
transform: rotate(90deg)_x000D_
}_x000D_
_x000D_
.vertical-heighest-first {_x000D_
-webkit-transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg);_x000D_
-o-transform: rotate(270deg);_x000D_
-ms-transform: rotate(270deg);_x000D_
transform: rotate(270deg)_x000D_
}
_x000D_
<div class="container" style="margin-left: 0px">_x000D_
<br><br>_x000D_
<input class="range vertical-lowest-first" type="range" min="0" max="1" step="0.1" value="1">_x000D_
<br><br><br>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<br><br>_x000D_
<input class="range vertical-heighest-first" type="range" min="0" max="1" step="0.1" value="1">_x000D_
<br><br><br>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="container">_x000D_
<br><br>_x000D_
<input class="range vertical-lowest-first round" type="range" min="0" max="1" step="0.1" value="1">_x000D_
<br><br><br>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="container" style="margin-right: 0px">_x000D_
<br><br>_x000D_
<input class="range vertical-heighest-first round" type="range" min="0" max="1" step="0.1" value="1">_x000D_
<br><br><br>_x000D_
</div>
_x000D_
Source: http://twiggle-web-design.com/tutorials/Custom-Vertical-Input-Range-CSS3.html
This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container
has display: flex;
and flex-direction: column;
, while the columns have flex: 3;
and flex: 2;
(where "One value, unitless number" determines the flex-grow
property) per MDN flex
docs.
#Container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
flex: 3;_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
<div class="Content">_x000D_
<div id="Detail"></div>_x000D_
<div id="ThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
have a look at the below code snippet.
@RequestMapping(value = "edit.htm", method = RequestMethod.GET)
public ModelAndView edit(@RequestParam("id") String id) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("user", userinfoDao.findById(id));
return new ModelAndView("edit", modelMap);
}
If you want the complete project to see how it works then download it from below link:-
Make sure the client computer has the same or higher version of the .NET framework that you built your program to.
If a global hotkey would suffice, then RegisterHotKey would do the trick
The he library is the only 100% reliable solution that I know of!
He is written by Mathias Bynens - one of the world's most renowned JavaScript gurus - and has the following features :
he.encode('foo © bar ? baz qux');
// Output : 'foo © bar ≠ baz 𝌆 qux'
he.decode('foo © bar ≠ baz 𝌆 qux');
// Output : 'foo © bar ? baz qux'
<script type="text/javascript">
function Check() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
}
else {
document.getElementById('ifYes').style.display = 'none';
}
}
</script>
</head>
<body>
Select os :
<br>
Two
<input type="radio" onclick="Check();" value="Two" name="categor`enter code here`y" id="yesCheck"/>One
<input type="radio" onclick="Check();" value="One"name="category"/>
<br>
<div id="ifYes" style="display:none" >
Three<input type="radio" name="win" value="Three"/>
Four<input type="radio" name="win" value="Four"/>
You can use ROW_NUMBER in a Common Table Expression to achieve this.
;WITH My_CTE AS
(
SELECT
col1,
col2,
ROW_NUMBER() OVER(ORDER BY col1) AS row_number
FROM
My_Table
WHERE
<<<whatever>>>
)
SELECT
col1,
col2
FROM
My_CTE
WHERE
row_number BETWEEN @start_row AND @end_row
According to the documentation, use a relative path for a local jar dependency as follows:
dependencies {
implementation files('libs/something_local.jar')
}
Obfuscation can never really work. For anyone who really wants to get at your code, it's just a speed bump. Worse, it keeps your users from fixing bugs (and shipping the fixes back to you), and makes it harder for you to diagnose problems in the field. Its a waste of your time and money.
Talk to a lawyer about intellectual property law and what your legal options are. "Open Source" does not mean "people can read the source". Instead, Open Source is a particular licensing model granting permission to freely use and modify your code. If you don't grant such a license then people copying your code are in violation and (in most of the world) you have legal options to stop them.
The only way you can really protect your code is to not ship it. Move the important code server-side and have your public Javascript code do Ajax calls to it.
This is common issue and its looking for .cmd
file from your root directory where you installed babel-cli
. Try the below command.
./node_modules/.bin/babel.cmd
Once you are able to see your source code in the command prompt. Your next step is to install one more npm module babel-preset-es2015
.
Follow the below answer to install babel-preset-es2015
and see why babel need this.
I ended up using GitKraken . I've installed, auth and connected to my repo in 30 seconds.
You may modify the source code 'jquery-ui.js' , find this default function for retrieving target element's title attribute content.
var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
content: function() {
// support: IE<9, Opera in jQuery <1.7
// .text() can't accept undefined, so coerce to a string
var title = $( this ).attr( "title" ) || "";
// Escape title, since we're going from an attribute to raw HTML
return $( "<a>" ).text( title ).html();
},
change it to
var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
content: function() {
// support: IE<9, Opera in jQuery <1.7
// .text() can't accept undefined, so coerce to a string
if($(this).attr('ignoreHtml')==='false'){
return $(this).prop("title");
}
var title = $( this ).attr( "title" ) || "";
// Escape title, since we're going from an attribute to raw HTML
return $( "<a>" ).text( title ).html();
},
thus whenever you want to display html tips , just add an attribute ignoreHtml='false' on your target html element;
like this
<td title="<b>display content</b><br/>other" ignoreHtml='false'>display content</td>
http://docs.python.org/library/logging.html#logging.basicConfig
logging.basicConfig(filename='/path/to/your/log', level=....)
Take a Look at this Plugin
Makes your code as easy as -> $('SelectorToPrint').printElement();
Your comment to cletus' (correct) answer implies that there are multiple Maven settings files involved.
Maven always uses either one or two settings files. The global settings defined in (${M2_HOME}/conf/settings.xml) is always required. The user settings file (defined in ${user.home}/.m2/settings.xml) is optional. Any settings defined in the user settings take precedence over the corresponding global settings.
You can override the location of the global and user settings from the command line, the following example will set the global settings to c:\global\settings.xml and the user settings to c:\user\settings.xml:
mvn install --settings c:\user\settings.xml
--global-settings c:\global\settings.xml
Currently there is no property or means to establish what user and global settings files were used from with Maven. To access these values, you would have to modify MavenCli and/or DefaultMavenSettingsBuilder to inject the file locations into the resolved Settings object.
Note: this is purely an IDEA/AS issue, gradlew clean
| Build > Clean | Build > Rebuild will just waste your time.
Most of the solutions here are blind stabbings in the dark. Here's what I found to be the root cause:
.iml
files may be missing (maybe because we deleted it),
check if the module erroring has .iml
..idea/modules.xml
has an entry for that moduleWhile syncing I noticed that IDEA/AS tries to put a new duplicate entry into .idea/modules.xml
while there's already one. This duplicate entry is probably disposed of twice while the sync tries to reset the modules in memory.
Quick Solution: In order to make it work the easiest is to delete .idea/modules.xml
along with the .iml
files. Additionally may worth deleting .idea/modules/
folder if it exists. Restart Android Studio (no need to clear cache) and force a Gradle sync from Gradle view or toolbar to recreate the files.
The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever
). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever
.
varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.
You can try following way to check Browser version.
<!DOCTYPE html>
<html>
<body>
<p>What is the name(s) of your browser?</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 )
{
alert('Opera');
}
else if(navigator.userAgent.indexOf("Chrome") != -1 )
{
alert('Chrome');
}
else if(navigator.userAgent.indexOf("Safari") != -1)
{
alert('Safari');
}
else if(navigator.userAgent.indexOf("Firefox") != -1 )
{
alert('Firefox');
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
alert('IE');
}
else
{
alert('unknown');
}
}
</script>
</body>
</html>
And if you need to know only IE Browser version then you can follow below code. This code works well for version IE6 to IE11
<!DOCTYPE html>
<html>
<body>
<p>Click on Try button to check IE Browser version.</p>
<button onclick="getInternetExplorerVersion()">Try it</button>
<p id="demo"></p>
<script>
function getInternetExplorerVersion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
var rv = -1;
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
{
if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
//For IE 11 >
if (navigator.appName == 'Netscape') {
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1);
alert(rv);
}
}
else {
alert('otherbrowser');
}
}
else {
//For < IE11
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
}
return false;
}}
</script>
</body>
</html>
Since 1.25.4, docker-compose supports the option --env-file
that enables you to specify a file containing variables.
Yours should look like this:
hostname=my-host-name
And the command:
docker-compose --env-file /path/to/my-env-file config
You can push the tags like this git push --tags
First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.
Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.
Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.
So, to sum it all up:
ptr++; // Pointer moves to the next int position (as if it was an array)
++ptr; // Pointer moves to the next int position (as if it was an array)
++*ptr; // The value of ptr is incremented
++(*ptr); // The value of ptr is incremented
++*(ptr); // The value of ptr is incremented
*ptr++; // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value of ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr; // Pointer moves to the next int position, and then get's accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault
As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.
EDIT:
So I was wrong, the precedence is a little more complicated than what I wrote, view it here: http://en.cppreference.com/w/cpp/language/operator_precedence
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
Hey so the accepted answer works, except if you need to debug the initial launch of the app. However I think that answer is more of a work around, and not an actual solution. From my understanding this message occurs when you have some weirdness in your provisioning profile / cert setup so make extra sure everything is in tip-top shape in that dept. before ramming your head against the wall repeatedly.
What worked for me was as follows from the apple docs:
Provisioning Profiles Known Issue If you have upgraded to the GM seed from other betas you may see your apps crashing due to provisioning profile issues.
Workaround:
Connect the device via USB to your Mac
Launch Xcode Choose Window ->Devices
Right click on the device in left column, choose "Show Provisioning Profiles"
Click on the provisioning profile in question
Press the "-" button Continue to removing all affected profiles.
Re-install the app
Make sure you right click on the image of the device not the name of the device or you won't see the provisioning profiles option. I restored my new phone from an old backup and there was a lot of cruft hanging around, i also had 2 different dev. certs active (not sure why) but i deleted one, made a new profile got rid of all the profiles on device and it worked.
Hope this helps someone else.
The only thing that worked for me -i command line argument.
Just put all your python code inside a .py file and then run the following command;
python -i script.py
It means that if you set -i variable and run your module then python doesn't exit on SystemExit. Read more at the this link.
This answer by Jaap :
<div class="image"></div>?
and in CSS :
div.image {
content:url(http://placehold.it/350x150);
}?
you can try it on this link : http://jsfiddle.net/XAh2d/
this is a link about css content http://css-tricks.com/css-content/
This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)
I've found that if the input has no name (e.g. the name attribute is not set), the browser can't autocomplete the field. I know this is not a solution for everyone, but if you submit your form through AJAX, you may try this.
Using the constraints
features UniqueConstraint
is preferred over unique_together.
From the Django documentation for unique_together
:
Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.
For example:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
]
Simple and better solution : %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe MyProject.sln I make a bat file like this %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe D:\GESTION-SOMECOPA\GestionCommercial\GestionCommercial.sln pause
Then I can see all errors and correct them. Because when you change the folder name (without spaces as seen above) you will have another problems. Visual Studio 2015 works fine after this.
You can use parents
method with specified .class
selector and check if any of them matches it:
if ($elem.parents('.left').length != 0) {
//someone has this class
}
In general, using update is better in MongoDB as it will just create the document if it doesn't exist yet, though I'm not sure how to work that with your python adapter.
Second, if you only need to know whether or not that document exists, count() which returns only a number will be a better option than find_one which supposedly transfer the whole document from your MongoDB causing unnecessary traffic.
You can use the blade template engine:
@include('view.name')
'view.name' would live in your main views folder:
// for laravel 4.X
app/views/view/name.blade.php
// for laravel 5.X
resources/views/view/name.blade.php
Another example
@include('hello.world');
would display the following view
// for laravel 4.X
app/views/hello/world.blade.php
// for laravel 5.X
resources/views/hello/world.blade.php
Another example
@include('some.directory.structure.foo');
would display the following view
// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php
// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php
So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views
folder for laravel 4.x or your resources/views
folder in laravel 5.x
ADDITIONAL
If you want to pass parameters: @include('view.name', array('paramName' => 'value'))
You can then use the value in your views like so <p>{{$paramName}}</p>
One is assigning a value while the other is adding to the Dictionary a new Key and Value.
You can create you own operator :
'%&%' <- function(x, y)paste0(x,y)
"new" %&% "operator"
[1] newoperator`
You can also redefine 'and' (&
) operator :
'&' <- function(x, y)paste0(x,y)
"dirty" & "trick"
"dirtytrick"
messing with baseline syntax is ugly, but so is using paste()/paste0()
if you work only with your own code you can (almost always) replace logical & and
operator with *
and do multiplication of logical values instead of using logical 'and &'
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
The connect router has now been removed (https://github.com/senchalabs/connect/issues/262), the author stating that you should use a framework on top of connect (like Express) for routing.
Express currently treats app.get("/foo*")
as app.get(/\/foo(.*)/)
, removing the need for two separate routes. This is in contrast to the previous answer (referring to the now removed connect router) which stated that "*
in a path is replaced with .+
".
Update: Express now uses the "path-to-regexp" module (since Express 4.0.0) which maintains the same behavior in the version currently referenced. It's unclear to me whether the latest version of that module keeps the behavior, but for now this answer stands.
A clean example.
<?php
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="example.txt"');
header("Content-Length: " . filesize("example.txt"));
$fp = fopen("example.txt", "r");
fpassthru($fp);
fclose($fp);
?>
In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.
This could be leveraged to act like a "global variable", plus you can refer to the value from VBA and in a worksheet cell, and the assigned value will even persist after closing & re-opening the workbook!
To "declare" the name myVariable
and assign it a value of 123
:
ThisWorkbook.Names.Add "myVariable", 123
To retrieve the value (for example to display the value in a MsgBox
):
MsgBox [myVariable]
Alternatively, you could refer to the name with a string: (identical result as square brackets)
MsgBox Evaluate("myVariable")
To use the value on a worksheet just use it's name in your formula as-is:
=myVariable
In fact, you could even store function expressions: (sort of like in JavaScript)
(Admittedly, I can't actually think of a situation where this would be beneficial - but I don't use them in JS either.)
ThisWorkbook.Names.Add "myDay", "=if(isodd(day(today())),""on day"",""off day"")"
Square brackets are just a shortcut for the Evaluate method. I've heard that using them is considered messy or "hacky", but I've had no issues and their use in Excel is supported by Microsoft.
There is probably also a way use the Range
function to refer to these names, but I don't see any advantage so I didn't look very deeply into it.
Names.Add
method (Excel)Application.Evaluate
method (Excel)This is an example using the Expr() Class - I needed this too some days ago and it took me some time to find out what is the exact syntax and way of usage:
/**
* fetches Products that are more expansive than the given price
*
* @param int $price
* @return array
*/
public function findProductsExpensiveThan($price)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$q = $qb->select(array('p'))
->from('YourProductBundle:Product', 'p')
->where(
$qb->expr()->gt('p.price', $price)
)
->orderBy('p.price', 'DESC')
->getQuery();
return $q->getResult();
}
In your example, you can simply replace null
with `nil and it will work fine.
require 'erb'
template = <<EOS
<% if (@objectname != nil) then %>
@objectname is not nil
<% else %>
@objectname is nil
<% end %>
EOS
@objectname = nil
ERB.new(template, nil, '>').result # => " @objectname is nil\n"
@objectname = 'some name'
ERB.new(template, nil, '>').result # => " @objectname is not nil\n"
Contrary to what the other poster said, you can see above that then
works fine in Ruby. It's not common, but it is fine.
#blank?
and #present?
have other implications. Specifically, if the object responds to #empty?
, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.
Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be
require 'erb'
template = <<EOS
<% if @objectname %>
@objectname is not nil
<% else %>
@objectname is nil
<% end %>
EOS
@objectname = nil
ERB.new(template, nil, '>').result # => " @objectname is nil\n"
@objectname = 'some name'
ERB.new(template, nil, '>').result # => " @objectname is not nil\n"
If you explicitly need to check nil
and not false
, you can use the #nil?
method, for which nil is the only object that will cause this to return true.
nil.nil? # => true
false.nil? # => false
Object.new.nil? # => false
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
I got this error because Int was int in one file. So stupid.
Finally I am able to upload image using Django. Here is my working code
views.py
class FileUploadView(APIView):
parser_classes = (FileUploadParser, )
def post(self, request, format='jpg'):
up_file = request.FILES['file']
destination = open('/Users/Username/' + up_file.name, 'wb+')
for chunk in up_file.chunks():
destination.write(chunk)
destination.close() # File should be closed only after all chuns are added
# ...
# do some stuff with uploaded file
# ...
return Response(up_file.name, status.HTTP_201_CREATED)
urls.py
urlpatterns = patterns('',
url(r'^imageUpload', views.FileUploadView.as_view())
curl request to upload
curl -X POST -S -H -u "admin:password" -F "[email protected];type=image/jpg" 127.0.0.1:8000/resourceurl/imageUpload
Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.
Javascript code embedded aswell:
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
});
declare @EventId int
CREATE TABLE #EventId (EventId int)
insert into #EventId exec rptInputEventId
set @EventId = (select * from #EventId)
drop table #EventId
You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.
Update
brew tap adoptopenjdk/openjdk
brew cask install adoptopenjdk/openjdk/adoptopenjdk8
https://stackoverflow.com/a/28635465
Old version For me the easiest and cleanest way to go is to install Java using homebrew like described here:
https://stackoverflow.com/a/28635465
brew update
brew cask install java
From ioS 7 onwards, there are newer ways for apps to run in background. Apple now recognizes that apps have to constantly download and process data constantly.
- Apps that play audible content to the user while in the background, such as a music player app
- Apps that record audio content while in the background.
- Apps that keep users informed of their location at all times, such as a navigation app
- Apps that support Voice over Internet Protocol (VoIP)
- Apps that need to download and process new content regularly
- Apps that receive regular updates from external accessories
You can declare app's supported background tasks in Info.plist using X Code 5+. For eg. adding UIBackgroundModes key to your app’s Info.plist file and adding a value of 'fetch' to the array allows your app to regularly download and processes small amounts of content from the network. You can do the same in the 'capabilities' tab of Application properties in XCode 5 (attaching a snapshot)
You can find more about this in Apple documentation
The ability to search commits has recently been added to GitHub.
To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master
), or the "Issues" tab to see pull requests containing the commit.
To be more explicit you can add the hash:
prefix to the search, but it's not really necessary.
There is also a REST API (at the time of writing it is still in preview).
Frame vs bounds
The easiest way without fiddling with command line:
Next time you want to use it, just click on the ios simulator icon in the dock.
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test("ABC") ("DEF")
A quick search on the conda official docs will help you to find what each flag does.
So far:
-y
: Do not ask for confirmation.-f
: I think it should be --file
, so it read package versions from the given file.-q
: Do not display progress bar.-c
: Additional channel to search for packages. These are URLs searched in the orderPress SHIFT 2 times and you can search Every-where , both Class and Method() in the project.
Ctrl + N for finding only Class name.
Ctrl + E for Recent Files.
anytime you run into this type of thing you should always think of your transaction log. The alter db statment with rollback immediate indicates this to be the case. Check this out: http://msdn.microsoft.com/en-us/library/ms189085.aspx
Bone up on checkpoints, etc. You need to decide if the transactions in your log are worth saving or not and then pick the mode to run your db in accordingly. There's really no reason for you to have to wait but also no reason for you to lose data either - you can have both.