Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
A new (Keller) method is supposed to improve speed over the -9999px method:
.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
recommended here:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/
I used to ponder and desire the same feature. But over time, I noticed it really isn't needed. When you stash, it's OK to leave the new files. Nothing "bad" can happen to them (when you check out something else, git will error and not overwrite the existing untracked file)
And since usually the time frame between the git stash
and the git stash pop
is rather small, you'll be needing the untracked file quickly again.
So I would say the inconvenience of the file showing up in git status
while you're working on something else (between the git stash
and the git stash pop
) is smaller then the inconvenience caused by the work and needed attention it would otherwise cost to try to add the untracked file to your stash.
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Tutorial" bundle:nil];
self.window.rootViewController = [storyboard instantiateInitialViewController];
I have modified the Coop's answer. Please check the example FIDDLE Here's my edits:
$(window).scroll(function(){
if ($(window).scrollTop() >= 330) {
$('.sticky-header').addClass('fixed');
}
else {
$('.sticky-header').removeClass('fixed');
}
});
something
{
something1
something2
}
something3
In Python
Something
something1
something2
something3
my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)
public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}
}
As an addition to @dulgan's answer, it is always a good approach to use firstObject
over objectAtIndex:0
, because while first one returns nil if there is no object in the array, latter one throws exception.
UIViewController *rootViewController = self.navigationController.rootViewController;
Alternatively, it'd be a big plus for you to create a category named UINavigationController+Additions
and define your method in that.
@interface UINavigationController (Additions)
- (UIViewController *)rootViewController;
@end
@implementation UINavigationController (Additions)
- (UIViewController *)rootViewController
{
return self.viewControllers.firstObject;
}
@end
You can use the following excel statement:
="INSERT INTO table_name(`"&$A$1&"`,`"&$B$1&"`,`"&$C$1&"`, `"&$D$1&"`) VALUES('"&SUBSTITUTE(A2, "'", "\'")&"','"&SUBSTITUTE(B2, "'", "\'")&"','"&SUBSTITUTE(C2, "'", "\'")&"', "&D2&");"
This improves upon Hart CO's answer as it takes into account column names and gets rid of compile errors due to quotes in the column. The final column is an example of a numeric value column, without quotes.
I have found the solution to this issue using ObjectDoesNotExist on this way
from django.core.exceptions import ObjectDoesNotExist
......
try:
# try something
except ObjectDoesNotExist:
# do something
After this, my code works as I need
Thanks any way, your post help me to solve my issue
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
class SuperType {
public static void classMethod(){
System.out.println("Super type class method");
}
public void instancemethod(){
System.out.println("Super Type instance method");
}
}
public class SubType extends SuperType{
public static void classMethod(){
System.out.println("Sub type class method");
}
public void instancemethod(){
System.out.println("Sub Type instance method");
}
public static void main(String args[]){
SubType s=new SubType();
SuperType su=s;
SuperType.classMethod();// Prints.....Super type class method
su.classMethod(); //Prints.....Super type class method
SubType.classMethod(); //Prints.....Sub type class method
}
}
This example for static method overriding
Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.
Static method belongs to class only.
It's not an insert if the record already exists in t1 (the user_id matches) unless you are happy to create duplicate user_id's.
You might want an update?
UPDATE t1
SET <t1.col_list> = (SELECT <t2.col_list>
FROM t2
WHERE t2.user_id = t1.user_id)
WHERE EXISTS
(SELECT 1
FROM t2
WHERE t1.user_id = t2.user_id);
Hope it helps...
This can be easily solved with the the utility make_axes_locatable
. I provide a minimal example that shows how this works and should be readily adaptable:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
m1 = np.random.rand(3, 3)
m2 = np.arange(0, 3*3, 1).reshape((3, 3))
fig = plt.figure(figsize=(16, 12))
ax1 = fig.add_subplot(121)
im1 = ax1.imshow(m1, interpolation='None')
divider = make_axes_locatable(ax1)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im1, cax=cax, orientation='vertical')
ax2 = fig.add_subplot(122)
im2 = ax2.imshow(m2, interpolation='None')
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im2, cax=cax, orientation='vertical');
In iOS 7 you must use the -barTintColor property:
navController.navigationBar.barTintColor = [UIColor barColor];
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
There are two ways to update your code. 1. Please open the file app.php file present in config directory at lool of your project. Go down the page and check Application Timezone where you will find
'timezone' => 'UTC',
Here you can add your timezone like
'timezone' => 'Europe/Paris',
If you want to manage your timezone from .env
file, then you can add below code in your config.php
file.
'timezone' => env('APP_TIMEZONE', 'UTC'),
and add the below line in your .env
file.
APP_TIMEZONE='Europe/Paris'
Please check the link below for more information: https://laravel.com/docs/5.6/configuration#accessing-configuration-values
I use the Apache commons HTTP Client package to do this in my current project and it works fine with SSL and a self-signed cert (after installing it into cacerts like you mentioned). Please take a look at it here:
This is what I use:
public static bool IsValidFileName(this string expression, bool platformIndependent)
{
string sPattern = @"^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$";
if (platformIndependent)
{
sPattern = @"^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?))\\)*[^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?$";
}
return (Regex.IsMatch(expression, sPattern, RegexOptions.CultureInvariant));
}
The first pattern creates a regular expression containing the invalid/illegal file names and characters for Windows platforms only. The second one does the same but ensures that the name is legal for any platform.
No need to modify the Makefile.
$ cat printvars.mak
print-%:
@echo '$*=$($*)'
$ cd /to/Makefile/dir
$ make -f ~/printvars.mak -f Makefile print-VARIABLE
Easy way with the popular (over 5m weekly downloads) and lightweight get-stream library:
https://www.npmjs.com/package/get-stream
const fs = require('fs');
const getStream = require('get-stream');
(async () => {
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream)); //output is string
})();
$("#startDate").val($.datepicker.formatDate("dd/mm/yy", new Date()));
$("#endDate").val($.datepicker.formatDate("dd/mm/yy", new Date()));
Add the above code at the end of the script. This is required because the datepicker plugin has no provision to set the date in the control while initializing.
You would be a fool not to use Perl.. Here come the flames..
Bone up on the following modules and ginsu any scrape around.
use LWP
use HTML::TableExtract
use HTML::TreeBuilder
use HTML::Form
use Data::Dumper
In my case, while playing video, I needed to call a function everytime currentTime
of video updates. So I used timeupdate
event of video and I came to know that it was fired at least 4 times a second (depends on the browser you use, see this). So I changed it to call a function every second like this:
var currentIntTime = 0;
var someFunction = function() {
currentIntTime++;
// Do something here
}
vidEl.on('timeupdate', function(){
if(parseInt(vidEl.currentTime) > currentIntTime) {
someFunction();
}
});
This reduces calls to someFunc
by at least 1/3
and it may help your browser to behave normally. It did for me !!!
Oracle
's locking concept is quite different from that of the other systems.
When a row in Oracle
gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.
This means that locking a record in Oracle
means updating the record's metadata and issuing a logical page write. For instance, you cannot do SELECT FOR UPDATE
on a read only tablespace.
More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.
This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.
Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.
You can obtain some special locks, like locked metadata objects (using v$locked_object
), lock waits (using v$session
) etc, but not the list of all locks on all objects in the database.
If you use nano with a language like python (as in your example) it's also a good idea to convert tabs to spaces.
Edit your ~/.nanorc file (or create it) and add:
set tabsize 4
set tabstospaces
If you already got a file with tabs and want to convert them to spaces i recommend the expand
command (shell):
expand -4 input.py > output.py
If you have an object and wish to become JObject you can use:
JObject o = (JObject)JToken.FromObject(miObjetoEspecial);
like this :
Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};
JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}
Here you have an example of a Dockerfile that runs nginx. As mentionned by Charles, it uses the daemon off
configuration:
https://github.com/darron/docker-nginx-php5/blob/master/Dockerfile#L17
Answer if you only want to use for each loop ..
for (WebElement s : options) {
int i = options.indexOf(s);
System.out.println(options.get(i).getText());
}
You're not including the C file that contains main()
when compiling, so the linker isn't seeing it.
You need to add it:
$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp
Create a text node and append it to the button element:
var t = document.createTextNode("test content");
b.appendChild(t);
This is an existing code posted above but I have updated it for IE's, the bug was when the existing text is selected and pasted will not delete the selected content. This has been fixed by the below code
selRange.deleteContents();
See complete code below
$('[contenteditable]').on('paste', function (e) {
e.preventDefault();
if (window.clipboardData) {
content = window.clipboardData.getData('Text');
if (window.getSelection) {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
selRange.deleteContents();
selRange.insertNode(document.createTextNode(content));
}
} else if (e.originalEvent.clipboardData) {
content = (e.originalEvent || e).clipboardData.getData('text/plain');
document.execCommand('insertText', false, content);
}
});
You have to use the String method .toLowerCase()
or .toUpperCase()
on both the input and the string you are trying to match it with.
Example:
public static void findPatient() {
System.out.print("Enter part of the patient name: ");
String name = sc.nextLine();
System.out.print(myPatientList.showPatients(name));
}
//the other class
ArrayList<String> patientList;
public void showPatients(String name) {
boolean match = false;
for(String matchingname : patientList) {
if (matchingname.toLowerCase().contains(name.toLowerCase())) {
match = true;
}
}
}
To update entries other than appsettings
, simply use XmlDocument
.
public static void UpdateAppConfig(string tagName, string attributeName, string value)
{
var doc = new XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var tags = doc.GetElementsByTagName(tagName);
foreach (XmlNode item in tags)
{
var attribute = item.Attributes[attributeName];
if (!ReferenceEquals(null, attribute))
attribute.Value = value;
}
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
This is how you call it:
Utility.UpdateAppConfig("endpoint", "address", "http://localhost:19092/NotificationSvc/Notification.svc");
Utility.UpdateAppConfig("network", "host", "abc.com.au");
This method can be improved to cater for appSettings values as well.
You may also want to try two backslashes (\\")
to escape the escape character.
Don't forget to call this.
style.setFillPattern(CellStyle.Align_Fill);
Parameter may differ according to your need. Maybe CellStyle.FINE_DOTS or so.
Here you can find solutions for both your problems.
document.body.style.height = '500px';
document.body.addEventListener('click', function(e){
var self = this,
old_bg = this.style.background;
this.style.background = this.style.background=='green'? 'blue':'green';
setTimeout(function(){
self.style.background = old_bg;
}, 1000);
})
var map = new google.maps.Map(document.getElementById("map"),{
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
bounds.extend(marker.position);
}
map.fitBounds(bounds);
Use text-center
class in the parent container for Bootstrap 4
To bring more prominence to the useful comment by @johanvdw:
If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile
file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/"
somewhere in the file.
When Cygwin starts, it'll search directories in PATH and this one for executable files to run.
here's a f# version:
let reverseNumber n =
let rec loop acc = function
|0 -> acc
|x -> loop (acc * 10 + x % 10) (x/10)
loop 0 n
let isPalindrome = function
| x when x = reverseNumber x -> true
| _ -> false
That's the compiler that comes with Apple's XCode tools package. They've hacked on it a little, but basically it's just g++.
You can download XCode for free (well, mostly, you do have to sign up to become an ADC member, but that's free too) here: http://developer.apple.com/technology/xcode.html
Edit 2013-01-25: This answer was correct in 2010. It needs an update.
While XCode tools still has a command-line C++ compiler, In recent versions of OS X (I think 10.7 and later) have switched to clang/llvm (mostly because Apple wants all the benefits of Open Source without having to contribute back and clang is BSD licensed). Secondly, I think all you have to do to install XCode is to download it from the App store. I'm pretty sure it's free there.
So, in order to get g++ you'll have to use something like homebrew (seemingly the current way to install Open Source software on the Mac (though homebrew has a lot of caveats surrounding installing gcc using it)), fink (basically Debian's apt system for OS X/Darwin), or MacPorts (Basically, OpenBSDs ports system for OS X/Darwin) to get it.
Fink definitely has the right packages. On 2016-12-26, it had gcc 5 and gcc 6 packages.
I'm less familiar with how MacPorts works, though some initial cursory investigation indicates they have the relevant packages as well.
Try this
String str="10,692,467,440,017.120".replaceAll(",","");
BigDecimal bd=new BigDecimal(str);
To open in a new tab use:
target = "_blank"
To open in the same tab use:
target = "_self"
May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.
//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
This is the correct way:
To execute code that will only be available to the index page, we could use this syntax:
$(document).on('pageinit', "#index", function() {
...
});
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
As Kristian Glass Said, there is no comparison between IaaS(AWS) and PaaS(Heroku, EngineYard).
PaaS basically helps developers to speed the development of app,thereby saving money and most importantly innovating their applications and business instead of setting up configurations and managing things like servers and databases. Other features buying to use PaaS is the application deployment process such as agility, High Availability, Monitoring, Scale / Descale, limited need for expertise, easy deployment, and reduced cost and development time.
But still there is a dark side to PaaS which lead barrier to PaaS adoption :
Apart from above you should have enough skill set to mange you IaaS:
If you have small scale business, PaaS will be best option for you:
It will be totally individual choice based on requirement. You can have details on my PPT Hosting Rails Apps.
My preffered way to compare nullable fields is: NULLIF(nullablefield, :ParameterValue) IS NULL AND NULLIF(:ParameterValue, nullablefield) IS NULL . This is cumbersome but is of universal use while Coalesce is impossible in some cases.
The second and inverse use of NULLIF is because "NULLIF(nullablefield, :ParameterValue) IS NULL" will always return "true" if the first parameter is null.
The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.
Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.
Here's an example of using a variable in plpgsql:
create table test (id int);
insert into test values (1);
insert into test values (2);
insert into test values (3);
create function test_fn() returns int as $$
declare val int := 2;
begin
return (SELECT id FROM test WHERE id = val);
end;
$$ LANGUAGE plpgsql;
SELECT * FROM test_fn();
test_fn
---------
2
Have a look at the plpgsql docs for more information.
For me as I have already xampp on 127.0.0.1 and django on 127.0.1.1 and i kept trying adding hosts
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'www.yourdomain.com', '*', '127.0.1.1']
and i got the same error or (400) bad request
so I change the url to 127.0.1.1:(the used port)/project and voila !
you have to check what is your virtual network address, for me as i use bitnami django stack 2.2.3-1 on Linux i can check which port django is using. if you have an error ( 400 bad request ) then i guess django on different virtual network .. good luck
Another way to generate the serialVersionUID is to use >Analyze >Run Inspection by Name
from the context menu ( or the keyboard short cut, which is ctrl+alt+shift+i by default) and then type "Serializable class without 'serialVersionUID'" (or simply type "serialVersionUID" and the type ahead function will find it for you.
You will then get a context menu where you can choose where to run the inspections on (e.g. all from a specific module, whole project, one file, ...)
With this approach you don't even have to set the general inspection rules to anything.
Add 0.001
first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)
Code example:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(b);
}
I found out you can only share either Text or Image, not both using Intents
. Below code shares only Image if exists, or only Text if Image does not exits. If you want to share both, you need to use Facebook SDK from here.
If you use other solution instead of below code, don't forget to specify package name com.facebook.lite as well, which is package name of Facebook Lite. I haven't test but com.facebook.orca is package name of Facebook Messenger if you want to target that too.
You can add more methods for sharing with WhatsApp, Twitter ...
public class IntentShareHelper {
/**
* <b>Beware,</b> this shares only image if exists, or only text if image does not exits. Can't share both
*/
public static void shareOnFacebook(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,!TextUtils.isEmpty(textBody) ? textBody : "");
if (fileUri != null) {
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
}
boolean facebookAppFound = false;
List<ResolveInfo> matches = appCompatActivity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana") ||
info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.lite")) {
intent.setPackage(info.activityInfo.packageName);
facebookAppFound = true;
break;
}
}
if (facebookAppFound) {
appCompatActivity.startActivity(intent);
} else {
showWarningDialog(appCompatActivity, appCompatActivity.getString(R.string.error_activity_not_found));
}
}
public static void shareOnWhatsapp(AppCompatActivity appCompatActivity, String textBody, Uri fileUri){...}
private static void showWarningDialog(Context context, String message) {
new AlertDialog.Builder(context)
.setMessage(message)
.setNegativeButton(context.getString(R.string.close), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setCancelable(true)
.create().show();
}
}
For getting Uri from File, use below class:
public class UtilityFile {
public static @Nullable Uri getUriFromFile(Context context, @Nullable File file) {
if (file == null)
return null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
return FileProvider.getUriForFile(context, "com.my.package.fileprovider", file);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
return Uri.fromFile(file);
}
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public static Uri getLocalBitmapUri(Context context, ImageView imageView) {
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
// Use methods on Context to access package-specific directories on external storage.
// This way, you don't need to request external read/write permission.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = getUriFromFile(context, file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
}
For writing FileProvider, use this link: https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents
Is it good to use async action everywhere in ASP.NET MVC?
It's good to do so wherever you can use an async method especially when you have performance issues at the worker process level which happens for massive data and calculation operations. Otherwise, no need because unit testing will need casting.
Regarding awaitable methods: shall I use async/await keywords when I want to query a database (via EF/NHibernate/other ORM)?
Yes, it's better to use async for any DB operation as could as possible to avoid performance issues at the level of worker processes. Note that EF has created many async alternatives for most operations, such as:
.ToListAsync()
.FirstOrDefaultAsync()
.SaveChangesAsync()
.FindAsync()
How many times can I use await keywords to query the database asynchronously in one single action method?
The sky is the limit
In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.
self.clear = function () {
//location.reload(true); Doesn't work to IE neither Firefox;
//also, hash tags must be removed or no postback will occur.
window.location.href = window.location.href.replace(/#.*$/, '');
};
You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi
In case you get the error "No 'Access-Control-Allow-Origin' header is present on the requested resource." Specifically for PUT and DELETE requests, you could try to disable WebDAV on IIS.
Apparently, the WebDAVModule is enabled by default and is disabling PUT and DELETE requests by default.
To disable the WebDAVModule, add this to your web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
</system.webServer>
I think the answer given by D. Squire was accurate, but possibly only a tad vague. If you change directories to a project and then type ng --version, it will display the angular version in the project. If done from a default directory (not within a project), you will only get the Angular CLI version, which is probably not what you are looking for and will give the output shown by Vik2696.
$ cd my-project
$ ng --version // done within project directory
Angular CLI: 1.6.8
Node: 8.9.4
OS: win32 x64
Angular: 5.2.5
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
@angular/cli: 1.6.8
@angular-devkit/build-optimizer: 0.0.42
@angular-devkit/core: 0.0.29
@angular-devkit/schematics: 0.0.52
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.8
@schematics/angular: 0.1.17
typescript: 2.5.3
webpack: 3.10.0
I've settled on one based on Nultyi's answer:
MISSING=$(dpkg --get-selections $PACKAGES 2>&1 | grep -v 'install$' | awk '{ print $6 }')
# Optional check here to skip bothering with apt-get if $MISSING is empty
sudo apt-get install $MISSING
Basically, the error message from dpkg --get-selections
is far easier to parse than most of the others, because it doesn't include statuses like "deinstall". It also can check multiple packages simultaneously, something you can't do with just error codes.
Explanation/example:
$ dpkg --get-selections python3-venv python3-dev screen build-essential jq
dpkg: no packages found matching python3-venv
dpkg: no packages found matching python3-dev
screen install
build-essential install
dpkg: no packages found matching jq
So grep removes installed packages from the list, and awk pulls the package names out from the error message, resulting in MISSING='python3-venv python3-dev jq'
, which can be trivially inserted into an install command.
I'm not blindly issuing an apt-get install $PACKAGES
because as mentioned in the comments, this can unexpectedly upgrade packages you weren't planning on; not really a good idea for automated processes that are expected to be stable.
is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6
I've reworked VonC's script to do everything automatically and not ask me for anything. You give it two commit SHA1s and it will squash everything between them into one commit named "squashed history":
#!/bin/sh
# Go back to the last commit that we want
# to form the initial commit (detach HEAD)
git checkout $2
# reset the branch pointer to the initial commit (= $1),
# but leaving the index and working tree intact.
git reset --soft $1
# amend the initial tree using the tree from $2
git commit --amend -m "squashed history"
# remember the new commit sha1
TARGET=`git rev-list HEAD --max-count=1`
# go back to the original branch (assume master for this example)
git checkout master
# Replay all the commits after $2 onto the new initial commit
git rebase --onto $TARGET $2
To open the Eye Dropper simply:
Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.
The second form is preferred:
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(3);
arr.add("ss");
Always specify generic arguments when using generic types (such as ArrayList<T>
). This rules out the first form.
As to the last form, it is more verbose and does extra work for no benefit.
You need to iterate the 2d array in order to get the min value of each row, then you have to push any gotten min value to another array and finally you need to get the min value of the array where each min row value was pushed
def get_min_value(self, table):
min_values = []
for i in range(0, len(table)):
min_value = min(table[i])
min_values.append(min_value)
return min(min_values)
Improvement of Alejandro's answer. You can leave the $start
or $end
arguments empty and it will use the start or end of the string.
echo get_string_between("Hello my name is bob", "my", ""); //output: " name is bob"
private function get_string_between($string, $start, $end){ // Get
if($start != ''){ //If $start is empty, use start of the string
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
}
else{
$ini = 0;
}
if ($end == '') { //If $end is blank, use end of string
return substr($string, $ini);
}
else{
$len = strpos($string, $end, $ini) - $ini; //Work out length of string
return substr($string, $ini, $len);
}
}
You can do
result = {'a': 'b'}
return jsonify(result), 201
if you want to return a JSON data in the response along with the error code You can read about responses here and here for make_response API details
I thought I had this configured but it turns out I set the URL in the wrong place. I followed the URL provided in the Google error page and added my URL here. Stupid mistake from my part, but easily done. Hope this helps
timestamp=$(awk 'BEGIN {srand(); print srand()}')
srand without a value uses the current timestamp with most Awk implementations.
What you can try is writing your code as normal for python using the normal input
command. However the trick is to add at the beginning of you program the command input=raw_input
.
Now all you have to do is disable (or enable) depending on if you're running in Python/IDLE or Terminal. You do this by simply adding '#' when needed.
Switched off for use in Python/IDLE
#input=raw_input
And of course switched on for use in terminal.
input=raw_input
I'm not sure if it will always work, but its a possible solution for simple programs or scripts.
You could also use the following function.
void tokenize(const string& str, vector<string>& tokens, const string& delimiters = ",")
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first non-delimiter.
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters.
lastPos = str.find_first_not_of(delimiters, pos);
// Find next non-delimiter.
pos = str.find_first_of(delimiters, lastPos);
}
}
If we get the value as int
and we set it to String
, the error occurs. PFB my solution,
Textview = tv_property_count;
int property_id;
tv_property_count.setText(String.valueOf(property_id));
Frustratingly the Numpy package published to PyPI won't install on most Windows computers https://github.com/numpy/numpy/issues/5479
Instead:
pip install numpy-1.10.2+mkl-cp35-none-win_amd64.whl
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
These are my favorite
Haskell: Functional Programming with Types
Joeri van Eekelen, et al. | Wikibooks
Published in 2012, 597 pages
B. O'Sullivan, J. Goerzen, D. Stewart | OReilly Media, Inc.
Published in 2008, 710 pages
In my case, the error occured when I tried to pass a variable which was looking like a bytes-object (b"xxxx") but was actually a string.
You can convert the string to a real bytes object like this:
foo.strip('b"').replace("\\n", "\n").encode()
My five cents:
Both direction array of integers function.
When range(0, 5) become [0, 1, 2, 3, 4, 5]
.
And range(5, 0) become [5, 4, 3, 2, 1, 0]
.
Based on this answer.
function range(start, end) {
const isReverse = (start > end);
const targetLength = isReverse ? (start - end) + 1 : (end - start ) + 1;
const arr = new Array(targetLength);
const b = Array.apply(null, arr);
const result = b.map((discard, n) => {
return (isReverse) ? n + end : n + start;
});
return (isReverse) ? result.reverse() : result;
}
P.S. For use in real life you should also check args for isFinite()
and isNaN()
.
You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.
class Book {
public BookId: number;
public Title: string;
public Author: string;
public Price: number;
public Description: string;
}
var bks: Book[] = [];
bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"}); //This is all done in JSON.
While some of the above solutions work, I thought I'd post our eventual solution - which defines a 'ready' method that will fire as soon as FB is initialized and ready to go. It has the advantage over other solutions that it's safe to call either before or after FB is ready.
It can be used like so:
f52.fb.ready(function() {
// safe to use FB here
});
Here's the source file (note that it's defined within a 'f52.fb' namespace).
if (typeof(f52) === 'undefined') { f52 = {}; }
f52.fb = (function () {
var fbAppId = f52.inputs.base.fbAppId,
fbApiInit = false;
var awaitingReady = [];
var notifyQ = function() {
var i = 0,
l = awaitingReady.length;
for(i = 0; i < l; i++) {
awaitingReady[i]();
}
};
var ready = function(cb) {
if (fbApiInit) {
cb();
} else {
awaitingReady.push(cb);
}
};
window.fbAsyncInit = function() {
FB.init({
appId: fbAppId,
xfbml: true,
version: 'v2.0'
});
FB.getLoginStatus(function(response){
fbApiInit = true;
notifyQ();
});
};
return {
/**
* Fires callback when FB is initialized and ready for api calls.
*/
'ready': ready
};
})();
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
Nobody pointed out that if you have a single vector, and want to find the angle of the vector from the X axis, you can take advantage of the fact that the argument to atan2() is actually the slope of the line, or (delta Y / delta X). So if you know the slope, you can do the following:
given:
A = angle of the vector/line you wish to determine (from the X axis).
m = signed slope of the vector/line.
then:
A = atan2(m, 1)
Very useful!
Here ya go.
const arr = Array.from(el.features.selectedOptions) //get array from selectedOptions property
const list = []
arr.forEach(item => list.push(item.value)) //push each item to empty array
console.log(list)
The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:
If t
is a Tensor
object, t.eval()
is shorthand for sess.run(t)
(where sess
is the current default session. The two following snippets of code are equivalent:
sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)
c = tf.constant(5.0)
with tf.Session():
print c.eval()
In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with
block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run()
.
I'd recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.
One possible reason for this error is: your annual subscription has been renewed. Once the subscription is renewed, all devices related to the active provision profiles will be detached.
After this, rebuild project with Xcode and the error will disappear.
use whereIn
condition and pass the array
$array = [1008,1009,1010];
User::whereIn('users.id', $array)->get();
Here's a really simple approach, worked well for me, courtesy Davy Schmeits's Weblog:
cat foo | col -b > foo2
Where foo is the file that has the Control+M characters at the end of the line, and foo2 the new file you are creating.
In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.
I tried the code posted by larsmans above but, there are a couple of problems:
1) The code as is will throw the error as mentioned by mauguerra 2) If you change the code to the following:
...
d1 = d1.strftime("%Y-%m-%d")
d2 = d2.strftime("%Y-%m-%d")
return abs((d2 - d1).days)
This will convert your datetime objects to strings but, two things
1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and 2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings
What I found is that you literally only need the following:
import datetime
end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)
print difference_in_days
You can access Current logged in user by using the following code:
request.user.id
The best way I found to do this was to use the same intent as the Android home screen uses - the app Launcher.
For example:
Intent i = new Intent(this, MyMainActivity.class);
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
This way, whatever activity in my package was most recently used by the user is brought back to the front again. I found this useful in using my service's PendingIntent to get the user back to my app.
The single " | " operator will evaluate both sides of the expression.
if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
{
// Do stuff here
}
The double operator " || " will only evaluate the left side if the expression returns true.
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
// Do stuff here
}
C# has many similarities to C++ but their still are differences between the two languages ;)
Select * from table where upper(table.name) like upper('IgNoreCaSe');
Alternatively, substitute lower for upper.
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
In this method just pass a view object and it will returns a UIImage object.
-(UIImage*)getUIImageFromView:(UIView*)yourView
{
UIGraphicsBeginImageContext(yourView.bounds.size);
[yourView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
You do not use UTF-8 to encode text data for HTML forms. The html standard defines two encodings, and the relevant part of that standard is here. The "old" encoding, than handles ascii, is application/x-www-form-urlencoded. The new one, that works properly, is multipart/form-data.
Specifically, the form declaration looks like this:
<FORM action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">
<P>
What is your name? <INPUT type="text" name="submit-name"><BR>
What files are you sending? <INPUT type="file" name="files"><BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</FORM>
And I think that's all you have to worry about - the webserver should handle it. If you are writing something that directly reads the InputStream from the web client, then you will need to read RFC 2045 and RFC 2046.
-webkit-transition: all 1s ease; /* Safari and Chrome */
-moz-transition: all 1s ease; /* Firefox */
-ms-transition: all 1s ease; /* IE 9 */
-o-transition: all 1s ease; /* Opera */
transition: all 1s ease;
just want to make a note on the above transitions only need
-webkit-transition: all 1s ease; /* Safari and Chrome */
transition: all 1s ease;
and -ms- certainly doenst work for IE 9 i dont know where you got that idea from.
First, I would check what i
gets initialized to, to see if the elements returned by getElementsByName
are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0
, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).
Also, for your if-condition, this should suffice:
if (!timetemp[0].value) {
// The value is empty.
}
else {
// The value is not empty.
}
The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.
For the Scripting.Dictionary type, you can either use late binding (as already pointed out ) with:
Dim Dict as Object
Set Dict = CreateObject("Scripting.Dictionary")
Which works, but you don't get the code auto completion. Or you use early binding, but you need to make sure that VBA can find the Scripting.Dictionary type by adding the reference to the Microsoft Scripting Library via VBA-->Tools-->References--> "Microsoft Scripting Runtime". Then you can use:
Dim Dict as Scripting.Dictionary
Set Dict = New Scripting.Dictionary
... and auto completion will work.
create table a1
(weddingTable INT(3),
tableSeat INT(3),
tableSeatID INT(6),
Name varchar(10));
insert into a1
(weddingTable, tableSeat, tableSeatID, Name)
values (001,001,001001,'Bob'),
(001,002,001002,'Joe'),
(001,003,001003,'Dan'),
(002,001,002001,'Mark');
create table a2
(weddingTable int(3),
tableSeat int(3),
Meal varchar(10));
insert into a2
(weddingTable, tableSeat, Meal)
values
(001,001,'Chicken'),
(001,002,'Steak'),
(001,003,'Salmon'),
(002,001,'Steak');
select x.*, y.Meal
from a1 as x
JOIN a2 as y ON (x.weddingTable = y.weddingTable) AND (x.tableSeat = y. tableSeat);
I've checked DamienG's answer in LinqPad. Instead of
g.Group.Max(s => s.uid)
should be
g.Max(s => s.uid)
Thank you!
In Swift 3.0,
static func callToNumber(number:String) {
let phoneFallback = "telprompt://\(number)"
let fallbackURl = URL(string:phoneFallback)!
let phone = "tel://\(number)"
let url = URL(string:phone)!
let shared = UIApplication.shared
if(shared.canOpenURL(fallbackURl)){
shared.openURL(fallbackURl)
}else if (shared.canOpenURL(url)){
shared.openURL(url)
}else{
print("unable to open url for call")
}
}
If you have access to the code that creates the canvas - simply call the function right there after the canvas is created.
If you have no access to that code (eg. If it is a 3rd party code such as google maps) then what you could do is test for the existence in an interval:
var checkExist = setInterval(function() {
if ($('#the-canvas').length) {
console.log("Exists!");
clearInterval(checkExist);
}
}, 100); // check every 100ms
But note - many times 3rd party code has an option to activate your code (by callback or event triggering) when it finishes to load. That may be where you can put your function. The interval solution is really a bad solution and should be used only if nothing else works.
From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:
const mysql = require('mysql');
var connection;
module.exports = {
dbConnection: function () {
connection = mysql.createConnection({
host: "127.0.0.1",
user: "Your_user",
password: "Your_password",
database: 'Your_bd'
});
connection.connect();
return connection;
}
};
Then, the file where you are going to use the connection could be like useDb.js:
const dbConnection = require('./db');
var connection;
function callDb() {
try {
connection = dbConnectionManager.dbConnection();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (!error) {
let response = "The solution is: " + results[0].solution;
console.log(response);
} else {
console.log(error);
}
});
connection.end();
} catch (err) {
console.log(err);
}
}
Use serialize()
on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
I usually do this with classes, that seems to force the browsers to reassess all the styling.
.hiddendiv {display:none;}
.visiblediv {display:block;}
then use;
<script>
function show() {
document.getElementById('benefits').className='visiblediv';
}
function close() {
document.getElementById('benefits').className='hiddendiv';
}
</script>
Note the casing of "className" that trips me up a lot
For me, it was a much different solution since it was running on a virtualbox, so I had to edit the hosts file and add the virtualbox as a localhost
127.0.0.1 VirtualBox-blahblah
This will do it in Delphi. Note the use of the BitBlt function, which is a Windows API call, not something specific to Delphi.
Edit: Added example usage
function TForm1.GetScreenShot(OnlyActiveWindow: boolean) : TBitmap;
var
w,h : integer;
DC : HDC;
hWin : Cardinal;
r : TRect;
begin
//take a screenshot and return it as a TBitmap.
//if they specify "OnlyActiveWindow", then restrict the screenshot to the
//currently focused window (same as alt-prtscrn)
//Otherwise, get a normal screenshot (same as prtscrn)
Result := TBitmap.Create;
if OnlyActiveWindow then begin
hWin := GetForegroundWindow;
dc := GetWindowDC(hWin);
GetWindowRect(hWin,r);
w := r.Right - r.Left;
h := r.Bottom - r.Top;
end //if active window only
else begin
hWin := GetDesktopWindow;
dc := GetDC(hWin);
w := GetDeviceCaps(DC,HORZRES);
h := GetDeviceCaps(DC,VERTRES);
end; //else entire desktop
try
Result.Width := w;
Result.Height := h;
BitBlt(Result.Canvas.Handle,0,0,Result.Width,Result.Height,DC,0,0,SRCCOPY);
finally
ReleaseDC(hWin, DC) ;
end; //try-finally
end;
procedure TForm1.btnSaveScreenshotClick(Sender: TObject);
var
bmp : TBitmap;
savdlg : TSaveDialog;
begin
//take a screenshot, prompt for where to save it
savdlg := TSaveDialog.Create(Self);
bmp := GetScreenshot(False);
try
if savdlg.Execute then begin
bmp.SaveToFile(savdlg.FileName);
end;
finally
FreeAndNil(bmp);
FreeAndNil(savdlg);
end; //try-finally
end;
The accepted answer does not preserve STDERR as a separate file descriptor. That means
./script.sh >/dev/null
will not output bar
to the terminal, only to the logfile, and
./script.sh 2>/dev/null
will output both foo
and bar
to the terminal. Clearly that's not
the behaviour a normal user is likely to expect. This can be
fixed by using two separate tee processes both appending to the same
log file:
#!/bin/bash
# See (and upvote) the comment by JamesThomasMoon1979
# explaining the use of the -i option to tee.
exec > >(tee -ia foo.log)
exec 2> >(tee -ia foo.log >&2)
echo "foo"
echo "bar" >&2
(Note that the above does not initially truncate the log file - if you want that behaviour you should add
>foo.log
to the top of the script.)
The POSIX.1-2008 specification of tee(1)
requires that output is unbuffered, i.e. not even line-buffered, so in this case it is possible that STDOUT and STDERR could end up on the same line of foo.log
; however that could also happen on the terminal, so the log file will be a faithful reflection of what could be seen on the terminal, if not an exact mirror of it. If you want the STDOUT lines cleanly separated from the STDERR lines, consider using two log files, possibly with date stamp prefixes on each line to allow chronological reassembly later on.
Try using cURL
set_time_limit(0); // unlimited max execution time
$options = array(
CURLOPT_FILE => '/path/to/download/the/file/to.zip',
CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files
CURLOPT_URL => 'http://remoteserver.com/path/to/big/file.zip',
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
I'm not sure but I believe with the CURLOPT_FILE
option it writes as it pulls the data, ie. not buffered.
You can avoid compilation errors if you remove the method definitions from the header files and let the classes contain only the method declarations and variable declarations/definitions. The method definitions should be placed in a .cpp file (just like a best practice guideline says).
The down side of the following solution is (assuming that you had placed the methods in the header file to inline them) that the methods are no longer inlined by the compiler and trying to use the inline keyword produces linker errors.
//A.h
#ifndef A_H
#define A_H
class B;
class A
{
int _val;
B* _b;
public:
A(int val);
void SetB(B *b);
void Print();
};
#endif
//B.h
#ifndef B_H
#define B_H
class A;
class B
{
double _val;
A* _a;
public:
B(double val);
void SetA(A *a);
void Print();
};
#endif
//A.cpp
#include "A.h"
#include "B.h"
#include <iostream>
using namespace std;
A::A(int val)
:_val(val)
{
}
void A::SetB(B *b)
{
_b = b;
cout<<"Inside SetB()"<<endl;
_b->Print();
}
void A::Print()
{
cout<<"Type:A val="<<_val<<endl;
}
//B.cpp
#include "B.h"
#include "A.h"
#include <iostream>
using namespace std;
B::B(double val)
:_val(val)
{
}
void B::SetA(A *a)
{
_a = a;
cout<<"Inside SetA()"<<endl;
_a->Print();
}
void B::Print()
{
cout<<"Type:B val="<<_val<<endl;
}
//main.cpp
#include "A.h"
#include "B.h"
int main(int argc, char* argv[])
{
A a(10);
B b(3.14);
a.Print();
a.SetB(&b);
b.Print();
b.SetA(&a);
return 0;
}
Remember that casing is a locale specific operation. Depending on scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not. This why I use following function in my utils library (note that type checking is not included for performance reason).
function compareStrings (string1, string2, ignoreCase, useLocale) {
if (ignoreCase) {
if (useLocale) {
string1 = string1.toLocaleLowerCase();
string2 = string2.toLocaleLowerCase();
}
else {
string1 = string1.toLowerCase();
string2 = string2.toLowerCase();
}
}
return string1 === string2;
}
It looks like you're using the wrong tool there. Grep isn't that sophisticated, I think you want to step up to awk as the tool for the job:
awk '/blah/ { getline; print $0 }' logfile
If you get any problems let me know, I think its well worth learning a bit of awk, its a great tool :)
p.s. This example doesn't win a 'useless use of cat award' ;) http://porkmail.org/era/unix/award.html
use auto and min or max width like this:
td {
max-width:50px;
width:auto;
min-width:10px;
}
I found my realm file by issuing this command in Terminal:
sudo find / -name "*.realm"
.
Hope this helps!
Looks like you missed a few closing tags and you nshould have "http://" on the front of an external URL. Also, you should move your styles to external style sheets instead of using inline styles.
.box{
float:right;
}
.box a img{
vertical-align: middle;
border: 0px;
}
<div class="box">
<a href="<?php echo "http://www.someotherwebsite.com"; ?>">
<img src="<?php echo url::file_loc('img'); ?>media/img/twitter.png" alt="Image Decription">
</a>
</div>
As noted in other comments, it may be easier to use straight HTML, depending on your exact setup.
<div class="box">
<a href="http://www.someotherwebsite.com">
<img src="file_location/media/img/twitter.png" alt="Image Decription">
</a>
</div>
I think the problem is the realpath of the file. For example your script is working on './', your file is inside the directory './xml'. So better check if the file exists or not, before you get filemtime or unlink it:
function deleteOldFiles(){
if ($handle = opendir('./xml')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/^.*\.(xml|xsl)$/i", $file)){
$fpath = 'xml/'.$file;
if (file_exists($fpath)) {
$filelastmodified = filemtime($fpath);
if ( (time() - $filelastmodified ) > 24*3600){
unlink($fpath);
}
}
}
}
closedir($handle);
}
}
Apparently, action
was required prior to HTML5 (and #
was just a stand in), but you no longer have to use it.
See The Action Attribute:
When specified with no attributes, as below, the data is sent to the same page that the form is present on:
<form>
In my case, all warn disappeared after I directly changed swift version from 2.x to 4.0 in build settings except two warn.
These warning related to myprojectnameTests
and myprojectnameUITests
folder. I didn't notice and I thought its relate to direct immigration from Xcode 7 to Xcode 9 and I thought I couldn't solve this problem and I should install missed Xcode 8 version.
In my case, I deleted these folders and all warns disappeared, but you can recreate this folder and contains using this:
file > new > target > (uitest or unittest extensions)
and use this article for create test cases: https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/04-writing_tests.html
@GetMapping
is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)
.
@GetMapping
is the newer annotaion.
It supports consumes
Consume options are :
consumes = "text/plain"
consumes = {"text/plain", "application/*"}
For Further details see: GetMapping Annotation
or read: request mapping variants
RequestMapping supports consumes as well
GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level
DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
It wasn't working because your image was too big - there are restrictions on the image dimensions. In Firefox, for example, the size limit is 128x128px. See this page for more details.
Additionally, you also have to add in auto
.
jsFiddle demo here - note that's an actual image, and not a default cursor.
.test {_x000D_
background:gray;_x000D_
width:200px;_x000D_
height:200px;_x000D_
cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif), auto;_x000D_
}
_x000D_
<div class="test">TEST</div>
_x000D_
Here's an example to get ASM-7 using Maven 3.6:
mvn dependency:get -DremoteRepositories=maven.apache.org -Dartifact=org.ow2.asm:7.0:sources:jar
Or you can download the jar from here: https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm and then
mvn install:install-file -DgroupId=org.ow2.asm -DartifactId=asm -Dversion=7.0 -Dclassifier=sources -Dpackaging=jar -Dfile=/path/to/asm-7.0.jar
According to the docs, it means the total number throughout history:
Connections
The number of connection attempts (successful or not) to the MySQL server.
You can see the number of active connections either through the Threads_connected
status variable:
Threads_connected
The number of currently open connections.
mysql> show status where `variable_name` = 'Threads_connected';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 4 |
+-------------------+-------+
1 row in set (0.00 sec)
... or through the show processlist
command:
mysql> show processlist;
+----+------+-----------------+--------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------------+--------+---------+------+-------+------------------+
| 3 | root | localhost | webapp | Query | 0 | NULL | show processlist |
| 5 | root | localhost:61704 | webapp | Sleep | 208 | | NULL |
| 6 | root | localhost:61705 | webapp | Sleep | 208 | | NULL |
| 7 | root | localhost:61706 | webapp | Sleep | 208 | | NULL |
+----+------+-----------------+--------+---------+------+-------+------------------+
4 rows in set (0.00 sec)
You can do it from code by placing the following code in Window Loaded
event handler, for example:
yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();
If you need to bind it in XAML you need to use ObjectDataProvider
to create object available as binding source:
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects">
<Window.Resources>
<ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="StyleAlias:EffectStyle"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
SelectedItem="{Binding Path=CurrentEffectStyle}" />
</Grid>
</Window>
Draw attention on the next code:
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"
Guide how to map namespace and assembly you can read on MSDN.
The method GetFileNameWithoutExtension
, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.
Arrays can't be passed as function parameters by value in C.
You can put the array in a struct:
typedef struct type24 {
char byte[3];
} type24;
and then pass that by value, but of course then it's less convenient to use: x.byte[0]
instead of x[0]
.
Your function type24_to_int32(char value[3])
actually passes by pointer, not by value. It's exactly equivalent to type24_to_int32(char *value)
, and the 3
is ignored.
If you're happy passing by pointer, you could stick with the array and do:
type24_to_int32(const type24 *value);
This will pass a pointer-to-array, not pointer-to-first-element, so you use it as:
(*value)[0]
I'm not sure that's really a gain, since if you accidentally write value[1]
then something stupid happens.
Given an object which I suspect to be some kind of IList<>
, how can I determine of what it's an IList<>
?
Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.
/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
Contract.Requires(type != null);
var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);
innerType = interfaceTest(type);
if (innerType != null)
{
return true;
}
foreach (var i in type.GetInterfaces())
{
innerType = interfaceTest(i);
if (innerType != null)
{
return true;
}
}
return false;
}
Example usage:
object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();
Returns
True
typeof(Int32)
Let us consider a binary tree of height 'h'. A binary tree is called a complete binary tree if all the leaves are present at height 'h' or 'h-1' without any missing numbers in the sequence.
1
/ \
2 3
/ \
4 5
It is a complete binary tree.
1
/ \
2 3
/ /
4 6
It is not a complete binary tree as the node of number 5 is missing in the sequence
In Python 3.x, 5 / 2
will return 2.5
and 5 // 2
will return 2
. The former is floating point division, and the latter is floor division, sometimes also called integer division.
In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division
, which causes Python 2.x to adopt the 3.x behavior.
Regardless of the future import, 5.0 // 2
will return 2.0
since that's the floor division result of the operation.
You can find a detailed description at https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator
You do this:
private void PassArray() {
String[] arrayw = new String[4]; //populate array
PrintA(arrayw);
}
private void PrintA(String[] a) {
//do whatever with array here
}
Just pass it as any other variable.
In Java, arrays are passed by reference.
The resolution of DateTime.Now
depends on your system timer (~10ms on a current Windows OS)...so it's giving the same ending value there (it doesn't count any more finite than that).
At your parent DIV add
display:table;
and at your child element add
display:table-cell;
vertical-align:middle;
There's also the approach some shops take of using some of C++'s features in a C-like way, but avoiding ones that are objectionable. For example, using classes and class methods and function overloading (which are usually easy for even C diehards to cope with), but not the STL, stream operators, and Boost (which are harder to learn and can have bad memory characteristics).
Or using message
message("Current working dir: ", wd)
@agstudy's answer is the more suitable here
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
I have added this answer only because the problem is explained based on more complex data pattern and I found it hard to understand here.
I created a fairly simple application. This error occurred inside Edit POST action. The action accepted ViewModel as an input parameter. The reason for using the ViewModel was to make some calculation before the record was saved.
Once the action passed through validation such as if(ModelState.IsValid)
, my wrongdoing was to project values from ViewModel into a completely new instance of Entity. I thought I'd have to create a new instance to store updated data and then saved such instance.
What I had realised later was that I had to read the record from database:
Student student = db.Students.Find(s => s.StudentID == ViewModel.StudentID);
and updated this object. Everything works now.
You may try
document.getElementById('name').style.borderColor='#e52213';
document.getElementById('name').style.border='solid';
if ($("#Password").val() != $("#ConfirmPassword").val()) {
alert("Passwords do not match.");
}
A JQuery approach that will eliminate needless code.
I know this is a bit old, but I had the same problem and my search brought me here. I wanted two select elements and a button all inline, which worked in 2 but not 3. I ended up wrapping the three elements in <form class="form-inline">...</form>
. This actually worked perfectly for me.
Indeed ADD go /usr/local/
will add content of go
folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR
to /usr/local/
then add your directory to it like:
WORKDIR /usr/local/
COPY go go/
or
WORKDIR /usr/local/go
COPY go ./
But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . .
and exclude all unwanted directories and files in .dockerignore
, let's say I got folders and files:
- src
- tmp
- dist
- assets
- go
- justforfun
- node_modules
- scripts
- .dockerignore
- Dockerfile
- headache.lock
- package.json
and I want to add src assets package.json justforfun go
so:
in Dockerfile:
FROM galaxy:latest
WORKDIR /usr/local/
COPY . .
in .dockerignore file:
node_modules
headache.lock
tmp
dist
Or for more fun (or you like to confuse more people make them suffer as well :P) can be:
*
!src
!assets
!go
!justforfun
!scripts
!package.json
In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".
It is a late answer but adding more ways to do the same covering even more cases.
Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/
1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.
OR:
2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.
Is a JNDI problem. You will see that exception if the InitialContext
class has neither default properties for the JNDI service provider nor explicitly configured server properties.
Set the Context.INITIAL_CONTEXT_FACTORY
environment property to the class name of the initial context implementation that you are using. This class must be available to your program in the classpath.
Check:
$destroy
can refer to 2 things: method and event
.directive("colorTag", function(){
return {
restrict: "A",
scope: {
value: "=colorTag"
},
link: function (scope, element, attrs) {
var colors = new App.Colors();
element.css("background-color", stringToColor(scope.value));
element.css("color", contrastColor(scope.value));
// Destroy scope, because it's no longer needed.
scope.$destroy();
}
};
})
See @SunnyShah's answer.
The top rated answers are working perfect (a bit old but still working), but I just want to mention that since Android N we all can configure your apps in order to have diff trust SSL certificates (for release , debug only and so on), including Charles SSL Proxy certificate (if you download the Charles certificate and put .pem file in your raw folder). More info can be found here: https://developer.android.com/training/articles/security-config.html
Also the official Charles documentation can be useful to setup this : https://www.charlesproxy.com/documentation/using-charles/ssl-certificates/
Hope this will help to setup Charles inside your app project not on every single Android device.
This error also shows up when the repository does not exist. I tried all the answers until I saw the repo name was missing a dash
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.hide(currentFragment);
ft.add(R.id.content_frame, newFragment.newInstance(context), "Profile");
ft.addToBackStack(null);
ft.commit();
In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using @RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore
instead of org.codehaus.jackson.annotate.JsonIgnore
, as otherwise, it simply did nothing.
Make sure you're calling super()
as the first thing in your constructor.
You should set this
for setAuthorState
method
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
constructor(props) {
super(props);
this.handleAuthorChange = this.handleAuthorChange.bind(this);
}
handleAuthorChange(event) {
let {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
Another alternative based on arrow function
:
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
handleAuthorChange = (event) => {
const {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
The following characters must be escaped in JSON data to avoid any problems:
"
(double quote)\
(backslash)\n
, \t
JSON Parser can help you to deal with JSON.
Assuming that the name is everywhere "Microsoft .NET Framework 3.5 SP1", you can use this:
string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
{
return rk.GetSubKeyNames().Contains("Microsoft .NET Framework 3.5 SP1");
}
Try this!
Client client = ClientBuilder.newClient();
String jsonStr = client
.target("http:....")
.request(MediaType.APPLICATION_JSON)
.header("WM_SVC.NAME", "RegistryService")
.header("WM_QOS.CORRELATION_ID", "d1f0c0d2-2cf4-497b-b630-06d609d987b0")
.get(String.class);
P.S You can add any number of headers like this!
You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:
root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}
#we capture release hash
$curr_os = $os['release']
case $curr_os['major'] {
'7': { .... something }
*: {something}
}
That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.
The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) {
was returning an invalid character error because it was trying to watch the value of attrs.dynamic
which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
The modulus is a mathematical operation, sometimes described as "clock arithmetic." I find that describing it as simply a remainder is misleading and confusing because it masks the real reason it is used so much in computer science. It really is used to wrap around cycles.
Think of a clock: Suppose you look at a clock in "military" time, where the range of times goes from 0:00 - 23.59. Now if you wanted something to happen every day at midnight, you would want the current time mod 24 to be zero:
if (hour % 24 == 0):
You can think of all hours in history wrapping around a circle of 24 hours over and over and the current hour of the day is that infinitely long number mod 24. It is a much more profound concept than just a remainder, it is a mathematical way to deal with cycles and it is very important in computer science. It is also used to wrap around arrays, allowing you to increase the index and use the modulus to wrap back to the beginning after you reach the end of the array.
My workaround had been using gnu sed
. Worked fine for my purposes.
Reply from @Ib33X is awesome. If you want to remove every empty string, after stripped. you need to use the strip method too. Otherwise, it will return the empty string too if it has white spaces. Like, " " will be valid too for that answer. So, can be achieved by.
strings = ["first", "", "second ", " "]
[x.strip() for x in strings if x.strip()]
The answer for this will be ["first", "second"]
.
If you want to use filter
method instead, you can do like
list(filter(lambda item: item.strip(), strings))
. This is give the same result.
As per Android API 28 and above you need to do the following to turn on the screen
setShowWhenLocked(true);
setTurnScreenOn(true);
KeyguardManager keyguardManager = (KeyguardManager)
getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
You cannot close a window with javascript that you did not open. It will not work in chrome or firefox.
See https://stackoverflow.com/a/19768082/2623781 for more information.
In more recent versions of NERDTree you can use the command :NERDTreeFocus
, which will move focus to the NERDTree window.
echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';
I think that's what you're looking for?
In other words, use htmlspecialchars() in PHP
Sounds to me like you could create a simple iterator with a callback for testing. Like so:
function findElements(array, predicate)
{
var matchingIndices = [];
for(var j = 0; j < array.length; j++)
{
if(predicate(array[j]))
matchingIndices.push(j);
}
return matchingIndices;
}
Then you could invoke like so:
var someArray = [
{ id: 1, text: "Hello" },
{ id: 2, text: "World" },
{ id: 3, text: "Sup" },
{ id: 4, text: "Dawg" }
];
var matchingIndices = findElements(someArray, function(item)
{
return item.id % 2 == 0;
});
// Should have an array of [1, 3] as the indexes that matched
For the first rule,
Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.
For the second,
Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.
For the third,
Same as the second, except your formula is =".8*" rather than .9.
Function GetSearchArray(strSearch)
Dim strResults As String
Dim SHT As Worksheet
Dim rFND As Range
Dim sFirstAddress
For Each SHT In ThisWorkbook.Worksheets
Set rFND = Nothing
With SHT.UsedRange
Set rFND = .Cells.Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rFND Is Nothing Then
sFirstAddress = rFND.Address
Do
If strResults = vbNullString Then
strResults = "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
Else
strResults = strResults & "|" & "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
End If
Set rFND = .FindNext(rFND)
Loop While Not rFND Is Nothing And rFND.Address <> sFirstAddress
End If
End With
Next
If strResults = vbNullString Then
GetSearchArray = Null
ElseIf InStr(1, strResults, "|", 1) = 0 Then
GetSearchArray = Array(strResults)
Else
GetSearchArray = Split(strResults, "|")
End If
End Function
Sub test2()
For Each X In GetSearchArray("1")
Debug.Print X
Next
End Sub
Careful when doing a Find Loop that you don't get yourself into an infinite loop... Reference the first found cell address and compare after each "FindNext" statement to make sure it hasn't returned back to the first initially found cell.
I was stuck on this for a long time. After a lot of tries I was able to configured it properly.
There can be different reasons of raising the error. I am trying to provide the reason and the solution to overcome from that situation.
6379 Port
is not allowed by ufw firewall.
Solution: type following command sudo ufw allow 6379
The issue can be related to permission of redis
user. May be redis user doesn't have permission of modifying necessary redis
directories. The redis
user should have permissions in the following directories:
/var/lib/redis
/var/log/redis
/run/redis
/etc/redis
To give the owner permission to redis
user, type the following commands:
sudo chown -R redis:redis /var/lib/redis
sudo chown -R redis:redis /var/log/redis
sudo chown -R redis:redis /run/redis
sudo chown -R redis:redis /etc/redis
.Now restart redis-server
by following command:
sudo systemctl restart redis-server
Hope this will be helpful for somebody.
Another way would be to use attributes of a suitable object, e.g. like so:
function plus(a,b) { return a+b; };
Plus = { a: function(x) { return { b: function(y) { return plus(x,y) }}},
b: function(y) { return { a: function(x) { return plus(x,y) }}}};
sum = Plus.a(3).b(5);
Of course for this made up example it is somewhat meaningless. But in cases where the function looks like
do_something(some_connection_handle, some_context_parameter, some_value)
it might be more useful. It also could be combined with "parameterfy" idea to create such an object out of an existing function in a generic way. That is for each parameter it would create a member that can evaluate to a partial evaluated version of the function.
This idea is of course related to Schönfinkeling aka Currying.
Thanks for the answers above, that helped me a lot :-) But for those (like me) forced to still support Android 1.5 we can use java reflection for backward compatible:
Configuration conf = getResources().getConfiguration();
int screenLayout = 1; // application default behavior
try {
Field field = conf.getClass().getDeclaredField("screenLayout");
screenLayout = field.getInt(conf);
} catch (Exception e) {
// NoSuchFieldException or related stuff
}
// Configuration.SCREENLAYOUT_SIZE_MASK == 15
int screenType = screenLayout & 15;
// Configuration.SCREENLAYOUT_SIZE_SMALL == 1
// Configuration.SCREENLAYOUT_SIZE_NORMAL == 2
// Configuration.SCREENLAYOUT_SIZE_LARGE == 3
// Configuration.SCREENLAYOUT_SIZE_XLARGE == 4
if (screenType == 1) {
...
} else if (screenType == 2) {
...
} else if (screenType == 3) {
...
} else if (screenType == 4) {
...
} else { // undefined
...
}
concat()
function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
It's difficult to tell what you're actually trying to do and if this is what you really need but you might also use a callback:
function myFunction(value1,callback)
{
//Do stuff and
if(typeof callback == 'function'){
callback(somevalue2,somevalue3);
}
}
myFunction("1", function(value2, value3){
if(value2 && value3)
{
//Do some stuff
}
});
It depends on what you mean by "multiple lines". Different operating systems use different line separators.
In Java, \r
is always carriage return, and \n
is line feed. On Unix, just \n
is enough for a newline, whereas many programs on Windows require \r\n
. You can get at the platform default newline use System.getProperty("line.separator")
or use String.format("%n")
as mentioned in other answers.
But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n
and this should be used even if you're running on Unix. So it's all about context.
This one worked for me:
>> print(df)
TotalVolume Symbol
2016-04-15 09:00:00 108400 2802.T
2016-04-15 09:05:00 50300 2802.T
>> print(df.set_index(pd.to_datetime(df.index.values) - datetime(2016, 4, 15)))
TotalVolume Symbol
09:00:00 108400 2802.T
09:05:00 50300 2802.T
You can also put your templates folder under src/main/resources instead of src/main/java. Works for me and it's a preferable location since templates are not java source.
The *_all() functions are so simple that for a few methods I'd just write the functions. If you have lots of identical functions, you can write a generic function:
def apply_on_all(seq, method, *args, **kwargs):
for obj in seq:
getattr(obj, method)(*args, **kwargs)
Or create a function factory:
def create_all_applier(method, doc=None):
def on_all(seq, *args, **kwargs):
for obj in seq:
getattr(obj, method)(*args, **kwargs)
on_all.__doc__ = doc
return on_all
start_all = create_all_applier('start', "Start all instances")
stop_all = create_all_applier('stop', "Stop all instances")
...
If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:
position:absolute;
right:0;
top:0;
If you want it to float at the right of a particular parent section, you can add position: relative
to that section.
If you simply need to transfer data from one elasticsearch server to another, you could also use elasticsearch-document-transfer.
Steps:
$ npm install elasticsearch-document-transfer.
config.js
config.js
options.js
$ node index.js
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.
If base URI contains non-empty path, merge procedure discards it's last part (after last /
). Relevant section:
5.2.3. Merge Paths
The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:
If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise
return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).
If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.
print "financial return of outcome 1 = $%.2f" % (out1)
I have used this small snippet. Might be slower but works every time.
for i in 'find . -type f -name "*.jar"'; do
jar tvf $i | grep "com.foo.bar.MyClass.clss";
if [ $? -eq 0 ]; then echo $i; fi;
done
We have two options.
Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.
Set HEADER_SEARCH_PATHS
parameter in build settings on project info. I added "${SRCROOT}"
here without recursion. This setting works well for most projects.
About 2nd option:
Xcode uses Clang which has GCC compatible command set.
GCC has an option -Idir
which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS
in Xcode project build setting.
However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.
But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space
if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}"
.
Or just use .
to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.
The ${SRCROOT}
is predefined value by Xcode. This means source directory. You can find more values in Reference document.
PS. Actually you don't have to use braces {}
. I get same result with $SRCROOT
. If you know the difference, please let me know.
When an element, such as a div
is floated
, its parent container no longer considers its height, i.e.
<div id="main">
<div id="child" style="float:left;height:40px;"> Hi</div>
</div>
The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.
So the clearfix
class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.
Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.
Can read more here
Use the FolderExists
method of the Scripting
object.
Public Function dirExists(s_directory As String) As Boolean
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
dirExists = oFSO.FolderExists(s_directory)
End Function
If you want to do this by code, you can add the behavior like this:
serviceHost.Description.Behaviors.Remove(
typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });
Here is some relevant code:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
// Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}
This will completely disable SSL checking—just don't learn exception handling from such code!
To do what you want, you would have to implement a check in your TrustManager that prompts the user.
Found a great solution at https://bitsofco.de/styling-broken-images/
img { _x000D_
position: relative;_x000D_
}_x000D_
_x000D_
/* style this to fit your needs */_x000D_
/* and remove [alt] to apply to all images*/_x000D_
img[alt]:after { _x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: #fff;_x000D_
font-family: 'Helvetica';_x000D_
font-weight: 300;_x000D_
line-height: 2; _x000D_
text-align: center;_x000D_
content: attr(alt);_x000D_
}
_x000D_
<img src="error">_x000D_
<br>_x000D_
<img src="broken" alt="A broken image">_x000D_
<br>_x000D_
<img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png" alt="A bird" style="width: 120px">
_x000D_
"Editor's" note: This post may contain outdated information. Please see comments and this question regarding changes in Git since 1.6.1.
Symlinked directories:
It's important to note what happens when there is a directory which is a soft link. Any Git pull with an update removes the link and makes it a normal directory. This is what I learnt hard way. Some insights here and here.
Example
Before
ls -l
lrwxrwxrwx 1 admin adm 29 Sep 30 15:28 src/somedir -> /mnt/somedir
git add/commit/push
It remains the same
After git pull
AND some updates found
drwxrwsr-x 2 admin adm 4096 Oct 2 05:54 src/somedir
You Only Need to close the bufferedReader i.e reader.close() and it will work fine .
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
This is because You're sorting entire result-set, You should sort, every part of union separately, or You can use ORDER BY (Something ie. subquery distance) THEN (something ie row id) clause
Here is a simple example :
Create or alter PROCEDURE getPersonCountByLastName (
@lastName varchar(20),
@count int OUTPUT
)
As
Begin
select @count = count(personSid) from Person where lastName like @lastName
End;
Execute below statements in one batch (by selecting all)
1. Declare @count int
2. Exec getPersonCountByLastName kumar, @count output
3. Select @count
When i tried to execute statements 1,2,3 individually, I had the same error. But when executed them all at one time, it worked fine.
The reason is that SQL executes declare, exec statements in different sessions.
Open to further corrections.
The fix for me was to put "log4j.properties" into the "src" folder. It did not work in my package folder it has to be one up at the very root of source. Adding it to the build path which then moves it to the "Reference Libraries" also did not work.
To repeat: put log4j.properties at the root of your src folder.
my log4j.properties files has the following content which works on the latest version of Spring Tool Suite which is based on Eclipse.
# Configure logging for testing: optionally with log file
#log4j.rootLogger=INFO, stdout
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%
Depending on what you want you might be interested in the SPL Object Storage class.
http://php.net/manual/en/class.splobjectstorage.php
It lets you use objects as keys, has an interface to count, get the hash and other goodies.
$s = new SplObjectStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o2->foo = 'bar';
$s[$o1] = 'baz';
$s[$o2] = 'bingo';
echo $s[$o1]; // 'baz'
echo $s[$o2]; // 'bingo'
Non of them worked for me. I did this and it worked:
To encode as a json:
JSONObject obj = new JSONObject();
obj.put("productId", 100);
To decode:
long temp = (Long) obj.get("productId");