Given a function you'd like to time,
test.py:
def foo():
# print "hello"
return "hello"
the easiest way to use timeit
is to call it from the command line:
% python -mtimeit -s'import test' 'test.foo()'
1000000 loops, best of 3: 0.254 usec per loop
Do not try to use time.time
or time.clock
(naively) to compare the speed of functions. They can give misleading results.
PS. Do not put print statements in a function you wish to time; otherwise the time measured will depend on the speed of the terminal.
Just to highlight @Darkonaut answer because I think it should be more visible.
new_list = []
or new_list = list()
are both fine (ignoring performance), but append()
returns None
, as result you can't do new_list = new_list.append(something)
.
Another simple timeit example:
def your_function_to_test():
# do some stuff...
time_to_run_100_times = timeit.timeit(lambda: your_function_to_test, number=100)
simply pass your entire code as an argument of timeit:
import timeit
print(timeit.timeit(
"""
limit = 10000
prime_list = [i for i in range(2, limit+1)]
for prime in prime_list:
for elem in range(prime*2, max(prime_list)+1, prime):
if elem in prime_list:
prime_list.remove(elem)
"""
, number=10))
You can use dialog.setCanceledOnTouchOutside(true);
which will close the dialog if you touch outside of the dialog.
Something like,
Dialog dialog = new Dialog(context)
dialog.setCanceledOnTouchOutside(true);
Or if your Dialog in non-model then,
1 - Set the flag-FLAG_NOT_TOUCH_MODAL
for your dialog's window attribute
Window window = this.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
2 - Add another flag to windows properties,, FLAG_WATCH_OUTSIDE_TOUCH
- this one is for dialog to receive touch event outside its visible region.
3 - Override onTouchEvent()
of dialog and check for action type. if the action type is
'MotionEvent.ACTION_OUTSIDE
' means, user is interacting outside the dialog region. So in this case, you can dimiss your dialog or decide what you wanted to perform.
view plainprint?
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_OUTSIDE){
System.out.println("TOuch outside the dialog ******************** ");
this.dismiss();
}
return false;
}
For more info look at How to dismiss a custom dialog based on touch points? and How to dismiss your non-modal dialog, when touched outside dialog region
This should work for SQL Server:
SELECT * FROM myTable
WHERE month = DATEPART(m, GETDATE()) AND
year = DATEPART(yyyy, GETDATE())
At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut
is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.
System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));
If you're after a promise-based solution, this is @Dmitri's code adapted for that:
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
data => console.log(data)
);
latest
is really designed to work with date fields (it probably does work with other total-ordered types too, but not sure). And the only way you can use it without specifying the field name is by setting the get_latest_by
meta attribute, as mentioned here.
Key differences:
C++ is a general-purpose programming language, but is developed from the originally C programming language. It was developed by Bjarne Stroustrup at Bell Labs starting in 1979. C++ was originally named C with Classes. It was renamed C++ in 1983.
Visual C++, on the other hand, is not a programming language at all. It is in fact a development environment. It is an “integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages.” Microsoft Visual C++, also known as MSVC or VC++, is sold as part of the Microsoft Visual Studio app.
I was finally able to figure out the issue. I had to change some settings in mysql configuration my.ini This article helped a lot http://mathiasbynens.be/notes/mysql-utf8mb4#character-sets
First i changed the character set in my.ini to utf8mb4 Next i ran the following commands in mysql client
SET NAMES utf8mb4;
ALTER DATABASE dreams_twitter CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
Use the following command to check that the changes are made
SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';
In my case, I modified directory tag.
From
<Directory "D:/Devel/matysart/matysart_dev1">
Allow from all
Order Deny,Allow
</Directory>
To
<Directory "D:/Devel/matysart/matysart_dev1">
Require local
</Directory>
And it seriously worked. It's seems changed with Apache 2.4.2.
For even more robustness:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
and
...
var el = document.getElementById('targetFrame');
var frame_win = getIframeWindow(el);
if (frame_win) {
frame_win.targetFunction();
...
}
...
(SELECT ename FROM EMP WHERE empno = mgr)
There are no records in EMP that meet this criteria.
You need to self-join to get this relation.
SELECT e.ename AS Employee, e.empno, m.ename AS Manager, m.empno
FROM EMP AS e LEFT OUTER JOIN EMP AS m
ON e.mgr =m.empno;
EDIT:
The answer you selected will not list your president because it's an inner join. I'm thinking you'll be back when you discover your output isn't what your (I suspect) homework assignment required. Here's the actual test case:
> select * from emp;
empno | ename | job | deptno | mgr
-------+-------+-----------+--------+------
7839 | king | president | 10 |
7698 | blake | manager | 30 | 7839
(2 rows)
> SELECT e.ename employee, e.empno, m.ename manager, m.empno
FROM emp AS e LEFT OUTER JOIN emp AS m
ON e.mgr =m.empno;
employee | empno | manager | empno
----------+-------+---------+-------
king | 7839 | |
blake | 7698 | king | 7839
(2 rows)
The difference is that an outer join returns all the rows. An inner join will produce the following:
> SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM emp e, emp m
WHERE e.mgr = m.empno;
ename | empno | manager | mgr
-------+-------+---------+------
blake | 7698 | king | 7839
(1 row)
The above answers are good, except they don't have proper tick placement on the colorbar. I like having the ticks in the middle of the color so that the number -> color mapping is more clear. You can solve this problem by changing the limits of the matshow call:
import matplotlib.pyplot as plt
import numpy as np
def discrete_matshow(data):
#get discrete colormap
cmap = plt.get_cmap('RdBu', np.max(data)-np.min(data)+1)
# set limits .5 outside true range
mat = plt.matshow(data,cmap=cmap,vmin = np.min(data)-.5, vmax = np.max(data)+.5)
#tell the colorbar to tick at integers
cax = plt.colorbar(mat, ticks=np.arange(np.min(data),np.max(data)+1))
#generate data
a=np.random.randint(1, 9, size=(10, 10))
discrete_matshow(a)
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>
There's also MSMQ (Microsoft Message Queueing) which can operate across networks as well as on a local computer. Although there are better ways to communicate it's worth looking into: https://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx
This May be helpful:
//I personally prefer dynamic import (angular 8)
{ path: 'pages', loadChildren: () => import('./pages/pages.module').then(mod => mod.PageModule) }
In child routing it should look like: { path: 'about', component: AboutComponent },
Note that there is no pages
in path of child routing and in routerLink
or nsRouterLink
it should look like routerLink="/pages/about"
I hope thi help someone out there.
In MAMP, You could load huge files by :
creating a new folder in this directory /MAMP/bin/phpMyAdmin/"folderName"
and then edit "/MAMP/bin/phpMyAdmin/config.inc.php" line 531 :
$cfg['UploadDir']= 'folderName';
Copy your .sql or .csv Files into this folder.
Now you will have another option in "PhpMyAdmin" : Select from the web server upload directory newFolder/: You could select your file and import it.
You could load any file now !!
One thing to be mindful of is setting strings then referring back to them. You have to make sure the quotes aren't colliding.
set start_date = '2019-01-21';
select ${hiveconf:start_date};
When setting dates then referring to them in code as the strings can conflict. This wouldn't work with the start_date set above.
'${hiveconf:start_date}'
We have to be mindful of not setting twice single or double quotes for strings when referring back to them in the query.
Diagnose
Look up the following inside your script file
phpinfo();
If you can't find Soap Client
set to enabled
like so:
Fix
Do the following:
php.ini
in your apache bin folder, I.e Apache/bin/php.ini
;
from the beginning of extension=php_soap.dll
phpinfo();
again and check if you see a similar picture to the one aboveOn the other hand if this doesn't solve your issue, you may want to check the requirements for SOAP here. Also in the comment section you can find good advice on connecting to https.
You could try the following:
import matplotlib.pyplot as plt
import numpy as np
def plot_figures(figures, nrows = 1, ncols=1):
"""Plot a dictionary of figures.
Parameters
----------
figures : <title, figure> dictionary
ncols : number of columns of subplots wanted in the display
nrows : number of rows of subplots wanted in the figure
"""
fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
for ind,title in zip(range(len(figures)), figures):
axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
axeslist.ravel()[ind].set_title(title)
axeslist.ravel()[ind].set_axis_off()
plt.tight_layout() # optional
# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}
# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)
plt.show()
However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.
I hope this helps.
You'll need to either insert BR
tag appropriately in the resulting string, or use for example a PRE
tag so that the formatting of the stringify
is retained:
var data = { a: 1, b: 2 };
var Hello = React.createClass({
render: function() {
return <div><pre>{JSON.stringify(data, null, 2) }</pre></div>;
}
});
React.render(<Hello />, document.getElementById('container'));
class PrettyPrintJson extends React.Component {
render() {
// data could be a prop for example
// const { data } = this.props;
return (<div><pre>{JSON.stringify(data, null, 2) }</pre></div>);
}
}
ReactDOM.render(<PrettyPrintJson/>, document.getElementById('container'));
const PrettyPrintJson = ({data}) => {
// (destructured) data could be a prop for example
return (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>);
}
Or, ...
const PrettyPrintJson = ({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>);
(You might even want to use a memo, 16.6+)
const PrettyPrintJson = React.memo(({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>));
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
There's no easy way to do this, but something like this will work:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
See man git-add
:
-f, --force
Allow adding otherwise ignored files.
So run this
git add --force my/ignore/file.foo
If, like me, you're running gVim on Windows then your .vimrc file may be sourcing another 'example' Vimscript file that automatically sets textwidth
(in my case to 78
) for text files.
My answer to a similar question as this one – How to stop gVim wrapping text at column 80 – on the Vi and Vim Stack Exchange site:
In my case, Vitor's comment suggested I run the following:
:verbose set tw?
Doing so gave me the following output:
textwidth=78 Last set from C:\Program Files (x86)\Vim\vim74\vimrc_example.vim
In vimrc_example.vim, I found the relevant lines:
" Only do this part when compiled with support for autocommands. if has("autocmd") ... " For all text files set 'textwidth' to 78 characters. autocmd FileType text setlocal textwidth=78 ...
And I found that my .vimrc is sourcing that file:
source $VIMRUNTIME/vimrc_example.vim
In my case, I don't want
textwidth
to be set for any files, so I just commented out the relevant line in vimrc_example.vim.
I just deleted the existing DB that i wanted to override with the backup and restored it from backup and it worked without the error.
Try creating a duplicate table, preferably a temporary table, without the unique constraint and do your bulk load into that table. Then select only the unique (DISTINCT) items from the temporary table and insert into the target table.
res.json
forces the argument to JSON. res.send
will take an non-json object or non-json array and send another type. For example:
This will return a JSON number.
res.json(100)
This will return a status code and issue a warning to use sendStatus.
res.send(100)
If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json
.
I would like to contribute this code as an structural solution for the question posed, according (I hope so) to the accepted answer. (You can very easily customize it).
// ------------------------------------------------------
// server.js
// .......................................................
// requires
var fs = require('fs');
var express = require('express');
var myBusinessLogic = require('../businessLogic/businessLogic.js');
// .......................................................
// security options
/*
1. Generate a self-signed certificate-key pair
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out certificate.pem
2. Import them to a keystore (some programs use a keystore)
keytool -importcert -file certificate.pem -keystore my.keystore
*/
var securityOptions = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('certificate.pem'),
requestCert: true
};
// .......................................................
// create the secure server (HTTPS)
var app = express();
var secureServer = require('https').createServer(securityOptions, app);
// ------------------------------------------------------
// helper functions for auth
// .............................................
// true if req == GET /login
function isGETLogin (req) {
if (req.path != "/login") { return false; }
if ( req.method != "GET" ) { return false; }
return true;
} // ()
// .............................................
// your auth policy here:
// true if req does have permissions
// (you may check here permissions and roles
// allowed to access the REST action depending
// on the URI being accessed)
function reqHasPermission (req) {
// decode req.accessToken, extract
// supposed fields there: userId:roleId:expiryTime
// and check them
// for the moment we do a very rigorous check
if (req.headers.accessToken != "you-are-welcome") {
return false;
}
return true;
} // ()
// ------------------------------------------------------
// install a function to transparently perform the auth check
// of incoming request, BEFORE they are actually invoked
app.use (function(req, res, next) {
if (! isGETLogin (req) ) {
if (! reqHasPermission (req) ){
res.writeHead(401); // unauthorized
res.end();
return; // don't call next()
}
} else {
console.log (" * is a login request ");
}
next(); // continue processing the request
});
// ------------------------------------------------------
// copy everything in the req body to req.body
app.use (function(req, res, next) {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
// ------------------------------------------------------
// REST requests
// ------------------------------------------------------
// .......................................................
// authenticating method
// GET /login?user=xxx&password=yyy
app.get('/login', function(req, res){
var user = req.query.user;
var password = req.query.password;
// rigorous auth check of user-passwrod
if (user != "foobar" || password != "1234") {
res.writeHead(403); // forbidden
} else {
// OK: create an access token with fields user, role and expiry time, hash it
// and put it on a response header field
res.setHeader ('accessToken', "you-are-welcome");
res.writeHead(200);
}
res.end();
});
// .......................................................
// "regular" methods (just an example)
// newBook()
// PUT /book
app.put('/book', function (req,res){
var bookData = JSON.parse (req.body);
myBusinessLogic.newBook(bookData, function (err) {
if (err) {
res.writeHead(409);
res.end();
return;
}
// no error:
res.writeHead(200);
res.end();
});
});
// .......................................................
// "main()"
secureServer.listen (8081);
This server can be tested with curl:
echo "---- first: do login "
curl -v "https://localhost:8081/login?user=foobar&password=1234" --cacert certificate.pem
# now, in a real case, you should copy the accessToken received before, in the following request
echo "---- new book"
curl -X POST -d '{"id": "12341324", "author": "Herman Melville", "title": "Moby-Dick"}' "https://localhost:8081/book" --cacert certificate.pem --header "accessToken: you-are-welcome"
Winston is a pretty good logging library. You can write logs out to a file using it.
Code would look something like:
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
],
exitOnError: false
});
module.exports = logger;
You can then use this like:
var logger = require('./log');
logger.info('log to file');
When you specify the -Force
flag, PowerShell will not complain if the folder already exists.
One-liner:
Get-ChildItem D:\TopDirec\SubDirec\Project* | `
%{ Get-ChildItem $_.FullName -Filter Revision* } | `
%{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") }
BTW, for scheduling the task please check out this link: Scheduling Background Jobs.
You can convert to a Double[]
by calling frameList.toArray(new Double[frameList.size()])
, but you'll need to iterate the list/array to convert to double[]
Just adding to the solutions already suggested. Assumes same height, no resizing.
import sys
import glob
from PIL import Image
Image.MAX_IMAGE_PIXELS = 100000000 # For PIL Image error when handling very large images
imgs = [ Image.open(i) for i in list_im ]
widths, heights = zip(*(i.size for i in imgs))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
# Place first image
new_im.paste(imgs[0],(0,0))
# Iteratively append images in list horizontally
hoffset=0
for i in range(1,len(imgs),1):
**hoffset=imgs[i-1].size[0]+hoffset # update offset**
new_im.paste(imgs[i],**(hoffset,0)**)
new_im.save('output_horizontal_montage.jpg')
We do a lot of work where we need to figure out which IP's are within certain subnets. I've found that the simplest and most reliable way to do this is:
ALTER FUNCTION [dbo].[IP_To_INT ]
(
@IP CHAR(15)
)
RETURNS BIGINT
AS
BEGIN
DECLARE @IntAns BIGINT,
@block1 BIGINT,
@block2 BIGINT,
@block3 BIGINT,
@block4 BIGINT,
@base BIGINT
SELECT
@block1 = CONVERT(BIGINT, PARSENAME(@IP, 4)),
@block2 = CONVERT(BIGINT, PARSENAME(@IP, 3)),
@block3 = CONVERT(BIGINT, PARSENAME(@IP, 2)),
@block4 = CONVERT(BIGINT, PARSENAME(@IP, 1))
IF (@block1 BETWEEN 0 AND 255)
AND (@block2 BETWEEN 0 AND 255)
AND (@block3 BETWEEN 0 AND 255)
AND (@block4 BETWEEN 0 AND 255)
BEGIN
SET @base = CONVERT(BIGINT, @block1 * 16777216)
SET @IntAns = @base +
(@block2 * 65536) +
(@block3 * 256) +
(@block4)
END
ELSE
SET @IntAns = -1
RETURN @IntAns
END
In terminal run this command in the folder where the systlesheets are:
sass --watch style.scss:style.css
Source:
When ever it notices a change in the .scss
file it will update your .css
This only works when your .scss
is on your local machine. Try copying the code to a file and running it locally.
When you have two or more windows open horizontally or vertically and want to switch them all to the other orientation, you can use the following:
(switch to horizontal)
:windo wincmd K
(switch to vertical)
:windo wincmd H
It's effectively going to each window individually and using ^WK or ^WH.
If g++
still gives error Try using:
g++ file.c -lstdc++
Look at this post: What is __gxx_personality_v0 for?
Make sure -lstdc++
is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.
Strongly typed means that there are restrictions between conversions between types.
Statically typed means that the types are not dynamic - you can not change the type of a variable once it has been created.
It was easier to implement it only with one line of code:
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
You can use sklearn.preprocessing:
from sklearn.preprocessing import normalize
data = np.array([
[1000, 10, 0.5],
[765, 5, 0.35],
[800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1. 1. 1. ]
[ 0.765 0.5 0.7 ]
[ 0.8 0.7 0.18 ]]
In your main.js file, you have to import Vue like this :
import Vue from 'vue'
Then you have to declare your global variable in the main.js file like this :
Vue.prototype.$actionButton = 'Not Approved'
If you want to change the value of the global variable from another component, you can do it like this :
Vue.prototype.$actionButton = 'approved'
https://vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example
When you use string literals, such as "this is a string"
and in your case "sssss"
and "kkkk"
, the compiler puts them in read-only memory. However, strcat
attempts to write the second argument after the first. You can solve this problem by making a sufficiently sized destination buffer and write to that.
char destination[10]; // 5 times s, 4 times k, one zero-terminator
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
strcpy(destination, str1);
printf("%s",strcat(destination,str2));
Note that in recent compilers, you usually get a warning for casting string literals to non-const character pointers.
Keep scroll position by using @DawnYu answer to wrap notifyDataSetChanged()
like this:
val recyclerViewState = recyclerView.layoutManager?.onSaveInstanceState()
adapter.notifyDataSetChanged()
recyclerView.layoutManager?.onRestoreInstanceState(recyclerViewState)
The problem id because of inp.read();
method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.
What you can do simply
for(int i=0;i<T;i++) {
String s= inp.readLine();
String[] intValues = inp.readLine().split(" ");
int[] m= new int[2];
m[0]=Integer.parseInt(intValues[0]);
m[1]=Integer.parseInt(intValues[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
}
I am using Angular 5.2 and RxJS 5.5.6
This code did not work:
import { Observable,of } from 'rxjs/Observable';
getHeroes(): Observable<Hero[]> {
return of(Hero[]) HEROES;
}
Below code worked:
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
getHeroes(): Observable<Hero[]>
{
return Observable.create((observer: Subscriber<any>) => {
observer.next(HEROES);
observer.complete();
});
}
Calling method:
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
I think they might moved/changed of() functionality in RxJS 5.5.2
I know this is an old thread, but there is a particular case when this may happen:
If you are using AWS api gateway coupled with a VPC link, and if the Network Load Balancer has proxy protocol v2 enabled, a 400 Bad Request will happen as well.
Took me the whole afternoon to figure it out, so if it may help someone I'd be glad :)
For dynamic SQL use:
'IN(' ||array_to_string(some_array, ',')||')'
DO LANGUAGE PLPGSQL $$
DECLARE
some_array bigint[];
sql_statement text;
BEGIN
SELECT array[1, 2] INTO some_array;
RAISE NOTICE '%', some_array;
sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
RAISE NOTICE '%', sql_statement;
END;
$$;
Result:
NOTICE: {1,2}
NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)
Another way of accomplishing this is using animation
which provides more control.
#content #nav a {
background-color: #FF0;
/* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
animation-duration: 1s; /* same as transition duration */
animation-timing-function: linear; /* kind of same as transition timing */
animation-delay: 0ms; /* same as transition delay */
animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
animation-play-state: running; /* can be set dynamically to pause mid animation*/
/* declaring the states of the animation to transition through */
/* optionally add other properties that will change here, or new states (50% etc) */
@keyframes onHoverAnimation {
0% {
background-color: #FF0;
}
100% {
background-color: #AD310B;
}
}
}
#content #nav a:hover {
/* animation wont run unless the element is given the name of the animation. This is set on hover */
animation-name: onHoverAnimation;
}
Just had a look at the DOM (document.scripts[1].attributes) of this page that uses google analytics. I can tell you that google is using async="".
[type="text/javascript", async="", src="http://www.google-analytics.com/ga.js"]
The accepted answer works but can got complicated when I wanted to try adding Accept headers. This is what I ended up with. It seems simpler to me so I think I'll stick with it in the future:
client.DefaultRequestHeaders.Add("Accept", "application/*+xml;version=5.1");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + authstring);
You can't access java objects from JavaScript because there are no objects on client side. It only receives plain HTML page (hidden fields can help but it's not very good approach).
I suggest you to use ajax and @ResponseBody
.
Method 1:
If the method DoSomethingBeta was static you need only call:
Beta.DoSomethingBeta();
Method 2:
If Alpha extends from Beta you could call DoSomethingBeta() directly.
public class Alpha extends Beta{
public void DoSomethingAlpha() {
DoSomethingBeta(); //?
}
}
Method 3:
Alternatively you need to have access to an instance of Beta to call the methods from it.
public class Alpha {
public void DoSomethingAlpha() {
Beta cbeta = new Beta();
cbeta.DoSomethingBeta(); //?
}
}
Incidentally is this homework?
I copied the dynamic Webproject before the issue came up. So, changing the org.eclipse.wst.common.component file in the .settings directory solved the issue for me. The other solutions did not work.
If you prefer a non-object-oriented approach, move plt.xticks(rotation=70)
to right before the two avail_plot
calls, eg
plt.xticks(rotation=70)
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
This sets the rotation property before setting up the labels. Since you have two axes here, plt.xticks
gets confused after you've made the two plots. At the point when plt.xticks
doesn't do anything, plt.gca()
does not give you the axes you want to modify, and so plt.xticks
, which acts on the current axes, is not going to work.
For an object-oriented approach not using plt.xticks
, you can use
plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )
after the two avail_plot
calls. This sets the rotation on the correct axes specifically.
If you're in Rails, .blank?
should be the method you are looking for:
a = nil
b = []
c = ""
a.blank? #=> true
b.blank? #=> true
c.blank? #=> true
d = "1"
e = ["1"]
d.blank? #=> false
e.blank? #=> false
So the answer would be:
variable = id if variable.blank?
Although both versions of the specific example are equivalent, as already mentioned in the other answers, there is still one small difference between them. The first version includes an unnecessary implicit barrier, encountered at the end of the "omp for". The other implicit barrier can be found at the end of the parallel region. Adding "nowait" to "omp for" would make the two codes equivalent, at least from an OpenMP perspective. I mention this because an OpenMP compiler could generate slightly different code for the two cases.
Here is my solution to smooth scroll to div / anchor using jQuery in case you have a fixed header so that it doesn't scroll underneath it. Also it works if you link it from other page.
Just replace ".site-header" to div that contains your header.
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: (target.offset().top - headerheight)
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - headerheight
}, 1);
return false;
}
}
});
<?php
if(!@mysql_connect('127.0.0.1', 'root', '*your default password*'))
{
echo "mysql not connected ".mysql_error();
exit;
}
echo 'great work';
?>
if no error then you will get greatwork as output.
Try it saved my life XD XD
I think you have to write your own filter for that. It's actually the example for custom filters in the documentation: http://jinja.pocoo.org/docs/api/#custom-filters
Using the Date object's methods will could come in handy.
e.g.:
myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));
That seems to work for me:
<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>
The expected behaviour is to change the colour of the word "fruit".
Perhaps your document was not fully loaded when you called the routine?
Pass in the straight XML instead of a dictionary.
Passing params
GET request to "/cars/honda"
returns a list of Honda car models
Passing query
GET request to "/car/honda?color=blue"
returns a list of Honda car models, but filtered so only models with an stock color of blue are returned.
It doesn't make sense to add those filters into the URL parameters (/car/honda/color/blue) because according to REST, that would imply that we want to get a bunch of information about the color "blue". Since what we really want is a filtered list of Honda models, we use query strings to filter down the results that get returned.
Notice that the query strings are really just { key: value } pairs in a slightly different format: ?key1=value1&key2=value2&key3=value3.
add label
to subview
of custom view
, no need of self.view.addSubview(view)
, because viewForHeaderInSection
return the UIView
view.addSubview(label)
For interpolated strings:
$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"
If the intention of the question is to view the contents of the JAR file, then the following java command would help.. (provided, JDK location is added to the environment variables.)
Windows Command prompt> jar tvf yourJarFile.jar
Example:
jar tvf log4j-extras-1.2.17.jar
Reference: http://docs.oracle.com/javase/tutorial/deployment/jar/view.html
Now that we have Java 8/streams, we can add one more possible answer to the list:
Assuming that each of the values actually are String
objects, the cast to String
should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.
Map<String,Object> map = new HashMap<>();
Map<String,String> newMap = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
The dot character means match any character, so .*
means zero or more occurrences of any character. You probably mean to use .*
rather than just *
.
**
operator would be helpful here.
**
operator will unpack the dict elements and thus **{'type':'Event'}
would be treated as type='Event'
func(**{'type':'Event'})
is same as func(type='Event')
i.e the dict elements would be converted to the keyword arguments
.
FYI
*
will unpack the list elements and they would be treated as positional arguments
.
func(*['one', 'two'])
is same as func('one', 'two')
If start
can't find what it's looking for, it does what you describe.
Since what you're doing should work, it's very likely you're leaving out some quotes (or putting extras in).
I had the same problem. You could also check which way the slash is pointing. For me it worked to use backslash, instead of forward slash. Example
xcopy /s /y "C:\SFML\bin\*.dll" "$(OutDir)"
Instead of:
xcopy /s /y "C:/SFML/bin/*.dll" "$(OutDir)"
You can use following queries
Users whose Logon Name(Pre-Windows 2000) is equal to John
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(sAMAccountName=**John**))
All Users
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370))
Enabled Users
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(!userAccountControl:1.2.840.113556.1.4.803:=2))
Disabled Users
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(userAccountControl:1.2.840.113556.1.4.803:=2))
LockedOut Users
(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(lockouttime>=1))
select table_name
from information_schema.columns
where COLUMN_NAME = 'MyColumn'
The technique we use at work is to request the javascript file using an AJAX request and then eval() the return. If you're using the prototype library, they support this functionality in their Ajax.Request call.
Just in case someone else is recently getting into this same issue, I'm using React Native 0.59.8 (tested with RN 0.60 as well) and I can confirm some of the other answers, here are the steps:
Uninstall the latest compiled version of your app installed you have on your device
Run react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
run cd android/ && ./gradlew assembleDebug
Get your app-debug.apk in folder android/app/build/outputs/apk/debug
good luck!
Try SuperPuTTY. It is similar to puttycm.
If you're using the command console to compile the servlet, then you should include Tomcat's /lib/servlet-api.jar
in the compile classpath.
javac -cp .:/path/to/tomcat/lib/servlet-api.jar com/example/MyServlet.java
(use ;
instead of :
as path separator in Windows)
If you're using an IDE, then you should integrate Tomcat in the IDE and reference it as target runtime in the project. If you're using Eclipse as IDE, see also this for more detail: How do I import the javax.servlet API in my Eclipse project?
Doing it as a stored procedure does have lot of advantages. You can get the sequence that is inserted into the table using syntax insert into table_name values returning
.
Like:
declare
some_seq_val number;
lv_seq number;
begin
some_seq_val := your_seq.nextval;
insert into your_tab (col1, col2, col3)
values (some_seq_val, val2, val3) returning some_seq_val into lv_seq;
dbms_output.put_line('The inserted sequence is: '||to_char(lv_seq));
end;
/
Or just return some_seq_val
. In case you are not making use of SEQUENCE, and arriving the sequence on some calculation, you can make use of returning into
effectively.
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
The following code is my WCF named pipes solution to register a single-instance application. It's nice because it also raises an event when another instance attempts to start, and receives the command line of the other instance.
It's geared toward WPF because it uses the System.Windows.StartupEventHandler
class, but this could be easily modified.
This code requires a reference to PresentationFramework
, and System.ServiceModel
.
Usage:
class Program
{
static void Main()
{
var applicationId = new Guid("b54f7b0d-87f9-4df9-9686-4d8fd76066dc");
if (SingleInstanceManager.VerifySingleInstance(applicationId))
{
SingleInstanceManager.OtherInstanceStarted += OnOtherInstanceStarted;
// Start the application
}
}
static void OnOtherInstanceStarted(object sender, StartupEventArgs e)
{
// Do something in response to another instance starting up.
}
}
/// <summary>
/// A class to use for single-instance applications.
/// </summary>
public static class SingleInstanceManager
{
/// <summary>
/// Raised when another instance attempts to start up.
/// </summary>
public static event StartupEventHandler OtherInstanceStarted;
/// <summary>
/// Checks to see if this instance is the first instance running on this machine. If it is not, this method will
/// send the main instance this instance's startup information.
/// </summary>
/// <param name="guid">The application's unique identifier.</param>
/// <returns>True if this instance is the main instance.</returns>
public static bool VerifySingleInstace(Guid guid)
{
if (!AttemptPublishService(guid))
{
NotifyMainInstance(guid);
return false;
}
return true;
}
/// <summary>
/// Attempts to publish the service.
/// </summary>
/// <param name="guid">The application's unique identifier.</param>
/// <returns>True if the service was published successfully.</returns>
private static bool AttemptPublishService(Guid guid)
{
try
{
ServiceHost serviceHost = new ServiceHost(typeof(SingleInstance));
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
serviceHost.AddServiceEndpoint(typeof(ISingleInstance), binding, CreateAddress(guid));
serviceHost.Open();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Notifies the main instance that this instance is attempting to start up.
/// </summary>
/// <param name="guid">The application's unique identifier.</param>
private static void NotifyMainInstance(Guid guid)
{
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
EndpointAddress remoteAddress = new EndpointAddress(CreateAddress(guid));
using (ChannelFactory<ISingleInstance> factory = new ChannelFactory<ISingleInstance>(binding, remoteAddress))
{
ISingleInstance singleInstance = factory.CreateChannel();
singleInstance.NotifyMainInstance(Environment.GetCommandLineArgs());
}
}
/// <summary>
/// Creates an address to publish/contact the service at based on a globally unique identifier.
/// </summary>
/// <param name="guid">The identifier for the application.</param>
/// <returns>The address to publish/contact the service.</returns>
private static string CreateAddress(Guid guid)
{
return string.Format(CultureInfo.CurrentCulture, "net.pipe://localhost/{0}", guid);
}
/// <summary>
/// The interface that describes the single instance service.
/// </summary>
[ServiceContract]
private interface ISingleInstance
{
/// <summary>
/// Notifies the main instance that another instance of the application attempted to start.
/// </summary>
/// <param name="args">The other instance's command-line arguments.</param>
[OperationContract]
void NotifyMainInstance(string[] args);
}
/// <summary>
/// The implementation of the single instance service interface.
/// </summary>
private class SingleInstance : ISingleInstance
{
/// <summary>
/// Notifies the main instance that another instance of the application attempted to start.
/// </summary>
/// <param name="args">The other instance's command-line arguments.</param>
public void NotifyMainInstance(string[] args)
{
if (OtherInstanceStarted != null)
{
Type type = typeof(StartupEventArgs);
ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
StartupEventArgs e = (StartupEventArgs)constructor.Invoke(null);
FieldInfo argsField = type.GetField("_args", BindingFlags.Instance | BindingFlags.NonPublic);
Debug.Assert(argsField != null);
argsField.SetValue(e, args);
OtherInstanceStarted(null, e);
}
}
}
}
my work code. Returns utf8 xml enable empty namespace.
// override StringWriter
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
private string GenerateXmlResponse(Object obj)
{
Type t = obj.GetType();
var xml = "";
using (StringWriter sww = new Utf8StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
var ns = new XmlSerializerNamespaces();
// add empty namespace
ns.Add("", "");
XmlSerializer xsSubmit = new XmlSerializer(t);
xsSubmit.Serialize(writer, obj, ns);
xml = sww.ToString(); // Your XML
}
}
return xml;
}
Example returns response Yandex api payment Aviso url:
<?xml version="1.0" encoding="utf-8"?><paymentAvisoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" performedDatetime="2017-09-01T16:22:08.9747654+07:00" code="0" shopId="54321" invoiceId="12345" orderSumAmount="10643" />
If you use CDATA, you could embed the line breaks directly into the XML I think. Example:
<song>
<title>Song Title</title>
<lyric><![CDATA[Line 1
Line 2
Line 3]]></lyric>
</song>
Simple object hasher:
(function () {
Number.prototype.toHex = function () {
var ret = ((this<0?0x8:0)+((this >> 28) & 0x7)).toString(16) + (this & 0xfffffff).toString(16);
while (ret.length < 8) ret = '0'+ret;
return ret;
};
Object.hashCode = function hashCode(o, l) {
l = l || 2;
var i, c, r = [];
for (i=0; i<l; i++)
r.push(i*268803292);
function stringify(o) {
var i,r;
if (o === null) return 'n';
if (o === true) return 't';
if (o === false) return 'f';
if (o instanceof Date) return 'd:'+(0+o);
i=typeof o;
if (i === 'string') return 's:'+o.replace(/([\\\\;])/g,'\\$1');
if (i === 'number') return 'n:'+o;
if (o instanceof Function) return 'm:'+o.toString().replace(/([\\\\;])/g,'\\$1');
if (o instanceof Array) {
r=[];
for (i=0; i<o.length; i++)
r.push(stringify(o[i]));
return 'a:'+r.join(';');
}
r=[];
for (i in o) {
r.push(i+':'+stringify(o[i]))
}
return 'o:'+r.join(';');
}
o = stringify(o);
for (i=0; i<o.length; i++) {
for (c=0; c<r.length; c++) {
r[c] = (r[c] << 13)-(r[c] >> 19);
r[c] += o.charCodeAt(i) << (r[c] % 24);
r[c] = r[c] & r[c];
}
}
for (i=0; i<r.length; i++) {
r[i] = r[i].toHex();
}
return r.join('');
}
}());
The meat here is the stringifier, which simply converts any object into a unique string. hashCode then runs over the object, hashing together the characters of the stringified object.
For extra points, export the stringifier and create a parser.
http://momentjs.com/docs/#/displaying/unix-timestamp/
You get the number of unix seconds, not milliseconds!
You you need to multiply it with 1000 or using valueOf()
and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.
moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()
Most readable solution is using Static Import. Then you will not need to use AnotherClass.constant
.
Write a class with the constant as public static
field.
package ConstantPackage;
public class Constant {
public static int PROTEINS = 1;
}
Then just use Static Import where you need the constant.
import static ConstantPackage.Constant.PROTEINS;
public class StaticImportDemo {
public static void main(String[]args) {
int[] myArray = new int[5];
myArray[PROTEINS] = 0;
}
}
To know more about Static Import please see this stack overflow question.
I would use return null;
to indicate that there is no data to be returned
In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.
Logcat is nothing but a console of your Emulator or Device.
System.out.println
does not work in Android. So you have to handle every thing in Logcat. More Info Look out this Documentation.
Edit 1: System.out.println is working on Logcat. If you use that the Tag will be like System.out and Message will be your message.
I had the same issue and I tried most of the solution provided by other folks but it worked for me with below steps. I have VS 2017.
Steps:
Install-Package EntityFramework -IncludePrerelease
then create a class as
public class MyDBContext : DbContext { public MyDBContext() { } }
and at the last execute
Enable-Migrations -EnableAutomaticMigrations
What didn't work for me:
: Restarting VS.
: only "Enable-Migrations" command, which is without -EnableAutomaticMigrations.
: restoring or updating Nuget Package Manager.
My original error in the beginning was
/* The term 'enable-migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.At line:1 char:1 + enable-migration + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (enable-migration:String) [], CommandNotFoundException */
GDB uses the thread-id (aka kernel pid, aka LWP) for short numbers on Linux. Try:
#include <syscall.h>
...
printf("tid = %d\n", syscall(SYS_gettid));
I googled a bit, and found this code here:
File file = getJarFileToLoadFrom();
String lcStr = getNameOfClassToLoad();
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
Can anyone share opinions/comments/answers regarding this approach?
Hmm... I think you can use e.clipboardData
to catch the data being pasted. If it doesn't pan out, have a look here.
$(this).live("paste", function(e) {
alert(e.clipboardData); // [object Clipboard]
});
You can create your own prototype to do this:
something like:
Array.prototype.indexOfObject = function (object) {
for (var i = 0; i < this.length; i++) {
if (JSON.stringify(this[i]) === JSON.stringify(object))
return i;
}
}
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
While awk
's printf
can be used, you may want to look into pr
or (on BSDish systems) rs
for formatting.
Late to the game but you could alternatively just apply a python filter
to the result of a glob
:
files = glob.iglob('your_path_here')
files_i_care_about = filter(lambda x: not x.startswith("eph"), files)
or replacing the lambda with an appropriate regex search, etc...
EDIT: I just realized that if you're using full paths the startswith
won't work, so you'd need a regex
In [10]: a
Out[10]: ['/some/path/foo', 'some/path/bar', 'some/path/eph_thing']
In [11]: filter(lambda x: not re.search('/eph', x), a)
Out[11]: ['/some/path/foo', 'some/path/bar']
Probably the fastest way is:
myString.All(c => char.IsDigit(c))
Note: it will return True in case your string is empty which is incorrect (if you not considering empty as valid number/digit )
JavaScript Minifier gives a good API you can use programatically:
curl -X POST -s --data-urlencode 'input=$(function() { alert("Hello, World!"); });' http://javascript-minifier.com/raw
Or by uploading a file and redirecting to a new file:
curl -X POST -s --data-urlencode '[email protected]' http://javascript-minifier.com/raw > ready.min.js
Hope that helps.
I'm not sure why. But
oTable6.fnDraw();
Works for me. I put it in the next line.
Found the solution:
It should be:
"{'Id1':'2','Id2':'2'}"
and not
"{'Id1':'2'},{'Id2':'2'}"
With the currently accepted solution you cannot print the page which contains the dialog itself anymore. Here's a much more dynamic solution:
JavaScript:
$().ready(function () {
$('.modal.printable').on('shown.bs.modal', function () {
$('.modal-dialog', this).addClass('focused');
$('body').addClass('modalprinter');
if ($(this).hasClass('autoprint')) {
window.print();
}
}).on('hidden.bs.modal', function () {
$('.modal-dialog', this).removeClass('focused');
$('body').removeClass('modalprinter');
});
});
CSS:
@media print {
body.modalprinter * {
visibility: hidden;
}
body.modalprinter .modal-dialog.focused {
position: absolute;
padding: 0;
margin: 0;
left: 0;
top: 0;
}
body.modalprinter .modal-dialog.focused .modal-content {
border-width: 0;
}
body.modalprinter .modal-dialog.focused .modal-content .modal-header .modal-title,
body.modalprinter .modal-dialog.focused .modal-content .modal-body,
body.modalprinter .modal-dialog.focused .modal-content .modal-body * {
visibility: visible;
}
body.modalprinter .modal-dialog.focused .modal-content .modal-header,
body.modalprinter .modal-dialog.focused .modal-content .modal-body {
padding: 0;
}
body.modalprinter .modal-dialog.focused .modal-content .modal-header .modal-title {
margin-bottom: 20px;
}
}
Example:
<div class="modal fade printable autoprint">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="window.print();">Print</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
This error can occur on anything that requires elevated privileges in Windows.
It happens when the "Application Information" service is disabled in Windows services. There are a few viruses that use this as an attack vector to prevent people from removing the virus. It also prevents people from installing software to remove viruses.
The normal way to fix this would be to run services.msc, or to go into Administrative Tools and run "Services". However, you will not be able to do that if the "Application Information" service is disabled.
Instead, reboot your computer into Safe Mode (reboot and press F8 until the Windows boot menu appears, select Safe Mode with Networking). Then run services.msc and look for services that are designated as "Disabled" in the Startup Type column. Change these "Disabled" services to "Automatic".
Make sure the "Application Information" service is set to a Startup Type of "Automatic".
When you are done enabling your services, click Ok at the bottom of the tool and reboot your computer back into normal mode. The problem should be resolved when Windows reboots.
Something like:
SELECT id, email, IF(active = 1, 'enabled', 'disabled') AS account_status FROM users
This allows you to make operations and show it as columns.
EDIT:
you can also use joins and show operations as columns:
SELECT u.id, e.email, IF(c.id IS NULL, 'no selected', c.name) AS country
FROM users u LEFT JOIN countries c ON u.country_id = c.id
Try to do something like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:bottom="-20dp" android:left="-20dp">
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="20dp" />
</shape>
</item>
</layer-list>
It seems does not suitable to set different corner radius of rectangle. So you can use this hack.
Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.
To fill the array with something else you can use Arrays.fill() or as part of the declaration
int[] a = new int[] {0, 0, 0, 0};
There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
Adding .
before \r\n
makes it work if the original string before \r\n
has no .
Other characters may work. I didn't try.
With or without the three lines including IsBodyHtml, not a matter.
For global access to jquery then several options exist. In my most recent webpack project, I wanted global access to jquery so I added the following to my plugins declarations:
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
This then means that jquery is accessible from within the JavaScript source code via global references $ and jQuery.
Of course, you need to have also installed jquery via npm:
$ npm i jquery --save
For a working example of this approach please feel free to fork my app on github
After having so many nightmares, I found a solution.
utf8_decode(chr(10))
I tried \n
, <br/>
and chr(10)
but nothing worked. Then I realized that it was utf-8
and just tried the above one. It works fine with MultiCell
but not with Cell
.
Minor note: Please consider that when you import from a default export, the naming is completely independent. This actually has an impact on refactorings.
Let's say you have a class Foo
like this with a corresponding import:
export default class Foo { }
// The name 'Foo' could be anything, since it's just an
// Identifier for the default export
import Foo from './Foo'
Now if you refactor your Foo
class to be Bar
and also rename the file, most IDEs will NOT touch your import. So you will end up with this:
export default class Bar { }
// The name 'Foo' could be anything, since it's just an
// Identifier for the default export.
import Foo from './Bar'
Especially in TypeScript, I really appreciate named exports and the more reliable refactoring. The difference is just the lack of the default
keyword and the curly braces. This btw also prevents you from making a typo in your import since you have type checking now.
export class Foo { }
//'Foo' needs to be the class name. The import will be refactored
//in case of a rename!
import { Foo } from './Foo'
Size of a pointer should be 8 byte on any 64-bit C/C++ compiler, but not necessarily size of int.
As the answers above are not showing all strategy details. For example, some answer is missing the details about the import resolve
option and the recursive
which has many sub options as ours
, theirs
, patience
, renormalize
, etc.
Therefore, I would recommend to visit the official git
documentation which explains all the possible features features:
this is a follow up on the patricus [answer][1] above but for nested arrays:
$topLevelFields = ['id','status'];
$userFields = ['first_name','last_name','email','phone_number','op_city_id'];
return $onlineShoppers->map(function ($user) {
return collect($user)->only($topLevelFields)
->merge(collect($user['user'])->only($userFields))->all();
})->all();
dicejs.com (formally cssobjs) is a client-side version of SASS. You can set variables in your CSS (stored in json formatted CSS) and re-use your color variables.
//create the CSS JSON object with variables and styles
var myCSSObjs = {
cssVariables : {
primaryColor:'#FF0000',
padSmall:'5px',
padLarge:'$expr($padSmall * 2)'
}
'body' : {padding:'$padLarge'},
'h1' : {margin:'0', padding:'0 0 $padSmall 0'},
'.pretty' : {padding:'$padSmall', margin:'$padSmall', color:'$primaryColor'}
};
//give your css objects a name and inject them
$.cssObjs('myStyles',myCSSObjs).injectStyles();
And here is a link to a complete downloadable demo which is a little more helpful then their documentation : dicejs demo
If you do not want to install Xcode and/or MacPorts/Fink/Homebrew, you could always use the standalone installer: https://sourceforge.net/projects/git-osx-installer/
It seems as if Git won't find the editor if there are spaces in the path. So you will have to put the batch file mentioned in Patrick's answer into a non-whitespace path.
I realise that's not the case here but it might help someone.
Double-check you didn't create the conf file in /etc/apache2/sites-enabled by mistake. You get the same error.
this is most better
html
<div id="here_table"> </div>
jQuery
$('#here_table').append( '<table>' );
for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' + i + '</tr>' );
for(ii=0;ii<3;ii++)
{
$('#here_table').append( '<td>' + 'result' + i + '</tr>' );
}
}
$('#here_table').append( '</table>' );
The only working solution in my case was adding the following block to pom.xml
:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version> <configuration> <release>12</release>
</configuration>
</plugin>
</plugins>
</build>
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
You will find I have added the session_start() at the very top of the page. I have also removed the session_start() call later in the page. This page should work fine.
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);
},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="header"> </td>
</tr>
<tr>
<td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
<tr>
<td>
<ul id="nav">
<li><a href="#">Catalog</a>
<ul><li><a href="#">Products</a></li>
<li><a href="#">Bulk Upload</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">Purchase </a>
</li>
<li><a href="#">Customer Service</a>
<ul>
<li><a href="#">Contact Us</a></li>
<li><a href="#">CS Panel</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">All Reports</a></li>
<li><a href="#">Configuration</a>
<ul> <li><a href="#">Look and Feel </a></li>
<li><a href="#">Business Details</a></li>
<li><a href="#">CS Details</a></li>
<li><a href="#">Emaqil Template</a></li>
<li><a href="#">Domain and Analytics</a></li>
<li><a href="#">Courier</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">Accounts</a>
<ul><li><a href="#">Ledgers</a></li>
<li><a href="#">Account Details</a></li>
</ul>
<div class="clear"></div></li>
</ul></td></tr></table></td>
</tr>
<tr>
<td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td> </td>
</tr>
<tr>
<td height="45"><strong>-> Products</strong></td>
</tr>
<tr>
<td height="61"><strong>-> Categories</strong></td>
</tr>
<tr>
<td height="48"><strong>-> Sub Categories</strong></td>
</tr>
</table></td>
<td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
<tr>
<td>
<table width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="26%"> </td>
<td width="74%"><h2>Manage Categories</h2></td>
</tr>
</table></td>
</tr>
<tr>
<td height="30">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<table width="49%" align="center" cellpadding="0" cellspacing="0">
<tr><td>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>
Here are a couple basic examples to get started quick and dirty.
Set variable:
SET(INSTALL_ETC_DIR "etc")
Use variable:
SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")
Set variable:
SET(PROGRAM_SRCS
program.c
program_utils.c
a_lib.c
b_lib.c
config.c
)
Use variable:
add_executable(program "${PROGRAM_SRCS}")
404 Not Found technically means that uri does not currently map to a resource. In your example, I interpret a request to http://mywebsite/api/user/13
that returns a 404 to imply that this url was never mapped to a resource. To the client, that should be the end of conversation.
To address concerns with ambiguity, you can enhance your API by providing other response codes. For example, suppose you want to allow clients to issue GET requests the url http://mywebsite/api/user/13
, you want to communicate that clients should use the canonical url http://mywebsite/restapi/user/13
. In that case, you may want to consider issuing a permanent redirect by returning a 301 Moved Permanently and supply the canonical url in the Location header of the response. This tells the client that for future requests they should use the canonical url.
Option 1 allows you to use a place specified exactly for explicitly initializing member variables.
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
When using JUnit asserts, I always make the message nice and clear. It saves huge amounts of time debugging. Doing it this way avoids having to add a added dependency on hamcrest Matchers.
previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";
Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);
assertTrue("Previous (" + prev + ") should be greater than current (" + curr + ")", prev > curr);
Several problems arise in this question.
Problem #1 - css Specificity (how to override important rule).
According to specification - to override this selector your selector should be 'stronger' which mean it should be!important and have at least 1 id, 1 class and something else - according to you creating this selector is impossible(as you can't alter page content). So the only possible option is to put something into element style which (could be done with js). Note: style rule should also have !important to override.
Problem #2 - background is not a single property - it is a set of properties (see specification)
So you really need to know what are exact names of properties you want to change (in your case it would be background-image)
Problem #3 - How to remove rule already applied (to get previous value)?
Unfortunately css have no mechanism to dismiss rule which qualify for an element - only to override with "stronger" rule. So you won't be able to solve this task with just setting value to something like 'inherit' or 'default' cause value you want to see is neither inherit from parent nor default. To solve this problem you have couple of options.
1) You may already know what is the value you want to apply. For example you can find out this value based on selector used. So in this case you may know that for selector ".image-list li" you need background-image: url("http://placekitten.com/150/50"). If so - just you this script:
jQuery(".image-list li").attr('style', 'background-image: url("http://placekitten.com/150/50") !important; ');
2) If you don't know the value then you can try to alter page content in such a way, that rule you want to dismiss is no longer qualify for element, whereas rule you want to be shown - still qualify. In this case you may temporary remove id from container element. Here is the code:
jQuery("#an-element").attr('id', '');
var backgroundImage = jQuery(".image-list li").css('background-image');
jQuery("#an-element").attr('id', 'an-element');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');
Here is link to fiddle http://jsfiddle.net/o3jn9mzo/
3) As third solution - you may generate element which will qualify for desired selection to find out property value - something like this:
var backgroundImage = jQuery("<div class='image-list'><li></li></div>").find('li').css('background-image');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');
P.S.: Sorry for really late response.
As said earlier, your code will work unless you have the same classes loaded on two different class loaders. This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).
In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.
public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
// TODO handle nulls maybe?
return c1.getCanonicalName().equals(c2.getCanonicalName());
}
Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.
In Python version 3.6 and above you can use f-string to format result.
str = "hello world"
print(" ".join(f"{ord(i):08b}" for i in str))
01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100
The left side of the colon, ord(i), is the actual object whose value will be formatted and inserted into the output. Using ord() gives you the base-10 code point for a single str character.
The right hand side of the colon is the format specifier. 08 means width 8, 0 padded, and the b functions as a sign to output the resulting number in base 2 (binary).
While there is no technical difference, I have seen the two used to denote slightly different things.
For a template that should accept any type as T, including built-ins (such as an array )
template<typename T>
class Foo { ... }
For a template that will only work where T is a real class.
template<class T>
class Foo { ... }
But keep in mind that this is purely a style thing some people use. Not mandated by the standard or enforced by compilers
Just remove this line android:screenOrientation="portrait"
of activity in Manifiest.xml
That activity will get orientation from it's previous activity so no need to apply orientation which has <item name="android:windowIsTranslucent">true</item>
.
This is what I did:
EF:
using (var context = new SomeDBContext())
{
foreach (var item in model.ShopItems) // ShopItems is a posted list with values
{
var feature = context.Shop
.Where(h => h.ShopID == 123 && h.Type == item.Type).ToList();
feature.ForEach(a => a.SortOrder = item.SortOrder);
}
context.SaveChanges();
}
Hope helps someone.
I've used HttpClient in .NET 4.0 applications on numerous occasions. If you are familiar with NuGet, you can do an Install-Package Microsoft.Net.Http to add it to your project. See the link below for further details.
As Unwind points out f and g provide different default outputs.
Roughly speaking if you care more about the details of what comes after the decimal point I would do with f and if you want to scale for large numbers go with g. From some dusty memories f is very nice with small values if your printing tables of numbers as everything stays lined up but something like g is needed if you stand a change of your numbers getting large and your layout matters. e is more useful when your numbers tend to be very small or very large but never near ten.
An alternative is to specify the output format so that you get the same number of characters representing your number every time.
Sorry for the woolly answer but it is a subjective out put thing that only gets hard answers if the number of characters generated is important or the precision of the represented value.
str.strip
is the best approach for this situation, but more_itertools.strip
is also a general solution that strips both leading and trailing elements from an iterable:
Code
import more_itertools as mit
iterables = ["231512-n\n"," 12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']
Details
Notice, here we strip both leading and trailing "0"
s among other elements that satisfy a predicate. This tool is not limited to strings.
See also docs for more examples of
more_itertools.strip
: strip both endsmore_itertools.lstrip
: strip the left endmore_itertools.rstrip
: strip the right endmore_itertools
is a third-party library installable via > pip install more_itertools
.
The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as
pip3 install hide_code
Visit https://github.com/kirbs-/hide_code/ for more info about this extension.
Don't call write.close()
in writeToFile()
.
For me the answer was to force a Maven rebuild. In Eclipse:
NOTE: For those wanting to use web workers and you need to avoid using document and nativeElement this will work.
I answered the same question here: https://stackoverflow.com/questions/47571144
Copy/Paste from the above link:
I had the same issue when I was making a drop-down menu and a confirmation dialog I wanted to dismiss them when clicking outside.
My final implementation works perfectly but requires some css3 animations and styling.
NOTE: i have not tested the below code, there may be some syntax problems that need to be ironed out, also the obvious adjustments for your own project!
What i did:
I made a separate fixed div with height 100%, width 100% and transform:scale(0), this is essentially the background, you can style it with background-color: rgba(0, 0, 0, 0.466); to make obvious the menu is open and the background is click-to-close. The menu gets a z-index higher than everything else, then the background div gets a z-index lower than the menu but also higher than everything else. Then the background has a click event that close the drop-down.
Here it is with your html code.
<div class="dropdownbackground" [ngClass]="{showbackground: qtydropdownOpened}" (click)="qtydropdownOpened = !qtydropdownOpened"><div>
<div class="zindex" [class.open]="qtydropdownOpened">
<button (click)="qtydropdownOpened = !qtydropdownOpened" type="button"
data-toggle="dropdown" aria-haspopup="true" [attr.aria-expanded]="qtydropdownOpened ? 'true': 'false' ">
{{selectedqty}}<span class="caret margin-left-1x "></span>
</button>
<div class="dropdown-wrp dropdown-menu">
<ul class="default-dropdown">
<li *ngFor="let quantity of quantities">
<a (click)="qtydropdownOpened = !qtydropdownOpened;setQuantity(quantity)">{{quantity }}</a>
</li>
</ul>
</div>
</div>
Here is the css3 which needs some simple animations.
/* make sure the menu/drop-down is in front of the background */
.zindex{
z-index: 3;
}
/* make background fill the whole page but sit behind the drop-down, then
scale it to 0 so its essentially gone from the page */
.dropdownbackground{
width: 100%;
height: 100%;
position: fixed;
z-index: 2;
transform: scale(0);
opacity: 0;
background-color: rgba(0, 0, 0, 0.466);
}
/* this is the class we add in the template when the drop down is opened
it has the animation rules set these how you like */
.showbackground{
animation: showBackGround 0.4s 1 forwards;
}
/* this animates the background to fill the page
if you don't want any thing visual you could use a transition instead */
@keyframes showBackGround {
1%{
transform: scale(1);
opacity: 0;
}
100% {
transform: scale(1);
opacity: 1;
}
}
If you aren't after anything visual you can just use a transition like this
.dropdownbackground{
width: 100%;
height: 100%;
position: fixed;
z-index: 2;
transform: scale(0);
opacity: 0;
transition all 0.1s;
}
.dropdownbackground.showbackground{
transform: scale(1);
}
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
Unlike subversion, git does not have a per-file history. If you look at the commit data structure, it only points to the previous commits and the new tree object for this commit. No explicit information is stored in the commit object which files are changed by the commit; nor the nature of these changes.
The tools to inspect changes can detect renames based on heuristics. E.g. "git diff" has the option -M that turns on rename detection. So in case of a rename, "git diff" might show you that one file has been deleted and another one created, while "git diff -M" will actually detect the move and display the change accordingly (see "man git diff" for details).
So in git this is not a matter of how you commit your changes but how you look at the committed changes later.
Another solution I ran across tonight, which worked for my needs, was to add box-sizing
attributes:
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
These attributes force the border to be part of the box model's width and height and correct the issue as well.
According to caniuse.com » box-sizing, box-sizing
is supported in IE8+.
If you're using LESS or Sass there is a Bootstrap mixin for this.
LESS:
.box-sizing(border-box);
Sass:
@include box-sizing(border-box);
please check if code below would work for you; it iterates through cells of the datagris's first column and checks if cell content equals to the textbox.text value and selects the row.
for (int i = 0; i < dataGrid.Items.Count; i++)
{
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
TextBlock cellContent = dataGrid.Columns[0].GetCellContent(row) as TextBlock;
if (cellContent != null && cellContent.Text.Equals(textBox1.Text))
{
object item = dataGrid.Items[i];
dataGrid.SelectedItem = item;
dataGrid.ScrollIntoView(item);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
break;
}
}
hope this helps, regards
Simple answer
If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080
If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.
NULL need not to be 0. As long you use always NULL and never 0, NULL can be any value. Asuming you programme a von Neuman Microcontroller with flat memory, that has its interrupt vektors at 0. If NULL is 0 and something writes at a NULL Pointer the Microcontroller crashes. If NULL is lets say 1024 and at 1024 there is a reserved variable, the write won't crash it, and you can detect NULL Pointer assignments from inside the programme. This is Pointless on PCs, but for space probes, military or medical equipment it is important not to crash.
This might help...
test_list = [5, 8]
test_list[0] = None
print test_list
#prints [None, 8]
To join Array1 and Array2, create a new array say JointArray
Dim JointArray As Variant
ReDim JointArray(UBound(Array1) + UBound(Array2) + 1) As Variant
For i = 0 To UBound(JointArray)
If i <= UBound(Array1) Then
JointArray(i) = Array1(i)
Else
JointArray(i) = Array2(i - UBound(Array1) - 1)
End If
Next
You are populating your dictionaries with references to a single list so when you update it, the update is reflected across all the references. Try a dictionary comprehension instead. See Create a dictionary with list comprehension in Python
d = {k : v for k in blah blah blah}
$('#usersSearch').keyup(function() { // handle keyup event on search input field
var key = e.which || e.keyCode; // store browser agnostic keycode
if(key == 13)
$(this).closest('form').submit(); // submit parent form
}
This is the correct way:
You should declare the length of the array after "="
Veicle[] cars = new Veicle[N];
If It is simple Session you can apply NULL
Check directly Session["emp_num"] != null
But if it's a session of a list Item then You need to apply any one of the following option
Option 1:
if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
{
//Your Logic here
}
Option 2:
List<int> val= Session["emp_num"] as List<int>; //Get the value from Session.
if (val.FirstOrDefault() != null)
{
//Your Logic here
}
The Control class has HorizontalContentAlignment and VerticalContentAlignment properties. These properties determine how a control’s content fills the space within the control.
Set HorizontalContentAlignment and VerticalContentAlignment to Center.
Roc answer is a great help. I would like to add a small block to it:
mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
SFTP is not FTP over SSH, it's a different protocol and being similar to SCP, it's offers more capabilities.
@jmetz's answer is probably the one most people need; however it yields a one-dimensional array, e.g. making it unusable to remove entire rows or columns in matrices.
To do so, one should reduce the logical array to one dimension, then index the target array. For instance, the following will remove rows which have at least one NaN value:
x = x[~numpy.isnan(x).any(axis=1)]
See more detail here.
Code:
function search($array, $key, $value)
{
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}
return $results;
}
$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>"cat 1"));
print_r(search($arr, 'name', 'cat 1'));
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => cat 1
)
[1] => Array
(
[id] => 3
[name] => cat 1
)
)
If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results
array rather than merging arrays together, like so:
function search($array, $key, $value)
{
$results = array();
search_r($array, $key, $value, $results);
return $results;
}
function search_r($array, $key, $value, &$results)
{
if (!is_array($array)) {
return;
}
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
search_r($subarray, $key, $value, $results);
}
}
The key there is that search_r
takes its fourth parameter by reference rather than by value; the ampersand &
is crucial.
FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r
rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results)
.
This is for version 1.4.4
<div data-role="header" >
<h1>CHANGE HOUSE ANIMATION</h1>
<a href="#" data-rel="back" class="ui-btn-left ui-btn ui-icon-back ui-btn-icon-notext ui-shadow ui-corner-all" data-role="button" role="button">Back</a>
</div>
Answer: NO
Here's Why ... I think a key reason for having stored procs in a database is that you're executing SP code in the same process as the SQL engine. This makes sense for database engines designed to work as a network connected service but the imperative for SQLite is much less given that it runs as a DLL in your application process rather than in a separate SQL engine process. So it makes more sense to implement all your business logic including what would have been SP code in the host language.
You can however extend SQLite with your own user defined functions in the host language (PHP, Python, Perl, C#, Javascript, Ruby etc). You can then use these custom functions as part of any SQLite select/update/insert/delete. I've done this in C# using DevArt's SQLite to implement password hashing.
@Jacob already showed you how to use the Gaussian filter in Matlab, so I won't repeat that.
I would choose filter size to be about 3*sigma in each direction (round to odd integer). Thus, the filter decays to nearly zero at the edges, and you won't get discontinuities in the filtered image.
The choice of sigma depends a lot on what you want to do. Gaussian smoothing is low-pass filtering, which means that it suppresses high-frequency detail (noise, but also edges), while preserving the low-frequency parts of the image (i.e. those that don't vary so much). In other words, the filter blurs everything that is smaller than the filter.
If you're looking to suppress noise in an image in order to enhance the detection of small features, for example, I suggest to choose a sigma that makes the Gaussian just slightly smaller than the feature.
There is a another way also
<div id="loadhtml"></div>
step 3: in Any Controller
var htmlcontent = $('#loadhtml ');
htmlcontent.load('/Pages/Common/contact.html')
$compile(htmlcontent.contents())($scope);
This Will Load a html page in Current page
Why, in all this discussion, has there been no mention of UTF-8? Being able to store the full unicode span of characters does not mean one has to always allocate two-bytes-per-character (or "code point" to use the UNICODE term). All of ASCII is UTF-8. Does SQL Server check for VARCHAR() fields that the text is strict ASCII (i.e. top byte bit zero)? I would hope not.
If then you want to store unicode and want compatibility with older ASCII-only applications, I would think using VARCHAR() and UTF-8 would be the magic bullet: It only uses more space when it needs to.
For those of you unfamiliar with UTF-8, might I recommend a primer.
Yet another possibility not yet mentioned here is to use NumPy tile:
a = numpy.tile(numpy.nan, (3, 3))
Also gives
array([[ NaN, NaN, NaN],
[ NaN, NaN, NaN],
[ NaN, NaN, NaN]])
I don't know about speed comparison.
I use get-pip and virtualenv-burrito to install all this. Not sure if python-setuptools is required.
# might be optional. I install as part of my standard ubuntu setup script
sudo apt-get -y install python-setuptools
# install pip (using get-pip.py from pip contrib)
curl -O https://raw.github.com/pypa/pip/develop/contrib/get-pip.py && sudo python get-pip.py
# one-line virtualenv and virtualenvwrapper using virtualenv-burrito
curl -s https://raw.github.com/brainsik/virtualenv-burrito/master/virtualenv-burrito.sh | bash
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.
([1-9][0-9]*,[ ])*[1-9][0-9]*
Here's how I built that mentally:
[0-9] any digit.
[1-9][0-9]* leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ] as above, followed by a space
([1-9][0-9]*[ ])* as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]* as above, with a final number that doesn't have a comma.
Apart from HTML 5 data-tip You can use css also for making a totally customizable tooltip to be used anywhere throughout your markup.
/* ToolTip classses */ _x000D_
.tooltip {_x000D_
display: inline-block; _x000D_
}_x000D_
.tooltip .tooltiptext {_x000D_
margin-left:9px;_x000D_
width : 320px;_x000D_
visibility: hidden;_x000D_
background-color: #FFF;_x000D_
border-radius:4px;_x000D_
border: 1px solid #aeaeae;_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
padding: 5px;_x000D_
margin-top : -15px; _x000D_
opacity: 0;_x000D_
transition: opacity 0.5s;_x000D_
}_x000D_
.tooltip .tooltiptext::after {_x000D_
content: " ";_x000D_
position: absolute;_x000D_
top: 5%;_x000D_
right: 100%; _x000D_
margin-top: -5px;_x000D_
border-width: 5px;_x000D_
border-style: solid;_x000D_
border-color: transparent #aeaeae transparent transparent;_x000D_
}_x000D_
_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
<input type="text" />_x000D_
<span class="tooltiptext">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </span>_x000D_
</div>
_x000D_
For using another docker-compose network you just do these(to share networks between docker-compose):
- Run the first docker-compose project by
up -d
- Find the network name of the first docker-compose by:
docker network ls
(It contains the name of the root directory project)- Then use that name by this structure at below in the second docker-compose file.
second docker-compose.yml
version: '3'
services:
service-on-second-compose: # Define any names that you want.
.
.
.
networks:
- <put it here(the network name that comes from "docker network ls")>
networks:
- <put it here(the network name that comes from "docker network ls")>:
external: true
I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2
.
Try the following:
int[][] multi = new int[5][10];
... which is a short hand for something like this:
int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];
Note that every element will be initialized to the default value for int
, 0
, so the above are also equivalent to:
int[][] multi = new int[][]{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
HTML
<mat-form-field>
<mat-select [(ngModel)]="modeSelect" placeholder="Mode">
<mat-option *ngFor="let obj of Array" [value]="obj.value">{{obj.value}}</mat-option>
</mat-select>
Now set your default value to
modeSelect
, where you are getting the values in Array variable.
I tried several answers and the only thing what finally did the job was this configuration for the compiler plugin in the pom:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<fork>true</fork>
<meminitial>128m</meminitial>
<maxmem>512m</maxmem>
<source>1.6</source>
<target>1.6</target>
<!-- prevent PermGen space out of memory exception -->
<!-- <argLine>-Xmx512m -XX:MaxPermSize=512m</argLine> -->
</configuration>
</plugin>
hope this one helps.
A good trick is to use inner box-shadow, and let it do all the fading for you rather than applying it to the image.
Resolve is also more straightforward
from django.urls import resolve
resolve('edit_project', project_id=4)
When using a pandas df this worked for me
import math
def truncate(number, digits) -> float:
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
df['trunc'] = df['float_val'].apply(lambda x: truncate(x,1))
df['trunc']=df['trunc'].map('{:.1f}'.format)
Things you can add to declarations: [] in modules
Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.
Try this:
SELECT 'I like ' || type_column_name || ' cake with ' ||
icing_column_name || ' and a ' fruit_column_name || '.'
AS Cake_Column FROM your_table_name;
It should concatenate all that data as a single column entry named "Cake_Column".
You must use code as this:
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="logo" rel="home" href="#" title="Buy Sell Rent Everyting">
<img style=""
src="/img/transparent-white-logo.png">
</a>
</div>
Class of A tag must be "logo" not navbar-brand.
I had the same issue with gcc "gnat1" and it was due to the path being wrong. Gnat1 was on version 4.6 but I was executing version 4.8.1, which I had installed. As a temporary solution, I copied gnat1 from 4.6 and pasted under the 4.8.1 folder.
The path to gcc on my computer is /usr/lib/gcc/i686-linux-gnu/
You can find the path by using the find command:
find /usr -name "gnat1"
In your case you would look for cc1plus:
find /usr -name "cc1plus"
Of course, this is a quick solution and a more solid answer would be fixing the broken path.
The V8 debugger released as part of the Google Chrome Developer Tools can be used to debug Node.js scripts. A detailed explanation of how this works can be found in the Node.js GitHub wiki.
May be this time stamp fit you better Code
Function LastInputTimeStamp() As Date
LastInputTimeStamp = Now()
End Function
and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this
=IF(C36>0,LastInputTimeStamp(),"")
Super-brief summary from what Professor Brasilford explains in this video.
Turing Complete ? do anything that a Turing Machine can do.
It has conditional branching (i.e. "if statement"). Also, implies "go to" and thus permitting loop.
It has arbitrary amount of memory (e.g. long enough tape) that the program needs.
Yet another way is this:
You have a gnuplot script named scriptname.gp
:
#!/usr/bin/gnuplot -p
# This code is in the file 'scriptname.gp'
EPATH = $0
FILENAME = $1
plot FILENAME
Now you can call the gnuplot script scriptname.gp
by this convoluted peace of syntax:
echo "call \"scriptname.gp\" \"'.'\" \"'data.dat'\"" | gnuplot
You can try following solutions:
Use Application Loader to upload your app, as Xcode organizer can't upload file (rejects IPA) sometimes, without genuine reason and it's frequently occurring issue, with Xcode Organizer, that apple could not resolve permanently.
- Apple app upload server is not working properly (not in connection or lost connection during file upload). Just wait and try again later (may be after a day).
- Fluctuation in your network connection, during file upload.
- You may not have added privacy statements in your info.plist file.
Cocoa Keys: Here, is list of keys (with privacy statements) that you should consider to add in your info.plist file, if you have used that service in your application.
Nowadays, you may also face, this error code: 90186 (with app loader)
- Outdated application loader can be reason of this error. Use latest Xcode tool and use application loader from Xcode Tool.
- Incorrect/invalid provisioning profile, associated with your build. Ensure, your have used correct provisioning profile (A provisioning profile with Distribution/Production mode is require. A Development mode provisioning profile won't allow your to upload app on store.)
You can find latest Application Loader Tool from latest Xcode Tool: Xcode -> Open Developer Tool -> Application Loader
You have an error in your syntax here:
this._possessions = new Thing[100]();
This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:
this._possessions = [];
Of the array constructor if you want to set the length:
this._possessions = new Array(100);
I have created a brief working example you can try in the playground.
module Entities {
class Thing {
}
export class Person {
private _name: string;
private _possessions: Thing[];
private _mostPrecious: Thing;
constructor (name: string) {
this._name = name;
this._possessions = [];
this._possessions.push(new Thing())
this._possessions[100] = new Thing();
}
}
}
You can add a class to each of your .row
divs to add some space in between them like so:
.spacer {
margin-top: 40px; /* define margin as you see fit */
}
You can then use it like so:
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
Here's the intended way to convert a String to a Date:
String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);
Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.
git aliases (and sections in git configs) to the rescue!
add an alias (from command line):
git config --global alias.identity '! git config user.name "$(git config user.$1.name)"; git config user.email "$(git config user.$1.email)"; :'
then, set, for example
git config --global user.github.name "your github username"
git config --global user.github.email [email protected]
and in a new or cloned repo you can run this command:
git identity github
This solution isn't automatic, but unsetting user and email in your global ~/.gitconfig
and setting user.useConfigOnly
to true
would force git to remind you to set them manually in each new or cloned repo.
git config --global --unset user.name
git config --global --unset user.email
git config --global user.useConfigOnly true
If you are looking for a particular type of element that is further away than the immediate parent, you can use a function that goes up the DOM until it finds one, or doesn't:
// Find first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
// Many DOM methods return null if they don't
// find the element they are searching for
// It would be OK to omit the following and just
// return undefined
return null;
}
The given answers work if you're in a context where conda is in your PATH environment variable, e.g. if you set it up that way during installation, or if you're running the "Anaconda Prompt".
If that's not the case, e.g. if you're trying to locate conda for use in a script, you should be able to pick up its installation location by probing HKCU\Software\Python
for available Python installations. For example:
>for /F "tokens=2,*" %a in ('reg query HKCU\Software\Python /f InstallPath /s /k /ve ^| findstr Default') do @echo %b
C:\Users\<username>\Miniconda3
C:\Users\<username>\Miniconda3
Here are the results I got with ipython's timeit function:
from datetime import date
today = date.today()
timeit[Model.objects.filter(date_created__year=today.year, date_created__month=today.month, date_created__day=today.day)]
1000 loops, best of 3: 652 us per loop
timeit[Model.objects.filter(date_created__gte=today)]
1000 loops, best of 3: 631 us per loop
timeit[Model.objects.filter(date_created__startswith=today)]
1000 loops, best of 3: 541 us per loop
timeit[Model.objects.filter(date_created__contains=today)]
1000 loops, best of 3: 536 us per loop
contains seems to be faster.
When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.
File file = new File(filePath);
if(file.exists())
//do something
You can presumably pass-in, as a parameter, a delegate which will convert from string to T.
Easiest way is use this way
my_var=`echo 2`
echo $my_var
output
: 2
note that is not simple single quote is back quote ( ` ).
- Import project folders into the eclipse workspace.(when projects use different Jre).
- Update or Reinstall eclipse
- Change Jre or Build related Settings.
- Or by there is a configuration mismatch.
You get two errors for each misconfigured files.
- The project cannot be built until build path errors are resolved.
- Unbound classpath container: 'JRE System Library.
- Select each project and apply Quick fix(Ctrl+1)
- Either Replace the project's JRE with default JRE or Specify Alternate JRE (or JDK).
You can do the same by right-click project-->Properties(from context menu)-->Java Build Path-->Libraries-->select current unbound library -->Remove-->Add Libraries-->Jre System library-->select default or alternate Jre.
Or directly choose Build Path-->Add libraries in project's context menu.
EITHER
- Open the current workspace (in which your project is) in File Explorer.
- Delete all org.eclipse.jdt.core.prefs file present in .settings folder of your imported projects.(Be careful while deleting. Don't delete any files or folders inside .metadata folder.)**
- Now,Select the .classpath files of projects (those with errors) and open them in a powerful text editor(such as Notepad++).
- Find the line similar to
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
and replace it with<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- Save all the files. And Refresh or restart Eclipse IDE. All the problems are gone.
OR
Get the JRE used by the projects and install on your computer and then specify it..
You might need to Deserialize your anonymous JSON type from the request body.
var jsonBody = HttpContext.Request.Content.ReadAsStringAsync().Result;
ScoreInputModel myDeserializedClass = JsonConvert.DeserializeObject<ScoreInputModel>(jsonBody);
you can do it with awk and backtics
ps auxf |grep 'python csp_build.py'|`awk '{ print "kill " $2 }'`
$2 in awk prints column 2, and the backtics runs the statement that's printed.
But a much cleaner solution would be for the python process to store it's process id in /var/run and then you can simply read that file and kill it.
This solution uses a new array, and an object map inside the function. All it does is loop through the original array, and adds each integer into the object map.If while looping through the original array it comes across a repeat, the
`if (!unique[int])`
catches this because there is already a key property on the object with the same number. Thus, skipping over that number and not allowing it to be pushed into the new array.
function removeRepeats(ints) {
var unique = {}
var newInts = []
for (var i = 0; i < ints.length; i++) {
var int = ints[i]
if (!unique[int]) {
unique[int] = 1
newInts.push(int)
}
}
return newInts
}
var example = [100, 100, 100, 100, 500]
console.log(removeRepeats(example)) // prints [100, 500]
I think you have got it in that last attempt, you just need to grab the string.. in Chrome's console..
startdate = moment();
startdate.subtract(1, 'd');
startdate.format('DD-MM-YYYY');
"14-04-2015"
startdate = moment();
startdate.subtract(1, 'd');
myString = startdate.format('DD-MM-YYYY');
"14-04-2015"
myString
"14-04-2015"