In android google maps application there is a very easy way to find distance between 2 locations, to do so follow the following easy steps:
when you first open the app go to " your timeline " from the drop menue on the top left.
once the new windwo opens, chose from the settings on your top right menue and choose "add place".
Good luck
You can add new columns within the initial Schema::create
method like this:
Schema::create('users', function($table) {
$table->integer("paied");
$table->string("title");
$table->text("description");
$table->timestamps();
});
If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table
method:
Schema::table('users', function($table) {
$table->string("title");
$table->text("description");
$table->timestamps();
});
The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4.
Here is my solution based on Skeptic answer. It gets page title from WordPress DB, not from URL because there is a problem with latin characters (slug doesn't has a latin characters). You can also choose to display "home" item or not.
/**
* Show Breadcrumbs
*
* @param string|bool $home
* @param string $class
* @return string
*
* Using: echo breadcrumbs();
*/
function breadcrumbs($home = 'Home', $class = 'items') {
$breadcrumb = '<ul class="'. $class .'">';
$breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
if ($home) {
$breadcrumb .= '<li><a href="' . get_site_url() . '">' . $home . '</a></li>';
}
$path = '';
foreach ($breadcrumbs as $crumb) {
$path .= $crumb . '/';
$page = get_page_by_path($path);
if ($home && ($page->ID == get_option('page_on_front'))) {
continue;
}
$breadcrumb .= '<li><a href="'. get_permalink($page) .'">' . $page->post_title . '</a></li>';
}
$breadcrumb .= '</ul>';
return $breadcrumb;
}
Using:
<div class="breadcrumb">
<div class="container">
<h3 class="breadcrumb__title">Jazda na maxa!</h3>
<?php echo breadcrumbs('Start', 'breadcrumb__items'); ?>
</div>
</div>
This works for me.
<div style="position: relative;width:100%;">
<div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
This will be on the left
</div>
<div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
This will be on the right
</div>
</div>
If you are not sure that you have not multiple minimum values, I would suggest:
d = {320:1, 321:0, 322:3, 323:0}
print ', '.join(str(key) for min_value in (min(d.values()),) for key in d if d[key]==min_value)
"""Output:
321, 323
"""
A reference is an implicit pointer. Basically you can change the value the reference points to but you can't change the reference to point to something else. So my 2 cents is that if you only want to change the value of a parameter pass it as a reference but if you need to change the parameter to point to a different object pass it using a pointer.
Just for the record (took me quite a while) before Grzegorzs answer worked for me I had to install "android support repository" through the SDK Manager!
Install it and add the following code above apply plugin: 'android-library' in the build.gradle of actionbarsherlock folder!
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.+'
}
}
All these answers are partially wrong.
Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.
Even the lack of TFS support is not true. I can verify it is present and works perfectly.
EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)
EDIT: Even over the revenue limit, open source is still free.
There is a much simpler way to do it using seaborn:
import seaborn as sns
from scipy.stats import norm
data = norm.rvs(5,0.4,size=1000) # you can use a pandas series or a list if you want
sns.distplot(data)
plt.show()
for more information:seaborn.distplot
The answer above was mostly correct, just needed some tweaking for the different parameters in Mac OSX.
ps -A | grep [f]irefox | awk '{print $1}'
As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.
The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.
Use
for /r path %%var in (*.*) do some_command %%var
with:
I got this error after upgrading from Visual Studio 2013 to 2015. After a bit of searching and trying various fixes I found the problem can be resolved by removing the following from web.config:
<staticContent>
<mimeMap fileExtension=".less" mimeType="text/css" />
</staticContent >
Apparently staticContent is deprecated now?
Edit 1
This sort of prevented IIS from serving .json files when the program was deployed. If you do this you're supposed to re-add .json (application/json) to the mime types of your site in IIS. Here is some more info: http://www.iis.net/configreference/system.webserver/staticcontent/mimemap
Edit 2
I noticed that in my situation the above edit 1 solution only works temporarily. Once I redeploy the entry gets removed. So, I moved the mimeMap XML into Web.Release.config
. Works fine now.
Absolutely. Try this:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
Don't forget also to create the constant PICK_IMAGE, so you can recognize when the user comes back from the image gallery Activity:
public static final int PICK_IMAGE = 1;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE) {
//TODO: action
}
}
That's how I call the image gallery. Put it in and see if it works for you.
EDIT:
This brings up the Documents app. To allow the user to also use any gallery apps they might have installed:
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.
The variable %0
in a batch script is set to the name of the executing batch file.
The ~dp
special syntax between the %
and the 0
basically says to expand the variable %0
to show the drive letter and path, which gives you the current directory containing the batch file!
Help = Link
Yes it's the exact same thing in Python 2:
d.values()
In Python 3 (where dict.values
returns a view of the dictionary’s values instead):
list(d.values())
Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry. Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies! Okay, let me try:
1) They are all event-driven things. (I hear the laugh, but read on)
If you don't know what event-driven is Then think you place a button on the page, hook it up w/ a function using "on-click", waiting for users to click on it to trigger the actions you plant inside the function. Or think of "trigger" of SQL Server / Oracle.
2) $watch is "on-click".
What's special about is it takes 2 functions as parameters, first one gives the value from the event, second one takes the value into consideration...
3) $digest is the boss who checks around tirelessly, bla-bla-bla but a good boss.
4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)
Now, let's make it visual. Picture this to make it even more easy to grab the idea:
In a restaurant,
- WAITERS
are supposed to take orders from customers, this is
$watch(
function(){return orders;},
function(){Kitchen make it;}
);
- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()
- OWNER has the ultimate power to drive everyone upon request, this is $apply()
Just pass with sshpass -p "your password"
at the beginning of your scp
command
sshpass -p "your password" scp ./abc.txt hostname/abc.txt
I had faced the similar error when supporting one application. It was about the generated classes for a SOAP Webservice.
The issue was caused due to the missing classes. When javax.xml.bind.Marshaller was trying to marshal the jaxb object it was not finding all dependent classes which were generated by using wsdl and xsd. after adding the jar with all the classes at the class path the issue was resolved.
stdin.read(1)
will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.
First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before
not @BeforeClass
. It might be run a bunch, but it's cheap.
Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.
$property_images = $_FILES['property_images']['name'];
if(!empty($property_images))
{
for($up=0;$up<count($property_images);$up++)
{
move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
}
}
Try as
String s = "ABC[ This is to extract ]";
Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
Matcher m = p.matcher(s);
m.find();
String text = m.group(1);
System.out.println(text);
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
Change remote git URI to
[email protected]
rather thanhttps://github.com
git remote set-url origin [email protected]:<username>/<repo>.git
Example:
git remote set-url origin [email protected]:Chetabahana/my_repo_name.git
The benefit is that you may do git push
automatically when you use ssh-agent :
#!/bin/bash
# Check ssh connection
ssh-add -l &>/dev/null
[[ "$?" == 2 ]] && eval `ssh-agent`
ssh-add -l &>/dev/null
[[ "$?" == 1 ]] && expect $HOME/.ssh/agent
# Send git commands to push
git add . && git commit -m "your commit" && git push -u origin master
Put a script file $HOME/.ssh/agent
to let it runs ssh-add
using expect as below:
#!/usr/bin/expect -f
set HOME $env(HOME)
spawn ssh-add $HOME/.ssh/id_rsa
expect "Enter passphrase for $HOME/.ssh/id_rsa:"
send "<my_passphrase>\n";
expect "Identity added: $HOME/.ssh/id_rsa ($HOME/.ssh/id_rsa)"
interact
If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.
I hope it, will be helpfull.
HTML :
<a href="#" class="btn btn-default" file-name="'fileName.extension'" ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>
DIRECTIVE :
directive('fileDownload',function(){
return{
restrict:'A',
scope:{
fileDownload:'=',
fileName:'=',
},
link:function(scope,elem,atrs){
scope.$watch('fileDownload',function(newValue, oldValue){
if(newValue!=undefined && newValue!=null){
console.debug('Downloading a new file');
var isFirefox = typeof InstallTrigger !== 'undefined';
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isIE = /*@cc_on!@*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isBlink = (isChrome || isOpera) && !!window.CSS;
if(isFirefox || isIE || isChrome){
if(isChrome){
console.log('Manage Google Chrome download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var downloadLink = angular.element('<a></a>');//create a new <a> tag element
downloadLink.attr('href',fileURL);
downloadLink.attr('download',scope.fileName);
downloadLink.attr('target','_self');
downloadLink[0].click();//call click function
url.revokeObjectURL(fileURL);//revoke the object from URL
}
if(isIE){
console.log('Manage IE download>10');
window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName);
}
if(isFirefox){
console.log('Manage Mozilla Firefox download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var a=elem[0];//recover the <a> tag from directive
a.href=fileURL;
a.download=scope.fileName;
a.target='_self';
a.click();//we call click function
}
}else{
alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
}
}
});
}
}
})
IN CONTROLLER:
$scope.myBlobObject=undefined;
$scope.getFile=function(){
console.log('download started, you can show a wating animation');
serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
.then(function(data){//is important that the data was returned as Aray Buffer
console.log('Stream download complete, stop animation!');
$scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
},function(fail){
console.log('Download Error, stop animation and show error message');
$scope.myBlobObject=[];
});
};
IN SERVICE:
function getStream(params){
console.log("RUNNING");
var deferred = $q.defer();
$http({
url:'../downloadURL/',
method:"PUT",//you can use also GET or POST
data:params,
headers:{'Content-type': 'application/json'},
responseType : 'arraybuffer',//THIS IS IMPORTANT
})
.success(function (data) {
console.debug("SUCCESS");
deferred.resolve(data);
}).error(function (data) {
console.error("ERROR");
deferred.reject(data);
});
return deferred.promise;
};
BACKEND(on SPRING):
@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
@RequestBody Map<String,String> spParams
) throws IOException {
OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}
If it's reconnecting and getting connection ID 2, the server has almost definitely just crashed.
Contact the server admin and get them to diagnose the problem. No non-malicious SQL should crash the server, and the output of mysqldump certainly should not.
It is probably the case that the server admin has made some big operational error such as assigning buffer sizes of greater than the architecture's address-space limits, or more than virtual memory capacity. The MySQL error-log will probably have some relevant information; they will be monitoring this if they are competent anyway.
Set the display in li
as flex and set align-items
to center
.
li {
display: flex;
/* Align items vertically */
align-items: center;
/* Align items horizontally */
justify-content: center;
}
I, personally, would also target pseudo elements and use border-box
(Universal selector * and pseudo elements)
*,
*::before,
*::after {
padding: 0;
margin: 0;
box-sizing: border-box;
}
I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:
var str = theText.split('A').join('')
will remove all occurrences of 'A' from the string, obviously it's not case sensitive
If you are ok to do transformation, you may try this.
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());
On Windows 10:
C:\Program Files\nodejs\node_modules\npm\bin
select it, and click edit button to your right, then edit the field to the path where you have the nodejs folder, in my case it was just shortening it to :
C:\Program Files\nodejs
Then I closed all my cmd or powershell terminals, opened them again and npm was working.
Does:
Set Sheets("Output").Range("$A$1:$A$500") = Sheets(sheet_).Range("$A$1:$A$500")
...work? (I don't have Excel in front of me, so can't test.)
Use the ->pluck() method
$roles = DB::table('roles')->pluck('title');
If you would like to retrieve an array containing the values of a single column, you may use the pluck method
Use the ->lists() method
$roles = DB::table('roles')->lists('title');
This method will return an array of role titles. You may also specify a custom key column for the returned array:
I had this issue myself, and I wanted to both be able to set the width, and have it update on rotate and allow the user to scale and zoom the page (the current answer provides the first but prevents the later as a side-effect).. so I came up with a fix that keeps the view width correct for the orientation, but still allows for zooming, though it is not super straight forward.
First, add the following Javascript to the webpage you are displaying:
<script type='text/javascript'>
function setViewPortWidth(width) {
var metatags = document.getElementsByTagName('meta');
for(cnt = 0; cnt < metatags.length; cnt++) {
var element = metatags[cnt];
if(element.getAttribute('name') == 'viewport') {
element.setAttribute('content','width = '+width+'; maximum-scale = 5; user-scalable = yes');
document.body.style['max-width'] = width+'px';
}
}
}
</script>
Then in your - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation method, add:
float availableWidth = [EmailVC webViewWidth];
NSString *stringJS;
stringJS = [NSString stringWithFormat:@"document.body.offsetWidth"];
float documentWidth = [[_webView stringByEvaluatingJavaScriptFromString:stringJS] floatValue];
if(documentWidth > availableWidth) return; // Don't perform if the document width is larger then available (allow auto-scale)
// Function setViewPortWidth defined in EmailBodyProtocolHandler prepend
stringJS = [NSString stringWithFormat:@"setViewPortWidth(%f);",availableWidth];
[_webView stringByEvaluatingJavaScriptFromString:stringJS];
Additional Tweaking can be done by modifying more of the viewportal content settings:
Also, I understand you can put a JS listener for onresize or something like to trigger the rescaling, but this worked for me as I'm doing it from Cocoa Touch UI frameworks.
Hope this helps someone :)
I got same problem lot of time. Check your request url, if you are requesting on local server like 127.1.1/api or 192.168...., try to change it, make sure you are hitting cloud.
Not sure if this helps, but with XSL, I'd do something like:
<xsl:for-each select="a/b">
<xsl:value-of select="c"/>
<xsl:value-of select="d"/>
<xsl:value-of select="e"/>
</xsl:for-each>
and won't this XPath select all children of B nodes:
a/b/*
Use r.URL.Query()
when you appending to existing query, if you are building new set of params use the url.Values
struct like so
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
// if you appending to existing query this works fine
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
// or you can create new url.Values struct and encode that like so
q := url.Values{}
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
You probably want something like this:
Collections.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
return s1.getName().compareTo(s2.getName());
} else {
return s1.getAge().compareTo(s2.getAge());
}
}
);
This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.
I use this approach:
var myNamespace = {}
myNamespace._construct = function()
{
var staticVariable = "This is available to all functions created here"
function MyClass()
{
// Depending on the class, we may build all the classes here
this.publicMethod = function()
{
//Do stuff
}
}
// Alternatively, we may use a prototype.
MyClass.prototype.altPublicMethod = function()
{
//Do stuff
}
function privateStuff()
{
}
function publicStuff()
{
// Code that may call other public and private functions
}
// List of things to place publically
this.publicStuff = publicStuff
this.MyClass = MyClass
}
myNamespace._construct()
// The following may or may not be in another file
myNamespace.subName = {}
myNamespace.subName._construct = function()
{
// Build namespace
}
myNamespace.subName._construct()
External code can then be:
var myClass = new myNamespace.MyClass();
var myOtherClass = new myNamepace.subName.SomeOtherClass();
myNamespace.subName.publicOtherStuff(someParameter);
For primitives and Strings:
/** The empty String. */
const val EMPTY_STRING = ""
For other cases:
/** The empty array of Strings. */
@JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
Example:
/*
* Copyright 2018 Vorlonsoft LLC
*
* Licensed under The MIT License (MIT)
*/
package com.vorlonsoft.android.rate
import com.vorlonsoft.android.rate.Constants.Utils.Companion.UTILITY_CLASS_MESSAGE
/**
* Constants Class - the constants class of the AndroidRate library.
*
* @constructor Constants is a utility class and it can't be instantiated.
* @since 1.1.8
* @version 1.2.1
* @author Alexander Savin
*/
internal class Constants private constructor() {
/** Constants Class initializer block. */
init {
throw UnsupportedOperationException("Constants$UTILITY_CLASS_MESSAGE")
}
/**
* Constants.Date Class - the date constants class of the AndroidRate library.
*
* @constructor Constants.Date is a utility class and it can't be instantiated.
* @since 1.1.8
* @version 1.2.1
* @author Alexander Savin
*/
internal class Date private constructor() {
/** Constants.Date Class initializer block. */
init {
throw UnsupportedOperationException("Constants.Date$UTILITY_CLASS_MESSAGE")
}
/** The singleton contains date constants. */
companion object {
/** The time unit representing one year in days. */
const val YEAR_IN_DAYS = 365.toShort()
}
}
/**
* Constants.Utils Class - the utils constants class of the AndroidRate library.
*
* @constructor Constants.Utils is a utility class and it can't be instantiated.
* @since 1.1.8
* @version 1.2.1
* @author Alexander Savin
*/
internal class Utils private constructor() {
/** Constants.Utils Class initializer block. */
init {
throw UnsupportedOperationException("Constants.Utils$UTILITY_CLASS_MESSAGE")
}
/** The singleton contains utils constants. */
companion object {
/** The empty String. */
const val EMPTY_STRING = ""
/** The empty array of Strings. */
@JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
/** The part 2 of a utility class unsupported operation exception message. */
const val UTILITY_CLASS_MESSAGE = " is a utility class and it can't be instantiated!"
}
}
}
This worked for me.
/**
* return date in specific format, given a timestamp.
*
* @param timestamp $datetime
* @return string
*/
public static function showDateString($timestamp)
{
if ($timestamp !== NULL) {
$date = new DateTime();
$date->setTimestamp(intval($timestamp));
return $date->format("d-m-Y");
}
return '';
}
On Linux you can run $(dirname $(dirname $(readlink -f $(which javac))))
On Mac you can run $(dirname $(readlink $(which javac)))/java_home
I'm not sure about windows but I imagine where javac
would get you pretty close
You can use this code it works fine.
var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/");<br>
var marker = new google.maps.Marker({
position: yourlatlong,
icon: pinImage,
map: map
});
Another approach is to use @ExceptionHandler
with @ControllerAdvice
to centralize all your handlers in the same class, if not you must put the handler methods in every controller you want to manage an exception.
Your handler class:
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MyBadRequestException.class)
public ResponseEntity<MyError> handleException(MyBadRequestException e) {
return ResponseEntity
.badRequest()
.body(new MyError(HttpStatus.BAD_REQUEST, e.getDescription()));
}
}
Your custom exception:
public class MyBadRequestException extends RuntimeException {
private String description;
public MyBadRequestException(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
Now you can throw exceptions from any of your controllers, and you can define other handlers inside you advice class.
Try this
import ("strconv")
value := "123"
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //Convert uint64 To int
The most important thing is, the action created must return partial view, see below.
public ActionResult _YourPartialViewSection()
{
return PartialView();
}
In case you need short unique IDs as your filename, try shortuuid
, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.
>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22
compared to
>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'
// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})
(function ($) {
$.fn.sizeChanged = function (handleFunction) {
var element = this;
var lastWidth = element.width();
var lastHeight = element.height();
setInterval(function () {
if (lastWidth === element.width()&&lastHeight === element.height())
return;
if (typeof (handleFunction) == 'function') {
handleFunction({ width: lastWidth, height: lastHeight },
{ width: element.width(), height: element.height() });
lastWidth = element.width();
lastHeight = element.height();
}
}, 100);
return element;
};
}(jQuery));
<TextView
android:id="@+id/product_description"
android:layout_width="165dp"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:text="Pack of 4 summer printed pajama"
android:textColor="#d2131c"
android:textSize="12sp"
android:maxLines="2"
android:ellipsize="end"/>
Use
git rev-parse --verify <tag>^{commit}
(which would return SHA-1 of a commit even for annotated tag).
git show-ref <tag>
would also work if <tag>
is not annotated. And there is always git for-each-ref
(see documentation for details).
html { overflow-y: scroll; }
This css
rule causes a vertical scrollbar to always appear.
Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/
You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:
$('td').click(function(){
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
alert('Row: ' + row + ', Column: ' + col);
});
Check a running example here.
In python
linesWithSessionIdCollect = linesWithSessionId.collect()
linesWithSessionIdCollect
This will printout all the contents of the RDD
Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.
Example here: https://codesandbox.io/s/21r4z95p7j
You can even utilize the bottom gutter space if you so choose, simply by adding another "item".
Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background-color: #334;_x000D_
color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
min-height: 100vh;_x000D_
min-width: 100vw;_x000D_
display: grid;_x000D_
grid-template-columns: 100%;_x000D_
grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
background-color: #558;_x000D_
padding: 2px;_x000D_
margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<title>Parcel Sandbox</title>_x000D_
<meta charset="UTF-8" />_x000D_
<link rel="stylesheet" href="src/index.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="app">_x000D_
<div class="main">_x000D_
<div class="item">Item 1</div>_x000D_
<!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
This might be due to a security check. This thread might help you.
There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...
One thing that got this working for me is to make sure that github.com
is in ~jenkins/.ssh/known_hosts
.
Solution in Swift 3:
button.setTitleColor(UIColor.red, for: .normal)
This will set the title color of button.
You are trying to send headers information after outputing content.
If you want to do this, look for output buffering.
Therefore, look to use ob_start();
A similar approach to @mwigdahl's answer, you can also implement a .NET CLR in C#, with code such as;
using System.Data.SqlTypes;
using RX = System.Text.RegularExpressions;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Regex(string input, string regex)
{
var match = RX.Regex.Match(input, regex).Groups[1].Value;
return new SqlString (match);
}
}
Installation instructions can be found here
TEXT
c
bytes of disk space, where c
is the length of the stored string.VARCHAR(M)
M
charactersM
needs to be between 1 and 65535c
bytes (for M
≤ 255) or 2 + c
(for 256 ≤ M
≤ 65535) bytes of disk space where c
is the length of the stored stringTEXT
has a fixed max size of 2¹6-1 = 65535
characters.
VARCHAR
has a variable max size M
up to M = 2¹6-1
.
So you cannot choose the size of TEXT
but you can for a VARCHAR
.
The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT
column.
So if you want to have an index on the column, you have to use VARCHAR
. But notice that the length of an index is also limited, so if your VARCHAR
column is too long you have to use only the first few characters of the VARCHAR
column in your index (See the documentation for CREATE INDEX
).
But you also want to use VARCHAR
, if you know that the maximum length of the possible input string is only M
, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30)
instead of TINYTEXT
or TEXT
and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)
Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT
or LONGTEXT
, but be careful: MEDIUMTEXT
stores strings up to 16 MB, LONGTEXT
up to 4 GB. If you use LONGTEXT
and get the data via PHP (at least if you use mysqli
without store_result
), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.
However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.
Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30)
, VARCHAR(100)
and TINYTEXT
, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000)
or a TEXT
column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).
For more information have a look at the documentation.
Finally, I want to add a notice, that both, TEXT
and VARCHAR
are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR
. You can read more about this here.
I put together a short function that allows for a little more flexibility when inserting a row:
def insert_row(idx, df, df_insert):
dfA = df.iloc[:idx, ]
dfB = df.iloc[idx:, ]
df = dfA.append(df_insert).append(dfB).reset_index(drop = True)
return df
which could be further shortened to:
def insert_row(idx, df, df_insert):
return df.iloc[:idx, ].append(df_insert).append(df.iloc[idx:, ]).reset_index(drop = True)
Then you could use something like:
df = insert_row(2, df, df_new)
where 2
is the index position in df
where you want to insert df_new
.
Just to clarify why :set list
won't show CR's as ^M
without e ++ff=unix
and why :set list
has nothing to do with ^M
's.
Internally when Vim reads a file into its buffer, it replaces all line-ending characters with its own representation (let's call it $
's). To determine what characters should be removed, it firstly detects in what format line endings are stored in a file. If there are only CRLF '\r\n'
or only CR '\r'
or only LF '\n'
line-ending characters, then the 'fileformat'
is set to dos
, mac
and unix
respectively.
When list
option is set, Vim displays $
character when the line break occurred no matter what fileformat
option has been detected. It uses its own internal representation of line-breaks and that's what it displays.
Now when you write buffer to the disc, Vim inserts line-ending characters according to what fileformat
options has been detected, essentially converting all those internal $
's with appropriate characters. If the fileformat
happened to be unix
then it will simply write \n
in place of its internal line-break.
The trick is to force Vim to read a dos
encoded file as unix
one. The net effect is that it will remove all \n
's leaving \r
's untouched and display them as ^M
's in your buffer. Setting :set list
will additionally show internal line-endings as $
. After all, you see ^M$
in place of dos
encoded line-breaks.
Also notice that :set list
has nothing to do with showing ^M
's. You can check it by yourself (make sure you have disabled list
option first) by inserting single CR using CTRL-V
followed by Enter
in insert mode. After writing buffer to disc and opening it again you will see ^M
despite list
option being set to 0.
You can find more about file formats on http://vim.wikia.com/wiki/File_format or by typing:help 'fileformat'
in Vim.
You're trying to call the isEmpty()
method on a null
reference (as List test = null;
). This will surely throw a NullPointerException
. You should do if(test!=null)
instead (Checking for null
first).
The method isEmpty()
returns true, if an ArrayList
object contains no elements; false otherwise (for that the List
must first be instantiated that is in your case is null
).
Edit:
You may want to see this question.
Here is a list of special characters that you can escape when creating a string literal for JSON:
\b Backspace (ASCII code 08) \f Form feed (ASCII code 0C) \n New line \r Carriage return \t Tab \v Vertical tab \' Apostrophe or single quote \" Double quote \\ Backslash character
Reference: String literals
Some of these are more optional than others. For instance, your string should be perfectly valid whether you escape the tab character or leave in a tab literal. You should certainly be handling the backslash and quote characters, though.
var obj = [
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
];
// the code you're looking for
var needle = 'AL';
// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
// look for the entry with a matching `code` value
if (obj[i].code == needle){
// we found it
// obj[i].name is the matched result
}
}
You are missing a space between else
and if
It should be else if
instead of elseif
if(condition)
{
}
else if(condition)
{
}
else
{
}
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.
I recommend this pattern:
@Entity(name = User.PERSISTANCE_NAME)
@Table(name = User.PERSISTANCE_NAME )
public class User {
static final String PERSISTANCE_NAME = "USER";
// Column definitions here
}
Go to path and type
go get -u ./..
It will update all require packages.
one way
$bad='/[\/:*?"<>|]/';
$string = 'fi?le*';
function sanitize($str,$pat)
{
return preg_replace($pat,"",$str);
}
echo sanitize($string,$bad);
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.
Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.
You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.
To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.
A typical C++ code will be:
hVaultLib = LoadLibrary(L"vaultcli.dll");
if (hVaultLib != NULL)
{
pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");
bStatus = (pVaultEnumerateVaults != NULL)
&& (pVaultFree != NULL)
&& (pVaultGetItemW7 != NULL)
&& (pVaultGetItemW8 != NULL)
&& (pVaultOpenVault != NULL)
&& (pVaultCloseVault != NULL)
&& (pVaultEnumerateItems != NULL);
}
Then you enumerate all stored credentials by calling
VaultEnumerateVaults
Then you go over the results.
You're missing a closing parenthesis )
in print()
:
print('{0}+{1}={2}'.format(n1,n2,t1))
and you're also not storing the returned value from int()
, so z
is still a string.
z = input('?')
z = int(z)
or simply:
z = int(input('?'))
For multiple files; note the newer "multiple" attribute for input:
Form:
@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<label for="files">Filename:</label>
<input type="file" name="files" multiple="true" id="files" />
<input type="submit" />
}
Controller:
[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
return View();
}
Easier solution;
#/bin/bash
if (( ${1:-2} >= 2 )); then
echo "First parameter must be 0 or 1"
fi
# rest of script...
Output
$ ./test
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1
Explanation
(( ))
- Evaluates the expression using integers.${1:-2}
- Uses parameter expansion to set a value of 2
if undefined.>= 2
- True if the integer is greater than or equal to two 2
.As David Olsson has said, you can use HTML in your string resources:
<resource>
<string name="my_string">A string with <i>actual</i> <b>formatting</b>!</string>
</resources>
Then if you use getText(R.string.my_string)
rather than getString(R.string.my_string)
you get back a CharSequence
rather than a String
that contains the formatting embedded.
This is what worked for me.
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
}
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedMethods("*")
.allowedHeaders("*")
.allowedOrigins("*")
.allowCredentials(true);
}
}
How about merging 2 data tables and then comparing the changes? Not sure if that will fill 100% of your needs but for the quick compare it will do a job.
public DataTable GetTwoDataTablesChanges(DataTable firstDataTable, DataTable secondDataTable)
{
firstDataTable.Merge(secondDataTable);
return secondDataTable.GetChanges();
}
You can read more about DataTable.Merge()
I ran this in the command prompt(have windows 7 os): JAVA_HOME=C:\Program Files\Android\Android Studio\jre
where what its = to is the path to that jre folder, so anyone's can be different.
My case? I had startup file, but it is excluded in the project. I just included it and the error left.
Try to split the characters into multiple chunks like the query below and try:
Insert into table (clob_column) values ( to_clob( 'chunk 1' ) || to_clob( 'chunk 2' ) );
It worked for me.
A lot of these answers only accept single-character separators, or don't deal with edge cases well (e.g. empty separators), so I thought I would provide a more definitive solution.
Here are two functions, gsplit
and split
, adapted from the code in the Scribunto MediaWiki extension, which is used on wikis like Wikipedia. The code is licenced under the GPL v2. I have changed the variable names and added comments to make the code a bit easier to understand, and I have also changed the code to use regular Lua string patterns instead of Scribunto's patterns for Unicode strings. The original code has test cases here.
-- gsplit: iterate over substrings in a string separated by a pattern
--
-- Parameters:
-- text (string) - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean) - if true (or truthy), pattern is interpreted as a plain
-- string, not a Lua pattern
--
-- Returns: iterator
--
-- Usage:
-- for substr in gsplit(text, pattern, plain) do
-- doSomething(substr)
-- end
local function gsplit(text, pattern, plain)
local splitStart, length = 1, #text
return function ()
if splitStart then
local sepStart, sepEnd = string.find(text, pattern, splitStart, plain)
local ret
if not sepStart then
ret = string.sub(text, splitStart)
splitStart = nil
elseif sepEnd < sepStart then
-- Empty separator!
ret = string.sub(text, splitStart, sepStart)
if sepStart < length then
splitStart = sepStart + 1
else
splitStart = nil
end
else
ret = sepStart > splitStart and string.sub(text, splitStart, sepStart - 1) or ''
splitStart = sepEnd + 1
end
return ret
end
end
end
-- split: split a string into substrings separated by a pattern.
--
-- Parameters:
-- text (string) - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean) - if true (or truthy), pattern is interpreted as a plain
-- string, not a Lua pattern
--
-- Returns: table (a sequence table containing the substrings)
local function split(text, pattern, plain)
local ret = {}
for match in gsplit(text, pattern, plain) do
table.insert(ret, match)
end
return ret
end
Some examples of the split
function in use:
local function printSequence(t)
print(unpack(t))
end
printSequence(split('foo, bar,baz', ',%s*')) -- foo bar baz
printSequence(split('foo, bar,baz', ',%s*', true)) -- foo, bar,baz
printSequence(split('foo', '')) -- f o o
If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.
It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.
If you want to fade to black(ish), you'll need a black container around the image. Something like:
.ctr {
margin: 0;
padding: 0;
background-color: black;
display: inline-block;
}
and
<div class="ctr"><img ... /></div>
Under Linux, got same problem after Android Studio update (and several months without using it...).
I solved it by running the following command in a console:
mv .subversion/ .subversion.bak
I prefer that command to rm -R .subversion
since it left me a rollback option.
Yes you can do this.
*[id^='term-']{
[css here]
}
This will select all ids that start with 'term-'
.
As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.
For one line!
Try using for wmic OS Get localdatetime^|find "."
in for /f
without tokens
and/or delims
, this works in any language / region and also, no user settings interfere with the layout of the output.
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo=month: !_date:~4,2!&echo= day: !_date:~6,2!"
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo=month: !_date:~4,2!&echo= day: !_date:~6,2!"
Results:
year: 2019
month: 06
day: 12
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo= month: !_date:~4,2!&echo= day: !_date:~6,2!&echo= hour: !_date:~8,2!&echo=minute: !_date:~10,2!"
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo= month: !_date:~4,2!&echo= day: !_date:~6,2!&echo= hour: !_date:~8,2!&echo=minute: !_date:~10,2!"
Results:
year: 2020
month: 05
day: 16
hour: 00
minute: 46
Here's another idiomatic use case besides searching. Let's say you wanted to wait for a condition to be true, e.g. a port to be open on a remote server, along with some timeout. Then you could utilize a while...else
construct like so:
import socket
import time
sock = socket.socket()
timeout = time.time() + 15
while time.time() < timeout:
if sock.connect_ex(('127.0.0.1', 80)) is 0:
print('Port is open now!')
break
print('Still waiting...')
else:
raise TimeoutError()
if status
is of type Status
enum, status.name()
will give you its defined name.
Regarding how you log messages within code, I would opt for the second approach:
ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");
Where messages sent to the log above will be 'named' using the fully-qualifed type Bar
, e.g.
MyNamespace.Foo.Bar [INFO] message
The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar
specifically to DEBUG:
<log4net>
<!-- appenders go here -->
<root>
<level value="INFO" />
<appender-ref ref="myLogAppender" />
</root>
<logger name="MyNamespace.Foo.Bar">
<level value="DEBUG" />
</logger>
</log4net>
The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog"
, you loose much of this power!
Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.
For further reading, here is a codeproject article I wrote on logging:
You can install eclipse theme plugin then select default. Please visit here: http://eclipsecolorthemes.org/?view=plugin
A one-liner for object configs:
new Date(new Date().setHours(0,0,0,0));
When creating an element:
dateFieldConfig = {
name: "mydate",
value: new Date(new Date().setHours(0, 0, 0, 0)),
}
There is an easy way
array_walk_recursive(
$array,
function (&$entry) {
$entry = mb_convert_encoding(
$entry,
'UTF-8'
);
}
);
Also make sure your Workspace Settings aren't overriding your User Settings. The UI doesn't make it very obvious which settings you're editing and "File > Preferences > Settings" defaults to User Settings even though Workspace Settings trump User Settings.
You can also edit Workspace settings directly: /.vscode/settings.json
#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep() --- just a function that waits a certain amount of milliseconds
using namespace std;
int main()
{
clock_t cl; //initializing a clock type
cl = clock(); //starting time of clock
_sleep(5167); //insert code here
cl = clock() - cl; //end point of clock
_sleep(1000); //testing to see if it actually stops at the end point
cout << cl/(double)CLOCKS_PER_SEC << endl; //prints the determined ticks per second (seconds passed)
return 0;
}
//outputs "5.17"
Text boxes in worksheets are sometimes not updated when their text or formatting is changed, and even the DoEvent command does not help.
As there is no command in Excel to refresh a worksheet in the way a user form can be refreshed, it is necessary to use a trick to force Excel to update the screen.
The following commands seem to do the trick:
- ActiveSheet.Calculate
- ActiveWindow.SmallScroll
- Application.WindowState = Application.WindowState
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located
update_attribute
and update_attributes
are similar, but
with one big difference: update_attribute
does not run validations.
Also:
update_attribute
is used to update record with single attribute.
Model.update_attribute(:column_name, column_value1)
update_attributes
is used to update record with multiple attributes.
Model.update_attributes(:column_name1 => column_value1, :column_name2 => column_value2, ...)
These two methods are really easy to confuse given their similar names and works. Therefore, update_attribute
is being removed in favor of update_column
.
Now, in Rails4 you can use Model.update_column(:column_name, column_value)
at the place of Model.update_attribute(:column_name, column_value)
Click here to get more info about update_column
.
I have also used the SimpleViewPagerIndicator from @JROD. It also crashes as described by @manuelJ.
According to his documentation:
SimpleViewPagerIndicator pageIndicator = (SimpleViewPagerIndicator) findViewById(R.id.page_indicator);
pageIndicator.setViewPager(pager);
Make sure you add this line as well:
pageIndicator.notifyDataSetChanged();
It crashes with an array out of bounds exception because the SimpleViewPagerIndicator is not getting instantiated properly and the items are empty. Calling the notifyDataSetChanged results in all the values being set properly or rather reset properly.
This answer is for users of SourceTree with limited terminal git experience.
Open the problematic submodule from within the Git project (super-project).
Fetch and ensure 'Fetch all tags' is checked.
Rebase pull your Git project.
This will solve the 'reference is not a tree' problem 9 out of ten times. That 1 time it won't, is a terminal fix as described by the top answer.
Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame
Windows are just normal WPF application Windows, but can host Pages via a Frame container
git checkout filename
git reset --hard
might do the trick as well
If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system()
with subprocess.Popen()
:
sts = os.system("mycmd" + " myarg")
...does the same thing as...
sts = Popen("mycmd" + " myarg", shell=True).wait()
The "improved" code looks more complicated, but it's better because once you know subprocess.Popen()
, you don't need anything else. subprocess.Popen()
replaces several other tools (os.system()
is just one of those) that were scattered throughout three other Python modules.
If it helps, think of subprocess.Popen()
as a very flexible os.system()
.
The only way I've seen it done is if you do this:
for /f "delims=" %a in ('ver') do @set foobar=%a
ver
is the version command for Windows and on my system it produces:
Microsoft Windows [Version 6.0.6001]
Could it be this? http://docs.gunicorn.org/en/latest/settings.html#timeout
Other possibilities could be your response is taking too long or is stuck waiting.
yourArray.Length
:)
Better yet use a oneliner:
Dump remoteDB to localDB:
mysqldump -uroot -pMypsw -h remoteHost remoteDB | mysql -u root -pMypsw localDB
Dump localDB to remoteDB:
mysqldump -uroot -pmyPsw localDB | mysql -uroot -pMypsw -h remoteHost remoteDB
To view your iOS device's console in Safari on your Mac (Mac only apparently):
Safari's Inspector will appear showing a console for your iOS device.
@alvas has a good answer. But again it depends on the nature of the task, for example in your application you want to consider all conjunction
e.g. and, or, but, if, while and all determiner
e.g. the, a, some, most, every, no as stop words considering all others parts of speech as legitimate, then you might want to look into this solution which use Part-of-Speech Tagset to discard words, Check table 5.1:
import nltk
STOP_TYPES = ['DET', 'CNJ']
text = "some data here "
tokens = nltk.pos_tag(nltk.word_tokenize(text))
good_words = [w for w, wtype in tokens if wtype not in STOP_TYPES]
Batch Normalization is used to normalize the input layer as well as hidden layers by adjusting mean and scaling of the activations. Because of this normalizing effect with additional layer in deep neural networks, the network can use higher learning rate without vanishing or exploding gradients. Furthermore, batch normalization regularizes the network such that it is easier to generalize, and it is thus unnecessary to use dropout to mitigate overfitting.
Right after calculating the linear function using say, the Dense() or Conv2D() in Keras, we use BatchNormalization() which calculates the linear function in a layer and then we add the non-linearity to the layer using Activation().
from keras.layers.normalization import BatchNormalization
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('softmax'))
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True,
validation_split=0.2, verbose = 2)
How is Batch Normalization applied?
Suppose we have input a[l-1] to a layer l. Also we have weights W[l] and bias unit b[l] for the layer l. Let a[l] be the activation vector calculated(i.e. after adding the non-linearity) for the layer l and z[l] be the vector before adding non-linearity
Now define new parameters ? and ß that will change the scale of the hidden layer as follows:
z_norm[l] = ?.Z_temp[l] + ß
In this code excerpt, the Dense() takes the a[l-1], uses W[l] and calculates z[l]. Then the immediate BatchNormalization() will perform the above steps to give z_norm[l]. And then the immediate Activation() will calculate tanh(z_norm[l]) to give a[l] i.e.
a[l] = tanh(z_norm[l])
@Waisky suggested:
You need to use
setInterval
to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:
If you'd like to do the same thing, using Hooks:
const [time, setTime] = useState(Date.now());
useEffect(() => {
const interval = setInterval(() => setTime(Date.now()), 1000);
return () => {
clearInterval(interval);
};
}, []);
Regarding the comments:
You don't need to pass anything inside []
. If you pass time
in the brackets, it means run the effect every time the value of time
changes, i.e., it invokes a new setInterval
every time, time
changes, which is not what we're looking for. We want to only invoke setInterval
once when the component gets mounted and then setInterval
calls setTime(Date.now())
every 1000 seconds. Finally, we invoke clearInterval
when the component is unmounted.
Note that the component gets updated, based on how you've used time
in it, every time the value of time
changes. That has nothing to do with putting time
in []
of useEffect
.
you need to prevent the default behavior of your form when submitting
by adding this:
$("#postcontent").on('submit' , function(e) {
e.preventDefault();
//then the rest of your code
}
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.
However, I do agree that the lack of the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.
import cookielib
import urllib
import urllib2
url = 'http://www.someserver.com/auth/login'
values = {'email-email' : '[email protected]',
'password-clear' : 'Combination',
'password-password' : 'mypassword' }
data = urllib.urlencode(values)
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(cookies))
response = opener.open(url, data)
the_page = response.read()
http_headers = response.info()
# The login cookies should be contained in the cookies variable
For more information visit: https://docs.python.org/2/library/urllib2.html
I was running JUNIT 5 and was also referencing Hamcrest external jar. But Hamcrest is also part of JUNIT 5 library. So, I have to change the order of external Hamecrest jar file up the JUNIT 5 library in build path.
In addition to Gaby aka's method, we can find elements inside htmlObject
in this way -
htmlObj.find("#box").html();
Fiddle is available here - http://jsfiddle.net/ashwyn/76gL3/
Why do you want to enforce that only a single thread can access the DB at any one time?
It is the job of the database driver to implement any necessary locking, assuming a Connection
is only used by one thread at a time!
Most likely, your database is perfectly capable of handling multiple, parallel access
from PIL import Image
image = Image.open('File.jpg')
image.show()
Use $n
(where n is a digit) to refer to captured subsequences in replaceFirst(...)
. I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.
Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
// replace first number with "number" and second number with the first
String output = m.replaceFirst("number $3$1"); // number 46
}
Consider (\D+)
for the second group instead of (.*)
. *
is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d)
has nothing to match, before it can match to the final digit.
You almost had it right. The simplest way is
mylist[0][0] # get the first character from the first item in the list
but
mylist[0][:1] # get up to the first character in the first item in the list
would also work.
You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.
A third variant:
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readValue("{\"k1\":\"v1\"}", JsonNode.class);
I think the better way to go is to put switch to named functions (Check this overflow for more on that subject). That way you can call them from a single event.
Like so:
function firstFunction() {
console.log("first");
}
function secondFunction() {
console.log("second");
}
function thirdFunction() {
console.log("third");
}
That way you can load them in a single ready function.
jQuery(document).on('ready', function(){
firstFunction();
secondFunction();
thirdFunction();
});
This will output the following to your console.log:
first
second
third
This way you can reuse the functions for other events.
jQuery(window).on('resize',function(){
secondFunction();
});
I am facing problems with composer because it consumes all the available memory, and then, the process get killed ( actualy, the output message is "Killed")
So, I was looking for a solution to limit composer memory usage.
I tried ( from @Sven answers )
$ php -d memory_limit=512M /usr/local/bin/composer update
But it didn't work because
"Composer internally increases the memory_limit to 1.5G."
-> Thats from composer oficial website.
Then I found a command that works :
$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update
Althought, in my case 512mb is not enough !
Source : https://www.agileana.com/blog/composer-memory-limit-troubleshooting/
Old post, but I ran into this so if you're trying to output something to Output in a WPF project in Visual Studio, the contemporary method is:
Include this:
using System.Diagnostics;
And then:
Debug.WriteLine("something");
When you subtract two dates in Oracle, you get the number of days between the two values. So you just have to multiply to get the result in minutes instead:
SELECT (date2 - date1) * 24 * 60 AS minutesBetween
FROM ...
I've also had the same issue ( Website body background rendering a right white margin in iPhone Safari ) and found that adding the background image to the <html>
tag fixed the problem.
Before
body {background:url('images/back.jpg');}
After
html, body {background:url('images/back.jpg');}
They are implemented in very different ways.
hash_map
(unordered_map
in TR1 and Boost; use those instead) use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.
map
is implemented as a balanced binary search tree (usually a red/black tree).
An unordered_map
should give slightly better performance for accessing known elements of the collection, but a map
will have additional useful characteristics (e.g. it is stored in sorted order, which allows traversal from start to finish). unordered_map
will be faster on insert and delete than a map
.
I gave up on strictly CSS and used a little jquery:
var leftcol = $("#leftcolumn");
var rightcol = $("#rightcolumn");
var leftcol_height = leftcol.height();
var rightcol_height = rightcol.height();
if (leftcol_height > rightcol_height)
rightcol.height(leftcol_height);
else
leftcol.height(rightcol_height);
@GET
@Path("/test2")
public Response test2(){
List<String> list=new Vector<String>();
list.add("a");
list.add("b");
final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) { };
return Response.ok().entity(entity).build();
}
Something else to check is make sure viewstate is on (I just solved this yesterday). If you don't have viewstate on, the gridview will be blank until you load it again.
If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.
SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)
Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.
According to the documentation return false;
should do the job.
We can break the $.each() loop [..] by making the callback function return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue
works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
You could also use:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
What all the others said.
Specifically, I recommend you go to Project > Properties > Java Build Path > Libraries
and make sure you have exactly one copy of android.jar
referenced. (Sometimes you can get two if you're importing a project.) And that its path is correct.
Sometimes you can get the system to resolve this for you by clicking a different target SDK in Project > Properties > Android
, then restoring your original selection.
You can use the ToString overload. Have a look at this page for more info
So just Use myDate.ToString("yyyy-MM-dd HH:mm:ss")
or something equivalent
My preferred way is to use circular dependencies*, which node supports
var app = module.exports = express();
as your first order of businessvar app = require('./app')
to access itvar express = require('express');
var app = module.exports = express(); //now app.js can be required to bring app into any file
//some app/middleware, config, setup, etc, including app.use(app.router)
require('./routes'); //module.exports must be defined before this line
var app = require('./app');
app.get('/', function(req, res, next) {
res.render('index');
});
//require in some other route files...each of which requires app independently
require('./user');
require('./blog');
I think all these answers are missing the question. The problem was to "Round UP", not just "Round". It is my understanding that Round Up means that ANY fractional value about a whole digit rounds up to the next WHOLE digit. ie: 48.0000000 = 48 but 25.00001 = 26. Is this not the definition of rounding up? (or have my past 60 years in accounting been misplaced?
I use this method )
public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);
public static bool CompareTwoArrays<T1, T2>(this IEnumerable<T1> array1, IEnumerable<T2> array2, CompareValue<T1, T2> compareValue)
{
return array1.Select(item1 => array2.Any(item2 => compareValue(item1, item2))).All(search => search)
&& array2.Select(item2 => array1.Any(item1 => compareValue(item1, item2))).All(search => search);
}
This is a bit confusing, but follow these steps to save the session.
To open the session, double click on particular saved session.
Also from guava libraries... com.google.common.primitives.Ints:
List<Integer> Ints.asList(int...)
As the OP said that he wants letters and numbers ONLY (no underscore!), one more way to have this in php regex is to use posix expressions:
/^[[:alnum:]]+$/
Note: This will not work in Java, JavaScript, Python, Ruby, .NET
Connect to MySQL
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Also mysqli_connect() function to open a new connection to the MySQL server.
<?php
// Create connection
$con=mysqli_connect(host,username,password,dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
The shared pointer manages both the object itself, and a small object containing the reference count and other housekeeping data. make_shared
can allocate a single block of memory to hold both of these; constructing a shared pointer from a pointer to an already-allocated object will need to allocate a second block to store the reference count.
As well as this efficiency, using make_shared
means that you don't need to deal with new
and raw pointers at all, giving better exception safety - there is no possibility of throwing an exception after allocating the object but before assigning it to the smart pointer.
row_count = $('#my_table').find('tr').length;
column_count = $('#my_table').find('td').length / row_count;
One way to do it is with NumPy transpose. For a list, a:
>>> import numpy as np
>>> np.array(a).T.tolist()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Or another one without zip:
>>> map(list,map(None,*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
You can find everything you need to know about Gradle here: Gradle Plugin User Guide
Goals of the new Build System
The goals of the new build system are:
- Make it easy to reuse code and resources
- Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application
- Make it easy to configure, extend and customize the build process
- Good IDE integration
Why Gradle?
Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.
Here are some of its features that made us choose Gradle:
- Domain Specific Language (DSL) to describe and manipulate the build logic
- Build files are Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL elements to provide custom logic.
- Built-in dependency management through Maven and/or Ivy.
- Very flexible. Allows using best practices but doesn’t force its own way of doing things.
- Plugins can expose their own DSL and their own API for build files to use.
- Good Tooling API allowing IDE integration
Short Answer: Encrypt the link like youtube does, don't know how than ask youtube/google of how they do it. (Just in case you want to get straight into the point.)
I would like to point out to anyone that this is possible because youtube does it and if they can so can any other website and it isn't from the browser either because I tested it on a couple browsers such as microsoft edge and internet explorer and so there is a way to disable it and seen that people still say it...I tries looking for an answer because if youtube can than there has to be a way and the only way to see how they do it is if someone looked into the scripts of youtube which I am doing now. I also checked to see if it was a custom context menu as well and it isn't because the context menu is over flowing the inspect element and I mean like it is over it and I looked and it never creates a new class and also it is impossible to actually access inspect element with javascript so it can't be. You can tell when it double right-click a youtube video that it pops up the context menu for chrome. Besides...youtube wouldn't add that function in. I am doing research and looking through the source of youtube so I will be back if I find the answer...if anyone says you can't than, well they didn't do research like I have. The only way to download youtube videos is through a video download.
Okay...I did research and my research stays that you can disable it except there is no javascript to it...you have to be able to encrypt the links to the video for you to be able to disable it because I think any browser won't show it if it can't find it and when I opened a youtube video link it showed as this "blob:https://www.youtube.com/e5c4808e-297e-451f-80da-3e838caa1275" without quotes so it is encrypting it so it cannot be saved...you need to know php for that but like the answer you picked out of making it harder, youtube makes it the hardest of heavy encrypting it, you need to be an advance php programmer but if you don't know that than take the person you picked as best answer of making it hard to download it...but if you know php than heavy encrypt the video link so it only is able to be read on yours...I don't know how to explain how they do it but they did and there is a way. The way youtube Encrypts there videos is quite smart so if you want to know how to than just ask youtube/google of how they do it...hope this helps for you although you already picked a best answer. So encrypting the link is best in short terms.
Git GUI has a PUSH button - pardon the pun, and the dialog box it opens has a checkbox for tags.
I pushed a branch from the command line, without tags, and then tried again pushing the branch using the --follow-tags
option descibed above. The option is described as following annotated tags. My tags were simple tags.
I'd fixed something, tagged the commit with the fix in, (so colleagues can cherry pick the fix,) then changed the software version number and tagged the release I created (so colleagues can clone that release).
Git returned saying everything was up-to-date. It did not send the tags! Perhaps because the tags weren't annotated. Perhaps because there was nothing new on the branch.
When I did a similar push with Git GUI, the tags were sent.
For the time being, I am going to be pushing my changes to my remotes with Git GUI and not with the command line and --follow-tags
.
If you're using the command-line tools, running git --version
should give you the version number.
I discovered that there is a second portion of the answer to this.
The first portion helped me, but I still had a space to the right of my type=number
input. I had zeroed out the margin on the input, but apparently I had to zero out the margin on the spinner as well.
This fixed it:
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
This answer will do what you need, although usually you don't add specific usernames to sudoers
. Instead, you have a group of sudoers and just add your user to that group when needed. This way you don't need to use visudo
more than once when giving sudo
permission to users.
If you're on Ubuntu, the group is most probably already set up and called admin
:
$ sudo cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
...
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
# See sudoers(5) for more information on "#include" directives:
#includedir /etc/sudoers.d
On other distributions, like Arch and some others, it's usually called wheel
and you may need to set it up: Arch Wiki
To give users in the wheel group full root privileges when they precede a command with "sudo", uncomment the following line: %wheel ALL=(ALL) ALL
Also note that on most systems visudo
will read the EDITOR
environment variable or default to using vi
. So you can try to do EDITOR=vim visudo
to use vim
as the editor.
To add a user to the group you should run (as root):
# usermod -a -G groupname username
where groupname
is your group (say, admin
or wheel
) and username
is the username (say, john
).
package main
type Proxy struct {
Address string
Port string
}
type Configuration struct {
Proxy
Val string
}
func main() {
c := &Configuration{
Val: "test",
Proxy: Proxy {
Address: "addr",
Port: "80",
},
}
}
For Angular:
getUserPicture(userId) {
FB.api('/' + userId, {fields: 'picture.width(800).height(800)'}, function(response) {
console.log('getUserPicture',response);
});
}
If you know your Root Password and just wish to reset it then do as below:
Start MySQL Service from control panel > Administrative Tools > Services. (only if it was stopped by you earlier ! Otherwise, just skip this step)
Start MySQL Workbench
Type in this command/SQL line
ALTER USER 'root'@'localhost' PASSWORD EXPIRE;
To reset any other user password... just type other user name instead of root.
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
I'm quite happy with my "make a weak pin storage program" solution. Maybe it will help people who need a very simple binary file IO example to follow.
$ ls
WeakPin my_pin_code.pin weak_pin.c
$ ./WeakPin
Pin: 45 47 49 32
$ ./WeakPin 8 2
$ Need 4 ints to write a new pin!
$./WeakPin 8 2 99 49
Pin saved.
$ ./WeakPin
Pin: 8 2 99 49
$
$ cat weak_pin.c
// a program to save and read 4-digit pin codes in binary format
#include <stdio.h>
#include <stdlib.h>
#define PIN_FILE "my_pin_code.pin"
typedef struct { unsigned short a, b, c, d; } PinCode;
int main(int argc, const char** argv)
{
if (argc > 1) // create pin
{
if (argc != 5)
{
printf("Need 4 ints to write a new pin!\n");
return -1;
}
unsigned short _a = atoi(argv[1]);
unsigned short _b = atoi(argv[2]);
unsigned short _c = atoi(argv[3]);
unsigned short _d = atoi(argv[4]);
PinCode pc;
pc.a = _a; pc.b = _b; pc.c = _c; pc.d = _d;
FILE *f = fopen(PIN_FILE, "wb"); // create and/or overwrite
if (!f)
{
printf("Error in creating file. Aborting.\n");
return -2;
}
// write one PinCode object pc to the file *f
fwrite(&pc, sizeof(PinCode), 1, f);
fclose(f);
printf("Pin saved.\n");
return 0;
}
// else read existing pin
FILE *f = fopen(PIN_FILE, "rb");
if (!f)
{
printf("Error in reading file. Abort.\n");
return -3;
}
PinCode pc;
fread(&pc, sizeof(PinCode), 1, f);
fclose(f);
printf("Pin: ");
printf("%hu ", pc.a);
printf("%hu ", pc.b);
printf("%hu ", pc.c);
printf("%hu\n", pc.d);
return 0;
}
$
Under some circumstances (if you get "ERROR 1064 (42000): You have an error in your SQL syntax;...") you need to do
ALTER TABLE mytable MODIFY mytable.mycolumn varchar(255);
I think people have put too much weight into the application logic versus protocol matter. The important thing is that the response should make sense. What if you have an API that serves a dynamic resource and a request is made for X which is derived from template Y with data Z and either Y or Z isn't currently available? Is that a business logic error or a technical error? The correct answer is, "who cares?"
Your API and your responses need to be intelligible and consistent. It should conform to some kind of spec, and that spec should define what a valid response is. Something that conforms to a valid response should yield a 200 code. Something that does not conform to a valid response should yield a 4xx or 5xx code indicative of why a valid response couldn't be generated.
If your spec's definition of a valid response permits { "error": "invalid ID" }
, then it's a successful response. If your spec doesn't make that accommodation, it would be a poor decision to return that response with a 200 code.
I'd draw an analogy to calling a function parseFoo
. What happens when you call parseFoo("invalid data")
? Does it return an error result (maybe null)? Or does it throw an exception? Many will take a near-religious position on whether one approach or the other is correct, but ultimately it's up to the API specification.
"The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request"
Obviously there's a difference of opinion with regards to whether "successfully returning an error" constitutes an HTTP success or error. I see different people interpreting the same specs different ways. So pick a side, sure, but also accept that either way the whole world isn't going to agree with you. Me? I find myself somewhere in the middle, but I'll offer some commonsense considerations.
500 Internal Server Error
. This seems to be OP's situation. The application should not return a 200
for unexpected errors, but also see point 3.In OP's situation, it sounds like you have a de-facto standard that unhandled exceptions yield a 200 with a distinguishable response body. It's not ideal, but if it's not breaking things and actively causing problems, you probably have bigger, more important problems to solve.
The following can also add fields' name based on the CSV header:
import sqlite3
def csv_sql(file_dir,table_name,database_name):
con = sqlite3.connect(database_name)
cur = con.cursor()
# Drop the current table by:
# cur.execute("DROP TABLE IF EXISTS %s;" % table_name)
with open(file_dir, 'r') as fl:
hd = fl.readline()[:-1].split(',')
ro = fl.readlines()
db = [tuple(ro[i][:-1].split(',')) for i in range(len(ro))]
header = ','.join(hd)
cur.execute("CREATE TABLE IF NOT EXISTS %s (%s);" % (table_name,header))
cur.executemany("INSERT INTO %s (%s) VALUES (%s);" % (table_name,header,('?,'*len(hd))[:-1]), db)
con.commit()
con.close()
# Example:
csv_sql('./surveys.csv','survey','eco.db')
I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log()
is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout
or stderr
with process.stdout.write()
instead of console.log()
, then you'll get the console output from the spawned process 'as is'.
I saw that solution here: Node.js: printing to console without a trailing newline?
Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).
I have created this function, or class. Im kinda new but my friend needed this also so I created this:
public String[] name(int index, String[] z ){
if(index > z.length){
return z;
} else {
String[] returnThis = new String[z.length - 1];
int newIndex = 0;
for(int i = 0; i < z.length; i++){
if(i != index){
returnThis[newIndex] = z[i];
newIndex++;
}
}
return returnThis;
}
}
Since its pretty revelant, I thought I would post it here.
Here's technique I figured out after a bit of trial and error that allows you to preserve your XML styles and avoid the issues of using a <merge/>
(i.e. inflate() requires a merge to attach to root, and returns the root node). No runtime new TableRow()
s or new TextView()
s required.
Code
Note: Here CheckBalanceActivity
is some sample Activity
class
TableLayout table = (TableLayout)CheckBalanceActivity.this.findViewById(R.id.attrib_table);
for(ResourceBalance b : xmlDoc.balance_info)
{
// Inflate your row "template" and fill out the fields.
TableRow row = (TableRow)LayoutInflater.from(CheckBalanceActivity.this).inflate(R.layout.attrib_row, null);
((TextView)row.findViewById(R.id.attrib_name)).setText(b.NAME);
((TextView)row.findViewById(R.id.attrib_value)).setText(b.VALUE);
table.addView(row);
}
table.requestLayout(); // Not sure if this is needed.
attrib_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow style="@style/PlanAttribute" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
style="@style/PlanAttributeText"
android:id="@+id/attrib_name"
android:textStyle="bold"/>
<TextView
style="@style/PlanAttributeText"
android:id="@+id/attrib_value"
android:gravity="right"
android:textStyle="normal"/>
</TableRow>
For Angular9+, according to this, you can use:
.mat-select-panel {
background: red;
....
}
mat-select-content
as class name for the select list content. For its styling I would suggest four options.
1. Use ::ng-deep:
Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
CSS:
::ng-deep .mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
2. Use ViewEncapsulation
... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.
None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:
Typscript:
import {ViewEncapsulation } from '@angular/core';
....
@Component({
....
encapsulation: ViewEncapsulation.None
})
CSS
.mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
3. Set class style in style.css
This time you have to 'force' styles with !important
too.
style.css
.mat-select-content{
width:2000px !important;
background-color: red !important;
font-size: 10px !important;
}
4. Use inline style
<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>
On Debian/Ubuntu use:
sudo apt-get install g++-multilib libc6-dev-i386
Following should work. I have verified. May be your problem is somewhere else.
Receiver:
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
Log.d("TAG", "MyReceiver");
Intent serviceIntent = new Intent(context, Test1Service.class);
context.startService(serviceIntent);
}
}
}
Service:
public class Test1Service extends Service {
/** Called when the activity is first created. */
@Override
public void onCreate() {
super.onCreate();
Log.d("TAG", "Service created.");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "Service started.");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("TAG", "Service started.");
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS"
/>
<!-- <activity android:name=".MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity> -->
<service android:name=".Test1Service"
android:label="@string/app_name"
>
</service>
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
The simplest thing you can do is use reset.css. It normalizes the default stylesheet across browsers, and coincidentally allows button { vertical-align: middle; } to work just fine. Give it a shot - I use it in virtually all of my projects just to kill little bugs like this.
Use the following syntax:
ALTER TABLE your_table
MODIFY COLUMN column1 datatype,
MODIFY COLUMN column2 datatype,
... ... ... ... ...
... ... ... ... ...
Based on that, your ALTER
command should be:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100)
Note that:
MODIFY
statements.MODIFY
statements for two separate columns.This is the standard format of the MODIFY
statement for an ALTER
command on multiple columns in a MySQL table.
Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement
You want to use:
git checkout --ours foo/bar.java
git add foo/bar.java
If you rebase a branch feature_x
against main
(i.e. running git rebase main
while on branch feature_x
), during rebasing ours
refers to main
and theirs
to feature_x
.
As pointed out in the git-rebase docs:
Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.
For further details read this thread.
Try this: tar -cf file.tar file-to-compress ; xz -z file.tar
Note:
|
because this runs commands simultaneously. Using ;
or &
executes commands one after another.This will also work
$(this).parent().parent().find('td').text()
came to this question via google.
Here is what i did in the simplest way.
git checkout branch_to_clone
then create a new git branch from this branch
git checkout -b new_cloned_branch
Switched to branch 'new_cloned_branch'
come back to original branch and continue:
git checkout branch_to_clone
Assuming you screwed up and need to restore something from backup branch :
git checkout new_cloned_branch -- <filepath> #notice the space before and after "--"
Best part if anything is screwed up, you can just delete the source branch and move back to backup branch!!
I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (MySql 8):
-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion
-- Some boundaries
set @startDate = '2015-01-01'
, @endDate = '2020-12-31' ;
-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as -- this has to go _before_ the "with", Duh-oh!
WITH RECURSIVE t as (
select @startDate as dt
UNION
SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
)
select * FROM t -- need this to get the "with"'s results as a "result set", into the "create"
;
-- Exists?
select * from tmpDates ;
Which produces:
dt |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|
How about :
SQL> select * from all_users;
it will return list of all users/schemas, their ID's and date created in DB :
USERNAME USER_ID CREATED
------------------------------ ---------- ---------
SCHEMA1 120 09-SEP-15
SCHEMA2 119 09-SEP-15
SCHEMA3 118 09-SEP-15
There are n!
total permutations for the given array size n
. Here is code written in Java using DFS.
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) {
return results;
}
List<Integer> result = new ArrayList<>();
dfs(nums, results, result);
return results;
}
public void dfs(int[] nums, List<List<Integer>> results, List<Integer> result) {
if (nums.length == result.size()) {
List<Integer> temp = new ArrayList<>(result);
results.add(temp);
}
for (int i=0; i<nums.length; i++) {
if (!result.contains(nums[i])) {
result.add(nums[i]);
dfs(nums, results, result);
result.remove(result.size() - 1);
}
}
}
For input array [3,2,1,4,6], there are totally 5! = 120 possible permutations which are:
[[3,4,6,2,1],[3,4,6,1,2],[3,4,2,6,1],[3,4,2,1,6],[3,4,1,6,2],[3,4,1,2,6],[3,6,4,2,1],[3,6,4,1,2],[3,6,2,4,1],[3,6,2,1,4],[3,6,1,4,2],[3,6,1,2,4],[3,2,4,6,1],[3,2,4,1,6],[3,2,6,4,1],[3,2,6,1,4],[3,2,1,4,6],[3,2,1,6,4],[3,1,4,6,2],[3,1,4,2,6],[3,1,6,4,2],[3,1,6,2,4],[3,1,2,4,6],[3,1,2,6,4],[4,3,6,2,1],[4,3,6,1,2],[4,3,2,6,1],[4,3,2,1,6],[4,3,1,6,2],[4,3,1,2,6],[4,6,3,2,1],[4,6,3,1,2],[4,6,2,3,1],[4,6,2,1,3],[4,6,1,3,2],[4,6,1,2,3],[4,2,3,6,1],[4,2,3,1,6],[4,2,6,3,1],[4,2,6,1,3],[4,2,1,3,6],[4,2,1,6,3],[4,1,3,6,2],[4,1,3,2,6],[4,1,6,3,2],[4,1,6,2,3],[4,1,2,3,6],[4,1,2,6,3],[6,3,4,2,1],[6,3,4,1,2],[6,3,2,4,1],[6,3,2,1,4],[6,3,1,4,2],[6,3,1,2,4],[6,4,3,2,1],[6,4,3,1,2],[6,4,2,3,1],[6,4,2,1,3],[6,4,1,3,2],[6,4,1,2,3],[6,2,3,4,1],[6,2,3,1,4],[6,2,4,3,1],[6,2,4,1,3],[6,2,1,3,4],[6,2,1,4,3],[6,1,3,4,2],[6,1,3,2,4],[6,1,4,3,2],[6,1,4,2,3],[6,1,2,3,4],[6,1,2,4,3],[2,3,4,6,1],[2,3,4,1,6],[2,3,6,4,1],[2,3,6,1,4],[2,3,1,4,6],[2,3,1,6,4],[2,4,3,6,1],[2,4,3,1,6],[2,4,6,3,1],[2,4,6,1,3],[2,4,1,3,6],[2,4,1,6,3],[2,6,3,4,1],[2,6,3,1,4],[2,6,4,3,1],[2,6,4,1,3],[2,6,1,3,4],[2,6,1,4,3],[2,1,3,4,6],[2,1,3,6,4],[2,1,4,3,6],[2,1,4,6,3],[2,1,6,3,4],[2,1,6,4,3],[1,3,4,6,2],[1,3,4,2,6],[1,3,6,4,2],[1,3,6,2,4],[1,3,2,4,6],[1,3,2,6,4],[1,4,3,6,2],[1,4,3,2,6],[1,4,6,3,2],[1,4,6,2,3],[1,4,2,3,6],[1,4,2,6,3],[1,6,3,4,2],[1,6,3,2,4],[1,6,4,3,2],[1,6,4,2,3],[1,6,2,3,4],[1,6,2,4,3],[1,2,3,4,6],[1,2,3,6,4],[1,2,4,3,6],[1,2,4,6,3],[1,2,6,3,4],[1,2,6,4,3]]
Hope this helps.
Spring is a light weight and open source framework created by Rod Johnson in 2003. Spring is a complete and a modular framework, Spring framework can be used for all layer implementations for a real time application or spring can be used for the development of particular layer of a real time application.
Struts is an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model–view–controller (MVC) architecture. It was originally created by Craig McClanahan and donated to the Apache Foundation in May, 2000.
Listed below is the comparison chart of difference between Spring and Strut Framework
you can accept a 2D list in python this way ...
simply
arr2d = [[j for j in input().strip()] for i in range(n)]
# n is no of rows
for characters
n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
a[i] = list(input().strip())
print(a)
or
n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
a[i].append(list(input().strip()))
print(a)
for numbers
n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
a[i] = [int(j) for j in input().strip().split(" ")]
print(a)
where n is no of elements in columns while m is no of elements in a row.
In pythonic way, this will create a list of list
Use memory.limit()
. You can increase the default using this command, memory.limit(size=2500)
, where the size is in MB. You need to be using 64-bit in order to take real advantage of this.
One other suggestion is to use memory efficient objects wherever possible: for instance, use a matrix instead of a data.frame.
You can use optimizer hints
select /*+ INDEX(table_name index_name) */ from table
etc...
More on using optimizer hints: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/hintsref.htm
Try
$("#myModal").modal("toggle")
To open or close the modal with id myModal.
If the above is not working then it means bootstrap.js has been overridden by some other js file. Here is a solution
1:- Move bootstrap.js to the bottom so that it will override other js files.
2:- Make sure the order is like below
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Other js files -->
<script src="plugins/jQuery/bootstrap.min.js"></script>
The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic. Copy this in your main activity
FirebaseMessaging.getInstance().subscribeToTopic("all");
Now send the request as
{
"to":"/topics/all",
"data":
{
"title":"Your title",
"message":"Your message"
"image-url":"your_image_url"
}
}
This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.
You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM
To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA
and either TopicB
or TopicC
:
{
"data":
{
"title": "Your title",
"message": "Your message"
"image-url": "your_image_url"
},
"condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}
Read more about conditions and topics here on FCM documentation
From my experience I've found that some commands which run in IPython do not run in base Python. For example, pwd
and ls
don't work alone in base Python. However they will work if prefaced with a %
such as: %pwd
and %ls
.
Also, in IPython, you can run the cd command like: cd C:\Users\
... This doesn't seem to work in base python, even when prefaced with a %
however.
For what it's worth.
```{r eval=FALSE}
The document will display the code by default but will prevent the code block from being executed, and thus will also not display any results.
I have done it like that
<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>
Note the optional parameter id
set to user instance id attribute.
there is a start item folder in C:\ drive. Remove ur anaconda3 folder there, simple and you are good to go. In my case I found here "C:\Users\pravu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs"
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
Assuming the file is called "CopyFile.java", do the following:
javac CopyFile.java
java -cp . CopyFile
The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).
var newDate = DateTime.Now; //newDate.Date property is date portion of DateTime
You cannot, because IEnumerable<T>
does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all! For example:
IEnumerable<string> ReadLines()
{
string s;
do
{
s = Console.ReadLine();
yield return s;
} while (!string.IsNullOrEmpty(s));
}
IEnumerable<string> lines = ReadLines();
lines.Add("foo") // so what is this supposed to do??
What you can do, however, is create a new IEnumerable
object (of unspecified type), which, when enumerated, will provide all items of the old one, plus some of your own. You use Enumerable.Concat
for that:
items = items.Concat(new[] { "foo" });
This will not change the array object (you cannot insert items into to arrays, anyway). But it will create a new object that will list all items in the array, and then "Foo". Furthermore, that new object will keep track of changes in the array (i.e. whenever you enumerate it, you'll see the current values of items).
Let's use the built in SqlDateTime class
new SqlDateTime(DateTime.Now).ToSqlString()
But still need to check for null values. This will throw overflow exception
new SqlDateTime(DateTime.MinValue).ToSqlString()
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between()
:
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)
plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()
See also the matplotlib examples.
use Extension
import java.text.NumberFormat
val Int.commaString: String
get() = NumberFormat.getInstance().format(this)
val String.commaString: String
get() = NumberFormat.getNumberInstance().format(this.toDouble())
val Long.commaString: String
get() = NumberFormat.getInstance().format(this)
val Double.commaString: String
get() = NumberFormat.getInstance().format(this)
result
1234.commaString => 1,234
"1234.456".commaString => 1,234.456
1234567890123456789.commaString => 1,234,567,890,123,456,789
1234.456.commaString => 1,234.456
Use jQuery
.In the HTML page -
<button type="button">Click Me</button>
<script>
$(document).ready(function() {
$("button").click(function(){
$.ajax({
url:"php_page.php", //the page containing php script
type: "POST", //request type
success:function(result){
alert(result);
}
});
});
})
</script>
Php page -
echo "Hello";
You need Set with objects:
Set rng = Sheet8.Range("A12")
Sheet8 is fine.
Sheet1.[a1]