There's a -f option to umount that you can try:
umount -f /mnt/fileshare
Are you specifying the '-t cifs' option to mount? Also make sure you're not specifying the 'hard' option to mount.
You may also want to consider fusesmb, since the filesystem will be running in userspace you can kill it just like any other process.
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
You want in page A to know the URL of page B?
Or to know in page B the URL of page A?
In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?
In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains
Ideally the background property would allow us to layer various backgrounds similar to the background image layering detailed at http://www.css3.info/preview/multiple-backgrounds/. Unfortunately, at least in Chrome (40.0.2214.115), adding an rgba background alongside a url() image background seems to break the property.
The solution I've found is to render the rgba layer as a 1px*1px Base64 encoded image and inline it.
.the-div:hover {
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgkAQAABwAGkn5GOoAAAAASUVORK5CYII=), url("the-image.png");
}
for base64 encoded 1*1 pixel images I used http://px64.net/
Here is your jsfiddle with these changes made. http://jsfiddle.net/325Ft/49/ (I also swapped the image to one that still exists on the internet)
Wrap your all statements in !IsPostBack
condition on page load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// all statements
}
}
This will fix your issue.
If the only thing you want to do is drop in an image onto a widget withouth the complexity of the graphics API, you can also just create a new QWidget and set the background with StyleSheets. Something like this:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ... QWidget *pic = new QWidget(this); pic->setStyleSheet("background-image: url(test.png)"); pic->setGeometry(QRect(50,50,128,128)); ... }
Cors change the request method before it's done, from POST to OPTIONS, so, your post data will not be sent. The way that worked to handle this cors issue, is performing the request with ajax, which does not support the OPTIONS method. example code:
$.ajax({
type: "POST",
crossdomain: true,
url: "http://localhost:1415/anything",
dataType: "json",
data: JSON.stringify({
anydata1: "any1",
anydata2: "any2",
}),
success: function (result) {
console.log(result)
},
error: function (xhr, status, err) {
console.error(xhr, status, err);
}
});
with this headers on c# server:
if (request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
response.AddHeader("Access-Control-Max-Age", "1728000");
}
response.AppendHeader("Access-Control-Allow-Origin", "*");
Use re.escape
>>> import re
>>> re.escape(r'\ a.*$')
'\\\\\\ a\\.\\*\\$'
>>> print(re.escape(r'\ a.*$'))
\\\ a\.\*\$
>>> re.escape('www.stackoverflow.com')
'www\\.stackoverflow\\.com'
>>> print(re.escape('www.stackoverflow.com'))
www\.stackoverflow\.com
Repeating it here:
re.escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
As of Python 3.7 re.escape()
was changed to escape only characters which are meaningful to regex operations.
You can also use joblib.dump and joblib.load which is much more efficient at handling numerical arrays than the default python pickler.
Joblib is included in scikit-learn:
>>> import joblib
>>> from sklearn.datasets import load_digits
>>> from sklearn.linear_model import SGDClassifier
>>> digits = load_digits()
>>> clf = SGDClassifier().fit(digits.data, digits.target)
>>> clf.score(digits.data, digits.target) # evaluate training error
0.9526989426822482
>>> filename = '/tmp/digits_classifier.joblib.pkl'
>>> _ = joblib.dump(clf, filename, compress=9)
>>> clf2 = joblib.load(filename)
>>> clf2
SGDClassifier(alpha=0.0001, class_weight=None, epsilon=0.1, eta0=0.0,
fit_intercept=True, learning_rate='optimal', loss='hinge', n_iter=5,
n_jobs=1, penalty='l2', power_t=0.5, rho=0.85, seed=0,
shuffle=False, verbose=0, warm_start=False)
>>> clf2.score(digits.data, digits.target)
0.9526989426822482
Edit: in Python 3.8+ it's now possible to use pickle for efficient pickling of object with large numerical arrays as attributes if you use pickle protocol 5 (which is not the default).
use a cookie getting script:
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
then call it:
var value = readCookie('obligations');
i stole the code above from quirksmode cookies page. you should read it.
I think you want to write text in an oval or circle? why not this one?
<span style="border-radius:50%; border:solid black 1px;padding:5px">Hello</span>
_x000D_
If you know the count of your columns (f.e. it's equal to a collection list). You can simply use this one liner to adjust all columns of one sheet (if you use at least java 8):
IntStream.range(0, columnCount).forEach((columnIndex) -> sheet.autoSizeColumn(columnIndex));
I know this is an old post, probably no one would scroll this far, I know I didn't. So, after hours of trying different stuff, I found this blog and dude killed it. Simplest way to do this, tried it and it works like a charm.
In the ViewModel:
...
public bool CanClose { get; set; }
private RelayCommand closeCommand;
public ICommand CloseCommand
{
get
{
if(closeCommand == null)
(
closeCommand = new RelayCommand(param => Close(), param => CanClose);
)
}
}
public void Close()
{
this.Close();
}
...
add an Action property to the ViewModel, but define it from the View’s code-behind file. This will let us dynamically define a reference on the ViewModel that points to the View.
On the ViewModel, we’ll simply add:
public Action CloseAction { get; set; }
And on the View, we’ll define it as such:
public View()
{
InitializeComponent() // this draws the View
ViewModel vm = new ViewModel(); // this creates an instance of the ViewModel
this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
if ( vm.CloseAction == null )
vm.CloseAction = new Action(() => this.Close());
}
When you writing scripts performance does not matter (in most cases).
If you care about performance 'Python vs Bash' is a false question.
Python:
+ easier to write
+ easier to maintain
+ easier code reuse (try to find universal error-proof way to include files with common code in sh
, I dare you)
+ you can do OOP with it too!
+ easier arguments parsing. well, not easier, exactly. it still will be too wordy to my taste, but python have argparse
facility built in.
- ugly ugly 'subprocess'. try to chain commands and not to cry a river how ugly your code will become. especially if you care about exit codes.
Bash:
+ ubiquity, as was said earlier, indeed.
+ simple commands chaining. that's how you glue together different commands in a simple way. Also Bash
(not sh
) have some improvements, like pipefail
, so chaining is really short and expressive.
+ do not require 3rd-party programs to be installed. can be executed right away.
- god, it's full of gotchas. IFS, CDPATH.. thousands of them.
If one writing a script bigger than 100 LOC: choose Python
If one need path manipulation in script: choose Python(3)
If one need somewhat like alias
but slightly complicated: choose Bash/sh
Anyway, one should try both sides to get the idea what are they capable of.
Maybe answer can be extended with packaging and IDE support points, but I'm not familiar with this sides.
As always you have to choose from turd sandwich and giant douche. And remember, just a few years ago Perl was new hope. Where it is now.
Fetch vs Pull
Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled
What is the difference between 'git pull' and 'git fetch'?
Merge vs Rebase
from Atlassian SourceTree Blog, Merge or Rebase:
Merging brings two lines of development together while preserving the ancestry of each commit history.
In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.
Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.
The easiest way is:
select top 1 CR
from table t
order by len(CR) desc
Note that this will only return one value if there are multiple with the same longest length.
The answer is not simple:
It depends on the target machines (mobile vs desktop), it depends on the nature of your data, the browser, the OS, the hardware it runs on... you will need to benchmark if you really want to know.
It is mostly a memory vs computation problem ... as with most performance issues the difference can become significant with repeated elements (n) like lists, especially when nested (n x n, or worse) and also what kind of computations you run inside these elements:
ng-show: If those optional elements are often present (dense), like say 90% of the time, it may be faster to have them ready and only show/hide them, especially if their content is cheap (just plain text, nothing to compute or load). This consumes memory as it fills the DOM with hidden elements, but just show/hide something which already exists is likely to be a cheap operation for the browser.
ng-if: If on the contrary elements are likely not to be shown (sparse) just build them and destroy them in real time, especially if their content is expensive to get (computations/sorted/filtered, images, generated images). This is ideal for rare or 'on-demand' elements, it saves memory in terms of not filling the DOM but can cost a lot of computation (creating/destroying elements) and bandwidth (getting remote content). It also depends on how much you compute in the view (filtering/sorting) vs what you already have in the model (pre-sorted/pre-filtered data).
To achieve it, you have to modify the background-color
of the element.
Ways to create a (semi-) transparent color:
The CSS color name transparent
creates a completely transparent color.
Usage:
.transparent{
background-color: transparent;
}
Using rgba
or hsla
color functions, that allow you to add the alpha channel (opacity) to the rgb
and hsl
functions. Their alpha values range from 0 - 1.
Usage:
.semi-transparent-yellow{
background-color: rgba(255, 255, 0, 0.5);
}
.transparent{
background-color: hsla(0, 0%, 0%, 0);
}
Besides the already mentioned solutions, you can also use the HEX format with alpha value (#RRGGBBAA
or #RGBA
notation).
That's pretty new (contained by CSS Color Module Level 4), but already implemented in larger browsers (sorry, no IE).
This differs from the other solutions, as this treats the alpha channel (opacity) as a hexadecimal value as well, making it range from 0 - 255 (FF
).
Usage:
.semi-transparent-yellow{
background-color: #FFFF0080;
}
.transparent{
background-color: #0000;
}
You can try them out as well:
transparent
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: transparent;
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `transparent`
</div>
_x000D_
rgba()
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: rgba(0, 255, 0, 0.3);
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `rgba()`
</div>
_x000D_
#RRGGBBAA
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: #FF000060
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `#RRGGBBAA`
</div>
_x000D_
maybe this will help you out:
or this page:
www.scala-lang.org/node/6372
I came here because I had a similar problem, the image was not being rendered. What I found out was that the content type header of my testing server wasn't correct. I fixed it by adding the following to my .htaccess file:
AddType image/svg+xml svg svgz
AddEncoding gzip svgz
You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the
tag (that you are looking for). The corresponding example from the documentation is as follows
For example, here is a comment that refers to the getComponentAt(int, int) method:
Use the {@link #getComponentAt(int, int) getComponentAt} method.
The package.class
part can be ommited if the referred method is in the current class.
Other useful links about JavaDoc are:
Using this.props.children
is the idiomatic way to pass instantiated components to a react component
const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>
When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div
or span
):
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
If what you want to do is to pass a children-like parameter as a prop, you can do that:
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />
After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.
I was having trouble with .
ERROR: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'mat-checkbox-checked': 'true'. Current value: 'false'.
The Problem here is that the updated value is not detected until the next change Detection Cycle runs.
The easiest solution is to add a Change Detection Strategy. Add these lines to your code:
import { ChangeDetectionStrategy } from "@angular/core"; // import
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: "abc",
templateUrl: "./abc.html",
styleUrls: ["./abc.css"],
})
For 1.8.1 based on @ManuelSchneid3r 's answer I had to do:
wget github.com/google/googletar xf release-1.8.1.tar.gz
tar xf release-1.8.1.tar.gz
cd googletest-release-1.8.1/
cmake -DBUILD_SHARED_LIBS=ON .
make
I then did make install
which seemed to work for 1.8.1, but
following @ManuelSchneid3r it would mean:
sudo cp -a googletest/include/gtest /usr/include
sudo cp -a googlemock/include/gmock /usr/include
sudo cp `find .|grep .so$` /usr/lib/
update: nowadays we have mobile and custom keyboards and we cannot continue trusting these arbitrary key codes such as 13 and 186. in other words, stop using event.which
/event.keyCode
and start using event.key
:
if (event.key === "Enter" || event.key === "ArrowUp" || event.key === "ArrowDown")
There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).
Headers or trailers (?1) like “sign-off” (?2) is, in current
practice in projects like Git and Linux, effectively structured metadata
for the commit. These are all appended to the end of the commit message,
after the “free form” (unstructured) part of the body of the message.
These are token–value (or key–value) pairs typically delimited by a
colon and a space (:?
).
Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:
mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
This is an ancient bug that was actually attempted to be fixed once
(badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
get_user_pages() race for write access") but that was then undone due to
problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").
In the meantime, the s390 situation has long been fixed, and we can now
fix it by checking the pte_dirty() bit properly (and do it better). The
s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
software dirty bits") which made it into v3.9. Earlier kernels will
have to look at the page state itself.
Also, the VM has become more scalable, and what used a purely
theoretical race back then has become easier to trigger.
To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
we already did a COW" rather than play racy games with FOLL_WRITE that
is very fundamental, and then use the pte dirty flag to validate that
the FOLL_COW flag is still valid.
Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
Acked-by: Hugh Dickins <[email protected]>
Reviewed-by: Michal Hocko <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: Greg Thelen <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
In addition to the “sign-off” trailer in the above, there is:
Other projects, like for example Gerrit, have their own headers and associated meaning for them.
See: https://git.wiki.kernel.org/index.php/CommitMessageConventions
It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.
[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.
One can catch that you may change it through windows registry key
(SQLEXPRESS instance):
"Software\Microsoft\Microsoft SQL Server\SQLEXPRESS\LoginMode" = 2
... and restart service
[I understand this is an old thread, just adding some more detail] The two answers by Mark and Jon Hanna sum up the differences, albeit it may interest some that
Guid.NewGuid()
Eventually calls CoCreateGuid (a COM call to Ole32) (reference here) and the actual work is done by UuidCreate.
Guid.Empty is meant to be used to check if a Guid contains all zeroes. This could also be done via comparing the value of the Guid in question with new Guid()
So, if you need a unique identifier, the answer is Guid.NewGuid()
This seems to work great :
if( response.getEntity() != null ) {
response.getEntity().consumeContent();
}//if
And don't forget to consume the entity even if you didn't open its content. For instance, you expect a HTTP_OK status from the response and don't get it, you still have to consume the entity !
http://www.codeproject.com/KB/cs/SingleInstancingWithIpc.aspx
Setting the img
tag color
works
img {color:#fff}
body {background:#000022}_x000D_
img {color:#fff}
_x000D_
<img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" />
_x000D_
The simplest answer of all is...
<a href="javascript:alert('You clicked!')">My link</a>
_x000D_
Or to answer the question of calling a javascript function:
<script type="text/javascript">_x000D_
function myFunction(myMessage) {_x000D_
alert(myMessage);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<a href="javascript:myFunction('You clicked!')">My link</a>
_x000D_
You can also create a batch file like the following if you need finer granularity between calls:
:loop
CallYour.Exe
timeout /t timeToWaitBetweenCallsInSeconds /nobreak
goto :loop
git clone <remote-url>
<=>
git init
// init new repositorygit remote add origin <remote-url>
// add remotegit fetch
// fetch all remote branchsgit switch <default_branch>
// switch to the default branchgit pull
<=>
git pull <remote> <branch>
<=>
You can pass a binding of
{'n' : range(n) }
to the template, then do
{% for i in n %}
...
{% endfor %}
Note that you'll get 0-based behavior (0, 1, ... n-1).
(Updated for Python3 compatibility)
def skip_elements(elements):
new_list = []
for index,element in enumerate(elements):
if index == 0:
new_list.append(element)
elif (index % 2) == 0:
new_list.append(element)
return new_list
Also can use for loop + enumerate. elif (index % 2) == 0: ## Checking if number is even, not odd cause indexing starts from zero not 1.
#include <stdio.h>
#include <string.h>
int main(void){
char word[17], outword[33];//17:16+1, 33:16*2+1
int i, len;
printf("Intro word:");
fgets(word, sizeof(word), stdin);
len = strlen(word);
if(word[len-1]=='\n')
word[--len] = '\0';
for(i = 0; i<len; i++){
sprintf(outword+i*2, "%02X", word[i]);
}
printf("%s\n", outword);
return 0;
}
If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.
I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.
Here is example code. Tryout on your FireBug Console
var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];
var json = "{ ";
for(var i = 0; i < key.length; i++) {
(i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);
I think your solution would be to wrap your content container and your sidebar in a parent containing div. Float your sidebar to the left and give it the background image. Create a wide margin at least the width of your sidebar for your content container. Add clearing a float hack to make it all work.
If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE
like this:
UPDATE MyTable
SET MyColumn = UPPER(MyColumn)
WHERE MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS
Cases sensitivity is based on your collation settings, and is typically case insensitive by default.
Collation can be set at the Server, Database, Column, or Query Level:
-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL
Collation Names specify how a string should be encoded and read, for example:
Latin1_General_CI_AS
? Case InsensitiveLatin1_General_CS_AS
? Case Sensitivecreate table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null constraint fk_exam_id foreign key references exams(exam_id),
question_text varchar(1024) not null,
question_point_value decimal
);
--That will work too. Pehaps a bit more intuitive construct?
Iam using Catalina and use this mysql_secure_installation
command and now works for me:
$ mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.
Enter current password for root (enter for none): << enter root here >>
i enter root
as current password
OK, successfully used password, moving on...
Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.
and do the rest
Updated code for jake's answer. Run this alongside your https server.
// set up plain http server
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
// set up a route to redirect http to https
app.get('*', function(req, res) {
res.redirect('https://' + req.headers.host + req.url);
})
// have it listen on 80
server.listen(80);
The best practice for this situation. Use RETURNING … INTO
.
INSERT INTO teams VALUES (...) RETURNING id INTO last_id;
Note this is for PLPGSQL
Something missing from gipinani's answer
@Scheduled(cron = "0 1 1,13 * * ?", zone = "CST")
This will execute at 1.01 and 13.01. It can be used when you need to run the job without a pattern multiple times a day.
And the zone attribute is very useful, when you do deployments in remote servers. This was introduced with spring 4.
This might help http://docs.pytest.org/en/latest/xunit_setup.html
In my test suite, I group my test cases into classes. For the setup and teardown I need for all the test cases in that class, I use the setup_class(cls)
and teardown_class(cls)
classmethods.
And for the setup and teardown I need for each of the test case, I use the setup_method(method)
and teardown_method(methods)
Example:
lh = <got log handler from logger module>
class TestClass:
@classmethod
def setup_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
@classmethod
def teardown_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
def setup_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def teardown_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def test_tc1(self):
<tc_content>
assert
def test_tc2(self):
<tc_content>
assert
Now when I run my tests, when the TestClass execution is starting, it logs the details for when it is beginning execution, when it is ending execution and same for the methods..
You can add up other setup and teardown steps you might have in the respective locations.
Hope it helps!
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
A list of all addresses is stored in a fact ansible_all_ipv4_addresses
, a default address in ansible_default_ipv4.address
.
---
- hosts: localhost
connection: local
tasks:
- debug: var=ansible_all_ipv4_addresses
- debug: var=ansible_default_ipv4.address
Then there are addresses assigned to each network interface... In such cases you can display all the facts and find the one that has the value you want to use.
Try this:
CREATE FUNCTION dbo.FnDAYSADDNOWK(
@addDate AS DATE,
@numDays AS INT
) RETURNS DATETIME AS
BEGIN
WHILE @numDays > 0 BEGIN
SET @addDate = DATEADD(day, 1, @addDate)
IF DATENAME(DW, @addDate) <> 'sunday' BEGIN
SET @numDays = @numDays - 1
END
END
RETURN CAST(@addDate AS DATETIME)
END
CREATE TABLE someTable (
id serial PRIMARY KEY,
col1 int NOT NULL,
col2 int NOT NULL,
UNIQUE (col1, col2)
)
autoincrement
is not postgresql. You want a serial
.
If col1
and col2
make a unique and can't be null then they make a good primary key:
CREATE TABLE someTable (
col1 int NOT NULL,
col2 int NOT NULL,
PRIMARY KEY (col1, col2)
)
Adding screen shots(examples) and some more context for the answer of @Thomas G.
import pandas as pd
is ran properly before checking below shortcut.Place the cursor in middle of parenthesis ()
before you use shortcut.
shift + tab
Display short document and few params
shift + tab + tab
Expands document with scroll bar
shift + tab + tab + tab
Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.
shift + tab + tab + tab + tab
It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.
Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode.
The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch'
ref using any Git client tool".
The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>
. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>
; it lies to the git client.
Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH>
refs.
When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].
After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>
. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository
.
You can try this way:
$datetime = new DateTime('2010-12-30 23:21:46');
echo $datetime->format(DATE_ATOM);
There is a GUI tool available, ASoft .NET Version Detector, which has always proven highly reliable. It can create XML files by specifying the file name of the XML output on the command line.
You could use this for automation. It is a tiny program, written in a non-.NET dependent language and does not require installation.
lsof -n -i4TCP:8080
PID
is the second field. Then, kill that process:
kill -9 PID
Go to /usr/local/bin/
(Can use command+shift+g in finder)
Make a file named stop
. Paste the below code in it:
#!/bin/bash
touch temp.text
lsof -n -i4TCP:$1 | awk '{print $2}' > temp.text
pidToStop=`(sed '2q;d' temp.text)`
> temp.text
if [[ -n $pidToStop ]]
then
kill -9 $pidToStop
echo "Congrates!! $1 is stopped."
else
echo "Sorry nothing running on above port"
fi
rm temp.text
chmod 755 stop
stop 8888
(or any port)That's because the byte[] output
is well, and array of bytes, you may think on it as an array of bytes representing each one an integer, but when you add them all into a single string you get something that is NOT an integer, that's why. You may either have it as an array of integers or try to create an instance of BigInteger.
Or, using datetimepicker plugin.
This worked for me perfectly.
Add this class navbar-fixed-bottom to your footer.
<div class="footer navbar-fixed-bottom">
I used it like this:
<div class="container-fluid footer navbar-fixed-bottom">
<!-- start footer -->
</div>
And it sets to bottom over the the full width.
Edit: This will set footer to always visible, it's something you need to take in consideration.
index.html
<!DOCTYPE html>
<html>
<body>
<form action="submit.php" method="POST">
First name: <input type="text" name="firstname" /><br /><br />
Last name: <input type="text" name="lastname" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
After that one more file which page you want to display after pressing the submit button
submit.php
<html>
<body>
Your First Name is - <?php echo $_POST["firstname"]; ?><br>
Your Last Name is - <?php echo $_POST["lastname"]; ?>
</body>
</html>
do you work with a 3d tool such as maya? for maya you can look at http://www.inka3d.com
Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux
instead of Other.
After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.
Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.
Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.
Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.
In VirtualBox screen, go to Devices>USB devices. Select your dongle.
Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.
Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.
Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .
Follow TOOLS->OPTIONS->Text Editor->CSS->Formatting Choose "Compact Rules" and uncheck "Hiearerchical indentation"
Even more simple if you accept using pandas :
import pandas
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
df = pandas.DataFrame(result, index=[0])
print df
gives :
0 1 2 3 4 5 6
0 1.118175 0.556608 0.471827 0.487167 1 0.139508 0.209416
If you moved the modules, modify your workspace.xml file and settings.gradle file to use the new paths of your module. Otherwise you will need to try using the import module feature.
in Python 3.x, the range()
function got its own type. so in this case you must use iterator
list(range(1000))
The following code snippet resolved my issue. Thought this might be useful to others.
var strEnc = this.$.txtSearch.value.replace(/\s/g, "-");_x000D_
strEnc = strEnc.replace(/-/g, " ");
_x000D_
Rather using default encodeURIComponent
my first line of code is converting all spaces
into hyphens
using regex pattern /\s\g
and the following line just does the reverse, i.e. converts all hyphens
back to spaces
using another regex pattern /-/g
. Here /g
is actually responsible for finding all
matching characters.
When I am sending this value to my Ajax call, it traverses as normal spaces
or simply %20
and thus gets rid of double-encoding
.
For example , a function which returns value of any parameters variable.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}?
And this is how you can use this function assuming the URL is,
"http://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".
Slight improvement on @arun-p-johny answer:
In html,
<pre id="log"></pre>
In js,
(function () {
var old = console.log;
var logger = document.getElementById('log');
console.log = function () {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == 'object') {
logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
} else {
logger.innerHTML += arguments[i] + '<br />';
}
}
}
})();
Start using:
console.log('How', true, new Date());
Click Search --> Replace --> Find What: \0 Replace with: "empty" Search mode: Extended --> Replace all
Here's what I suggest and what has worked for me. In your application class, implement an Application.ActivityLifeCycleCallbacks
listener and set a variable in your application class. Then query the variable as needed.
class YourApplication: Application.ActivityLifeCycleCallbacks {
var currentActivity: Activity? = null
fun onCreate() {
registerActivityLifecycleCallbacks(this)
}
...
override fun onActivityResumed(activity: Activity) {
currentActivity = activity
}
}
syntax is:
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
Example:
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));
Here the cell 0 to cell 5 will be merged of the 4th row.
Try something like:
CREATE FUNCTION ColumnExists(@TableName varchar(100), @ColumnName varchar(100))
RETURNS varchar(1) AS
BEGIN
DECLARE @Result varchar(1);
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName)
BEGIN
SET @Result = 'T'
END
ELSE
BEGIN
SET @Result = 'F'
END
RETURN @Result;
END
GO
GRANT EXECUTE ON [ColumnExists] TO [whoever]
GO
Then use it like this:
IF ColumnExists('xxx', 'yyyy') = 'F'
BEGIN
ALTER TABLE xxx
ADD yyyyy varChar(10) NOT NULL
END
GO
It should work on both SQL Server 2000 & SQL Server 2005. Not sure about SQL Server 2008, but don't see why not.
There are two options. Ayman's approach is the most simple, but I would add one extra note to it. You should really cache jQuery selections, there is no reason to call $("#input-field-id")
twice:
var input = $( "#input-field-id" );
input.val( input.val() + "more text" );
The other option, .val()
can also take a function as an argument. This has the advantange of easily working on multiple inputs:
$( "input" ).val( function( index, val ) {
return val + "more text";
});
According to this article. You will need to download LocaleHelper.java
referenced in that article.
MyApplication
class that will extends Application
attachBaseContext()
to update language.Register this class in manifest.
public class MyApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
}
}
<application
android:name="com.package.MyApplication"
.../>
Create BaseActivity
and override onAttach()
to update language. Needed for Android 6+
public class BaseActivity extends Activity {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base));
}
}
Make all activities on your app extends from BaseActivity
.
public class LocaleHelper {
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
public static Context onAttach(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, lang);
}
public static Context onAttach(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
return setLocale(context, lang);
}
public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}
public static Context setLocale(Context context, String language) {
persist(context, language);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}
private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale);
}
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
}
This is an old question, but here's my two cents. PeterSO's answer is slightly more concise, but slightly less efficient. You already know how big it's going to be so you don't even need to use append:
keys := make([]int, len(mymap))
i := 0
for k := range mymap {
keys[i] = k
i++
}
In most situations it probably won't make much of a difference, but it's not much more work, and in my tests (using a map with 1,000,000 random int64
keys and then generating the array of keys ten times with each method), it was about 20% faster to assign members of the array directly than to use append.
Although setting the capacity eliminates reallocations, append still has to do extra work to check if you've reached capacity on each append.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
if (true)
{
return View();
}
else
{
return View("another view name");
}
User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:
http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878
You can get Leigh Webber's source code here
If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.
I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access. Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).
With his classes, this is what it takes to copy to/from the clipboard:
Dim myClipboard As New vbaClipboard ' Create clipboard
' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"
' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)
He also provides other functions for manipulating the clipboard.
It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.
-Jim
I think you want to set it in your httpd.conf
file instead of the .htaccess
file.
I am not sure what OS you use, but this link for Ubuntu might give you some pointers on what to do.
https://help.ubuntu.com/community/EnablingUseOfApacheHtaccessFiles
I was looking for a solution which wouldn't add any new dependencies. Check out the following (Python 3) solution:
class VersionManager:
@staticmethod
def compare_version_tuples(
major_a, minor_a, bugfix_a,
major_b, minor_b, bugfix_b,
):
"""
Compare two versions a and b, each consisting of 3 integers
(compare these as tuples)
version_a: major_a, minor_a, bugfix_a
version_b: major_b, minor_b, bugfix_b
:param major_a: first part of a
:param minor_a: second part of a
:param bugfix_a: third part of a
:param major_b: first part of b
:param minor_b: second part of b
:param bugfix_b: third part of b
:return: 1 if a > b
0 if a == b
-1 if a < b
"""
tuple_a = major_a, minor_a, bugfix_a
tuple_b = major_b, minor_b, bugfix_b
if tuple_a > tuple_b:
return 1
if tuple_b > tuple_a:
return -1
return 0
@staticmethod
def compare_version_integers(
major_a, minor_a, bugfix_a,
major_b, minor_b, bugfix_b,
):
"""
Compare two versions a and b, each consisting of 3 integers
(compare these as integers)
version_a: major_a, minor_a, bugfix_a
version_b: major_b, minor_b, bugfix_b
:param major_a: first part of a
:param minor_a: second part of a
:param bugfix_a: third part of a
:param major_b: first part of b
:param minor_b: second part of b
:param bugfix_b: third part of b
:return: 1 if a > b
0 if a == b
-1 if a < b
"""
# --
if major_a > major_b:
return 1
if major_b > major_a:
return -1
# --
if minor_a > minor_b:
return 1
if minor_b > minor_a:
return -1
# --
if bugfix_a > bugfix_b:
return 1
if bugfix_b > bugfix_a:
return -1
# --
return 0
@staticmethod
def test_compare_versions():
functions = [
(VersionManager.compare_version_tuples, "VersionManager.compare_version_tuples"),
(VersionManager.compare_version_integers, "VersionManager.compare_version_integers"),
]
data = [
# expected result, version a, version b
(1, 1, 0, 0, 0, 0, 1),
(1, 1, 5, 5, 0, 5, 5),
(1, 1, 0, 5, 0, 0, 5),
(1, 0, 2, 0, 0, 1, 1),
(1, 2, 0, 0, 1, 1, 0),
(0, 0, 0, 0, 0, 0, 0),
(0, -1, -1, -1, -1, -1, -1), # works even with negative version numbers :)
(0, 2, 2, 2, 2, 2, 2),
(-1, 5, 5, 0, 6, 5, 0),
(-1, 5, 5, 0, 5, 9, 0),
(-1, 5, 5, 5, 5, 5, 6),
(-1, 2, 5, 7, 2, 5, 8),
]
count = len(data)
index = 1
for expected_result, major_a, minor_a, bugfix_a, major_b, minor_b, bugfix_b in data:
for function_callback, function_name in functions:
actual_result = function_callback(
major_a=major_a, minor_a=minor_a, bugfix_a=bugfix_a,
major_b=major_b, minor_b=minor_b, bugfix_b=bugfix_b,
)
outcome = expected_result == actual_result
message = "{}/{}: {}: {}: a={}.{}.{} b={}.{}.{} expected={} actual={}".format(
index, count,
"ok" if outcome is True else "fail",
function_name,
major_a, minor_a, bugfix_a,
major_b, minor_b, bugfix_b,
expected_result, actual_result
)
print(message)
assert outcome is True
index += 1
# test passed!
if __name__ == '__main__':
VersionManager.test_compare_versions()
EDIT: added variant with tuple comparison. Of course the variant with tuple comparison is nicer, but I was looking for the variant with integer comparison
Comparing sequencially the letters that have the same position against each other.. more like how you order words in a dictionary
I see that there is already some great advice and methods suggest for how to get the post back control. However I found another web page (Mahesh blog) with a method to retrieve post back control ID.
I will post it here with a little modification, including making it an extension class. Hopefully it is more useful in that way.
/// <summary>
/// Gets the ID of the post back control.
///
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is IButtonControl)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
Update (2016-07-22): Type check for Button
and ImageButton
changed to look for IButtonControl
to allow postbacks from third party controls to be recognized.
<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" >
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="HorizontalAlignment" Value="Right" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:
Root
--app.py <-- file from which app will be run
--models
----user.py <-- file with "User" model
----order.py <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration
Be careful about calling the "create_all" function from app.py.
This concept is explained better by the answer to this thread posted by @SuperShoot
First, make sure you have the following address in your Environment Variables
Path
C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.0
Then open your Command Prompt
and type the following command:
tsc -v
I was facing the same problem because some of the images are grey scale images in my data set, so i solve my problem by doing this
from PIL import Image
img = Image.open('my_image.jpg').convert('RGB')
# a line from my program
positive_images_array = np.array([np.array(Image.open(img).convert('RGB').resize((150, 150), Image.ANTIALIAS)) for img in images_in_yes_directory])
private void ButtonOpenWebActionPerformed(java.awt.event.ActionEvent evt) {
try {
String url = "https://www.google.com";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
} catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}
You can convert the QString type to python string by just using the str
function. Assuming you are not using any Unicode characters you can get a python
string as below:
text = str(combobox1.currentText())
If you are using any unicode characters, you can do:
text = unicode(combobox1.currentText())
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
Another approach would be to use the two-argument form of iter
:
from itertools import islice
def group(it, size):
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())
This can be adapted easily to use padding (this is similar to Markus Jarderot’s answer):
from itertools import islice, chain, repeat
def group_pad(it, size, pad=None):
it = chain(iter(it), repeat(pad))
return iter(lambda: tuple(islice(it, size)), (pad,) * size)
These can even be combined for optional padding:
_no_pad = object()
def group(it, size, pad=_no_pad):
if pad == _no_pad:
it = iter(it)
sentinel = ()
else:
it = chain(iter(it), repeat(pad))
sentinel = (pad,) * size
return iter(lambda: tuple(islice(it, size)), sentinel)
Hope this will work, try this:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);
str, your JSON String
As Simple as this, if you want emailid,
String emailIds = response.get("email id").toString();
Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service
if you're using jquery you can take advantage of grep to create array with all matching objects:
var results = $.grep(vendors, function (e) {
return e.Name == "Magenic";
});
and then use the results array:
for (var i=0, l=results.length; i<l; i++) {
console.log(results[i].ID);
}
Rather than preg_replace
, you could always use PHP's filter functions using the filter_var()
function with FILTER_SANITIZE_STRING
.
Another really easy way to make this work is just to create an extension of the UINavigationController class.
Since overriding the preferredStatusBarStyle:
method wont work UNLESS we do it inside of the UINavigationController class.
extension UINavigationController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
I know this question is old, but between all the answers, I miss one that is a common approach for this use-case in XSLT development.
I am imagining that the missing code from the OP looks something like this:
<xsl:template match="category">
<xsl:choose>
<xsl:when test="categoryName !=null">
<xsl:value-of select="categoryName " />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="other" />
</xsl:otherwise>
</xsl:choose>
</category>
And that the input looks something like this:
<categories>
<category>
<categoryName>Books</categoryName>
</category>
<category>
<categoryName>Magazines</categoryName>
<categoryName>Periodicals</categoryName>
<categoryName>Journals</categoryName>
</category>
<category>
<categoryName><!-- please fill in category --></categoryName>
</category>
<category>
<categoryName />
</category>
<category />
</categories>
I.e., I assume there can be zero, empty, single or multiple categoryName
elements. To deal with all these cases using xsl:choose
-style constructs, or in other words, imperatively, is quickly getting messy (even more so if elements can be at different levels!). A typical programming idiom in XSLT is using templates (hence the T in XSLT), which is declarative programming, not imperative (you don't tell the processor what to do, you just tell what you want output if certain conditions are met). For this use-case, that can look something like the following:
<!-- positive test, any category with a valid categoryName -->
<xsl:template match="category[categoryName[text()]]">
<xsl:apply-templates />
</xsl:template>
<!-- any other category (without categoryName, "null", with comments etc) -->
<xsl:template match="category">
<xsl:text>Category: Other</xsl:text>
</xsl:template>
<!-- matching the categoryName itself for easy handling of multiple names -->
<xsl:template match="categoryName">
<xsl:text>Category: </xsl:text>
<xsl:value-of select="." />
</xsl:template>
This works (with any XSLT version), because the first one above has a higher precedence (it has a predicate). The "fall-through" matching template, the second one, catches anything that is not valid. The third one then takes care of outputting the categoryName
value in a proper way.
Note that in this scenario there is no need to specifially match categories
or category
, because the processor will automatically process all children, unless we tell it otherwise (in this example, the second and third template do not further process the children, because there is no xsl:apply-templates
in them).
This approach is more easily extendible then the imperative approach, because it automically deals with multiple categories and it can be expanded for other elements or exceptions by just adding another matching template. Programming without if-branches.
Note: there is no such thing as null
in XML. There is xsi:nil, but that is rarely used, especially rarely in untyped scenarios without a schema of some sort.
The below code worked for me.
import pandas
df = pandas.read_csv('somefile.txt')
df = df.fillna(0)
It's very easy.
"your chrome path" -kiosk -fullscreen "your URL"
Example:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -kiosk -fullscreen http://google.com
Close all Chrome sessions first !
To exit: Press ALT-TAB > hold ALT and press X in the windows task. (win10)
These solutions are pretty good, but they are forgetting that there may be other status codes than 200 OK. This is a solution that I've used on production environments for status monitoring and such.
If there is a url redirect or some other condition on the target page, the return will be true using this method. Also, GetResponse() will throw an exception and hence you will not get a StatusCode for it. You need to trap the exception and check for a ProtocolError.
Any 400 or 500 status code will return false. All others return true. This code is easily modified to suit your needs for specific status codes.
/// <summary>
/// This method will check a url to see that it does not return server or protocol errors
/// </summary>
/// <param name="url">The path to check</param>
/// <returns></returns>
public bool UrlIsValid(string url)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load
request.Method = "HEAD"; //Get only the header information -- no need to download any content
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
if (statusCode >= 100 && statusCode < 400) //Good requests
{
return true;
}
else if (statusCode >= 500 && statusCode <= 510) //Server Errors
{
//log.Warn(String.Format("The remote server has thrown an internal error. Url is not valid: {0}", url));
Debug.WriteLine(String.Format("The remote server has thrown an internal error. Url is not valid: {0}", url));
return false;
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError) //400 errors
{
return false;
}
else
{
log.Warn(String.Format("Unhandled status [{0}] returned for url: {1}", ex.Status, url), ex);
}
}
catch (Exception ex)
{
log.Error(String.Format("Could not test url {0}.", url), ex);
}
return false;
}
For my case (a small, personal project) https://www.lambdatest.com/ was very helpful. Free tier allows for 6 sessions per month.
HTML5: async
, defer
In HTML5, you can tell browser when to run your JavaScript code. There are 3 possibilities:
<script src="myscript.js"></script>
<script async src="myscript.js"></script>
<script defer src="myscript.js"></script>
Without async
or defer
, browser will run your script immediately, before rendering the elements that's below your script tag.
With async
(asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.
With defer
, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)
When you testing try with UTF8
Encode stream like below
var stream = new MemoryStream();
var streamWriter = new StreamWriter(stream, System.Text.Encoding.UTF8);
Serializer.Serialize<SuperExample>(streamWriter, test);
Additional reminder:
If you have multiple configuration type, you need to specify the [ConfigurationName]
Update-Database -Configurationtypename [ConfigurationName] -TargetMigration [MigrationName]
I tried as following in spring boot:
ParameterizedTypeReference<Map<String, Object>> typeRef = new ParameterizedTypeReference<Map<String, Object>>() {};
public Map<String, Object> processResponse(String urlendpoint)
{
try{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//reqobj
JSONObject request = new JSONObject();
request.put("username", name);
//Or Hashmap
Map<String, Object> reqbody = new HashMap<>();
reqbody.put("username",username);
Gson gson = new Gson();//mvn plugin to convert map to String
HttpEntity<String> entity = new HttpEntity<>( gson.toJson(reqbody), headers);
ResponseEntity<Map<String, Object>> response = resttemplate.exchange(urlendpoint, HttpMethod.POST, entity, typeRef);//example of post req with json as request payload
if(Integer.parseInt(response.getStatusCode().toString()) == HttpURLConnection.HTTP_OK)
{
Map<String, Object> responsedetails = response.getBody();
System.out.println(responsedetails);//whole json response as map object
return responsedetails;
}
} catch (Exception e) {
// TODO: handle exception
System.err.println(e);
}
return null;
}
The Collection and Dictionary solutions are all nice and shine for a short approach, but if you want speed try using a more direct approach:
Function ArrayUnique(ByVal aArrayIn As Variant) As Variant
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ArrayUnique
' This function removes duplicated values from a single dimension array
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim aArrayOut() As Variant
Dim bFlag As Boolean
Dim vIn As Variant
Dim vOut As Variant
Dim i%, j%, k%
ReDim aArrayOut(LBound(aArrayIn) To UBound(aArrayIn))
i = LBound(aArrayIn)
j = i
For Each vIn In aArrayIn
For k = j To i - 1
If vIn = aArrayOut(k) Then bFlag = True: Exit For
Next
If Not bFlag Then aArrayOut(i) = vIn: i = i + 1
bFlag = False
Next
If i <> UBound(aArrayIn) Then ReDim Preserve aArrayOut(LBound(aArrayIn) To i - 1)
ArrayUnique = aArrayOut
End Function
Calling it:
Sub Test()
Dim aReturn As Variant
Dim aArray As Variant
aArray = Array(1, 2, 3, 1, 2, 3, "Test", "Test")
aReturn = ArrayUnique(aArray)
End Sub
For speed comparasion, this will be 100x to 130x faster then the dictionary solution, and about 8000x to 13000x faster than the collection one.
Drupal's Devel module has other useful functions including ones that can print formatted arrays and objects to log files. See the guide at http://ratatosk.net/drupal/tutorials/debugging-drupal.html
dd()
Logs any variable to a file named “drupal_debug.txt” in the site’s temp directory. All output from this function is appended to the log file, making it easy to see how the contents of a variable change as you modify your code.
If you’re using Mac OS X you can use the Logging Console to monitor the contents of the log file.
If you’re using a flavor of Linux you can use the command “tail -f drupal_debug.txt” to watch the data being logged to the file.
import platform
platform.architecture()
From the Python docs:
Queries the given executable (defaults to the Python interpreter binary) for various architecture information.
Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.
To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length
.
double sum = 0.0;
int length = 0;
for( double number : numbers ) {
sum += number;
length++;
}
return sum/length;
Variance is calculated similarly. Standard deviation is simply the square root of the variance:
double stddev = Math.sqrt( variance );
Also, would I be right in concluding that a list comprehension is the most efficient way to do this?
Maybe. List comprehensions are not inherently computationally efficient. It is still running in linear time.
From my personal experience: I have significantly reduced computation time when dealing with large data sets by replacing list comprehensions (specifically nested ones) with for-loop/list-appending type structures you have above. In this application I doubt you will notice a difference.
StreamReader reader = new StreamReader(Oldfilepath);
string fileContent = reader.ReadToEnd();
StreamWriter writer = new StreamWriter(NewFilePath);
writer.Write(fileContent);
The Date
object is used to work with dates and times.
Date objects are created with new Date()
var now = new Date();
now - Current date and time object.
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}
With the Date (and DateTime) classes you can do (end_date - start_date).to_i
to get the number of days difference.
Convert the Special characters to apostrophe,
Data <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)
Below code it to remove extra ''' apostrophe
Data <- gsub("''","" , Data ,ignore.case = TRUE)
Use gsub(..)
function for replacing the special character with apostrophe
I ran into the same problem. Placing a forward slash after the folder name worked for me.
ex: git add foldername/
use indexOf()
function
string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
//DO YOUR LOGIC
string errorCode = s.Substring(index+4);
}
UPDATE tbl_ClientNotes
SET
ordering=ISNULL@ordering,ordering),
title=isnull(@title,title),
content=isnull(@content,content)
WHERE id=@id
I think I remember seeing before that if you are updating to the same value SQL Server will actually recognize this and won't do an unnecessary write.
I think, the best way to do it is this:
body {
font-family: Arial,Verdana,sans-serif;
background:url("/images/image.jpg") no-repeat fixed bottom right transparent;
}
In this way there's no need to do nothing more and it's quite simple.
At least, it works for me.
I hope it helps.
Having a large Answer table, in and of itself, is not a problem. As long as the indexes and constraints are well defined you should be fine. Your second schema looks good to me.
Use ps
to find the process id for the application, then use top -p1010
(substitute 1010 for the real process id).
The RES column is the used physical memory and the VIRT column is the used virtual memory - including libraries and swapped memory.
More info can be found using "man top"
You can dynamically request icon images from the Google charts api with the urls:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FE7569
Which looks like this: the image is 21x34 pixels and the pin tip is at position (10, 34)
And you'll also want a separate shadow image (so that it doesn't overlap nearby icons):
http://chart.apis.google.com/chart?chst=d_map_pin_shadow
Which looks like this: the image is 40x37 pixels and the pin tip is at position (12, 35)
When you construct your MarkerImages you need to set the size and anchor points accordingly:
var pinColor = "FE7569";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
You can then add the marker to your map with:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0,0),
map: map,
icon: pinImage,
shadow: pinShadow
});
Simply replace "FE7569" with the color code you're after. Eg:
Credit due to Jack B Nimble for the inspiration ;)
To have access to stuff provided by math
module, like pi
. You need to import the module first:
import math
print (math.pi)
This works in all browsers (IE11, firefox, Edge, Chrome and Chrome Mobile) My documents are in multiple select elements. The browsers seem to have issues when you try to do it too fast... So I used a timeout.
//user clicks a download button to download all selected documents
$('#downloadDocumentsButton').click(function () {
var interval = 1000;
//select elements have class name of "document"
$('.document').each(function (index, element) {
var doc = $(element).val();
if (doc) {
setTimeout(function () {
window.location = doc;
}, interval * (index + 1));
}
});
});
This is a solution that uses promises:
function downloadDocs(docs) {
docs[0].then(function (result) {
if (result.web) {
window.open(result.doc);
}
else {
window.location = result.doc;
}
if (docs.length > 1) {
setTimeout(function () { return downloadDocs(docs.slice(1)); }, 2000);
}
});
}
$('#downloadDocumentsButton').click(function () {
var files = [];
$('.document').each(function (index, element) {
var doc = $(element).val();
var ext = doc.split('.')[doc.split('.').length - 1];
if (doc && $.inArray(ext, docTypes) > -1) {
files.unshift(Promise.resolve({ doc: doc, web: false }));
}
else if (doc && ($.inArray(ext, webTypes) > -1 || ext.includes('?'))) {
files.push(Promise.resolve({ doc: doc, web: true }));
}
});
downloadDocs(files);
});
Hi just use a text box additional to group of check box.When clicking on any check box put values in to that text box.Make that that text box required and readonly.
As suggested in the bug report, uncommenting the line
idea.jars.nocopy=false
in the idea.properties
file has solved the issue for me.
Note that this needs to be done every time Android Studio updates.
Something like this?
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=3 cols=50 name="text">Please type in this box. When you
click the Download button, the contents of this box will be downloaded to
your machine at the location you specify. Pretty nifty. </textarea>
<input type="submit" value="Download">
</form>
</body>
</html>
If you want to select a variable range containing all headers cells:
Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")
'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST
sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select
...as long as there's no other content on that row.
EDIT: updated to stress that when using Range(Cells(...), Cells(...))
it's good practice to qualify both Range
and Cells
with a worksheet reference.
WhatsApp is now providing a much simpler API https://wa.me/
This isn't introducing any new features, just a simpler way to execute things. There's no need to check for user agent while implementing this API as it will also work with native apps as well as the web interface of whatsapp (web.whatsapp.com) on desktop.
This can be used in multiple use cases
A Click to chat button : Use https://wa.me/whatsappphonenumber
to open a chat dialog with the specified whatsapp user. Please note that the whatsappphonenumber
should be a valid whatsapp number in international format without leading zeros, '+', '-' and spaces. e.g. 15551234567
<a href="https://wa.me/15551234567">Whatsapp Me</a>
A Share this on whatsapp button : Use https://wa.me/?text=urlencodedtext
to open a whatsapp contact selection dialog with a preset text. e.g.
<a href="https://wa.me/?text=I%20found%20a%20great%20website.%20Check%20out%20this%20link%20https%3A%2F%2Fwww.example.com%2F">Share on WhatsApp</a>
A Contact me button with prefilled text : A combination of the above two, Might be useful if you want to get a prefilled custom message from users landing on a particular page. Use format https://wa.me/whatsappphonenumber/?text=urlencodedtext
<a href="https://wa.me/15551234567?text=I%20am%20interested%20in%20your%20services.%20How%20to%20get%20started%3F">I am interested</a>
For official documentation visit https://faq.whatsapp.com/en/general/26000030
Given that canvas
is a canvas element,
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
One starting point could be to use this directive (ng-csv) just download the file as csv and that's something excel can understand
http://ngmodules.org/modules/ng-csv
Maybe you can adapt this code (updated link):
http://jsfiddle.net/Sourabh_/5ups6z84/2/
Altough it seems XMLSS (it warns you before opening the file, if you choose to open the file it will open correctly)
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:
Why do I need to write
"$foo"
? What happens without the quotes?
$foo
does not mean “take the value of the variablefoo
”. It means something much more complex:
- First, take the value of the variable.
- Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains
foo * bar ?
then the result of this step is the 3-element listfoo
,*
,bar
.- Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing
foo
, following by the list of files in the current directory, and finallybar
. If the current directory is empty, the result isfoo
,*
,bar
.Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception:
"$@"
to expand to the list of positional parameters, e.g."$@"
is equivalent to"$1" "$2" "$3"
if there are three positional parameters. See What is the difference between $* and $@?)The same happens to command substitution with
$(foo)
or with`foo`
. On a side note, don't use`foo`
: its quoting rules are weird and non-portable, and all modern shells support$(foo)
which is absolutely equivalent except for having intuitive quoting rules.The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming
IFS
doesn't contain digits or-
).See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.
Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.
I prefer the following syntax:
Dim number As Integer = 1
Dim str As String = String.TryCast(number)
If str IsNot Nothing Then
Hah you can tell I typically write code in C#. 8)
The reason I prefer TryCast is you do not have to mess with the overhead of casting exceptions. Your cast either succeeds or your variable is initialized to null and you deal with that accordingly.
Does not equal. The opposite of =
, equivalent to !=
.
Also, for everyone's info, this can return a non-zero number of rows. I see the OP has reformatted his question so it's a bit clearer, but as far as I can tell, this finds records where product ID is among those found in order #605, as is quantity, but it's not actually order #605. If order #605 contains 1 apple, 2 bananas and 3 crayons, #604 should match if it contains 2 apples (but not 3 dogs). It just won't match order #605. (And if ordid
is unique, then it would find exact duplicates.)
You can use this javascript code to redirect after a specific time. Hope it will work.
setRedirectTime(function ()
{
window.location.href= 'https://www.google.com'; // the redirect URL will be here
},10000); // 10 seconds
>>> from str2bool import str2bool
>>> str2bool('Yes')
True
>>> str2bool('FaLsE')
False
I also went through this problem and changed that:
<application android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">
to
<application tools:replace="android:allowBackup" android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">
To answer this not from an aesthetical but performance-oriented point of view, I've put all of the above suggestions through a benchmark. To be precise, I've considered the suggestions
x[length(x)]
mylast(x)
, where mylast
is a C++ function implemented through Rcpp,tail(x, n=1)
dplyr::last(x)
x[end(x)[1]]]
rev(x)[1]
and applied them to random vectors of various sizes (10^3, 10^4, 10^5, 10^6, and 10^7). Before we look at the numbers, I think it should be clear that anything that becomes noticeably slower with greater input size (i.e., anything that is not O(1)) is not an option. Here's the code that I used:
Rcpp::cppFunction('double mylast(NumericVector x) { int n = x.size(); return x[n-1]; }')
options(width=100)
for (n in c(1e3,1e4,1e5,1e6,1e7)) {
x <- runif(n);
print(microbenchmark::microbenchmark(x[length(x)],
mylast(x),
tail(x, n=1),
dplyr::last(x),
x[end(x)[1]],
rev(x)[1]))}
It gives me
Unit: nanoseconds
expr min lq mean median uq max neval
x[length(x)] 171 291.5 388.91 337.5 390.0 3233 100
mylast(x) 1291 1832.0 2329.11 2063.0 2276.0 19053 100
tail(x, n = 1) 7718 9589.5 11236.27 10683.0 12149.0 32711 100
dplyr::last(x) 16341 19049.5 22080.23 21673.0 23485.5 70047 100
x[end(x)[1]] 7688 10434.0 13288.05 11889.5 13166.5 78536 100
rev(x)[1] 7829 8951.5 10995.59 9883.0 10890.0 45763 100
Unit: nanoseconds
expr min lq mean median uq max neval
x[length(x)] 204 323.0 475.76 386.5 459.5 6029 100
mylast(x) 1469 2102.5 2708.50 2462.0 2995.0 9723 100
tail(x, n = 1) 7671 9504.5 12470.82 10986.5 12748.0 62320 100
dplyr::last(x) 15703 19933.5 26352.66 22469.5 25356.5 126314 100
x[end(x)[1]] 13766 18800.5 27137.17 21677.5 26207.5 95982 100
rev(x)[1] 52785 58624.0 78640.93 60213.0 72778.0 851113 100
Unit: nanoseconds
expr min lq mean median uq max neval
x[length(x)] 214 346.0 583.40 529.5 720.0 1512 100
mylast(x) 1393 2126.0 4872.60 4905.5 7338.0 9806 100
tail(x, n = 1) 8343 10384.0 19558.05 18121.0 25417.0 69608 100
dplyr::last(x) 16065 22960.0 36671.13 37212.0 48071.5 75946 100
x[end(x)[1]] 360176 404965.5 432528.84 424798.0 450996.0 710501 100
rev(x)[1] 1060547 1140149.0 1189297.38 1180997.5 1225849.0 1383479 100
Unit: nanoseconds
expr min lq mean median uq max neval
x[length(x)] 327 584.0 1150.75 996.5 1652.5 3974 100
mylast(x) 2060 3128.5 7541.51 8899.0 9958.0 16175 100
tail(x, n = 1) 10484 16936.0 30250.11 34030.0 39355.0 52689 100
dplyr::last(x) 19133 47444.5 55280.09 61205.5 66312.5 105851 100
x[end(x)[1]] 1110956 2298408.0 3670360.45 2334753.0 4475915.0 19235341 100
rev(x)[1] 6536063 7969103.0 11004418.46 9973664.5 12340089.5 28447454 100
Unit: nanoseconds
expr min lq mean median uq max neval
x[length(x)] 327 722.0 1644.16 1133.5 2055.5 13724 100
mylast(x) 1962 3727.5 9578.21 9951.5 12887.5 41773 100
tail(x, n = 1) 9829 21038.0 36623.67 43710.0 48883.0 66289 100
dplyr::last(x) 21832 35269.0 60523.40 63726.0 75539.5 200064 100
x[end(x)[1]] 21008128 23004594.5 37356132.43 30006737.0 47839917.0 105430564 100
rev(x)[1] 74317382 92985054.0 108618154.55 102328667.5 112443834.0 187925942 100
This immediately rules out anything involving rev
or end
since they're clearly not O(1)
(and the resulting expressions are evaluated in a non-lazy fashion). tail
and dplyr::last
are not far from being O(1)
but they're also considerably slower than mylast(x)
and x[length(x)]
. Since mylast(x)
is slower than x[length(x)]
and provides no benefits (rather, it's custom and does not handle an empty vector gracefully), I think the answer is clear: Please use x[length(x)]
.
Here is another possible workaround:
if exists (select * from master..sysservers where srvname = 'loopback')
exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver @server = N'loopback', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = @@servername
go
create function testit()
returns int
as
begin
declare @res int;
select @res=count(*) from openquery(loopback, 'exec sp_who');
return @res
end
go
select dbo.testit()
It's not so scary as xp_cmdshell
but also has too many implications for practical use.
if you add your remote repository by using git clone then follow the steps:-
git clone <repo_url>
then
git init
git add *
*means add all files
git commit -m 'your commit'
git remote -v
for check any branch run or not if not then nothing show then we add or fetch the repository.
"fetch first". You need to run git pull origin <branch>
or git pull -r origin <branch>
before a next push.
then
git remote add origin <git url>
git pull -r origin master
git push -u origin master```
Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:
[x * 0.1 for x in range(0, 10)]
(Replace the call to range with that expression.)
For the more general case, you may want to write a custom function or generator.
One more bit of advice for anyone trying to build CGAL in particular, with statically linked Boost. It is not enough to define Boost_USE_STATIC_LIBS
; it gets overridden by the time Boost_DEBUG
outputs its value. The thing to do here is to check the "Advanced" checkbox and to enable CGAL_Boost_USE_STATIC_LIBS
.
input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)
You have to enter input in either single or double quotes
Ex:'dude' -> correct
dude -> not correct
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
Replacing one string with another can be done in the below methods
Method 1: Using String replaceAll
String myInput = "HelloBrother";
String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
---OR---
String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
System.out.println("My Output is : " +myOutput);
Method 2: Using Pattern.compile
import java.util.regex.Pattern;
String myInput = "JAVAISBEST";
String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
---OR -----
String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
System.out.println("My Output is : " +myOutputWithRegEX);
Method 3: Using Apache Commons
as defined in the link below:
http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)
Add comments for two different columns of the EMPLOYEE table :
COMMENT ON EMPLOYEE
(WORKDEPT IS 'see DEPARTMENT table for names',
EDLEVEL IS 'highest grade level passed in school' )
just run mongod in terminal on the base folder if everything has been set up like installing mongo db and the client for it like mongoose. After running the command run the project file that you are working on and then the error shouldn't appear.
Just call the correct executable
If you want to use them as in swift 2, you can use these funcs:
For CGRectMake:
func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
return CGRect(x: x, y: y, width: width, height: height)
}
For CGPointMake:
func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
For CGSizeMake:
func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
return CGSize(width: width, height: height)
}
Just put them outside any class and it should work. (Works for me at least)
You can try this:
SELECT DATE(DATE_ADD(m_inv_reqdate, INTERVAL + 1 DAY)) FROM tr08_investment
In Addition to Ben's Answer, You can try Below Queries as per your need
USE {database-name};
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE {database-name}
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE ({database-file-name}, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE {database-name}
SET RECOVERY FULL;
GO
Update Credit @cema-sp
To find database file names use below query
select * from sys.database_files;
In monotouch / xamarin.ios this worked for me:
SomeParentUiView.Subviews.All(x => x.RemoveFromSuperview);
This is much easier in Swift 3 and later using reduce:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.reduce("") { $0 + String(format: "%02x", $1) }
DispatchQueue.global(qos: .background).async {
let url = URL(string: "https://example.com/myApp/apns.php")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: [
"token" : token,
"ios" : UIDevice.current.systemVersion,
"languages" : Locale.preferredLanguages.joined(separator: ", ")
])
URLSession.shared.dataTask(with: request).resume()
}
}
We can check error & 404 statusCode, and use try {} catch (err) {}
.
You can try this :
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
if (req.status == 404) {_x000D_
console.log("404");_x000D_
return false;_x000D_
}_x000D_
_x000D_
if (!(req.readyState == 4 && req.status == 200))_x000D_
return false;_x000D_
_x000D_
const json = (function(raw) {_x000D_
try {_x000D_
return JSON.parse(raw);_x000D_
} catch (err) {_x000D_
return false;_x000D_
}_x000D_
})(req.responseText);_x000D_
_x000D_
if (!json)_x000D_
return false;_x000D_
_x000D_
document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
Read more :
I use WinMerge. It is free and works pretty well (works for files and directories).
sh
files are unix (linux) shell executables files, they are the equivalent (but much more powerful) of bat
files on windows.
So you need to run it from a linux console, just typing its name the same you do with bat files on windows.
IIS version 8.5 +
To enable Event Tracing for Windows for your website/application
Custom Views > ServerRoles > Web Server
Windows Logs > System
Click is an event. In your code behind, you need to have a corresponding event handler to whatever you have in the XAML. In this case, you would need to have the following:
private void Command(object sender, RoutedEventArgs e)
{
}
Commands are different. If you need to wire up a command, you'd use the Commmand property of the button and you would either use some pre-built Commands or wire up your own via the CommandManager class (I think).
You can either add it this way:
arr['key3'] = value3;
or this way:
arr.key3 = value3;
The answers suggesting keying into the object with the variable key3
would only work if the value of key3
was 'key3'
.
Add an Id
property into the P
tag with value like text or something:
function gettext() {
var amount = document.getElementById('text').value;
}
Code Snippet1:
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray * values = [dictionary allValues];
[array addObject:values];
Code Snippet2: If you want to add further
[array addObject:value1];
[array addObject:value2];
[array addObject:value3];
And so on
Also you can store key values of dictionary to array
NSArray *keys = [dictionary allKeys];
This is the most native and scalable approach I could find:
>>> myindex = pd.Series(myseries.index, index=myseries)
>>> myindex[7]
3
>>> myindex[[7, 5, 7]]
7 3
5 4
7 3
dtype: int64
LayoutInflater inflater = (LayoutInflater) SettingActivity.this.getSystemService(SettingActivity.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.gd_quick_action_slide_fontsize, null),LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, true);
pw.showAtLocation(SettingActivity.this.findViewById(R.id.setting_fontsize), Gravity.CENTER, 0, 0);
View v= pw.getContentView();
TextView tv=v.findViewById(R.id.....);
There are 2 possibilities. In either case PyGame has to be initialized by pygame.init
.
import pygame
pygame.init()
Use either the pygame.font
module and create a pygame.font.SysFont
or pygame.font.Font
object. render()
a pygame.Surface
with the text and blit
the Surface to the screen:
my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))
Or use the pygame.freetype
module. Create a pygame.freetype.SysFont()
or pygame.freetype.Font
object. render()
a pygame.Surface
with the text or directly render_to()
the text to the screen:
my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))
See also Text and font
Minimal pygame.font
example: repl.it/@Rabbid76/PyGame-Text
import pygame
pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
window.blit(text, text.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
Minimal pygame.freetype
example: repl.it/@Rabbid76/PyGame-FreeTypeText
import pygame
import pygame.freetype
pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()
ft_font = pygame.freetype.SysFont('Times New Roman', 80)
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
text_rect = ft_font.get_rect('Hello World')
text_rect.center = window.get_rect().center
ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
pygame.display.flip()
pygame.quit()
exit()
packed
means it will use the smallest possible space for struct Ball
- i.e. it will cram fields together without paddingaligned
means each struct Ball
will begin on a 4 byte boundary - i.e. for any struct Ball
, its address can be divided by 4These are GCC extensions, not part of any C standard.
"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.
You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).
round(float('23.45678'))
In your 'head' section, add this code:
<style>
input[type='text'] { font-size: 24px; }
</style>
Or you can only add the:
input[type='text'] { font-size: 24px; }
to a CSS file which can later be included.
You can also change the font face by using the CSS property: font-family
font-family: monospace;
So you can have a CSS code like this:
input[type='text'] { font-size: 24px; font-family: monospace; }
You can find further help at the W3Schools website.
I suggest you to have a look at the CSS3 specification. With CSS3 you can also load a font from the web instead of having the limitation to use only the most common fonts or tell the user to download the font you're using.
If you only need to merge a particular directory and leave everything else intact and yet preserve history, you could possibly try this... create a new target-branch
off of the master
before you experiment.
The steps below assume you have two branches target-branch
and source-branch
, and the directory dir-to-merge
that you want to merge is in the source-branch
. Also assume you have other directories like dir-to-retain
in the target that you don't want to change and retain history. Also, assumes there are merge conflicts in the dir-to-merge
.
git checkout target-branch
git merge --no-ff --no-commit -X theirs source-branch
# the option "-X theirs", will pick theirs when there is a conflict.
# the options "--no--ff --no-commit" prevent a commit after a merge, and give you an opportunity to fix other directories you want to retain, before you commit this merge.
# the above, would have messed up the other directories that you want to retain.
# so you need to reset them for every directory that you want to retain.
git reset HEAD dir-to-retain
# verify everything and commit.
Just to fix the error to set current time
from django.utils import timezone
import datetime
datetime.datetime.now(tz=timezone.utc) # you can use this value
If you are using on the same domain then you can create a seperate HTML file and then import this using the code from this answer by @Stano :
The private key file should be protected. In my case i have been using the public_key authentication for a long time and i used to set the permission as 600 (rw- --- ---) for private key and 644 (rw- r-- r--) and for the .ssh folder in the home folder you will have 700 permission (rwx --- ---). For setting this go to the user's home folder and run the following command
Set the 700 permission for .ssh folder
chmod 700 .ssh
Set the 600 permission for private key file
chmod 600 .ssh/id_rsa
Set 644 permission for public key file
chmod 644 .ssh/id_rsa.pub
You can use the toolbarHeight property of Appbar, it does exactly what you want.
To Extend on @Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
I just tried the same and came up with following solution:
public enum Countries {
TEXAS,
FLORIDA,
OKLAHOMA,
KENTUCKY;
private static Countries[] list = Countries.values();
public static Countries getCountry(int i) {
return list[i];
}
public static int listGetLastIndex() {
return list.length - 1;
}
}
The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:
public static String getCountry(int i) {
return list[(i - 1)];
}
public static int listGetLastIndex() {
return list.length;
}
Inside my Main I get the needed countries-object with
public static void main(String[] args) {
int i = Countries.listGetLastIndex();
Countries currCountry = Countries.getCountry(i);
}
which sets currCountry to the last country, in this case Countries.KENTUCKY.
Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.
By setting you'd use setValue:(id)value forKey:(id)key
method of NSMutableDictionary
object:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[NSNumber numberWithInt:5] forKey:@"age"];
Or in modern Objective-C:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"age"] = @5;
The difference between mutable and "normal" is, well, mutability. I.e. you can alter the contents of NSMutableDictionary
(and NSMutableArray
) while you can't do that with "normal" NSDictionary
and NSArray
You are copying singleton's customVar
into a singletonVar
variable and changing that variable does not affect the original value in singleton.
// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;
On EF6.2, you can use HasIndex()
to add indexes for migration through fluent API.
https://github.com/aspnet/EntityFramework6/issues/274
Example
modelBuilder
.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
On EF6.1 onwards, you can use IndexAnnotation()
to add indexes for migration in your fluent API.
http://msdn.microsoft.com/en-us/data/jj591617.aspx#PropertyIndex
You must add reference to:
using System.Data.Entity.Infrastructure.Annotations;
Basic Example
Here is a simple usage, adding an index on the User.FirstName
property
modelBuilder
.Entity<User>()
.Property(t => t.FirstName)
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
Practical Example:
Here is a more realistic example. It adds a unique index on multiple properties: User.FirstName
and User.LastName
, with an index name "IX_FirstNameLastName"
modelBuilder
.Entity<User>()
.Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(60)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("IX_FirstNameLastName", 1) { IsUnique = true }));
modelBuilder
.Entity<User>()
.Property(t => t.LastName)
.IsRequired()
.HasMaxLength(60)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("IX_FirstNameLastName", 2) { IsUnique = true }));
If you are using a webkit browser you can change the color of the caret by following the next CSS snippet. I'm not sure if It's possible to change the format with CSS.
input,
textarea {
font-size: 24px;
padding: 10px;
color: red;
text-shadow: 0px 0px 0px #000;
-webkit-text-fill-color: transparent;
}
input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
color:
text-shadow: none;
-webkit-text-fill-color: initial;
}
Here is an example: http://jsfiddle.net/8k1k0awb/
It turns out I didn't have Microsoft visual c++ installed, installing it solved the problem for me.
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
Windows 10 ((Version 1511, build 10586, release 2015-11-10)) supports ANSI colors.
You can use the escape key to trigger the color codes.
In the Command Prompt:
echo ^[[32m HI ^[[0m
echo Ctrl+[[32m HI
Ctrl+[[0m
Enter
When using a text editor, you can use ALT key codes.
The ESC key code can be created using ALT and NUMPAD numbers : Alt+027
[32m HI [0m
Something that just happened to me and caused me some headaches:
I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).
The script had several of those "code" blocks:
rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"
Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.
Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.
... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:
rabbitmqctl change_password test test
(Another solution would have been to delete all users and then call the script again)
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
when I create my JLabel and enter the text to it, there is no wordwrap or anything
HTML formatting can be used to cause word wrap in any Swing component that offers styled text. E.G. as demonstrated in this answer.
I had to delete the
C:\Users{username}\AppData\Local\JetBrains folder. Then is was able to enable the shorcuts again.
Follow the link https://datatables.net/blog/2014-12-18
A very easy way to integrate ordering by date.
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script>
Put this code in before initializing the datatable:
$(document).ready(function () {
// ......
$.fn.dataTable.moment('DD-MMM-YY HH:mm:ss');
$.fn.dataTable.moment('DD.MM.YYYY HH:mm:ss');
// And any format you need
}
Use getpass.getpass()
:
from getpass import getpass
password = getpass()
An optional prompt can be passed as parameter; the default is "Password: "
.
Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.
If you use JetBrains based IDE like IntelliJ Idea and prefare using GUI over command line:
That's it. You uncommited all your changes. Now if you'll make a new commit it will be squashed
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellId = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
NSInteger lastRowIndexInSection = [tableView numberOfRowsInSection:indexPath.section] - 1;
if (row == lastRowIndexInSection) {
CGFloat halfWidthOfCell = cell.frame.size.width / 2;
cell.separatorInset = UIEdgeInsetsMake(0, halfWidthOfCell, 0, halfWidthOfCell);
}
}
Come on guys, there is no need to loop, just use simple math to solve this equation system:
a*b = i;
a+b = j;
a = j/b;
a = i-b;
j/b = i-b; so:
b + j/b + i = 0
b^2 + i*b + j = 0
From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.
EDIT:
There you go:
function finder($add,$product)
{
$inside_root = $add*$add - 4*$product;
if($inside_root >=0)
{
$b = ($add + sqrt($inside_root))/2;
$a = $add - $b;
echo "$a+$b = $add and $a*$b=$product\n";
}else
{
echo "No real solution\n";
}
}
Real live action:
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
Don't do this! Really, not a good idea.
If you know which tables you want to truncate, create a stored procedure which truncates them. You can fix the order to avoid foreign key problems.
If you really want to truncate them all (so you can BCP load them for example) you would be just as quick to drop the database and create a new one from scratch, which would have the additional benefit that you know exactly where you are.
You can also use string.match().
var string1 = "aBc";
var match = string1.match(/AbC/i);
if(match) {
}
ngOnInit()
is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
ngAfterViewInit()
is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.
I like @jesterjunk answer, however, a number is not always just digits. Consider those valid numbers: "123.5, 123,567.789, 12233234+E12"
So I just updated the regular expression:
var regex = /[\d|,|.|e|E|\+]+/g;
var string = "you can enter maximum 5,123.6 choices";
var matches = string.match(regex); // creates array from matches
document.write(matches); //5,123.6
(I know the question is old, but I think this might be good as a reference for people with similar questions)
If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:
If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load: