I get this warning displayed in vscode when creating a new Angular service with the
@Injectable({
providedIn: 'root'
})
syntax (rather than providing the service in app.module.ts).
The warning persists until I reference the new service somewhere in the project. Once the service gets used the warning goes away. No typescript configuration or vscode settings changes necessary.
[update] -- Well, my own foolishness provides the answer to this one. As it turns out, I was deleting the records from myTable before running the select COUNT statement.
How did I do that and not notice? Glad you asked. I've been testing a sql unit testing platform (tsqlunit, if you're interested) and as part of one of the tests I ran a truncate table statement, then the above. After the unit test is over everything is rolled back, and records are back in myTable. That's why I got a record count outside of my tests.
Sorry everyone...thanks for your help.
The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return
statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.
Therefore, you should do this:
remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
{
start = line.begin();
end = line.end();
bool temp = boost::regex_search(start, end, what, expression, flags);
return temp;
})
But really, your second expression is a lot more readable.
below will work with any previously pushed revision, not only HEAD
for abbreviated revision hash:
git log -1 --pretty=format:%h
for long revision hash:
git log -1 --pretty=format:%H
It appears that you are using the default route which is defined as this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The key part of that route is the {id}
piece. If you look at your action method, your parameter is k
instead of id
. You need to change your action method to this so that it matches the route parameter:
// change int k to int id
public ActionResult DetailsData(int id)
If you wanted to leave your parameter as k, then you would change the URL to be:
http://localhost:7317/Employee/DetailsData?k=4
You also appear to have a problem with your connection string. In your web.config, you need to change your connection string to this (provided by haim770 in another answer that he deleted):
<connectionStrings>
<add name="EmployeeContext"
connectionString="Server=.;Database=mytry;integrated security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
wget generally works in this way, but some sites may have problems and it may create too many unnecessary html files. In order to make this work easier and to prevent unnecessary file creation, I am sharing my getwebfolder script, which is the first linux script I wrote for myself. This script downloads all content of a web folder entered as parameter.
When you try to download an open web folder by wget which contains more then one file, wget downloads a file named index.html. This file contains a file list of the web folder. My script converts file names written in index.html file to web addresses and downloads them clearly with wget.
Tested at Ubuntu 18.04 and Kali Linux, It may work at other distros as well.
Usage :
extract getwebfolder file from zip file provided below
chmod +x getwebfolder
(only for first time)
./getwebfolder webfolder_URL
such as ./getwebfolder http://example.com/example_folder/
You can add a new series, and name it at the same time. The name will be the index of the new row, and all the values will automatically be NaN.
df.append(pd.Series(name='Afterthought'))
You can use the CellMouseEnter and CellMouseLeave to track the row number that the mouse is currently hovering over.
Then use a ContextMenu object to display you popup menu, customised for the current row.
Here's a quick and dirty example of what I mean...
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu m = new ContextMenu();
m.MenuItems.Add(new MenuItem("Cut"));
m.MenuItems.Add(new MenuItem("Copy"));
m.MenuItems.Add(new MenuItem("Paste"));
int currentMouseOverRow = dataGridView1.HitTest(e.X,e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));
}
m.Show(dataGridView1, new Point(e.X, e.Y));
}
}
you can put div tags inside a td tag, but not directly inside a table or tr tag. examples:
this works:
<table>_x000D_
<tr>_x000D_
<td> _x000D_
<div>This will work.</div> _x000D_
</td>_x000D_
</tr>_x000D_
<table>
_x000D_
this does not work:
<table>_x000D_
<tr>_x000D_
<div> this does not work. </div> _x000D_
</tr>_x000D_
</table>
_x000D_
nor does this work:
<table>_x000D_
<div> this does not work. </div>_x000D_
</table>
_x000D_
My first guess is that LaTeX chokes on | outside a math environment. Missing $ inserted is usually a symptom of something like that.
You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):
$string = "1654"
$integer = [int]$string
$string + 1
# Outputs 16541
$integer + 1
# Outputs 1655
As an example, the following snippet adds, to each object in $fileList
, an IntVal
property with the integer value of the Name
property, then sorts $fileList
on this new property (the default is ascending), takes the last (highest IntVal
) object's IntVal
value, increments it and finally creates a folder named after it:
# For testing purposes
#$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })
# OR
#$fileList = New-Object -TypeName System.Collections.ArrayList
#$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null
$highest = $fileList |
Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } |
Sort-Object IntVal |
Select-Object -Last 1
$newName = $highest.IntVal + 1
New-Item $newName -ItemType Directory
Sort-Object IntVal
is not needed so you can remove it if you prefer.
[int]::MaxValue = 2147483647
so you need to use the [long]
type beyond this value ([long]::MaxValue = 9223372036854775807
).
Given the context loader.getResourceAsStream("myPackage/myProp.properties")
should be used.
Leading '/'
doesn't work with ClassLoader.getResourceAsStream(String)
method.
Alternatively you could use Class.getResourceAsStream(String)
method, which uses '/'
to determine if the path is absolute or relative to the class location.
Examples:
myClass.class.getResourceAsStream("myProp.properties")
myClass.class.getResourceAsStream("/myPackage/myProp.properties")
If you're looking for a pure css option, try using the :focus pseudo class.
#style {
background-color: red;
}
#style:focus {
background-color:yellow;
}
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
Why not just use key name on dictionary, C# has this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("UserID", "test");
string userIDFromDictionaryByKey = dict["UserID"];
If you look at the tip suggestion:
You can also use ng-template, I think that would be more efficient while run time :)
<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
<div>2</div>
</ng-template>
Cheers
After combining the information in this thread with the R-help ?rect, I came up with this nice graph for circadian rhythm data (24h plot). The script for the background rectangles is this:
>rect(xleft, ybottom, xright, ytop, col = NA, border = NULL)
>i <- 24*(0:8)
>rect(8+i, 1, 24+i, 130, col = "lightgrey", border=NA)
>rect(8+i, -10, 24+i, 0.1, col = "black", border=NA)
The idea is to represent days of 24 hours with 8 h light and 16 h dark.
Cheers,
Romário
While it is true that you cannot change the type of the column after the DataTable
is filled, you can change it after you call FillSchema
, but before you call Fill
. For example, say the 3rd column is the one you want to convert from double
to Int32
, you could use:
adapter.FillSchema(table, SchemaType.Source);
table.Columns[2].DataType = typeof (Int32);
adapter.Fill(table);
This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.
For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.
I have left the read method unimplemented to keep the example small in size.
The realloc
function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.
For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.
Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.
var Buffer_A1 = function (chunk_size) {
this.buffer_list = [];
this.total_size = 0;
this.cur_size = 0;
this.cur_buffer = [];
this.chunk_size = chunk_size || 4096;
this.buffer_list.push(new Buffer(this.chunk_size));
};
Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;
var lastbuf = this.buffer_list.length - 1;
for (var x = 0; x < can_write; ++x) {
this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
}
this.cur_size += can_write;
this.total_size += can_write;
if (this.cur_size == this.chunk_size) {
this.buffer_list.push(new Buffer(this.chunk_size));
this.cur_size = 0;
}
return can_write;
};
/*
The `data` parameter can be anything that is array like. It just must
support indexing and a length and produce an acceptable value to be
used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
offset = offset == undefined ? 0 : offset;
length = length == undefined ? data.length : length;
var rem = length;
while (rem > 0) {
rem -= this.writeByteArrayLimited(data, length - rem, rem);
}
};
Buffer_A1.prototype.readByteArray = function (data, offset, length) {
/*
If you really wanted to implement some read functionality
then you would have to deal with unaligned reads which could
span two buffers.
*/
};
Buffer_A1.prototype.getSingleBuffer = function () {
var obuf = new Buffer(this.total_size);
var cur_off = 0;
var x;
for (x = 0; x < this.buffer_list.length - 1; ++x) {
this.buffer_list[x].copy(obuf, cur_off);
cur_off += this.buffer_list[x].length;
}
this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);
return obuf;
};
As it wasn't mentioned in any answers, just in case you want to align and space your text, you can use the string format features. (above python 2.5) Of course \t
is actually a TAB token whereas the described method generates spaces.
Example:
print "{0:30} {1}".format("hi", "yes")
> hi yes
Another Example, left aligned:
print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0 2.2 4.4
Another thing to check is a combination of previous entries
You can have in your web.xml file this:
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.acme.rest</param-value>
</init-param>
and you can have
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.providers</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.resources</param-name>
<param-value>false</param-value>
</context-param>
but you cannot have both or you get this sort of error. The fix in this case would be to comment out one or the other (probably the first code snippet would be commented out)
You can simply simply achieve it with any python module that gives you an interaction with command line(cmd
) like subprocess
, os
, etc.
but here I came up with examples on only two modules.
Here is syntax (command) cmd /c start browser_name "URL"
import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')
# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')
You can also run the command in the cmd it will work to or use other module call
click
which mainly used for writing command line utilities.
import click
click.launch('http://your_url')
if Ubound(yourArray)>-1 then
debug.print "The array is not empty"
else
debug.print "EMPTY"
end if
To manage non-integer inputs:
number = raw_input()
try:
value = int(number)
except ValueError:
value = 0
How about that?
<?php
while($items = array_pop($lists)){
echo "<ul>";
foreach($items as $item){
echo "<li>$item</li>";
}
echo "</ul>";
}
?>
Programatically:
edittext.requestFocus();
Through xml:
<EditText...>
<requestFocus />
</EditText>
Or call onClick method manually.
You can designate a button as the "AcceptButton" in the Form's properties and that will catch any "Enter" keypresses on the form and route them to that control.
See How to: Designate a Windows Forms Button as the Accept Button Using the Designer and note the few exceptions it outlines (multi-line text-boxes, etc.)
Ok, so this is what I have done:
$(document).on('change','#birthday',function(){
if($('#birthday').val()!==''){
$('#birthday').addClass('hasValue');
}else{
$('#birthday').removeClass('hasValue');
}
})
This is to remove the placeholder when a value is given.
input[type="date"]:before {
content: attr(placeholder) !important;
color: #5C5C5C;
margin-right: 0.5em;
}
input[type="date"]:focus:before,
input[type="date"].hasValue:before {
content: "" !important;
margin-right: 0;
}
On focus or if .hasValue, remove the placeholder and its margin.
after some test: If you send an email to an outlook client, and the subject is >77 chars, and it needs to use "=?ISO"
inside the subject (in my case because of accents) then OutLook will "cut" the subject in the middle of it and mesh it all that comes after, including body text, attaches, etc... all a mesh!
I have several examples like this one:
Subject: =?ISO-8859-1?Q?Actas de la obra N=BA.20100154 (Expediente N=BA.20100182) "NUEVA RED FERROVIARIA.=
TRAMO=20BEASAIN=20OESTE(Pedido=20PC10/00123-125),=20BEASAIN".?=
To:
As you see, in the subject line it cutted on char 78 with a "=" followed by 2 or 3 line feeds, then continued with the rest of the subject baddly.
It was reported to me from several customers who all where using OutLook, other email clients deal with those subjects ok.
If you have no ISO on it, it doesn't hurt, but if you add it to your subject to be nice to RFC, then you get this surprise from OutLook. Bit if you don't add the ISOs, then iPhone email will not understand it(and attach files with names using such characters will not work on iPhones).
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
In my case on Ubuntu 16.04 server, and default tomcat installation it's under:
/var/lib/tomcat8
DisplayFor
is also useful for templating. You could write a template for your Model, and do something like this:
@Html.DisplayFor(m => m)
Similar to @Html.EditorFor(m => m)
. It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.
Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:
http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/
It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress
data annotation, DisplayFor
will render it as a mailto:
link.
on my Ubuntu 12.04 32 bit. I edit the command to:
ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86/
And on Ubuntu 12.04 64 bit try:
ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86_64/
Starting with ElasticSearch 7.4, the best method to rename an index is to copy the index using the newly introduced Clone Index API, then to delete the original index using the Delete Index API.
The main advantage of the Clone Index API over the use of the Snapshot API or the Reindex API for the same purpose is speed, since the Clone Index API hardlinks segments from the source index to the target index, without reprocessing any of its content (on filesystems that support hardlinks, obviously; otherwise, files are copied at the file system level, which is still much more efficient that the alternatives). Clone Index also guarantee that the target index is identical in every point to the source index (that is, there is no need to manually copy settings and mappings, contrary to the Reindex approach), and doesn't require a local snapshot directory be configured.
Side note: even though this procedure is much faster than previous solutions, it still implies down time. There are real use cases that justify renaming indices (for example, as a step in a split, shrink or backup workflow), but renaming indices should not be part of day-to-day operations. If your workflow requires frequent index renaming, then you should consider using Indices Aliases instead.
Here is an example of a complete sequence of operations to rename index source_index
to target_index
. It can be executed using some ElasticSearch specific console, such as the one integrated in Kibana. See this gist for an alternative version of this example, using curl
instead of an Elastic Search console.
# Make sure the source index is actually open
POST /source_index/_open
# Put the source index in read-only mode
PUT /source_index/_settings
{
"settings": {
"index.blocks.write": "true"
}
}
# Clone the source index to the target name, and set the target to read-write mode
POST /source_index/_clone/target_index
{
"settings": {
"index.blocks.write": null
}
}
# Wait until the target index is green;
# it should usually be fast (assuming your filesystem supports hard links).
GET /_cluster/health/target_index?wait_for_status=green&timeout=30s
# If it appears to be taking too much time for the cluster to get back to green,
# the following requests might help you identify eventual outstanding issues (if any)
GET /_cat/indices/target_index
GET /_cat/recovery/target_index
GET /_cluster/allocation/explain
# Delete the source index
DELETE /source_index
Probably the file is not in the path specified. '../../../' will move 3 step up to the directory in which the page is located and look for the js file in a folder named JS.
Also the language attribute is Deprecated.
See Scripts:
18.2.1 The SCRIPT element
Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.
Edit
Try changing
<script src="../../../JS/Registration.js" language="javascript" type="text/javascript" />
to
<script src="../../../JS/Registration.js" language="javascript" type="text/javascript"></script>
Just to add to others, a note specific to forking.
It's good to realize that technically, cloning the repo and forking the repo are the same thing. Do:
git clone $some_other_repo
and you can tap yourself on the back---you have just forked some other repo.
Git, as a VCS, is in fact all about cloning forking. Apart from "just browsing" using remote UI such as cgit, there is very little to do with git repo that does not involve forking cloning the repo at some point.
However,
when someone says I forked repo X, they mean that they have created a clone of the repo somewhere else with intention to expose it to others, for example to show some experiments, or to apply different access control mechanism (eg. to allow people without Github access but with company internal account to collaborate).
Facts that: the repo is most probably created with other command than
git clone
, that it's most probably hosted somewhere on a server as
opposed to somebody's laptop, and most probably has slightly different
format (it's a "bare repo", ie. without working tree) are all just
technical details.
The fact that it will most probably contain different set of branches, tags or commits is most probably the reason why they did it in the first place.
(What Github does when you click "fork", is just cloning with added sugar: it clones the repo for you, puts it under your account, records the "forked from" somewhere, adds remote named "upstream", and most importantly, plays the nice animation.)
When someone says I cloned repo X, they mean that they have created a clone of the repo locally on their laptop or desktop with intention study it, play with it, contribute to it, or build something from source code in it.
The beauty of Git is that it makes this all perfectly fit together: all these repos share the common part of block commit chain so it's possible to safely (see note below) merge changes back and forth between all these repos as you see fit.
Note: "safely" as long as you don't rewrite the common part of the chain, and as long as the changes are not conflicting.
My simple solution. IMHO it's the cleanest.
First create a application.yml
spring.main.allow-bean-definition-overriding: true
security:
oauth2:
client:
clientId: XXX
clientSecret: XXX
accessTokenUri: XXX
tokenName: access_token
grant-type: client_credentials
Create the main class: Main
@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll();
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
return new OAuth2RestTemplate(details);
}
}
Then Create the controller class: Controller
@RestController
class OfferController {
@Autowired
private OAuth2RestOperations restOperations;
@RequestMapping(value = "/<your url>"
, method = RequestMethod.GET
, produces = "application/json")
public String foo() {
ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
return responseEntity.getBody();
}
}
Maven dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
</dependencies>
If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):
var UserInRole = db.UserProfiles.
Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
(u, uir) => new { u, uir }).
Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
.Where(m => m.r.u.UserId == 1)
.Select (m => new AddUserToRole
{
UserName = m.r.u.UserName,
RoleName = m.ro.RoleName
});
Hope that helps.
nameofList.getChildAt(position).setBackgroundColor(RED);
worked for me
From websites, using Firefox, I use the CopyPlainText extension.
try this one :
$('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})
using jQuery input mask plugin (6 whole and 2 decimal places):
HTML:
<input class="mask" type="text" />
jQuery:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});
I hope this helps someone
If you only have to view it, I've used this:
print cast(dbo.f_functiondeliveringbigformattedtext(seed) as text)
The end result is that I get line feeds and all the content in the messages window of SMSS. Of course, it only allows for a single cell - if you want to do a single cell from a number of rows, you could do this:
declare @T varchar(max)=''
select @T=@T
+ isnull(dbo.f_functiondeliveringbigformattedtext(x.a),'NOTHINGFOUND!')
+ replicate(char(13),4)
from x -- table containing multiple rows and a value in column a
print @T
I use this to validate JSON strings generated by SQL code. Too hard to read otherwise!
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
If you add the 'radio inline' class to the control label in the solution provided by user1938475 it should line up correctly with the other labels. Or if you're only using 'radio' like your 2nd example just include the 'radio' class.
<label class="radio control-label">Some label</label>
OR for 'radio inline'
<label class="radio-inline control-label">Some label</label>
In case this happens to anyone else who tried both alphazero and Paul's method and still didn't work.
For me, eclipse somehow 'cached' the compile errors even after doing a Project > Clean...
I had to uncheck Project > Build Automatically, then do a Project > Clean, and then build again.
Also, when in doubt, try restarting Eclipse. This can fix a lot of awkward, unexplainable errors.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
SELECT DATE_FORMAT(COLUMN_NAME, "%d/%m/%Y %h:%i %p");
OR
SELECT DATE_FORMAT("2019-05-10 19:30:10", "%d/%m/%Y %h:%i %p");
OUTPUT is 10/05/2019 07:30 PM
Try moving the order by
after group by
:
var groupByReference = (from m in context.Measurements
group m by new { m.Reference } into g
order by g.Avg(i => i.CreationTime)
select g).Take(numOfEntries).ToList();
Finally in .NET 4.5, the CLR allows one to hint/suggest1 method inlining using MethodImplOptions.AggressiveInlining
value. It is also available in the Mono's trunk (committed today).
// The full attribute usage is in mscorlib.dll,
// so should not need to include extra references
using System.Runtime.CompilerServices;
...
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void MyMethod(...)
1. Previously "force" was used here. Since there were a few downvotes, I'll try to clarify the term. As in the comments and the documentation, The method should be inlined if possible.
Especially considering Mono (which is open), there are some mono-specific technical limitations considering inlining or more general one (like virtual functions). Overall, yes, this is a hint to compiler, but I guess that is what was asked for.
Try this:
{
"ACCOUNT_EXIST": true,
"MultipleContacts": false
}
boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()
According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/
There is a search order for assemblies when building. The search order is as follows:
So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.
The easiest way is:
s = '"sajdkasjdsaasdasdasds"'
import json
s = json.loads(s)
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.
Use Date convert to compare with date: Try This:
select * from table
where TO_DATE(to_char(timespanColumn,'YYYY-MM-DD'),'YYYY-MM-DD') = to_timestamp('2018-03-26', 'YYYY-MM-DD')
- Each time you append or do any modification with it, it creates a new String
object.
- So use append()
method of StringBuilder
(If thread safety is not important), else use StringBuffer
(If thread safety is important.), that will be efficient way to do it.
If you only need to look at the existing disks, this one will suffice:
powershell "get-physicaldisk"
You can first find the position of the string in this case ":"
'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")
Then use Left(StringToCut, NumberOfCharacterToCut)
Result = Left(StringToSearch, position -1)
Unfortunately the Windows Mobile Device Center stopped working out of the box after the Creators Update for Windows 10. The application won't open and therefore it's impossible to get the sync working. In order to get it running now we need to modify the ActiveSync registry settings. Create a BAT file with the following contents and run it as administrator:
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\RapiMgr /v SvcHostSplitDisable /t REG_DWORD /d 1 /f
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\WcesComm /v SvcHostSplitDisable /t REG_DWORD /d 1 /f
Restart the computer and everything should work.
In your web.php
(routes):
add:
Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout');
In your LoginController.php
add:
public function logout(Request $request) {
Auth::logout();
return redirect('/login');
}
Also, in the top of LoginController.php
, after namespace
add:
use Auth;
Now, you are able to logout using yourdomain.com/logout
URL or if you have created logout button
, add href to /logout
Take this as a sample code. Replace imageheight and image width with your image dimensions.
<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>
You can use findHandlersJS
You can find the handler by doing in the chrome console:
findEventHandlers("click", "img.envio")
You'll get the following information printed in chrome's console:
More info here and you can try it in this example site here.
If you just need to search for one string within another, use the index
function (or rindex
if you want to start scanning from the end of the string):
if (index($string, $substring) != -1) {
print "'$string' contains '$substring'\n";
}
To search a string for a pattern match, use the match operator m//
:
if ($string =~ m/pattern/) {
print "'$string' matches the pattern\n";
}
I'm not familiar with grep but with Select-String you can do:
Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>
You can also do that with Get-Content:
(Get-Content filename.txt) -match 'pattern'
Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80>
and </VirtualHost>
After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane
<VirtualHost *:80>
##ServerAdmin [email protected]
DocumentRoot "C:/xampp/htdocs/www"
ServerName example.com
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
Be sure to create the www folder under htdocs
. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html
or index.php
file and place in the www
folder, then go to your browser and test it out localhost/
... Note: if your server is serving php files over html then remember to add localhost/index.html
if the html file is the one you choose to use for this test.
Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add
<VirtualHost *:80>
##ServerAdmin [email protected]
DocumentRoot "C:/xampp/htdocs"
ServerName htdocs.example.com
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.
The following code send and recieve the current date and time from and to the server
//The following code is for the server application:
namespace Server
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}
//this is the code for the client
namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}
You might be needed to restart
the process if app.get
not
working. Press ctl+c
and then restart node app
.
I had the same problem. with 64bit os all should be 64bit. Java and Eclipse. I tried all the methods in stackoverflow and also in youtube. non of them worked for me untill i found this easy method.
I installed 64bit java form Cnet download and the problem was automatically fixed. I mentioned the source because it is too easy to google and go to first Cnet lint rather than oficial site if you are a new bee.
p.s. if you have Android ADT bundle and tried to open eclipse from it and got the same error, you can fix that problem too with this method.
chmod +w <directory>
or chmod a+w <directory>
- Write permission for user, group and others
chmod u+w <directory>
- Write permission for user
chmod g+w <directory>
- Write permission for group
chmod o+w <directory>
- Write permission for others
First day of week (Monday):
SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)-1 first_day_week FROM dual;
Last day of week (Sunday):
SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)+5 last_day_week FROM dual;
Substituting your date or date field in these formulas will work for you!
You're trying to redirect to a named route whose name is login
, but you have no routes with that name:
Route::post('login', [ 'as' => 'login', 'uses' => 'LoginController@do']);
The 'as'
portion of the second parameter defines the name of the route. The first string parameter defines its route.
Python3:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')
handle.mainFunction(parameter)
This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).
There's also the more normal way of importing a python module in Python3,
import importlib
module = importlib.load_module('folder.filename')
module.function()
Kudos to Sebastian for spplying a similar answer for Python2:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
In my case, just add @ResponseBody
annotation to solve this issue.
In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.
I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:
DBCC TRACEON(1222, -1);
A quick search yielded this tutorial:
http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/
Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.
Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:
Disclaimer: I work for SQL Sentry.
The problem occurs when your custom class has for property some other class e.g. "Bitmap". What I made is to change the property field from "private Bitmap photo" to "private transient Bitmap photo". However the image is empty after I getIntent() in the receiver activity. Because of this I passed the custom class to the intent and also I've created a byte array from the image and pass it separatly to the intent:
selectedItem is my custom object and getPlacePhoto is his method to get image. I've already set it before and now I just get it first than convert it and pass it separatly:
Bitmap image = selectedItem.getPlacePhoto();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(YourPresentActivity.this,
TheReceiverActivity.class);
intent.putExtra("selectedItem", selectedItem);
intent.putExtra("image", byteArray);
startActivity(intent);
`
Then in the receiver activity I get my object and the image as byte array, decode the image and set it to my object as photo property.
Intent intent = getIntent();
selectedItem = (ListItem) intent.getSerializableExtra("selectedItem");
byte[] byteArray = getIntent().getByteArrayExtra("image");
Bitmap image = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
selectedItem.setPhoto(image);
This solution can be applied only if the issue is on a WordPress installation!
If you don't have FTP access or too lazy to edit files,
You can use Increase Maximum Upload File Size plugin to increase the maximum upload file size.
if you're using a MacBook or UNIX based system, use this:
function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()
Add -m to the recommended answer above to prune empty directories.
While I agree that in general inline-block
is better, there's one extra thing to take into account if you're using percentage widths to create a responsive grid (or if you want pixel-perfect widths):
If you're using inline-block
for grids that total 100% or near to 100% width, you need to make sure your HTML markup contains no white space between columns.
With floats, this is not something you need to worry about - the columns float over any whitespace or other content between columns. This question's answers have some good tips on ways to remove HTML whitespace without making your code ugly.
If for any reason you can't control the HTML markup (e.g. a restrictive CMS), you can try the tricks described here, or you might need to compromise and use floats instead of inline-block. There are also ugly CSS tricks that should only be used in extreme circumstances, like font-size:0;
on the column container then reapply font size within each column.
For example:
float: left
. It "just works" (but for the wrapper needing to be cleared).inline-block
. The whitespace between blocks creates a fixed-width space which pushes the total width beyond 100%, breaking the layout and causing the last column to drop down a line.inline-block
and no whitespace between columns in the HTML. It "just works" again - but the HTML is uglier and your CMS might force some kind of prettification or indenting to its HTML output making this difficult to achieve in reality.What you can do and what you should do are different matters.
If the list is very short, or you are only ever going to call find once then use the linear approach above.
However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.
First creates the function
$.UrlExists = function(url) {_x000D_
var http = new XMLHttpRequest();_x000D_
http.open('HEAD', url, false);_x000D_
http.send();_x000D_
return http.status!=404;_x000D_
}
_x000D_
After using the function as follows
if($.UrlExists("urlimg")){_x000D_
foto = "img1.jpg";_x000D_
}else{_x000D_
foto = "img2.jpg";_x000D_
}_x000D_
_x000D_
$('<img>').attr('src',foto);
_x000D_
If i am correct in believing that you are adding a variable to the array but when you change that variable outside of the array, it also changes inside the array but you don't want it to then it is a really simple solution.
When you are saving the variable to the array you should turn it into a string by simply putting str(variablename). For example:
array.append(str(variablename))
Using this method your code should look like this:
arrayList = []
for x in allValues:
result = model(x)
arrayList.append(str(wM)) #this is the only line that is changed.
wM.reset()
The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under
Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job
Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).
Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.
Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.
managementObjects.Cast<ManagementBaseObject>().ToList();
is a good choice.
You could improve performance by pre-initialising the list capacity:
public static class Helpers
{
public static List<T> CollectionToList<T>(this System.Collections.ICollection other)
{
var output = new List<T>(other.Count);
output.AddRange(other.Cast<T>());
return output;
}
}
You can this structure in Layout.cshtml file
<link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />
Integer division $x divided by $y ...
$z = -1 & $x / $y
How does it work?
$x / $y
return the floating point division
&
perform a bit-wise AND
-1
stands for
&HFFFFFFFF
for the largest integer ... whence
$z = -1 & $x / $y
gives the integer division ...
Assume, you have installed the latest gradle once. But, If your particular project gradle version not match with the gradle version that already installed in the machine, the gradle sycn want to download that version. To prevent this download there is one trick. First You have to know the gradle version that already installed in your machine. Go to : C:\Users{username}.gradle\wrapper\dists, here you see the versions allready installed, remember the latest version, assume it is gradle-6.1.1-all.zip . Now, come back to Android Studio. In your Opened project, navigate Android Studio's project tree, open the file gradle/wrapper/gradle-wrapper.properties. Change this entry:
distributionUrl=http\://services.gradle.org/distributions/gradle-6.1.1-all.zip
This way we prevent downloading the gradle again and again. But avoid this thing, if the version really old. If that, you will find this warning :
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.1.1/userguide/command_line_interface.html#sec:command_line_warnings
Expanding on user187291's post, you could also use getters/setters to get around having to use functions.
var x = 1;
var ref = {
get x() { return x; },
set x(v) { x = v; }
};
(ref.x)++;
console.log(x); // prints '2'
x--;
console.log(ref.x); // prints '1'
I have used
But none beats google's own tools
We need to do the following changes/fixes in our earlier onActivityResult()'s gallery picker code to run seamlessly on Android 4.4 (KitKat) and on all other earlier versions as well.
Uri selectedImgFileUri = data.getData();
if (selectedImgFileUri == null ) {
// The user has not selected any photo
}
try {
InputStream input = mActivity.getContentResolver().openInputStream(selectedImgFileUri);
mSelectedPhotoBmp = BitmapFactory.decodeStream(input);
}
catch (Throwable tr) {
// Show message to try again
}
Yep.
// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart). Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//
using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Dino.Tools.WebMonitor
{
public class FakeChartForm1 : Form
{
private System.ComponentModel.IContainer components = null;
System.Windows.Forms.DataVisualization.Charting.Chart chart1;
public FakeChartForm1 ()
{
InitializeComponent();
}
private double f(int i)
{
var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
return f1;
}
private void Form1_Load(object sender, EventArgs e)
{
chart1.Series.Clear();
var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
{
Name = "Series1",
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Line
};
this.chart1.Series.Add(series1);
for (int i=0; i < 100; i++)
{
series1.Points.AddXY(i, f(i));
}
chart1.Invalidate();
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
this.SuspendLayout();
//
// chart1
//
chartArea1.Name = "ChartArea1";
this.chart1.ChartAreas.Add(chartArea1);
this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
legend1.Name = "Legend1";
this.chart1.Legends.Add(legend1);
this.chart1.Location = new System.Drawing.Point(0, 50);
this.chart1.Name = "chart1";
// this.chart1.Size = new System.Drawing.Size(284, 212);
this.chart1.TabIndex = 0;
this.chart1.Text = "chart1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.chart1);
this.Name = "Form1";
this.Text = "FakeChart";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
this.ResumeLayout(false);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FakeChartForm1());
}
}
}
UI:
Another approach is the above:
List<WhateEver> lst = getdata();
string json = Newtonsoft.Json.JsonConvert.SerializeObject(lst);
DataTable pDt = JsonConvert.DeserializeObject<DataTable>(json);
Here's an easier way:
sudo apt-get install maven
More details are here.
The first option gives you more flexibilty:
var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);
And of course .html('*')
overrides the content while .append('*')
doesn't, but I guess, this wasn't your question.
Another good practice is prefixing your jQuery variables with $
:
Is there any specific reason behind using $ with variable in jQuery
Placing quotes around the "class"
property name will make it more compatible with less flexible browsers.
You need to create the instance of the RuntimeException, using new
the same way you would to create an instance of most other classes:
throw new RuntimeException(msg);
try this Function:
function addtoselect(param,value){
$('#mySelectBox').append('<option value='+value+'>'+param+'</option>');
}
https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects
To create and save an object in a single step, use the
create()
method.
Try this in the android manifest file corresponding to the activity.
<activity android:windowSoftInputMode="adjustPan"> </activity>
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
SELECT DATEDIFF (
DAY,
DATEDIFF(DAY, @CreatedDate, -1),
GETDATE())
I assume you're using RollingFileAppender? In which case, it has a property called MaxBackupIndex
which you can set to limit the number of files. For example:
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=7
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
import inspect
def s(template, **kwargs):
"Usage: s(string, **locals())"
if not kwargs:
frame = inspect.currentframe()
try:
kwargs = frame.f_back.f_locals
finally:
del frame
if not kwargs:
kwargs = globals()
return template.format(**kwargs)
Usage:
a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found
PS: performance may be a problem. This is useful for local scripts, not for production logs.
Duplicated:
Use the standard CSS tab-size
.
To insert a tab symbol (if standard tab key, move cursor) press Alt + 0 + 0 + 9
.element {
-moz-tab-size: 4;
tab-size: 4;
}
My preferred:
*{-moz-tab-size: 1; tab-size: 1;}
Look at snippet or quick found example at tab-size.
.t1{_x000D_
-moz-tab-size: 1;_x000D_
tab-size: 1;_x000D_
}_x000D_
.t2{_x000D_
-moz-tab-size: 2;_x000D_
tab-size: 2;_x000D_
}_x000D_
.t4{_x000D_
-moz-tab-size: 4;_x000D_
tab-size: 4;_x000D_
}_x000D_
pre {border: 1px dotted;}
_x000D_
<h3>tab = {default} space</h3>_x000D_
<pre>_x000D_
one tab text_x000D_
two tab text_x000D_
</pre>_x000D_
_x000D_
<h3>tab = 1 space</h3>_x000D_
<pre class="t1">_x000D_
one tab text_x000D_
two tab text_x000D_
</pre>_x000D_
_x000D_
<h3>tab = 2 space</h3>_x000D_
<pre class="t2">_x000D_
one tab text_x000D_
two tab text_x000D_
</pre>_x000D_
_x000D_
<h3>tab = 4 space</h3>_x000D_
<pre class="t4">_x000D_
one tab text_x000D_
two tab text_x000D_
</pre>
_x000D_
Also had this problem occurring on the web application surface. Eventually found out that the same error message comes from the SQL update statement in the specific table.
Finally then figured out that the column definition in the relating history table(s) did not map the original table column length of nvarchar
types in some specific cases.
The answer comes from the first paragraph of the documentation check if the results is greater than -1, not if it's true or false.
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.
I think Compiling Python Code would be a good place to start:
Python source code is automatically compiled into Python byte code by the CPython interpreter. Compiled code is usually stored in PYC (or PYO) files, and is regenerated when the source is updated, or when otherwise necessary.
To distribute a program to people who already have Python installed, you can ship either the PY files or the PYC files. In recent versions, you can also create a ZIP archive containing PY or PYC files, and use a small “bootstrap script” to add that ZIP archive to the path.
To “compile” a Python program into an executable, use a bundling tool, such as Gordon McMillan’s installer (alternative download) (cross-platform), Thomas Heller’s py2exe (Windows), Anthony Tuininga’s cx_Freeze (cross-platform), or Bob Ippolito’s py2app (Mac). These tools puts your modules and data files in some kind of archive file, and creates an executable that automatically sets things up so that modules are imported from that archive. Some tools can embed the archive in the executable itself.
This exception will come in case your server is based on JDK 7 and your client is on JDK 6 and using SSL certificates. In JDK 7 sslv2hello message handshaking is disabled by default while in JDK 6 sslv2hello message handshaking is enabled. For this reason when your client trying to connect server then a sslv2hello message will be sent towards server and due to sslv2hello message disable you will get this exception. To solve this either you have to move your client to JDK 7 or you have to use 6u91 version of JDK. But to get this version of JDK you have to get the
As an alternative, if you put a space between the date and time, DateTime.Parse
will recognize the format for you. That's about as simple as you can get it. (If ParseExact
was still not being recognized)
You need to check one if you have two
if(rbMale.Checked)
{
}
else
{
}
You need to check all the checkboxes if more then two
if(rb1.Checked)
{
}
else if(rb2.Checked)
{
}
else if(rb3.Checked)
{
}
Extend Date class with this function
// Add (or substract if value is negative) the value, expresed in timeUnit
// to the date and return the new date.
Date.dateAdd = function(currentDate, value, timeUnit) {
timeUnit = timeUnit.toLowerCase();
var multiplyBy = { w:604800000,
d:86400000,
h:3600000,
m:60000,
s:1000 };
var updatedDate = new Date(currentDate.getTime() + multiplyBy[timeUnit] * value);
return updatedDate;
};
So you can add or substract a number of minutes, seconds, hours, days... to any date.
add_10_minutes_to_current_date = Date.dateAdd( Date(), 10, "m");
subs_1_hour_to_a_date = Date.dateAdd( date_value, -1, "h");
You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.
See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.
if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:
set.seed(10)
x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]
cor(x)
Error in cor(x) : 'x' must be numeric
but
cor(x[sapply(x, is.numeric)])
V1 V2 V3 V4 V5 V6 V7
V1 1.00000000 0.3025766 -0.22473884 -0.72468776 0.18890578 0.14466161 0.05325308
V2 0.30257657 1.0000000 -0.27871430 -0.29075170 0.16095258 0.10538468 -0.15008158
V3 -0.22473884 -0.2787143 1.00000000 -0.22644156 0.07276013 -0.35725182 -0.05859479
V4 -0.72468776 -0.2907517 -0.22644156 1.00000000 -0.19305921 0.16948333 -0.01025698
V5 0.18890578 0.1609526 0.07276013 -0.19305921 1.00000000 0.07339531 -0.31837954
V6 0.14466161 0.1053847 -0.35725182 0.16948333 0.07339531 1.00000000 0.02514081
V7 0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954 0.02514081 1.00000000
V8 0.44705527 0.1698571 0.39970105 -0.42461411 0.63951574 0.23065830 -0.28967977
V9 0.21006372 -0.4418132 -0.18623823 -0.25272860 0.15921890 0.36182579 -0.18437981
V10 0.02326108 0.4618036 -0.25205899 -0.05117037 0.02408278 0.47630138 -0.38592733
V8 V9 V10
V1 0.447055266 0.210063724 0.02326108
V2 0.169857120 -0.441813231 0.46180357
V3 0.399701054 -0.186238233 -0.25205899
V4 -0.424614107 -0.252728595 -0.05117037
V5 0.639515737 0.159218895 0.02408278
V6 0.230658298 0.361825786 0.47630138
V7 -0.289679766 -0.184379813 -0.38592733
V8 1.000000000 0.001023392 0.11436143
V9 0.001023392 1.000000000 0.15301699
V10 0.114361431 0.153016985 1.00000000
Can't comment yet, but I just wanted to disagree/clarify with erikkallen.
You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.
In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().
I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.
I had the same problem, but non of the asweres worked for me. I am using bootstap and the following css code helped me:
label {
display: contents!important;
}
Here it is. Pure CSS. You do need one extra 'container' element.
The fiddle
(tinkerbin, actually): http://tinkerbin.com/rQ71nWDT
(Tinkerbin is dead.)
The solution.
Note I'm using an 100% throughout the example. You can use whichever percentage you'd like.
Since height percentages are relative to the height of the parent element, we can't rely on it. We must rely on something else. Luckily padding is relative to the width - whether it's horizontal or vertical padding. In padding-xyz: 100%
, 100% equals 100% of the box's width.
Unfortunately, padding is just that, padding. The content-box's height is 0. No problem!
Stick an absolutely positioned element, give it 100% width, 100% height and use it as your actual content box. The 100% height works because percentage heights on absolutely positioned elements are relative to the padding-box of the box their relatively positioned to.
HTML:
<div id="map_container">
<div id="map">
</div>
</div>
CSS:
#map_container {
position: relative;
width: 100%;
padding-bottom: 100%;
}
#map {
position: absolute;
width: 100%;
height: 100%;
}
In Eclipse, go to Window → Preferences → General → Network Connections. In the Active Provider combo box, choose "Manual". In the proxy entries table, for each entry click "Edit..." and supply your proxy host, port, username and password details.
These are identical for printf
but different for scanf
. For printf
, both %d
and %i
designate a signed decimal integer. For scanf
, %d
and %i
also means a signed integer but %i
inteprets the input as a hexadecimal number if preceded by 0x
and octal if preceded by 0
and otherwise interprets the input as decimal.
You just rebuilt your project
compile fileTree(dir: 'libs', include: ['*.jar'])
Thanks for your feed back got it to work I used the sshpass tool.
sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/
If you want to check if your -vm eclipse.ini
option worked correctly you can use this to see under what JVM the IDE itself runs: menu Help > About Eclipse > Installation Details > Configuration tab. Locate the line that says: java.runtime.version=...
.
All the above answers are valid, however, there are some cases that the String Literal Type is part of another complex type. Consider the following example:
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small',
};
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
// Here you will get the following error:
// Type 'string' is not assignable to type '"small" | "large"'.ts(2322)
['large', 'small'].forEach(size => (
useToolbarTheme({ size })
));
You have multiple solutions to fix this. Each solution is valid and has its own use cases.
1) The first solution is to define a type for the size and export it from the foo.ts. This is good if when you need to work with the size parameter by its own. For example, you have a function that accepts or returns a parameter of type size and you want to type it.
// in foo.ts
export type ToolbarThemeSize = 'large' | 'small';
export type ToolbarTheme = {
size: ToolbarThemeSize
};
// in bar.ts
import { ToolbarTheme, ToolbarThemeSize } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
function getToolbarSize(): ToolbarThemeSize {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size: size as ToolbarThemeSize })
));
2) The second option is to just cast it to the type ToolbarTheme. In this case, you don't need to expose the internal of ToolbarTheme if you don't need.
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small'
};
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size } as ToolbarTheme)
));
>>> for line in s.splitlines():
... line = line.strip()
... if not line:continue
... ary.append(line.split(":"))
...
>>> ary
[['Name', ' John Smith'], ['Home', ' Anytown USA'], ['Misc', ' Data with spaces'
]]
>>> dict(ary)
{'Home': ' Anytown USA', 'Misc': ' Data with spaces', 'Name': ' John Smith'}
>>>
I used the following approach for determining the frame of the keyboard in iOS 7.1.
In the init method of my view controller, I registered for the UIKeyboardDidShowNotification
:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardOnScreen:) name:UIKeyboardDidShowNotification object:nil];
Then, I used the following code in keyboardOnScreen:
to gain access to the frame of the keyboard. This code gets the userInfo
dictionary from the notification and then accesses the NSValue
associated with UIKeyboardFrameEndUserInfoKey
. You can then access the CGRect and convert it to the coordinates of the view of your view controller. From there, you can perform any calculations you need based on that frame.
-(void)keyboardOnScreen:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
NSValue *value = info[UIKeyboardFrameEndUserInfoKey];
CGRect rawFrame = [value CGRectValue];
CGRect keyboardFrame = [self.view convertRect:rawFrame fromView:nil];
NSLog(@"keyboardFrame: %@", NSStringFromCGRect(keyboardFrame));
}
Swift
And the equivalent implementation with Swift:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
@objc
func keyboardDidShow(notification: Notification) {
guard let info = notification.userInfo else { return }
guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardFrame = frameInfo.cgRectValue
print("keyboardFrame: \(keyboardFrame)")
}
panel.setStyle("-fx-background-color: #FFFFFF;");
I found this article which showing you how to delete data from multiple tables by using MySQL DELETE JOIN statement with good explanation.
setRetaininstance
is only useful when your activity
is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance
. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.
Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment
holding my bitmaps and add it to the manager and call setRetainInstance
,all the Bitmaps are still there even if the screen orientation changes.
This will occur in SQL Server as well if you don't run all of the statements at once. If you are highlighting a set of statements and executing the following:
DECLARE @LoopVar INT
SET @LoopVar = (SELECT COUNT(*) FROM SomeTable)
And then try to highlight another set of statements such as:
PRINT 'LoopVar is: ' + CONVERT(NVARCHAR(255), @LoopVar)
You will receive this error.
A stream is an object used to transfer data. There is a generic stream class System.IO.Stream
, from which all other stream classes in .NET are derived. The Stream
class deals with bytes.
The concrete stream classes are used to deal with other types of data than bytes. For example:
FileStream
class is used when the outside source is a fileMemoryStream
is used to store data in memorySystem.Net.Sockets.NetworkStream
handles network dataReader/writer streams such as StreamReader
and StreamWriter
are not streams - they are not derived from System.IO.Stream
, they are designed to help to write and read data from and to stream!
Assuming you are using Windows OS.
All you need to add the pip.exe
path to the Environment Variables (Path).
Generally, you can find it under ..Python\Scripts folder.
For me it is, C:\Program Files\Python36\Scripts\
Imagine, bind is not available. you can easily construct it as follow :
var someFunction=...
var objToBind=....
var bindHelper = function (someFunction, objToBind) {
return function() {
someFunction.apply( objToBind, arguments );
};
}
bindHelper(arguments);
There are three distinct ways to do this:
Negate the exit status with bash (no other answer has said this):
if ! [ -e "$file" ]; then
echo "file does not exist"
fi
Or:
! [ -e "$file" ] && echo "file does not exist"
Negate the test inside the test command [
(that is the way most answers before have presented):
if [ ! -e "$file" ]; then
echo "file does not exist"
fi
Or:
[ ! -e "$file" ] && echo "file does not exist"
Act on the result of the test being negative (||
instead of &&
):
Only:
[ -e "$file" ] || echo "file does not exist"
This looks silly (IMO), don't use it unless your code has to be portable to the Bourne shell (like the /bin/sh
of Solaris 10 or earlier) that lacked the pipeline negation operator (!
):
if [ -e "$file" ]; then
:
else
echo "file does not exist"
fi
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional use of fully qualified names is not an undue burden (unless the library really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language change.
So I guess we will not see this feature in Java anytime soon :-P
Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:
document.forms['yourform']['yourtextarea'].value = 'yourvalue';
where in the HTML your textarea is nested somewhere in a form like this:
<form name="yourform">
<textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>
And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
escape()
and unescape()
are intended to encode / decode strings for URLs, not HTML.
Actually, I use the following snippet to do the trick that doesn't require any framework:
var escapedHtml = html.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/"/g, '"')
.replace(/'/g, ''');
Abstraction is a very general term, and abstraction in software is not limited to object-oriented languages. A dictionary definition: "the act of considering something as a general quality or characteristic, apart from concrete realities, specific objects, or actual instances".
Assembly language can be thought of as an abstraction of machine code -- assembly expresses the essential details and structure of the machine code, but frees you from having to think about the opcodes used, the layout of the code in memory, making jumps go to the right address, etc.
Your operating system's API is an abstraction of the underlying machine. Your compiler provides a layer of abstraction which shields you from the details of assembly language. The TCP/IP stack built into your operating system abstracts away the details of transmitting bits over a network. If you go down all the way to the raw silicon, the people who designed your CPU did so using circuit diagrams written in terms of "diodes" and "transistors", which are abstractions of how electrons travel through semiconductor crystals.
In software, everything is an abstraction. We build programs which simulate or model some aspect of reality, but by necessity our models always abstract away some details of the "real thing". We build layer on layer on layer of abstractions, because it is the only way we get anything done. (Imagine you were trying to make, say, a sudoku solver, and you had to design it using only semiconductor crystals. "OK, I need a piece of N-type silicon here...")
In comparison, "encapsulation" is a very specific and limited term. Some of the other answers to this question have already given good definitions for it.
Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:
function blobToDataURL(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function(e) {callback(e.target.result);}
fileReader.readAsDataURL(blob);
}
In Visual Studio 2008 it is Ctrl + E + W.
I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent]
from decorator.
import {myDirective} from './myDirective';
No, you can't.
There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.
If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.
In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.
SQL> desc sys.com$
Name Null? Type
----------------------------------------- -------- ----------------------------
OBJ# NOT NULL NUMBER
COL# NUMBER
COMMENT$ VARCHAR2(4000)
SQL>
The column is optional and sys.col$
does not contain comment information.
I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.
There is a possibility not to use extra variables
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
There is the latest techniques to communicate fragment to activity without any interface follow the steps Step 1- Add the dependency in gradle
implementation 'androidx.fragment:fragment:1.3.0-rc01'
Just for the record, there is a new HTTP Response Header called Clear-Site-Data
. If your server reply includes a Clear-Site-Data: "cookies"
header, then the authentication credentials (not only cookies) should be removed. I tested it on Chrome 77 but this warning shows on the console:
Clear-Site-Data header on 'https://localhost:9443/clear': Cleared data types:
"cookies". Clearing channel IDs and HTTP authentication cache is currently not
supported, as it breaks active network connections.
And the auth credentials aren't removed, so this doesn't works (for now) to implement basic auth logouts, but maybe in the future will. Didn't test on other browsers.
References:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
https://www.w3.org/TR/clear-site-data/
https://github.com/w3c/webappsec-clear-site-data
https://caniuse.com/#feat=mdn-http_headers_clear-site-data_cookies
After you install the ftp server with sudo apt-get install vsftpd
you will have to configure it. To enable write access you have to edit the /etc/vsftpd.conf
file and uncomment the
#write_enable=YES
line, so it should read
write_enable=YES
Save the file and restart vsftpd
with sudo service vsftpd restart
.
For other configuration options consult this documentation or man vsftpd.conf
For a quick and lazy solution, (and not using VS at all) try these online converters:
XSD => XML => C# classes
Example XSD:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
Converts to XML:
<?xml version="1.0" encoding="utf-8"?>
<!-- Created with Liquid Technologies Online Tools 1.0 (https://www.liquid-technologies.com) -->
<shiporder xsi:noNamespaceSchemaLocation="schema.xsd" orderid="string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<orderperson>string</orderperson>
<shipto>
<name>string</name>
<address>string</address>
<city>string</city>
<country>string</country>
</shipto>
<item>
<title>string</title>
<note>string</note>
<quantity>3229484693</quantity>
<price>-6894.465094196054907</price>
</item>
<item>
<title>string</title>
<note>string</note>
<quantity>2181272155</quantity>
<price>-2645.585094196054907</price>
</item>
<item>
<title>string</title>
<note>string</note>
<quantity>2485046602</quantity>
<price>4023.034905803945093</price>
</item>
<item>
<title>string</title>
<note>string</note>
<quantity>1342091380</quantity>
<price>-810.825094196054907</price>
</item>
</shiporder>
Which converts to this class structure:
/*
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0
*/
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="shipto")]
public class Shipto {
[XmlElement(ElementName="name")]
public string Name { get; set; }
[XmlElement(ElementName="address")]
public string Address { get; set; }
[XmlElement(ElementName="city")]
public string City { get; set; }
[XmlElement(ElementName="country")]
public string Country { get; set; }
}
[XmlRoot(ElementName="item")]
public class Item {
[XmlElement(ElementName="title")]
public string Title { get; set; }
[XmlElement(ElementName="note")]
public string Note { get; set; }
[XmlElement(ElementName="quantity")]
public string Quantity { get; set; }
[XmlElement(ElementName="price")]
public string Price { get; set; }
}
[XmlRoot(ElementName="shiporder")]
public class Shiporder {
[XmlElement(ElementName="orderperson")]
public string Orderperson { get; set; }
[XmlElement(ElementName="shipto")]
public Shipto Shipto { get; set; }
[XmlElement(ElementName="item")]
public List<Item> Item { get; set; }
[XmlAttribute(AttributeName="noNamespaceSchemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
public string NoNamespaceSchemaLocation { get; set; }
[XmlAttribute(AttributeName="orderid")]
public string Orderid { get; set; }
[XmlAttribute(AttributeName="xsi", Namespace="http://www.w3.org/2000/xmlns/")]
public string Xsi { get; set; }
}
}
Attention! Take in account that this is just to Get-You-Started, the results obviously need refinements!
Just came across this and the short code for transparency is simply #00000000.
Run this code on the command line and enter the value of N:
N = gets; 1.step(N.to_i, 1) { |i| print "hello world\n" }
Updating nodejs
solved the issue:
npm cache clean -f
sudo npm install -g n
sudo n stable
node --version
node app.js
You have to run the second and third command as root/administrator.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
I think you can use date()
function to achive this
$date = '19:24:15 06/13/2013';
echo date('h:i:s a m/d/Y', strtotime($date));
This will output
07:24:15 pm 06/13/2013
h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)
Updated
This is with DateTime
$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;
I have had good success using Spring WS for the client end of a web service app - see http://static.springsource.org/spring-ws/sites/1.5/reference/html/client.html
My project uses a combination of:
XMLBeans (generated from a simple Maven job using the xmlbeans-maven-plugin)
Spring WS - using marshalSendAndReceive() reduces the code down to one line for sending and receiving
some Dozer - mapping the complex XMLBeans to simple beans for the client GUI
As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.
Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)
This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.
The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html
https://developer.android.com/reference/android/content/BroadcastReceiver.html
https://developer.android.com/guide/components/bound-services.html
In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:
https://developer.android.com/guide/components/aidl.html
Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip
This project will start an Activity which binds to a service; implementing the AIDL.
This project is also useful to re-factor for the purpose of IPC across different apps.
This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)
When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.
This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.
This project is developed in accordance to the above docs and is subsequently a clean solution.
There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.
Since Stack Overflow’s broken RSS just resurrected this question for me, here’s my almost-general solution: JAValueToString
This lets you write JA_DUMP(cgPoint)
and get cgPoint = {0, 0}
logged.
If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.
There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).
In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.
Hope it helps!
Here's an example if:
ifeq ($(strip $(OS)),Linux)
PYTHON = /usr/bin/python
FIND = /usr/bin/find
endif
Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.
2019's answer as this is still actively seen today
You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.
original hack from 2015 that still works in some situations
You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.
If you cannot pull it out of the div for some reason, you should change the position style with this css:
.full-width-div {
position: absolute;
width: 100%;
left: 0;
}
Instead of absolute, you could also use fixed, but then it will not move as you scroll.
OK, here's what we do: open the file, read it line by line, and split it by tabs. Then we grab the second integer and loop through the rest to find the path.
StreamReader reader = File.OpenText("filename.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] items = line.Split('\t');
int myInteger = int.Parse(items[1]); // Here's your integer.
// Now let's find the path.
string path = null;
foreach (string item in items)
{
if (item.StartsWith("item\\") && item.EndsWith(".ddj"))
path = item;
}
// At this point, `myInteger` and `path` contain the values we want
// for the current line. We can then store those values or print them,
// or anything else we like.
}
This can be done in 2 ways:
if (str.match(/abc|def/)) {
...
}
if (/abc|def/.test(str)) {
....
}
You can get the time & date seperately from Calendar.
// You can pass time zone and Local to getInstance() as parameter
Calendar calendar = Calendar.getInstance();
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int date = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
After reading Sime Vidas's answer, I searched more and found a very straight-forward and easy-to-understand explanation in the angular docs.
HTML attribute vs. DOM property
-------------------------------
Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).
A few HTML attributes have 1:1 mapping to properties.
id
is one example.Some HTML attributes don't have corresponding properties.
colspan
is one example.Some DOM properties don't have corresponding attributes.
textContent
is one example.Many HTML attributes appear to map to properties ... but not in the way you might think!
That last category is confusing until you grasp this general rule:
Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.
For example, when the browser renders
<input type="text" value="Bob">
, it creates a corresponding DOM node with avalue
property initialized to "Bob".When the user enters "Sally" into the input box, the DOM element
value
property becomes "Sally". But the HTMLvalue
attribute remains unchanged as you discover if you ask the input element about that attribute:input.getAttribute('value')
returns "Bob".The HTML attribute
value
specifies the initial value; the DOMvalue
property is the current value.
The
disabled
attribute is another peculiar example. A button'sdisabled
property isfalse
by default so the button is enabled. When you add thedisabled
attribute, its presence alone initializes the button'sdisabled
property totrue
so the button is disabled.Adding and removing the
disabled
attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing<button disabled="false">Still Disabled</button>.
Setting the button's
disabled
property disables or enables the button. The value of the property matters.The HTML attribute and the DOM property are not the same thing, even when they have the same name.
You can pivot your DataFrame after creating:
>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1 c1 c2
0
r1 avg11 avg12
r2 avg21 avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1 c1 c2
0
r1 stdev11 stdev12
r2 stdev21 stdev22
If you are working with MVC C#, this is the way to deal with printers and serial ports for dropdowns.
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;
public class Miclass
{
private void AllViews()
{
List<PortClass> ports = new List<PortClass>();
List<Printersclass> Printersfor = new List<Printersclass>();
string[] portnames = SerialPort.GetPortNames();
/*PORTS*/
for (int i = 0; i < portnames.Count(); i++)
{
ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
}
/*PRINTER*/
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
}
}
}
public class PortClass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
public class Printersclass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
If you want to create a garage and fill it up with new cars that can be accessed later, use this code:
for (int i = 0; i < garage.length; i++)
garage[i] = new Car("argument");
Also, the cars are later accessed using:
garage[0];
garage[1];
garage[2];
etc.
I couldn't get any of these methods to work, so I eventually did the following. For the element you want initially hidden:
<div <!--...--> style="display: none;" ng-style="style">
Then in your controller, add this at or near the top:
$scope.style = { display: 'block' };
This way, the element is initially hidden, and only shows when the controller code has actually run.
You can tune the placement to your needs, perhaps adding some logic. In my case, I switch to a login path if not currently logged in, and didn't want my interface flickering beforehand, so I set $scope.style
after the logged-in check.
ViewBag is of type dynamic. More, you cannot do ViewBag["Foo"]
. You will get exception - Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'.
Internal implementation of ViewBag
actually stores Foo into ViewData["Foo"]
(type of ViewDataDictionary), so those 2 are interchangeable. ViewData["Foo"]
and ViewBag.Foo
.
And scope. ViewBag and ViewData are ment to pass data between Controller's Actions and View it renders.
The best place to demystify this is the source code. The docs are woefully inadequate about explaining this.
dispatchTouchEvent is actually defined on Activity, View and ViewGroup. Think of it as a controller which decides how to route the touch events.
For example, the simplest case is that of View.dispatchTouchEvent which will route the touch event to either OnTouchListener.onTouch if it's defined or to the extension method onTouchEvent.
For ViewGroup.dispatchTouchEvent things are way more complicated. It needs to figure out which one of its child views should get the event (by calling child.dispatchTouchEvent). This is basically a hit testing algorithm where you figure out which child view's bounding rectangle contains the touch point coordinates.
But before it can dispatch the event to the appropriate child view, the parent can spy and/or intercept the event all together. This is what onInterceptTouchEvent is there for. So it calls this method first before doing the hit testing and if the event was hijacked (by returning true from onInterceptTouchEvent) it sends a ACTION_CANCEL to the child views so they can abandon their touch event processing (from previous touch events) and from then onwards all touch events at the parent level are dispatched to onTouchListener.onTouch (if defined) or onTouchEvent(). Also in that case, onInterceptTouchEvent is never called again.
Would you even want to override [Activity|ViewGroup|View].dispatchTouchEvent? Unless you are doing some custom routing you probably should not.
The main extension methods are ViewGroup.onInterceptTouchEvent if you want to spy and/or intercept touch event at the parent level and View.onTouchListener/View.onTouchEvent for main event handling.
All in all its overly complicated design imo but android apis lean more towards flexibility than simplicity.
Here are some benchmarks comparing different approaches and libraries. Guava beats Apache Commons Codec at decoding. Commons Codec beats Guava at encoding. And JHex beats them both for decoding and encoding.
String hexString = "596f752772652077656c636f6d652e";
byte[] decoded = JHex.decodeChecked(hexString);
System.out.println(new String(decoded));
String reEncoded = JHex.encode(decoded);
Everything is in a single class file for JHex. Feel free to copy paste if you don't want yet another library in your dependency tree. Also note, it is only available as Java 9 jar until I can figure out how to publish multiple release targets with Gradle and the Bintray plugin.
You could have simply replaced
names[i] = in.nextLine();
with names[i] = in.next();
Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.
I always place the path in double quotes when I am creating a .bat file. (I just added the PAUSE so it wont close the screen.)
For example:
"C:\Program Files\PageTech\PCLReader64_131\PCLReader64.exe"
PAUSE
Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).
This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.
You could actually use xlsread
to accomplish this. After first placing your sample data above in a file 'input_file.csv'
, here is an example for how you can get the numeric values, text values, and the raw data in the file from the three outputs from xlsread
:
>> [numData,textData,rawData] = xlsread('input_file.csv')
numData = % An array of the numeric values from the file
51.9358 4.1833
51.9354 4.1841
51.9352 4.1846
51.9343 4.1864
51.9343 4.1864
51.9341 4.1869
textData = % A cell array of strings for the text values from the file
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
rawData = % All the data from the file (numeric and text) in a cell array
'ABC' [51.9358] [4.1833]
'ABC' [51.9354] [4.1841]
'ABC' [51.9352] [4.1846]
'ABC' [51.9343] [4.1864]
'ABC' [51.9343] [4.1864]
'ABC' [51.9341] [4.1869]
You can then perform whatever processing you need to on the numeric data, then resave a subset of the rows of data to a new file using xlswrite
. Here's an example:
index = sqrt(sum(numData.^2,2)) >= 50; % Find the rows where the point is
% at a distance of 50 or greater
% from the origin
xlswrite('output_file.csv',rawData(index,:)); % Write those rows to a new file
Assuming you're fine with taking all of the changes in master, what you want is:
git checkout <my branch>
to switch the working tree to your branch; then:
git merge master
to merge all the changes in master with yours.
The package it-self is located under /data/app/com.company.appname-xxx.apk
.
/data/app/com.company.appname
is only a directory created to store files like native libs, cache, ecc...
You can retrieve the package installation path with the Context.getPackageCodePath()
function call.
Splitting the data frame seems counter-productive. Instead, use the split-apply-combine paradigm, e.g., generate some data
df = data.frame(grp=sample(letters, 100, TRUE), x=rnorm(100))
then split only the relevant columns and apply the scale()
function to x in each group, and combine the results (using split<-
or ave
)
df$z = 0
split(df$z, df$grp) = lapply(split(df$x, df$grp), scale)
## alternative: df$z = ave(df$x, df$grp, FUN=scale)
This will be very fast compared to splitting data.frames, and the result remains usable in downstream analysis without iteration. I think the dplyr syntax is
library(dplyr)
df %>% group_by(grp) %>% mutate(z=scale(x))
In general this dplyr solution is faster than splitting data frames but not as fast as split-apply-combine.
Could you add z-index style to the two sections so that the one you want appears on top?
I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.
My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!
You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:
Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
cout << "Numarul complex este: " << firstComplexNumber << endl;
// ^^^^^^^^^^^^^^^^^^ No need to dereference now
// ...
Complex::distanta(firstComplexNumber, secondComplexNumber);
Forget it; this might work with Outlook or maybe even GMail but you won't be able to get this working properly supporting most other E-mail clients out there (and there's a shitton of 'em).
You're better of using a simple PHP script (check out PHPMailer) or use a hosted solution (Google "email form hosted", "free email form hosting" or something similar)
By the way, you are looking for the term "Percent-encoding" (also called url-encoding and Javascript uses encodeUri/encodeUriComponent (make sure you understand the differences!)). You will need to encode a whole lot more than just newlines.
To extend Ted Cambron's answer above and something that hasn't been addressed here: If you remove all line breaks indiscriminately from a chunk of entered text, you will end up with paragraphs running into each other without spaces when you output that text later. This is what I use:
sub cleanLines{
my $text = shift;
$text =~ s/\r/ /; #replace \r with space
$text =~ s/\n/ /; #replace \n with space
$text =~ s/ / /g; #replace double-spaces with single space
return $text;
}
The last substitution uses the g 'greedy' modifier so it continues to find double-spaces until it replaces them all. (Effectively substituting anything more that single space)
Here's a small improvement that to @UltraInstinct's Tee class, modified to be a context manager and also captures any exceptions.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
To use the context manager:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
If you want to select any random single row for particular day, then
SELECT * FROM table_name GROUP BY DAY(start_date)
If you want to select single entry for each user per day, then
SELECT * FROM table_name GROUP BY DAY(start_date),owner_name
Glide version 4.6.1
Glide.with(context)
.load(url)
.apply(RequestOptions.bitmapTransform(new CircleCrop()))
.into(imageView);
You can start as Lauritz recommended, with:
except Exception as ex:
and then just to print ex
like so:
try:
#your try code here
except Exception as ex:
print ex
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
Just Javascript (as requested)
Add this function somewhere on your page (preferably in the <head>
)
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event:
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
If you prefer JQuery you could do:
$("#cart_item").html("");
Close, you can use
$('#select_2 option:selected').html()
In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml
), you can do so by just putting an array of mappings in the @WebFilter
annotation:
/**
* Filter implementation class LoginFilter
*/
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
...
And just as an FYI, this same thing works for servlets using the servlet annotation too:
/**
* Servlet implementation class LoginServlet
*/
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
...
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
you can use Array.select or Array.index to do that.
CSS Grid: place-items
Finally, we have place-items: center
for CSS Grid to make it easier.
HTML
<div class="parent">
<div class="to-center"></div>
</div>
CSS
.parent {
display: grid;
place-items: center;
}
Output:
html,
body {
height: 100%;
}
.container {
display: grid;
place-items: center;
height: 100%;
}
.center {
background: #5F85DB;
color: #fff;
font-weight: bold;
font-family: Tahoma;
padding: 10px;
}
_x000D_
<div class="container">
<div class="center" contenteditable>I am always super centered within my parent</div>
</div>
_x000D_
You can filter by multiple columns (more than two) by using the np.logical_and
operator to replace &
(or np.logical_or
to replace |
)
Here's an example function that does the job, if you provide target values for multiple fields. You can adapt it for different types of filtering and whatnot:
def filter_df(df, filter_values):
"""Filter df by matching targets for multiple columns.
Args:
df (pd.DataFrame): dataframe
filter_values (None or dict): Dictionary of the form:
`{<field>: <target_values_list>}`
used to filter columns data.
"""
import numpy as np
if filter_values is None or not filter_values:
return df
return df[
np.logical_and.reduce([
df[column].isin(target_values)
for column, target_values in filter_values.items()
])
]
Usage:
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4]})
filter_df(df, {
'a': [1, 2, 3],
'b': [1, 2, 4]
})
In fact, this is a "how to" subject. So, here is the reference implementation:
public class BOX
{
double height, length, breadth;
public static bool operator == (BOX b1, BOX b2)
{
if ((object)b1 == null)
return (object)b2 == null;
return b1.Equals(b2);
}
public static bool operator != (BOX b1, BOX b2)
{
return !(b1 == b2);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
var b2 = (BOX)obj;
return (length == b2.length && breadth == b2.breadth && height == b2.height);
}
public override int GetHashCode()
{
return height.GetHashCode() ^ length.GetHashCode() ^ breadth.GetHashCode();
}
}
REF: https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples
UPDATE: the cast to (object)
in the operator ==
implementation is important, otherwise, it would re-execute the operator == overload, leading to a stackoverflow. Credits to @grek40.
This (object)
cast trick is from Microsoft String
== implementaiton.
SRC: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs#L643
Assuming that it's a TCP (rather than UDP) port that you're trying to use:
On the server itself, use netstat -an
to check to see which ports are listening.
From outside, just use telnet host port
(or telnet host:port
on Unix systems) to see if the connection is refused, accepted, or timeouts.
On that latter test, then in general:
On Windows 7 or Windows Vista the default option 'telnet' is not recognized as an internal or external command, operable program or batch file. To solve this, just enable it: Click *Start** → Control Panel → Programs → Turn Windows Features on or off. In the list, scroll down and select Telnet Client and click OK.
An integer can't be null but there is a really simple way of doing what you want to do. Use an if-then statement in which you check the integer's value against all possible values.
Example:
int x;
// Some Code...
if (x <= 0 || x > 0){
// What you want the code to do if x has a value
} else {
// What you want the code to do if x has no value
}
Disclaimer: I am assuming that Java does not automatically set values of numbers to 0 if it doesn't see a value.
There is a null coalescing operator (??
), but it would not handle empty strings.
If you were only interested in dealing with null strings, you would use it like
string output = somePossiblyNullString ?? "0";
For your need specifically, there is the conditional operator bool expr ? true_value : false_value
that you can use to simplify if/else statement blocks that set or return a value.
string output = string.IsNullOrEmpty(someString) ? "0" : someString;
Jet Brains IDEA has this feature. You can use hotkey surround with for that (ctrl + alt + T). It's just IDEA feature.
Regions there look like this:
//region Description
Some code
//endregion
XML Layout: declare WebView instead of TextView
<WebView
android:id="@+id/textContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Java code: set text data to WebView
WebView view = (WebView) findViewById(R.id.textContent);
String text;
text = "<html><body><p align=\"justify\">";
text+= "This is the text will be justified when displayed!!!";
text+= "</p></body></html>";
view.loadData(text, "text/html", "utf-8");
This may Solve your problem. Its Fully worked for me.
This is the code you need:
string strInput = "0001234";
strInput = strInput.TrimStart('0');
A catch-all jQuery custom event based on an extension of it's core methods like it was proposed by different people in this thread:
(function() {
var ev = new $.Event('event.css.jquery'),
css = $.fn.css,
show = $.fn.show,
hide = $.fn.hide;
// extends css()
$.fn.css = function() {
css.apply(this, arguments);
$(this).trigger(ev);
};
// extends show()
$.fn.show = function() {
show.apply(this, arguments);
$(this).trigger(ev);
};
// extends hide()
$.fn.hide = function() {
hide.apply(this, arguments);
$(this).trigger(ev);
};
})();
An external library then, uses sth like $('selector').css('property', value)
.
As we don't want to alter the library's code but we DO want to extend it's behavior we do sth like:
$('#element').on('event.css.jquery', function(e) {
// ...more code here...
});
Example: user clicks on a panel that is built by a library. The library shows/hides elements based on user interaction. We want to add a sensor that shows that sth has been hidden/shown because of that interaction and should be called after the library's function.
Another example: jsfiddle.
It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)
This should work:
%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)
%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)