On Mac OS X 10.9, if you try xcode-select --install
, you will get the following error :
Can't install the software because it is not currently available from the Software Update server.
The solution is to download Command Line Tools (OS X 10.9) directly from Apple website : https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-
You will then be able to install the last version of Command Line Tools.
Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.
I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.
The answers here took the OP's question too literally. How can these answers be expanded into a scenario where there are MANY child elements, not just a single <a>
tag? Here's one way.
Let's say you have a photo gallery with a blacked out background and the photos centered in the browser. When you click the black background (but not anything inside of it) you want the overlay to close.
Here's some possible HTML:
<div class="gallery" style="background: black">
<div class="contents"> <!-- Let's say this div is 50% wide and centered -->
<h1>Awesome Photos</h1>
<img src="img1.jpg"><br>
<img src="img2.jpg"><br>
<img src="img3.jpg"><br>
<img src="img4.jpg"><br>
<img src="img5.jpg">
</div>
</div>
And here's how the JavaScript would work:
$('.gallery').click(
function()
{
$(this).hide();
}
);
$('.gallery > .contents').click(
function(e) {
e.stopPropagation();
}
);
This will stop the click events from elements inside .contents
from every research .gallery
so the gallery will close only when you click in the faded black background area, but not when you click in the content area. This can be applied to many different scenarios.
we can follow below procedure to avoid display of key-values in alphabetical order.
Javascript
$scope.data = {
"id": 2,
"project": "wewe2012",
"date": "2013-02-26",
"description": "ewew",
"eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
var test = {};
test[key]=$scope.data[key];
array.push(test);
}
$scope.data = array;
HTML
<p ng-repeat="obj in data">
<font ng-repeat="(key, value) in obj">
{{key}} : {{value}}
</font>
</p>
The code posted by @simon.buchan will work...
Thread.currentThread().getStackTrace()[2].getLineNumber()
But if you call it in a method it will always return the line number of the line in the method so rather use the code snippet inline.
Besides the wildcards, the difference between =
AND LIKE
will depend on both the kind of SQL server and on the column type.
Take this example:
CREATE TABLE testtable (
varchar_name VARCHAR(10),
char_name CHAR(10),
val INTEGER
);
INSERT INTO testtable(varchar_name, char_name, val)
VALUES ('A', 'A', 10), ('B', 'B', 20);
SELECT 'VarChar Eq Without Space', val FROM testtable WHERE varchar_name='A'
UNION ALL
SELECT 'VarChar Eq With Space', val FROM testtable WHERE varchar_name='A '
UNION ALL
SELECT 'VarChar Like Without Space', val FROM testtable WHERE varchar_name LIKE 'A'
UNION ALL
SELECT 'VarChar Like Space', val FROM testtable WHERE varchar_name LIKE 'A '
UNION ALL
SELECT 'Char Eq Without Space', val FROM testtable WHERE char_name='A'
UNION ALL
SELECT 'Char Eq With Space', val FROM testtable WHERE char_name='A '
UNION ALL
SELECT 'Char Like Without Space', val FROM testtable WHERE char_name LIKE 'A'
UNION ALL
SELECT 'Char Like With Space', val FROM testtable WHERE char_name LIKE 'A '
Using MS SQL Server 2012, the trailing spaces will be ignored in the comparison, except with LIKE
when the column type is VARCHAR
.
Using MySQL 5.5, the trailing spaces will be ignored for =
, but not for LIKE
, both with CHAR
and VARCHAR
.
Using PostgreSQL 9.1, spaces are significant with both =
and LIKE
using VARCHAR
, but not with CHAR
(see documentation).
The behaviour with LIKE
also differs with CHAR
.
Using the same data as above, using an explicit CAST
on the column name also makes a difference:
SELECT 'CAST none', val FROM testtable WHERE char_name LIKE 'A'
UNION ALL
SELECT 'CAST both', val FROM testtable WHERE
CAST(char_name AS CHAR) LIKE CAST('A' AS CHAR)
UNION ALL
SELECT 'CAST col', val FROM testtable WHERE CAST(char_name AS CHAR) LIKE 'A'
UNION ALL
SELECT 'CAST value', val FROM testtable WHERE char_name LIKE CAST('A' AS CHAR)
This only returns rows for "CAST both" and "CAST col".
There are two ways to do this
1) Use get/set service
2)
$scope.$emit('key', {data: value}); //to set the value
$rootScope.$on('key', function (event, data) {}); // to get the value
Here's an example script which demonstrates certificate validation:
import httplib
import re
import socket
import sys
import urllib2
import ssl
class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
def __init__(self, host, cert, reason):
httplib.HTTPException.__init__(self)
self.host = host
self.cert = cert
self.reason = reason
def __str__(self):
return ('Host %s returned an invalid certificate (%s) %s\n' %
(self.host, self.reason, self.cert))
class CertValidatingHTTPSConnection(httplib.HTTPConnection):
default_port = httplib.HTTPS_PORT
def __init__(self, host, port=None, key_file=None, cert_file=None,
ca_certs=None, strict=None, **kwargs):
httplib.HTTPConnection.__init__(self, host, port, strict, **kwargs)
self.key_file = key_file
self.cert_file = cert_file
self.ca_certs = ca_certs
if self.ca_certs:
self.cert_reqs = ssl.CERT_REQUIRED
else:
self.cert_reqs = ssl.CERT_NONE
def _GetValidHostsForCert(self, cert):
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def _ValidateCertificateHostname(self, cert, hostname):
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def connect(self):
sock = socket.create_connection((self.host, self.port))
self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
certfile=self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs)
if self.cert_reqs & ssl.CERT_REQUIRED:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise InvalidCertificateException(hostname, cert,
'hostname mismatch')
class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
def __init__(self, **kwargs):
urllib2.AbstractHTTPHandler.__init__(self)
self._connection_args = kwargs
def https_open(self, req):
def http_class_wrapper(host, **kwargs):
full_kwargs = dict(self._connection_args)
full_kwargs.update(kwargs)
return CertValidatingHTTPSConnection(host, **full_kwargs)
try:
return self.do_open(http_class_wrapper, req)
except urllib2.URLError, e:
if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1:
raise InvalidCertificateException(req.host, '',
e.reason.args[1])
raise
https_request = urllib2.HTTPSHandler.do_request_
if __name__ == "__main__":
if len(sys.argv) != 3:
print "usage: python %s CA_CERT URL" % sys.argv[0]
exit(2)
handler = VerifiedHTTPSHandler(ca_certs = sys.argv[1])
opener = urllib2.build_opener(handler)
print opener.open(sys.argv[2]).read()
I have found this answer and I edit that in more reliable way
def download_photo(self, img_url, filename):
try:
image_on_web = urllib.urlopen(img_url)
if image_on_web.headers.maintype == 'image':
buf = image_on_web.read()
path = os.getcwd() + DOWNLOADED_IMAGE_PATH
file_path = "%s%s" % (path, filename)
downloaded_image = file(file_path, "wb")
downloaded_image.write(buf)
downloaded_image.close()
image_on_web.close()
else:
return False
except:
return False
return True
From this you never get any other resources or exceptions while downloading.
I don't know of a "standard" shrink-wrapped way to do that with a Java app, but it's definitely a good idea (you want to benefit from the keep-alive and monitoring capabilities of the operating system if they are there). It's on the roadmap to provide something from the Spring Boot tool support (maven and gradle), but for now you are probably going to have to roll your own. The best solution I know of right now is Foreman, which has a declarative approach and one line commands for packaging init scripts for various standard OS formats (monit, sys V, upstart etc.). There is also evidence of people having set stuff up with gradle (e.g. here).
As well you can use:
mysql> show status like '%onn%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| Aborted_connects | 0 |
| Connections | 303 |
| Max_used_connections | 127 |
| Ssl_client_connects | 0 |
| Ssl_connect_renegotiates | 0 |
| Ssl_finished_connects | 0 |
| Threads_connected | 127 |
+--------------------------+-------+
7 rows in set (0.01 sec)
Feel free to use Mysql-server-status-variables or Too-many-connections-problem
For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:
range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)
And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")
edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?
Here is a quick summary of the segues and an example for each type.
Show - Pushes the destination view controller onto the navigation stack, sliding overtop from right to left, providing a back button to return to the source - or if not embedded in a navigation controller it will be presented modally
Example: Navigating inboxes/folders in Mail
Show Detail - For use in a split view controller, replaces the detail/secondary view controller when in an expanded 2 column interface, otherwise if collapsed to 1 column it will push in a navigation controller
Example: In Messages, tapping a conversation will show the conversation details - replacing the view controller on the right when in a two column layout, or push the conversation when in a single column layout
Present Modally - Presents a view controller in various animated fashions as defined by the Presentation option, covering the previous view controller - most commonly used to present a view controller that animates up from the bottom and covers the entire screen on iPhone, or on iPad it's common to present it as a centered box that darkens the presenting view controller
Example: Selecting Touch ID & Passcode in Settings
Popover Presentation - When run on iPad, the destination appears in a popover, and tapping anywhere outside of this popover will dismiss it, or on iPhone popovers are supported as well but by default it will present the destination modally over the full screen
Example: Tapping the + button in Calendar
Custom - You may implement your own custom segue and have control over its behavior
The deprecated segues are essentially the non-adaptive equivalents of those described above. These segue types were deprecated in iOS 8: Push, Modal, Popover, Replace.
For more info, you may read over the Using Segues documentation which also explains the types of segues and how to use them in a Storyboard. Also check out Session 216 Building Adaptive Apps with UIKit from WWDC 2014. They talked about how you can build adaptive apps using these new Adaptive Segues, and they built a demo project that utilizes these segues.
You can kill two birds with one regex stone:
>>> r = """
... \n\tName: John Smith
... \n\t Home: Anytown USA
... \n\t Phone: 555-555-555
... \n\t Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t Misc: Data with spaces
... """
>>> import re
>>> print re.findall(r'(\S[^:]+):\s*(.*\S)', r)
[('Name', 'John Smith'), ('Home', 'Anytown USA'), ('Phone', '555-555-555'), ('Other Home', 'Somewhere Else'), ('Notes', 'Other data'), ('Name', 'Jane Smith'), ('Misc', 'Data with spaces')]
>>>
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.echo $'hello\nworld'
prints
hello
world
$''
strings use ANSI C Quoting:
Words of the form
$'string'
are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.
Depends, if i remember correctly i think asp.net won't render the html object out when you set visible to false.
If you want to be able to control it from the client side, then you better just include the css value to set it invisible rather than using visible =false.
you need to register it in index.android.js / index.ios.js
like this:
'use strict';
import {
AppRegistry
} from 'react-native';
import app from "./app";
AppRegistry.registerComponent('test', () => app);
If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index
If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test
rather than the default unittest
module.
Consider these two examples, which do the same thing:
Example 1 (unittest):
import unittest
class LearningCase(unittest.TestCase):
def test_starting_out(self):
self.assertEqual(1, 1)
def main():
unittest.main()
if __name__ == "__main__":
main()
Example 2 (pytest):
def test_starting_out():
assert 1 == 1
Assuming that both files are named test_unittesting.py
, how do we run the tests?
Example 1 (unittest):
cd /path/to/dir/
python test_unittesting.py
Example 2 (pytest):
cd /path/to/dir/
py.test
If you want buffers to work like tabs, check out the tabline plugin.
That uses a single window, and adds a line on the top to simulate the tabs (just showing the list of buffers). This came out a long time ago when tabs were only supported in GVim but not in the command line vim. Since it is only operating with buffers, everything integrates well with the rest of vim.
Filter()
from the base package is the perfect function for that use-case:
You simply have to code:
Filter(is.numeric, x)
It is also much faster than select_if()
:
library(microbenchmark)
microbenchmark(
dplyr::select_if(mtcars, is.numeric),
Filter(is.numeric, mtcars)
)
returns (on my computer) a median of 60 microseconds for Filter
, and 21 000 microseconds for select_if
(350x faster).
If you want to have a dynamic function like the __call
function in PHP, you could use Proxies.
const target = {};
const handler = {
get: function (target, name) {
return (myArg) => {
return new Promise(resolve => setTimeout(() => resolve('some' + myArg), 600))
}
}
};
const proxy = new Proxy(target, handler);
(async function() {
const result = await proxy.foo('string')
console.log('result', result) // 'result somestring' after 600 ms
})()
In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:
Happy coding!
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t st;
void *fun_t(void *arg);
void *fun_t(void *arg)
{
printf("Linux\n");
sem_post(&st);
//pthread_exit("Bye");
while(1);
pthread_exit("Bye");
}
int main()
{
pthread_t pt;
void *res_t;
if(pthread_create(&pt,NULL,fun_t,NULL) == -1)
perror("pthread_create");
if(sem_init(&st,0,0) != 0)
perror("sem_init");
if(sem_wait(&st) != 0)
perror("sem_wait");
printf("Sanoundry\n");
//Try commenting out join here.
if(pthread_join(pt,&res_t) == -1)
perror("pthread_join");
if(sem_destroy(&st) != 0)
perror("sem_destroy");
return 0;
}
Copy and paste this code on a gdb. Onlinegdb would work and see for yourself.
Make sure you understand once you have created a thread, the process run along with main together at the same time.
void *fun_t(void *arg)
{
printf("Linux\n");
sem_post(&st);
if(2-1 == 1)
pthread_exit("Bye");
else
{
printf("We have a problem. Computer is bugged");
pthread_exit("Bye"); //This is redundant since the thread will exit at the end
//of scope. But there are instances where you have a bunch
//of else if here.
}
}
I would want to demonstrate how sometimes you would need to have a segment of code running first using semaphore in this example.
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t st;
void* fun_t (void* arg)
{
printf("I'm thread\n");
sem_post(&st);
}
int main()
{
pthread_t pt;
pthread_create(&pt,NULL,fun_t,NULL);
sem_init(&st,0,0);
sem_wait(&st);
printf("before_thread\n");
pthread_join(pt,NULL);
printf("After_thread\n");
}
Noticed how fun_t is being ran after "before thread" The expected output if it is linear from top to bottom would be before thread, I'm thread, after thread. But under this circumstance, we block the main from running any further until the semaphore is released by func_t. The result can be verified with https://www.onlinegdb.com/
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.
Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.
According to MDN's article on Browser detection using the user agent, it is encouraged to avoid this approach if possible and suggest other avenues such as feature detection.
However, if one must use the user agent as a means to detect if the device is mobile, they suggest:
In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.
Therefore, this one-liner will suffice:
const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");
[UPDATE]:
As @zenw0lf suggests in the comments, using a Regular Expression would be better:
const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)
I've read all of the above answers but it seems like they have no common strategy. I found a good article about best practices in Design API from Microsoft Documents. I think you should refer.
In more complex systems, it can be tempting to provide URIs that enable a client to navigate through several levels of relationships, such as
/customers/1/orders/99/products.
However, this level of complexity can be difficult to maintain and is inflexible if the relationships between resources change in the future. Instead, try to keep URIs relatively simple. Once an application has a reference to a resource, it should be possible to use this reference to find items related to that resource. The preceding query can be replaced with the URI/customers/1/orders
to find all the orders for customer 1, and then/orders/99/products
to find the products in this order.
.
Tip
Avoid requiring resource URIs more complex than
collection/item/collection
.
Just by using select select
you can select particular columns, give them readable names and cast them. For example like this:
spark.read.csv(path).select(
'_c0.alias("stn").cast(StringType),
'_c1.alias("wban").cast(StringType),
'_c2.alias("lat").cast(DoubleType),
'_c3.alias("lon").cast(DoubleType)
)
.where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)
I think you're almost there, try removing the extra square brackets around the lst
's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):
import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
{'lst1Title': lst1,
'lst2Title': lst2,
'lst3Title': lst3
})
percentile_list
lst1Title lst2Title lst3Title
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
...
If you need a more performant solution you can use np.column_stack
rather than zip
as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:
import numpy as np
percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]),
columns=['lst1Title', 'lst2Title', 'lst3Title'])
What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.
Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.
You can use gregexpr
gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")
[[1]]
[1] 4 24
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE
or perhaps str_locate_all
from package stringr
which is a wrapper for gregexpr
stringi::stri_locate_all
(as of stringr
version 1.0)
library(stringr)
str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired")
[[1]]
start end
[1,] 4 4
[2,] 24 24
note that you could simply use stringi
library(stringi)
stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)
Another option in base R
would be something like
lapply(strsplit(x, ''), function(x) which(x == '2'))
should work (given a character vector x
)
You can use VLOOKUP
.
Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:
=VLOOKUP(A2, Sheet2!A:B, 2, 0)
This will return you #N/A
if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.
A very simple approach to this kind of problem is to use a number of random element swap in the list.
In pseudo-code this would look like this:
do
r1 = randomPositionInList()
r2 = randomPositionInList()
swap elements at index r1 and index r2
for a certain number of times
The term "bootstrapping" usually applies to a situation where a system depends on itself to start, sort of a chicken and egg problem.
For instance:
In that case, bootstrapping refers to a way of breaking the circular dependency, usually with the help of an external entity, e.g.
etc.
Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;
my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length
Or, you can iterate over this array by adding the following script:
for element in "${my_array[@]}"
do
echo "${element}"
done
Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).
You may find out you want to use the same config for more domains.
Following snippet removes www before any domain:
if ($host ~* ^www\.(.*)$) {
rewrite / $scheme://$1 permanent;
}
Please try the below query. Use sys.columns to get the details :-
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';
In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.
First method you can try this
$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();
Another way to insert records into the database with create function
$department = new Department;
// Another Way to insert records
$department->create($request->all());
return redirect('admin/departments');
You need to set the filledby in Department model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $fillable = ['department_name','status'];
}
In your TS Definition file, e.g. typings.d.ts`, you can add this line:
declare module "*.json" {
const value: any;
export default value;
}
Then add this in your typescript(.ts) file:-
import * as data from './colors.json';
const word = (<any>data).name;
SELECT [T1].*
FROM [Table1] AS [T1]
WHERE NOT EXISTS (SELECT
1 AS [C1]
FROM [Table2] AS [T2]
WHERE ([T2].[MAKE] = [T1].[MAKE]) AND
([T2].[MODEL] = [T1].[MODEL]) AND
([T2].[Serial Number] = [T1].[Serial Number])
);
Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.
The .project
file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)
The .classpath
file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings
directory inside the project); the .classpath
file is just one of them. Specifically, the .classpath
file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).
Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath
file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath
file portability.
If you have an java.awt.Image
, rezising it doesn't require any additional libraries. Just do:
Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
Ovbiously, replace newWidth
and newHeight
with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.
There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:
Image.SCALE_DEFAULT
: Use the default image-scaling algorithm.Image.SCALE_FAST
: Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.Image.SCALE_SMOOTH
: Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.Image.SCALE_AREA_AVERAGING
: Use the Area Averaging image scaling algorithm.Image.SCALE_REPLICATE
: Use the image scaling algorithm embodied in the ReplicateScaleFilter
class.See the Javadoc for more info.
In notepad++ press CTRL+H , in search mode click on the "Extended (\n, \r, \t ...)" radio button then type in the "Find what" box: \r\n (short for CR LF) and leave the "Replace with" box empty..
Finally hit replace all
If rooted:
Runtime.getRuntime().exec("su -c service call activity 42 s16 com.example.your_app");
As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:
On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):
$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start
In case you want to see the local variables of a calling function use select-frame
before info locals
E.g.:
(gdb) bt
#0 0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1 0xfec36f39 in thr_kill () from /lib/libc.so.1
#2 0xfebe3603 in raise () from /lib/libc.so.1
#3 0xfebc2961 in abort () from /lib/libc.so.1
#4 0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5 0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb)
Meanwhile, MacOS High Sierra can be run in VirtualBox (on a PC) for Free. It's not really fast but it works for general browser testing.
How to setup see here: https://www.howtogeek.com/289594/how-to-install-macos-sierra-in-virtualbox-on-windows-10/
I'm using this for a while now and it works quite well
I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:
jQuery('.bookmarkMeLink').click(function() {
if (window.sidebar && window.sidebar.addPanel) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(document.title,window.location.href,'');
}
else if(window.sidebar && jQuery.browser.mozilla){
//for other version of FF add rel="sidebar" to link like this:
//<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
jQuery(this).attr('rel', 'sidebar');
}
else if(window.external && ('AddFavorite' in window.external)) {
// IE Favorite
window.external.AddFavorite(location.href,document.title);
} else if(window.opera && window.print) {
// Opera Hotlist
this.title=document.title;
return true;
} else {
// webkit - safari/chrome
alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
}
});
This answer comes a little bit late, but I just was in a similar need.
Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.
For example, use the directive like this:
<my-directive class2add="special-class" />
And get the following html:
<div>
<ul>
<li class="special-class">Item 1</li>
<li class="special-class">Item 2</li>
</ul>
</div>
The solution found here applied with templateUrl, would be:
app.directive("myDirective", function() {
return {
template: function(element, attrs){
return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
},
link: function(scope, element, attrs) {
var list = element.find("ul");
}
}
});
Just tried it successfully with AngularJS 1.4.9.
Hope it helps.
You must put your mathematical expressions inside $(( )).
One-liner:
for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;
Multiple lines:
for i in {1..600}; do
wget http://example.com/search/link$(($i % 5))
done
In iOS 12, Swift 4.2 & XCode 10.1
//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
// button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)
//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
// button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)
@objc func buttonClicked(sender:UIButton) {
print("Button \(sender.tag) clicked")
}
//You can add UIButton properties like this also
extension UIButton {
func btnProperties() {
layer.cornerRadius = 10//Set button corner radious
clipsToBounds = true
backgroundColor = .blue//Set background colour
//titleLabel?.textAlignment = .center//add properties like this
}
}
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
One possibility is, if you are familiar with PDF format:
You get an valid document of any size, entire file will be processed by a reader.
In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.
Just refresh the port in your ajax url string to the appropriate one.
conn = new WebSocket('ws://localhost:3030'); //should solve the issue
The simplest way ist just to start it with start
start notepad.exe
Here you can find more information about start
For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.
I suspect most everyone really wants to disable zoom/scroll in order to put together a more app-like experience; because the answers seem to contain elements of solutions for both zooming and scrolling, but nobody's really nailed either one down.
To answer OP, the only thing you seem to need to do to disable scrolling is intercept the window's scroll
and touchmove
events and call preventDefault
and stopPropagation
on the events they generate; like so
window.addEventListener("scroll", preventMotion, false);
window.addEventListener("touchmove", preventMotion, false);
function preventMotion(event)
{
window.scrollTo(0, 0);
event.preventDefault();
event.stopPropagation();
}
And in your stylesheet, make sure your body
and html
tags include the following:
html:
{
overflow: hidden;
}
body
{
overflow: hidden;
position: relative;
margin: 0;
padding: 0;
}
However, scrolling is one thing, but you probably want to disable zoom as well. Which you do with the meta tag in your markup:
<meta name="viewport" content="user-scalable=no" />
All of these put together give you an app-like experience, probably a best fit for canvas.
(Be wary of the advice of some to add attributes like initial-scale
and width
to the meta tag if you're using a canvas, because canvasses scale their contents, unlike block elements, and you'll wind up with an ugly canvas, more often than not).
Colon is always "true":
while :; do foo; sleep 2; done
For some reason, it doesn't properly add an icon when running Windows 8+. Here's how I solved it:
Using Windows Explorer, navigate to:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2013
In that folder, you'll see a shortcut named Visual Studio Tools
that maps to (assuming default installation):
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts
Double-click the shortcut (or go to the folder above).
From that folder, copy the shortcut named Developer Command Prompt for VS2013
(and any others you find useful) to the first directory (for the Start Menu
). You'll likely be prompted for administrative access (do so).
Once you've done that, you'll now have an icon available for the 2013 command prompt.
I would do it this way if you needed an instance variable of the object to work with:
if @business = Business.where(:user_id => current_user.id).first
#Do stuff
else
#Do stuff
end
Object Oriented Programming offers:
Functional Programming, in Haskell or even in Scala, can allow substitution through more general mechanism of type classes. Mutable internal state is either discouraged or forbidden. Encapsulation of internal representation can also be achieved. See Haskell vs OOP for a good comparison.
Norman's assertion that "Adding a new kind of thing to a functional program may require editing many function definitions to add a new case." depends on how well the functional code has employed type classes. If Pattern Matching on a particular Abstract Data Type is spread throughout a codebase, you will indeed suffer from this problem, but it is perhaps a poor design to start with.
EDITED Removed reference to implicit conversions when discussing type classes. In Scala, type classes are encoded with implicit parameters, not conversions, although implicit conversions are another means to acheiving substitution of compatible types.
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
The output of this query is very clean (original here)
clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt ' Output filename : '
spool &&outfile..gen
SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON
BEGIN
DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/
SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;
spool off
HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:
DivX Web Player (NPAPI browsers only)
And here is the HTML:
<embed id="divxplayer" type="video/divx" width="1024" height="768"
src ="path_to_file" autoPlay=\"true\"
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>
The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.
Executive summary: it's 64 bits, or larger.
unsigned long long
is the same as unsigned long long int
. Its size is platform-dependent, but guaranteed by the C standard (ISO C99) to be at least 64 bits. There was no long long
in C89, but apparently even MSVC supports it, so it's quite portable.
In the current C++ standard (issued in 2003), there is no long long
, though many compilers support it as an extension. The upcoming C++0x standard will support it and its size will be the same as in C, so at least 64 bits.
You can get the exact size, in bytes (8 bits on typical platforms) with the expression sizeof(unsigned long long)
. If you want exactly 64 bits, use uint64_t
, which is defined in the header <stdint.h>
along with a bunch of related types (available in C99, C++11 and some current C++ compilers).
Try add -H tcp://0.0.0.0:2375
(at end of Execstart
line) instead of -H 0.0.0.0:2375
.
Use below code for IMEI:
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String imei= tm.getDeviceId();
When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.
Open Arduino IDE and go to files and click on the preference in the Arduino IDE.
Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.
Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.
You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.
I just want to explain it in my own way with a small story that I experienced in one of my projects. First I want to explain Why DAO is important? rather than go to What is DAO? for better understanding.
Why DAO is important?
In my one project of my project, I used Client.class
which contains all the basic information of our system users. Where I need client then every time I need to do an ugly query where it is needed. Then I felt that decreases the readability and made a lot of redundant boilerplate code.
Then one of my senior developers introduced a QueryUtils.class
where all queries are added using public static
access modifier and then I don't need to do query everywhere. Suppose when I needed activated clients then I just call -
QueryUtils.findAllActivatedClients();
In this way, I made some optimizations of my code.
But there was another problem !!!
I felt that the QueryUtils.class was growing very highly. 100+ methods were included in that class which was also very cumbersome to read and use. Because this class contains other queries of another domain models ( For example- products, categories locations, etc ).
Then the superhero Mr. CTO introduced a new solution named DAO which solved the problem finally. I felt DAO is very domain-specific. For example, he created a DAO called ClientDAO.class
where all Client.class
related queries are found which seems very easy for me to use and maintain. The giant QueryUtils.class
was broken down into many other domain-specific DAO for example - ProductsDAO.class
, CategoriesDAO.class
, etc which made the code more Readable, more Maintainable, more Decoupled.
What is DAO?
It is an object or interface, which made an easy way to access data from the database without writing complex and ugly queries every time in a reusable way.
Expanding on Clint Pachl's answer:
Regex matching in Ruby returns nil
when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example:
"foobar" =~ /bar/ # returns 3
"foobar" =~ /foo/ # returns 0
"foobar" =~ /zzz/ # returns nil
It's important to note that in Ruby only nil
and the boolean expression false
evaluate to false. Everything else, including an empty Array, empty Hash, or the Integer 0, evaluates to true.
That's why the /foo/
example above works, and why.
if "string" =~ /regex/
works as expected, only entering the 'true' part of the if
block if a match occurred.
This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value
' Close customer workbook
customerWorkbook.Close
java.util.Deque
has descendingIterator()
- if your List
is a Deque
, you can use that.
The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.
You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \r
rather than the linux standard \n
or better still the suspenders and belt approach of windows with \r\n
.
pandas.read_csv(filename, sep='\t', lineterminator='\r')
You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.
import codecs
doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set
df = pandas.read_csv(doc, sep='\t')
PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.
Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.
From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.
python 2.6+:
from __future__ import print_function # needs to be first statement in file
print('.', end='')
python 3:
print('.', end='')
python <= 2.5:
import sys
sys.stdout.write('.')
if extra space is OK after each print, in python 2
print '.',
misleading in python 2 - avoid:
print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `
It's easy enough to write your own comparison function:
function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );
Or inline (c/o Marco Demaio):
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
RouterModule.forRoot([
{ path: 'welcome', component: WelcomeComponent },
{ path: '', redirectTo: 'welcome', pathMatch: 'full' },
{ path: '**', component: 'pageNotFoundComponent' }
])
Case 1 pathMatch:'full'
:
In this case, when app is launched on localhost:4200
(or some server) the default page will be welcome screen, since the url will be https://localhost:4200/
If https://localhost:4200/gibberish
this will redirect to pageNotFound screen because of path:'**'
wildcard
Case 2
pathMatch:'prefix'
:
If the routes have { path: '', redirectTo: 'welcome', pathMatch: 'prefix' }
, now this will never reach the wildcard route since every url would match path:''
defined.
I compiled a small Bash script for Mac (easily can be ported to Linux) to retrieve all CPU features and apply some of them to build TF. Im on TF master and use kinda often (couple times in a month).
https://gist.github.com/venik/9ba962c8b301b0e21f99884cbd35082f
If you are using sass as style preprocessor, you can switch back to native Sass compiler for dev dependency by:
npm install node-sass --save-dev
So that you can keep using /deep/ for development.
SELECT ... INTO ...
only works if the table specified in the INTO clause does not exist - otherwise, you have to use:
INSERT INTO dbo.TABLETWO
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE @search_key
This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:
INSERT INTO dbo.TABLETWO
(col1, col2)
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE @search_key
I recently upgraded Django from 1.6 to 1.8 and had few apps and migrations for them. I used south and schemamigrations
for creating migrations in Django 1.6, which is dropped in Django 1.8.
When I added new models after upgrade, the makemigrations
command wasn't detecting any changes. And then I tried the solution suggested by @drojf (1st answer), it worked fine, but failed to apply fake initial migration (python manage.py --fake-initial
). I was doing this as my tables (old tables) were already created.
Finally this worked for me, removed new models (or model changes) from models.py and then had to delete (or rename for safety backup) migrations folder of all apps and run python manage.py
makemigrations for all apps, then did python manage.py migrate --fake-initial
. This worked like a charm. Once initial migration is created for all apps and fake initial migrated, then added new models and followed regular process of makemigrations
and migrate on that app. The changes were detected now and everything went fine.
I just thought of sharing it here, if someone faces same problem (having schemamigrations
of south for their apps), it might help them :)
The accepted answer works for me (on Linux), but I wanted this command to also save the buffer before running, so I modified it slightly:
nnoremap <buffer> <F9> :w <bar> :exec '!python' shellescape(@%, 1)<cr>
The :w <bar>
saves the buffer THEN runs the code in it.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
command to remove cordova and ionic
sudo npm uninstall -g ionic
These kind of bugs are common when Python multi-threading. What happens is that, on interpreter tear-down, the relevant module (myThread
in this case) goes through a sort-of del myThread
.
The call self.sample()
is roughly equivalent to myThread.__dict__["sample"](self)
.
But if we're during the interpreter's tear-down sequence, then its own dictionary of known types might've already had myThread
deleted, and now it's basically a NoneType
- and has no 'sample' attribute.
Use the TRUNCATE TABLE
command.
If you are looking for a simple and free alternative to Google Feed API for your rss widget then rss2json.com could be a suitable solution for that.
You may try to see how it works on a sample code from the api documentation below:
google.load("feeds", "1");_x000D_
_x000D_
function initialize() {_x000D_
var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");_x000D_
feed.load(function(result) {_x000D_
if (!result.error) {_x000D_
var container = document.getElementById("feed");_x000D_
for (var i = 0; i < result.feed.entries.length; i++) {_x000D_
var entry = result.feed.entries[i];_x000D_
var div = document.createElement("div");_x000D_
div.appendChild(document.createTextNode(entry.title));_x000D_
container.appendChild(div);_x000D_
}_x000D_
}_x000D_
});_x000D_
}_x000D_
google.setOnLoadCallback(initialize);
_x000D_
<html>_x000D_
<head> _x000D_
<script src="https://rss2json.com/gfapi.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<p><b>Result from the API:</b></p>_x000D_
<div id="feed"></div>_x000D_
</body>_x000D_
</html>
_x000D_
The newest version of docker (18.03) offers a built in port forwarding solution. Inside your docker container simply have the db host set to host.docker.internal
. This will be forwarded to the host the docker container is running on.
Documentation for this is here: https://docs.docker.com/docker-for-mac/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host
@ and @@ in modules also work differently when a class extends or includes that module.
So given
module A
@a = 'module'
@@a = 'module'
def get1
@a
end
def get2
@@a
end
def set1(a)
@a = a
end
def set2(a)
@@a = a
end
def self.set1(a)
@a = a
end
def self.set2(a)
@@a = a
end
end
Then you get the outputs below shown as comments
class X
extend A
puts get1.inspect # nil
puts get2.inspect # "module"
@a = 'class'
@@a = 'class'
puts get1.inspect # "class"
puts get2.inspect # "module"
set1('set')
set2('set')
puts get1.inspect # "set"
puts get2.inspect # "set"
A.set1('sset')
A.set2('sset')
puts get1.inspect # "set"
puts get2.inspect # "sset"
end
class Y
include A
def doit
puts get1.inspect # nil
puts get2.inspect # "module"
@a = 'class'
@@a = 'class'
puts get1.inspect # "class"
puts get2.inspect # "class"
set1('set')
set2('set')
puts get1.inspect # "set"
puts get2.inspect # "set"
A.set1('sset')
A.set2('sset')
puts get1.inspect # "set"
puts get2.inspect # "sset"
end
end
Y.new.doit
So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.
The Content-Security-Policy
meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.
I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.
For brevity I won’t write the full tag in each sample. Instead I'll only show the content
property, so a sample that says content="default-src 'self'"
means this:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
1. How can I allow multiple sources?
You can simply list your sources after a directive as a space-separated list:
content="default-src 'self' https://example.com/js/"
Note that there are no quotes around parameters other than the special ones, like 'self'
. Also, there's no colon (:
) after the directive. Just the directive, then a space-separated list of parameters.
Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:
https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js
These, however, would not be valid:
http://example.com/js/file.js
^^^^ wrong protocol
https://example.com/file.js
^^ above the specified path
2. How can I use different directives? What do they each do?
The most common directives are:
default-src
the default policy for loading javascript, images, CSS, fonts, AJAX requests, etcscript-src
defines valid sources for javascript filesstyle-src
defines valid sources for css filesimg-src
defines valid sources for imagesconnect-src
defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400
errorThere are others, but these are the ones you're most likely to need.
3. How can I use multiple directives?
You define all your directives inside one meta-tag by terminating them with a semicolon (;
):
content="default-src 'self' https://example.com/js/; style-src 'self'"
4. How can I handle ports?
Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:
content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"
The above would result in:
https://ajax.googleapis.com:123
^^^^ Not ok, wrong port
https://ajax.googleapis.com - OK
http://example.com/free/stuff/file.js
^^ Not ok, only the port 123 is allowed
http://example.com:123/free/stuff/file.js - OK
As I mentioned, you can also use an asterisk to explicitly allow all ports:
content="default-src example.com:*"
5. How can I handle different protocols?
By default, only standard protocols are allowed. For example to allow WebSockets ws://
you will have to allow it explicitly:
content="default-src 'self'; connect-src ws:; style-src 'self'"
^^^ web Sockets are now allowed on all domains and ports.
6. How can I allow the file protocol file://
?
If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem
parameter:
content="default-src filesystem"
7. How can I use inline scripts and style definitions?
Unless explicitly allowed, you can't use inline style definitions, code inside <script>
tags or in tag properties like onclick
. You allow them like so:
content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"
You'll also have to explicitly allow inline, base64 encoded images:
content="img-src data:"
8. How can I allow eval()
?
I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:
content="script-src 'unsafe-eval'"
9. What exactly does 'self'
mean?
You might take 'self'
to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.
I've used 'self'
in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.
But hang on a minute! Can't I just use content="default-src *"
and be done with it?
No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:
content="default-src * 'unsafe-inline' 'unsafe-eval'"
... but I trust you won’t.
Further reading:
If you using pipenv, just doing pipenv --rm
solves the problem.
you can use online library
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
or else download library and add css in css folder and jquery in js folder.both folder you keep in laravel public folder then you can link like below
<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>
or else
{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}
You can also use remove to remove a value by index as well.
n = [1, 3, 5]
n.remove(n[1])
n would then refer to [1, 5]
There are no unsigned integers in Java. All integers are signed and in big endian.
On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.
It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.
To convert from unsigned byte to a Java integer:
int i = (int) b & 0xFF;
To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):
long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;
alp_num = [x for x in string.split() if x.isalnum() and re.search(r'\d',x) and
re.search(r'[a-z]',x)]
print(alp_num)
This returns all the string that has both alphabets and numbers in it. isalpha() returns the string with all digits or all characters.
! [rejected] master -> master (non-fast-forward)
Don’t panic, this is extremely easy to fix. All you have to do is issue a pull and your branch will be fast-forward:
$ git pull myrepo master
Then retry your push and everything should be fine:
$ git push github master
In JDK7:
if ({"a", "b", "c"}.contains("a")) {
Assuming the Project Coin collections literals project goes through.
Edit: It didn't.
For people like me, linq addicts, and based on svick's answer, here a linq approach:
using System.Linq;
//...
//make it linq iterable.
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();
Now you can make linq expressions like:
JToken x = obj_linq
.Where( d => d.Key == "my_key")
.Select(v => v)
.FirstOrDefault()
.Value;
string y = ((JValue)x).Value;
Or just:
var y = obj_linq
.Where(d => d.Key == "my_key")
.Select(v => ((JValue)v.Value).Value)
.FirstOrDefault();
Or this one to iterate over all data:
obj_linq.ToList().ForEach( x => { do stuff } );
In xml add
<ListView android:longClickable="true">
In java file
lv.setLongClickable(true)
try this setOnItemLongClickListener()
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
//final String category = "Position at : "+pos;
final String category = ((TextView) view.findViewById(R.id.textView)).getText().toString();
Toast.makeText(getActivity(),""+category,Toast.LENGTH_LONG).show();
args = new Bundle();
args.putString("category", category);
return false;
}
});
If you don't want to go the SMO route you can search and replace "GO" for ";" and the query as you would. Note that soly the the last result set will be returned.
The for-each loop in Java uses the underlying iterator mechanism. So it's identical to the following:
Iterator<String> iterator = someList.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
System.out.println(item);
}
You have declared a function as nonstatic in some file and you have implemented as static in another file or somewhere in the same file can cause this problem also. For example, the following code will produce this error.
void inlet_update_my_ratio(object_t *myobject);
//some where the implementation is like this
static void inlet_update_my_ratio(object_t *myobject) {
//code
}
If you remove the static from the implementation, the error will go away as below.
void inlet_update_my_ratio(object_t *myobject) {
//code
}
In case you need to ROUND the result, not truncate, can use this:
select convert(decimal(38,4), round(convert(decimal(38,10), '123456789.1234567'),4))
This will return the following:
'123456789.1235' for '123456789.1234567'
'123456789.1234' for '123456789.1234467'
I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477
Or you can read it there ==>
When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.
I hade same problem then i fixed like this
change "text/javascript"
to
type="application/json"
First rename your module from app to i.e. SurveyApp
Second add this to your project top-level (root project) gradle. It's working with Gradle 3.0
//rename apk for all sub projects
subprojects {
afterEvaluate { project ->
if (project.hasProperty("android")) {
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${project.name}-${variant.name}-${variant.versionName}.apk"
}
}
}
}
}
Just pointing out that the Java Validation API (javax.validation.constraints.*
) doesn't come with a @Nullable
annotation, which is very valuable in a static analysis context. It makes sense for runtime bean validation as this is the default for any non-primitive field in Java (i.e. nothing to validate/enforce). For the purposes stated that should weigh towards the alternatives.
Drop the user, flush the privileges; then, create the user. It does work!
You don't need to wrap the iframe with an additional tag. Just make sure you increase the width and height of the iframe by the same amount you scale down the iframe.
e.g. to scale the iframe content to 80% :
#frame { /* Example size! */
height: 400px; /* original height */
width: 100%; /* original width */
}
#frame {
height: 500px; /* new height (400 * (1/0.8) ) */
width: 125%; /* new width (100 * (1/0.8) )*/
transform: scale(0.8);
transform-origin: 0 0;
}
Basically, to get the same size iframe you need to scale the dimensions.
add following lines in gitignore, from all undesirable files
/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers, however they are not competing technologies.
Websockets connections can both send data to the browser and receive data from the browser. A good example of an application that could use websockets is a chat application.
SSE connections can only push data to the browser. Online stock quotes, or twitters updating timeline or feed are good examples of an application that could benefit from SSE.
In practice since everything that can be done with SSE can also be done with Websockets, Websockets is getting a lot more attention and love, and many more browsers support Websockets than SSE.
However, it can be overkill for some types of application, and the backend could be easier to implement with a protocol such as SSE.
Furthermore SSE can be polyfilled into older browsers that do not support it natively using just JavaScript. Some implementations of SSE polyfills can be found on the Modernizr github page.
Gotchas:
www.example1.com
and another 6 SSE connections to www.example2.com
(thanks Phate).HTML5Rocks has some good information on SSE. From that page:
Server-Sent Events vs. WebSockets
Why would you choose Server-Sent Events over WebSockets? Good question.
One reason SSEs have been kept in the shadow is because later APIs like WebSockets provide a richer protocol to perform bi-directional, full-duplex communication. Having a two-way channel is more attractive for things like games, messaging apps, and for cases where you need near real-time updates in both directions. However, in some scenarios data doesn't need to be sent from the client. You simply need updates from some server action. A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms (e.g. updating a client-side Web SQL Database or IndexedDB object store). If you'll need to send data to a server, XMLHttpRequest is always a friend.
SSEs are sent over traditional HTTP. That means they do not require a special protocol or server implementation to get working. WebSockets on the other hand, require full-duplex connections and new Web Socket servers to handle the protocol. In addition, Server-Sent Events have a variety of features that WebSockets lack by design such as automatic reconnection, event IDs, and the ability to send arbitrary events.
Advantages of SSE over Websockets:
Advantages of Websockets over SSE:
Ideal use cases of SSE:
SSE gotchas:
Laravel's Autoload is a bit different:
1) It will in fact use Composer for some stuff
2) It will call Composer with the optimize flag
3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php
4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.
If you are using 12.2, you can simply say
set markup csv on
spool myfile.csv
You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.
How do I write asynchronous functions for Node?
Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.
How should I implement error event handling correctly
Generally API's give you a callback with an err as the first argument. For example
database.query('something', function(err, result) {
if (err) handle(err);
doSomething(result);
});
Is a common pattern.
Another common pattern is on('error')
. For example
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
Edit:
var async_function = function(val, callback){
process.nextTick(function(){
callback(val);
});
};
The above function when called as
async_function(42, function(val) {
console.log(val)
});
console.log(43);
Will print 42
to the console asynchronously. In particular process.nextTick
fires after the current eventloop callstack is empty. That call stack is empty after async_function
and console.log(43)
have run. So we print 43 followed by 42.
You should probably do some reading on the event loop.
Suppose you want to store the result of an echo command
echo hello
x=$(echo hello)
echo "$x",world!
output:
hello
hello,world!
This should help:
function getQueryParams(){
try{
url = window.location.href;
query_str = url.substr(url.indexOf('?')+1, url.length-1);
r_params = query_str.split('&');
params = {}
for( i in r_params){
param = r_params[i].split('=');
params[ param[0] ] = param[1];
}
return params;
}
catch(e){
return {};
}
}
func setTitleColor(_ color: UIColor?, for state: UIControl.State)
Parameters:
color:
The color of the title to use for the specified state.state:
The state that uses the specified color. The possible values are described in UIControl.State.
Sample:
let MyButton = UIButton()
MyButton.setTitle("Click Me..!", for: .normal)
MyButton.setTitleColor(.green, for: .normal)
One nautical mile (1852 meters) is defined as one arcminute of longitude at the equator. However, you need to define a map projection (see also UTM) in which you are working for the conversion to really make sense.
Use .is(':checked')
to determine whether or not it's checked, and then set your value accordingly.
zlib
handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.
You can try libzip. It is free, portable and easy to use.
UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:
#include <zip.h>
int main()
{
//Open the ZIP archive
int err = 0;
zip *z = zip_open("foo.zip", 0, &err);
//Search for the file of given name
const char *name = "file.txt";
struct zip_stat st;
zip_stat_init(&st);
zip_stat(z, name, 0, &st);
//Alloc memory for its uncompressed contents
char *contents = new char[st.size];
//Read the compressed file
zip_file *f = zip_fopen(z, name, 0);
zip_fread(f, contents, st.size);
zip_fclose(f);
//And close the archive
zip_close(z);
//Do something with the contents
//delete allocated memory
delete[] contents;
}
Take a look at this.
Change your query to:
SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;
SELECT @rank;
The last select is your count.
As a oneliner:
import os
# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )
# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )
A more robust solution accounting for files and directories as well would be (2.7):
def rm(f):
if os.path.isdir(f): return os.rmdir(f)
if os.path.isfile(f): return os.unlink(f)
raise TypeError, 'must be either file or directory'
map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )
The rJava package looks for the /usr/lib/jvm/default-java/
folder. But it's not available as default. This folder have a symlink for the default java configured for the system.
To activate the default java install the following packages:
sudo apt-get install default-jre default-jre-headless
Tested on ubuntu 17.04 with CRAN R 3.4.1
And this is how you connect to PostgreSQL using psycopg2 driver (install with "apt-get install python-psycopg2" if you're on Debian Linux derivative OS).
import pandas.io.sql as psql
import psycopg2
conn = psycopg2.connect("dbname='datawarehouse' user='user1' host='localhost' password='uberdba'")
q = """select month_idx, sum(payment) from bi_some_table"""
df3 = psql.frame_query(q, conn)
Instead of testing for an Array,
just convert whatever you get into a one-level Array,
so your code only needs to handle the one case.
t = [*something] # or...
t = Array(something) # or...
def f *x
...
end
Ruby has various ways to harmonize an API which can take an object or an Array of objects, so, taking a guess at why you want to know if something is an Array, I have a suggestion.
The splat operator contains lots of magic you can look up, or you can just call Array(something)
which will add an Array wrapper if needed. It's similar to [*something]
in this one case.
def f x
p Array(x).inspect
p [*x].inspect
end
f 1 # => "[1]"
f [1] # => "[1]"
f [1,2] # => "[1, 2]"
Or, you could use the splat in the parameter declaration and then .flatten
, giving you a different sort of collector. (For that matter, you could call .flatten
above, too.)
def f *x
p x.flatten.inspect
end # => nil
f 1 # => "[1]"
f 1,2 # => "[1, 2]"
f [1] # => "[1]"
f [1,2] # => "[1, 2]"
f [1,2],3,4 # => "[1, 2, 3, 4]"
And, thanks gregschlom, it's sometimes faster to just use Array(x)
because when it's already an Array
it doesn't need to create a new object.
I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
The code would look something like this (to count user objects):
from sqlalchemy import func
session.query(func.count(User.id)).scalar()
Tips of using OS-dependent function to terminate C++ thread:
std::thread::native_handle()
only can get the thread’s valid native handle type before calling join()
or detach()
. After that, native_handle()
returns 0 - pthread_cancel()
will coredump.
To effectively call native thread termination function(e.g. pthread_cancel()
), you need to save the native handle before calling std::thread::join()
or std::thread::detach()
. So that your native terminator always has a valid native handle to use.
More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .
Please NOTICE (at least in centos 8) the user who you are assigning listen.owner
and other stuff to it MUST
be in the same POOL with the user for example given I am the foo user
[www] # WRONG | IN MY CASE I WAS UNDER www POOL SO IT WASNT WORKING FOR ME.
[foo] # CORRECT | THE POOL AND THE USER MATCHES.
listen.owner = foo
listen.group = foo
listen.mode = 0660
user = foo
group = foo
I dont know if there's a global pool but after hours of searching I finlly did it.
Or just use $json as an object:
$json->$user = array("first" => $first, "last" => $last);
This is how it is returned without the second parameter (as an instance of stdClass).
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the evente
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
Easiest and simplest way:
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayName = days[new Date().getDay()];
Tried the given example, but over VPN and with 400k+ keys it was too slow for me. Also it did not give me the key objects.
I wrote a small Python called tool redis-mass-get to combine KEYS
and MGET
requests against Redis:
# installation:
pip install redis-mass-get
# pipeline example CSV:
redis-mass-get -f csv -och redis://my.redis.url product:* | less
# write to json-file example with progress indicator:
redis-mass-get -d results.json -jd redis://my.redis.url product:*
It supports JSON, CSV and TXT output to file or stdout
for usage in pipes. More info can be found at: Reading multiple key/values from Redis.
JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [42, 47, 139]
}
Short answer: AngularJS ("jqlite") doesn't support this. Include jQuery on your page (before including Angular), and it should work. See https://groups.google.com/d/topic/angular/H4haaMePJU0/discussion
CSS to detect screen orientation:
@media screen and (orientation:portrait) { … }
@media screen and (orientation:landscape) { … }
The CSS definition of a media query is at http://www.w3.org/TR/css3-mediaqueries/#orientation
I didn't see (hope I didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):
if (obj && obj.prop) {
// Do something;
}
If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is usually the desired behavior in most code block statements (in JavaScript).
Just create a data.frame
with 0 length variables
eg
nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)
## 'data.frame': 0 obs. of 3 variables:
## $ x: num
## $ y: int
## $ z: Factor w/ 0 levels:
or to create a data.frame with 5 columns named a,b,c,d,e
nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
It looks suspicious because there is no apparent function that is being returned from!
It is an anonymous function that has been attached to the click event of the object.
why are you doing this, Steve?
Why on earth are you doi.....Ah nevermind, as you've mentioned, it really is widely adopted bad practice :)
Building on Brian's answer, the upload-pack path can be set permanently by running the following commands after cloning, which eliminates the need for --upload-pack
on subsequent pull/fetch requests. Similarly, setting receive-pack eliminates the need for --receive-pack
on push requests.
git config remote.origin.uploadpack /path/to/git-upload-pack
git config remote.origin.receivepack /path/to/git-receive-pack
These two commands are equivalent to adding the following lines to a repo's .git/config
.
[remote "origin"]
uploadpack = /path/to/git-upload-pack
receivepack = /path/to/git-receive-pack
Frequent users of clone -u
may be interested in the following aliases. myclone should be self-explanatory. myfetch/mypull/mypush can be used on repos whose config hasn't been modified as described above by replacing git push
with git mypush
, and so on.
[alias]
myclone = clone --upload-pack /path/to/git-upload-pack
myfetch = fetch --upload-pack /path/to/git-upload-pack
mypull = pull --upload-pack /path/to/git-upload-pack
mypush = push --receive-pack /path/to/git-receive-pack
Try 'build-essential' instead.
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!
Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
Finally create a new Date
object and strip minutes and seconds
let finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
I'm agree with this definition:
The word "single" means single object across the application life cycle, so the scope is at application level.
The static does not have any Object pointer, so the scope is at App Domain level.
Moreover both should be implemented to be thread-safe.
You can find interesting other differences about: Singleton Pattern Versus Static Class
The :&&
command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):
:6,10s/<search_string>/<replace_string>/g | 14,18&&
If you have many ranges though, I'd rather use a loop:
:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor
Follow this instructions from standard eclipse docs.
IMHO, the most convenient way is to follow "Import CSV data into postgresql, the comfortable way ;-)", using csvsql from csvkit, which is a python package installable via pip.
For me, I had to add:
git config --global --unset http.proxy
Basically, you can run:
git config --global -l
to get the list of all proxy defined, and then use "--unset" to disable them
There are many ways git log -1
is the easiest and most common, I think
you have to used.
String value= et.getText().toString();
int finalValue=Integer.parseInt(value);
if you have only allow enter number then set EditText property.
android:inputType="number"
if this is helpful then accept otherwise put your comment.
You could just outright select the elements of interest.
$('a[href*="?"]').each(function() {
alert('Contains question mark');
});
http://jsfiddle.net/mattball/TzUN3/
Note that you were using the attribute-ends-with
selector, the above code uses the attribute-contains
selector, which is what it sounds like you're actually aiming for.
URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".
RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).
In Java, the correct way to build a URL is with the URI
class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString()
method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI
object using the single-string constructor and then use the accessor methods (such as getPath()
) to retrieve the decoded components.
Don't use the URLEncoder
class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder
. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).
The decimal operator might be more in line with what you are looking for:
>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434
System.Collections.Generic.List<t>
is already thread safe for multiple readers. Trying to make it thread safe for multiple writers wouldn't make sense. (For reasons Henk and Stephen already mentioned)
The normally used load command will work if you specify the object_pairs_hook parameter:
import json
from collections import OrderedDict
with open('foo.json', 'r') as fp:
metrics_types = json.load(fp, object_pairs_hook=OrderedDict)
I'm using Bootstrap 4 and Dennis Puzak's solution does not work for me.
The next solution works for me
.form-control::placeholder { color: white;} /* Chrome, Firefox, Opera*/
:-ms-input-placeholder.form-control { color: white; } /* Internet Explorer*/
.form-control::-ms-input-placeholder { color: white; } /* Microsoft Edge*/
The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).
In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character
So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).
And you can mix “combining above” and “combining below” marks.
The sample text in the question starts with:
H
ͭ
̓
̓
̇
You could query the dataset and then loop the selected rows to set them as delete.
var rows = dt.Select("col1 > 5");
foreach (var row in rows)
row.Delete();
... and you could also create some extension methods to make it easier ...
myTable.Delete("col1 > 5");
public static DataTable Delete(this DataTable table, string filter)
{
table.Select(filter).Delete();
return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
foreach (var row in rows)
row.Delete();
}
If you want to replace the nulls with something you can do this:
def fix_nulls(s):
for line in s:
yield line.replace('\0', ' ')
r = csv.reader(fix_nulls(open(...)))
time.h
defines a strftime
function which can give you a textual representation of a time_t
using something like:
#include <stdio.h>
#include <time.h>
int main (void) {
char buff[100];
time_t now = time (0);
strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
printf ("%s\n", buff);
return 0;
}
but that won't give you sub-second resolution since that's not available from a time_t
. It outputs:
2010-09-09 10:08:34.000
If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.
This will work
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
Here is a working example of how you could implement custom functions for your anchors.
You can attach an id to your anchor:
<li><a id="alertMe" href="#">Action</a></li>
And then use jQuery's click event listener to listen for the click action and fire you function:
$('#alertMe').click(function(e) {
alert('alerted');
e.preventDefault();// prevent the default anchor functionality
});
:not()
pseudo class:For selecting everything but a certain element (or elements). We can use the :not()
CSS pseudo class. The :not()
pseudo class requires a CSS
selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.
/* This query selects All div elements except for */_x000D_
div:not(.foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
<nav id="foo">test</nav>_x000D_
<nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
</ul>
_x000D_
We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor_x000D_
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>
_x000D_
>>> class A(object): pass
>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>>
what do you mean by convert into a string? you can define your own repr and str_ methods:
>>> class A(object):
def __repr__(self):
return 'hei, i am A or B or whatever'
>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever
or i dont know..please add explainations ;)
I get this every time I want to create an application in VC++.
Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.
Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.
This is the way I solved my problem:
Pull
from master.UPDATE:
As Hugo Zuleta rightly pointed out, you should be careful while applying this. He says that it might end up saying the branch is up to date, but the changes aren't shown, resulting in desync from the branch.
(reposting this answer)
You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types
package main
import "fmt"
import "encoding/binary"
func main() {
var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
data := binary.BigEndian.Uint64(mySlice)
fmt.Println(data)
}
You could create a mutable wrapper of the primitive int and create a Set of those:
class MutableInteger
{
private int value;
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
}
class Test
{
public static void main(String[] args)
{
Set<MutableInteger> mySet = new HashSet<MutableInteger>();
// populate the set
// ....
for (MutableInteger integer: mySet)
{
integer.setValue(integer.getValue() + 1);
}
}
}
Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.
You should have if row[2] != "0"
. Otherwise it's not checking to see if the string value is equal to 0.
you can use
<p><a href="/link/to/url" target="_blank"><button id="btn_id">Present Name </button></a></p>
Instead of using -f or --force developers should use
--force-with-lease
Why? Because it checks the remote branch for changes which is absolutely a good idea. Let's imagine that James and Lisa are working on the same feature branch and Lisa has pushed a commit. James now rebases his local branch and is rejected when trying to push. Of course James thinks this is due to rebase and uses --force and would rewrite all Lisa's changes. If James had used --force-with-lease he would have received a warning that there are commits done by someone else. I don't see why anyone would use --force instead of --force-with-lease when pushing after a rebase.
What do you think about video
tag ? If you don't have to use iframe
tag you can use video
tag instead.
<video width="500" height="345" src="hey.mp4" />
You should not use autoplay
attribute in your video
tag to disable autoplay.
official Link of DB 2 JDBC Driver from IBM
Why is everyone trying to do it the hard way? Sure, some of these approaches will work, but they're more complicated than is necessary.
OK, first - you need an image that will fit within your navbar. You can adjust your image via css height attribute (allowing width to scale) or you can just use an appropriately sized image. Whatever you decide to do - the way this looks will depend on how well you size your image.
For some reason, everyone wants to stick the image inside of an anchor with navbar-brand
, and this isn't necessary. navbar-brand
applies text styles that aren't necessary to an image, as well as the navbar-left
class (just like pull-left, but for use in a navbar). All you really need is to add navbar-left
.
<a href="#" class="navbar-left"><img src="/path/to/image.png"></a>
You can even follow this with a navbar-brand item, which will appear to the right of the image.
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
sttr1.search(str2);
it will return the position of the match, or -1 if it isn't found.
My solution. The JSONServer is a class I wrote for running an HttpListener server in a console window.
class Program
{
public static JSONServer srv = null;
static void Main(string[] args)
{
Console.WriteLine("NLPS Core Server");
srv = new JSONServer(100);
srv.Start();
InputLoopProcessor();
while(srv.IsRunning)
{
Thread.Sleep(250);
}
}
private static async Task InputLoopProcessor()
{
string line = "";
Console.WriteLine("Core NLPS Server: Started on port 8080. " + DateTime.Now);
while(line != "quit")
{
Console.Write(": ");
line = Console.ReadLine().ToLower();
Console.WriteLine(line);
if(line == "?" || line == "help")
{
Console.WriteLine("Core NLPS Server Help");
Console.WriteLine(" ? or help: Show this help.");
Console.WriteLine(" quit: Stop the server.");
}
}
srv.Stop();
Console.WriteLine("Core Processor done at " + DateTime.Now);
}
}
The task gives you all the goodness of the task API:
Task.ContinueWith
)Note that in both cases you can make your code slightly simpler with method group conversions:
DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);
There is no do-while loop in Python.
This is a similar construct, taken from the link above.
while True:
do_something()
if condition():
break
Just use matrix
:
matrix(vec,nrow = 7,ncol = 7)
One advantage of using matrix
rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow
argument in matrix
.
Ohhh, the performance horror! The answer is a bit outdated, but still...
public static class StringUtils
{
#region Private members
[ThreadStatic]
private static StringBuilder m_ReplaceSB;
private static StringBuilder GetReplaceSB(int capacity)
{
var result = m_ReplaceSB;
if (null == result)
{
result = new StringBuilder(capacity);
m_ReplaceSB = result;
}
else
{
result.Clear();
result.EnsureCapacity(capacity);
}
return result;
}
public static string ReplaceAny(this string s, char replaceWith, params char[] chars)
{
if (null == chars)
return s;
if (null == s)
return null;
StringBuilder sb = null;
for (int i = 0, count = s.Length; i < count; i++)
{
var temp = s[i];
var replace = false;
for (int j = 0, cc = chars.Length; j < cc; j++)
if (temp == chars[j])
{
if (null == sb)
{
sb = GetReplaceSB(count);
if (i > 0)
sb.Append(s, 0, i);
}
replace = true;
break;
}
if (replace)
sb.Append(replaceWith);
else
if (null != sb)
sb.Append(temp);
}
return null == sb ? s : sb.ToString();
}
}
A possible pattern for this issue is that you dont have connection to Nexus and basically you want to build the project in offline mode. But when you import the project Idea tries to download Maven dependencies automatically.. and fails. You set Work Offline checkbox in Settings, but its too late: something was already broken during initial download attempt. Neither of the options listed here worked for me to resolve this. Instead I did the following:
This way it worked.
for Python 2.7+ the idiomatic answer is to use subprocess.check_output()
You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....
If args is just single command with no args of its own (or you have shell=True
set), it can be a string. Otherwise it must be a list.
for example... to invoke the ls
command, this is fine:
from subprocess import check_call
check_call('ls')
so is this:
from subprocess import check_call
check_call(['ls',])
however, if you want to pass some args to the shell command, you can't do this:
from subprocess import check_call
check_call('ls -al')
instead, you must pass it as a list:
from subprocess import check_call
check_call(['ls', '-al'])
the shlex.split()
function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses...
like this:
from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))
Apart from the solution above, you can use AS
to make it in one line.
CREATE TABLE tbl_new AS SELECT * FROM tbl_old;
Use stat
like this:
#include <sys/stat.h> // stat
#include <stdbool.h> // bool type
bool file_exists (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
and call it like this:
#include <stdio.h> // printf
int main(int ac, char **av) {
if (ac != 2)
return 1;
if (file_exists(av[1]))
printf("%s exists\n", av[1]);
else
printf("%s does not exist\n", av[1]);
return 0;
}
I know that this is already answered, but for the record and for anyone with the same requeriments as me I decided to post this related answer. The code is flooded with comments to explain the code.
Save the file as getopt.sh
:
#!/bin/bash
function get_variable_name_for_option {
local OPT_DESC=${1}
local OPTION=${2}
local VAR=$(echo ${OPT_DESC} | sed -e "s/.*\[\?-${OPTION} \([A-Z_]\+\).*/\1/g" -e "s/.*\[\?-\(${OPTION}\).*/\1FLAG/g")
if [[ "${VAR}" == "${1}" ]]; then
echo ""
else
echo ${VAR}
fi
}
function parse_options {
local OPT_DESC=${1}
local INPUT=$(get_input_for_getopts "${OPT_DESC}")
shift
while getopts ${INPUT} OPTION ${@};
do
[ ${OPTION} == "?" ] && usage
VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
[ "${VARNAME}" != "" ] && eval "${VARNAME}=${OPTARG:-true}" # && printf "\t%s\n" "* Declaring ${VARNAME}=${!VARNAME} -- OPTIONS='$OPTION'"
done
check_for_required "${OPT_DESC}"
}
function check_for_required {
local OPT_DESC=${1}
local REQUIRED=$(get_required "${OPT_DESC}" | sed -e "s/\://g")
while test -n "${REQUIRED}"; do
OPTION=${REQUIRED:0:1}
VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
[ -z "${!VARNAME}" ] && printf "ERROR: %s\n" "Option -${OPTION} must been set." && usage
REQUIRED=${REQUIRED:1}
done
}
function get_input_for_getopts {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}
function get_optional {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/[^[]*\(\[[^]]*\]\)[^[]*/\1/g" -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}
function get_required {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/\[[^[]*\]//g" -e "s/[][ -]//g"
}
function usage {
printf "Usage:\n\t%s\n" "${0} ${OPT_DESC}"
exit 10
}
Then you can use it like this:
#!/bin/bash
#
# [ and ] defines optional arguments
#
# location to getopts.sh file
source ./getopt.sh
USAGE="-u USER -d DATABASE -p PASS -s SID [ -a START_DATE_TIME ]"
parse_options "${USAGE}" ${@}
echo ${USER}
echo ${START_DATE_TIME}
I recently needed to use a generic approach. I came across with this solution:
#!/bin/bash
# Option Description:
# -------------------
#
# Option description is based on getopts bash builtin. The description adds a variable name feature to be used
# on future checks for required or optional values.
# The option description adds "=>VARIABLE_NAME" string. Variable name should be UPPERCASE. Valid characters
# are [A-Z_]*.
#
# A option description example:
# OPT_DESC="a:=>A_VARIABLE|b:=>B_VARIABLE|c=>C_VARIABLE"
#
# -a option will require a value (the colon means that) and should be saved in variable A_VARIABLE.
# "|" is used to separate options description.
# -b option rule applies the same as -a.
# -c option doesn't require a value (the colon absense means that) and its existence should be set in C_VARIABLE
#
# ~$ echo get_options ${OPT_DESC}
# a:b:c
# ~$
#
# Required options
REQUIRED_DESC="a:=>REQ_A_VAR_VALUE|B:=>REQ_B_VAR_VALUE|c=>REQ_C_VAR_FLAG"
# Optional options (duh)
OPTIONAL_DESC="P:=>OPT_P_VAR_VALUE|r=>OPT_R_VAR_FLAG"
function usage {
IFS="|"
printf "%s" ${0}
for i in ${REQUIRED_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
printf " %s" "-${i:0:1} $VARNAME"
done
for i in ${OPTIONAL_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
printf " %s" "[-${i:0:1} $VARNAME]"
done
printf "\n"
unset IFS
exit
}
# Auxiliary function that returns options characters to be passed
# into 'getopts' from a option description.
# Arguments:
# $1: The options description (SEE TOP)
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# OPTIONS=$(get_options ${OPT_DESC})
# echo "${OPTIONS}"
#
# Output:
# "h:f:PW"
function get_options {
echo ${1} | sed -e "s/\([a-zA-Z]\:\?\)=>[A-Z_]*|\?/\1/g"
}
# Auxiliary function that returns all variable names separated by '|'
# Arguments:
# $1: The options description (SEE TOP)
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# VARNAMES=$(get_values ${OPT_DESC})
# echo "${VARNAMES}"
#
# Output:
# "H_VAR|F_VAR|P_VAR|W_VAR"
function get_variables {
echo ${1} | sed -e "s/[a-zA-Z]\:\?=>\([^|]*\)/\1/g"
}
# Auxiliary function that returns the variable name based on the
# option passed by.
# Arguments:
# $1: The options description (SEE TOP)
# $2: The option which the variable name wants to be retrieved
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# H_VAR=$(get_variable_name ${OPT_DESC} "h")
# echo "${H_VAR}"
#
# Output:
# "H_VAR"
function get_variable_name {
VAR=$(echo ${1} | sed -e "s/.*${2}\:\?=>\([^|]*\).*/\1/g")
if [[ ${VAR} == ${1} ]]; then
echo ""
else
echo ${VAR}
fi
}
# Gets the required options from the required description
REQUIRED=$(get_options ${REQUIRED_DESC})
# Gets the optional options (duh) from the optional description
OPTIONAL=$(get_options ${OPTIONAL_DESC})
# or... $(get_options "${OPTIONAL_DESC}|${REQUIRED_DESC}")
# The colon at starts instructs getopts to remain silent
while getopts ":${REQUIRED}${OPTIONAL}" OPTION
do
[[ ${OPTION} == ":" ]] && usage
VAR=$(get_variable_name "${REQUIRED_DESC}|${OPTIONAL_DESC}" ${OPTION})
[[ -n ${VAR} ]] && eval "$VAR=${OPTARG}"
done
shift $(($OPTIND - 1))
# Checks for required options. Report an error and exits if
# required options are missing.
# Using function version ...
VARS=$(get_variables ${REQUIRED_DESC})
IFS="|"
for VARNAME in $VARS;
do
[[ -v ${VARNAME} ]] || usage
done
unset IFS
# ... or using IFS Version (no function)
OLDIFS=${IFS}
IFS="|"
for i in ${REQUIRED_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
[[ -v ${VARNAME} ]] || usage
printf "%s %s %s\n" "-${i:0:1}" "${!VARNAME:=present}" "${VARNAME}"
done
IFS=${OLDIFS}
I didn't test this roughly, so I could have some bugs in there.
Try using SCP on Windows to transfer files, you can download SCP from Putty's website. Then try running:
pscp.exe filename.extension [email protected]:directory/subdirectory
There is a full length guide here.
Similar to older answers, but a bit simpler, without the lambda:
filter_kwargs = {
'field_a': 123,
'field_b__in': (3, 4, 5, ),
}
To filter these two conditions using OR
:
Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))
To get the same result programmatically:
list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))
(broken in two lines here, for clarity)
operator
is in standard library: import operator
From docstring:
or_(a, b) -- Same as a | b.
For Python3, reduce
is not a builtin any more but is still in the standard library: from functools import reduce
P.S.
Don't forget to make sure list_of_Q
is not empty - reduce()
will choke on empty list, it needs at least one element.
You can use a lambda:
Collectors.toMap(p -> p.getLast(), Function.identity())
or, more concisely, you can use a method reference using ::
:
Collectors.toMap(Person::getLast, Function.identity())
and instead of Function.identity
, you can simply use the equivalent lambda:
Collectors.toMap(Person::getLast, p -> p)
If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.
If you refresh a page with POST data, the browser will confirm your resubmission. If you use GET data, the message will not be displayed. You could also have the second page, after saving the submission, redirect to a third page with no data.
Use this line to get the division behavior you want:
from __future__ import division
Alternatively, you could use modulus:
if (a % b) == 0: #do something
$(document).on 'ready turbolinks:load', ->
console.log '(document).turbolinks:load'
The latest version of virtual box 6.0 supports HyperV ! https://docs.oracle.com/en/virtualization/virtualbox/6.0/admin/hyperv-support.html
str.split (" ")
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)
Check for the import statements.It should be ended with semicolon. If you miss any, you will get this error.
Also check whether following import statement added in you component.
import { threadId } from 'worker_threads';
If so remove that line. It works for me.
I suppose you want to get the content generated by PHP, if so use:
$Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');
Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:
$Vdata = file_get_contents('path/to/YOUR/FILE.php');