We tried to implement RenderScript blur like mentioned above in different answers. We were limited to use the v8 RenderScript version and that caused us a lot of trouble.
I want to share our dirty Java-only version which is slow and should be done on a separate thread and, if possible, before usage and therefore persisted.
private final Paint mPaint = new Paint();
public Bitmap blur(final String pathToBitmap) {
final BitmapFactory.Options options = new BitmapFactory.Options();
final Bitmap normalOne = BitmapFactory.decodeFile(pathToBitmap, options);
final Bitmap resultBitmap = Bitmap.createBitmap(options.outWidth, options.outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(resultBitmap);
mPaint.setAlpha(180);
canvas.drawBitmap(normalOne, 0, 0, mPaint);
int blurRadius = 12;
for (int row = -blurRadius; row < blurRadius; row += 2) {
for (int col = -blurRadius; col < blurRadius; col += 2) {
if (col * col + row * row <= blurRadius * blurRadius) {
mPaint.setAlpha((blurRadius * blurRadius) / ((col * col + row * row) + 1) * 2);
canvas.drawBitmap(normalOne, row, col, mPaint);
}
}
}
normalOne.recycle();
return resultBitmap;
}
This solution is far from perfect but creates a reasonable blur effect based on the fact, that it draws highly transparent version of the same image on top of a barely transparent "sharp" version. The alpha depends on the distance to the origin.
You can adjust some "magic numbers" to your needs. I just wanted to share that "solution" for everybody who has issues with the v8 support version of RenderScript.
The pattern you want is something like (see it on rubular.com):
^[a-zA-Z0-9_.-]*$
Explanation:
^
is the beginning of the line anchor$
is the end of the line anchor[...]
is a character class definition*
is "zero-or-more" repetitionNote that the literal dash -
is the last character in the character class definition, otherwise it has a different meaning (i.e. range). The .
also has a different meaning outside character class definitions, but inside, it's just a literal .
Here's a snippet to show how you can use this pattern:
<?php
$arr = array(
'screen123.css',
'screen-new-file.css',
'screen_new.js',
'screen new file.css'
);
foreach ($arr as $s) {
if (preg_match('/^[\w.-]*$/', $s)) {
print "$s is a match\n";
} else {
print "$s is NO match!!!\n";
};
}
?>
The above prints (as seen on ideone.com):
screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!
Note that the pattern is slightly different, using \w
instead. This is the character class for "word character".
This seems to follow your specification, but note that this will match things like .....
, etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.
The above regex also matches the empty string. If you need at least one character, then use +
(one-or-more) instead of *
(zero-or-more) for repetition.
In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.
The problem is not with extract
, which can certainly handle 'military time'. It looks like you have a default timestamp format which has HH
instead of HH24
; or at least that's the only way I can see to recreate this:
SQL> select value from nls_session_parameters
2 where parameter = 'NLS_TIMESTAMP_FORMAT';
VALUE
--------------------------------------------------------------------------------
DD-MON-RR HH24.MI.SSXFF
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
15
alter session set nls_timestamp_format = 'DD-MON-YYYY HH:MI:SS';
Session altered.
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') as timestamp)) from dual
*
ERROR at line 1:
ORA-01849: hour must be between 1 and 12
So the simple 'fix' is to set the format to something that does recognise 24-hours:
SQL> alter session set nls_timestamp_format = 'DD-MON-YYYY HH24:MI:SS';
Session altered.
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
15
Although you don't need the to_char
at all:
SQL> select extract(hour from cast(sysdate as timestamp)) from dual;
EXTRACT(HOURFROMCAST(SYSDATEASTIMESTAMP))
-----------------------------------------
15
It's probably faster and easier to use numpy.digitize()
:
import numpy
data = numpy.random.random(100)
bins = numpy.linspace(0, 1, 10)
digitized = numpy.digitize(data, bins)
bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]
An alternative to this is to use numpy.histogram()
:
bin_means = (numpy.histogram(data, bins, weights=data)[0] /
numpy.histogram(data, bins)[0])
Try for yourself which one is faster... :)
You can also drop the column and its constraint(s) in a single statement rather than individually.
CREATE TABLE #T
(
Col1 INT CONSTRAINT UQ UNIQUE CONSTRAINT CK CHECK (Col1 > 5),
Col2 INT
)
ALTER TABLE #T DROP CONSTRAINT UQ ,
CONSTRAINT CK,
COLUMN Col1
DROP TABLE #T
(but not other possible column dependencies such as foreign keys, unique and primary key constraints, computed columns, indexes)
CREATE TABLE [dbo].[TestTable]
(
A INT DEFAULT '1' CHECK (A=1),
B INT,
CHECK (A > B)
)
GO
DECLARE @TwoPartTableNameQuoted nvarchar(500) = '[dbo].[TestTable]',
@ColumnNameUnQuoted sysname = 'A',
@DynSQL NVARCHAR(MAX);
SELECT @DynSQL =
'ALTER TABLE ' + @TwoPartTableNameQuoted + ' DROP' +
ISNULL(' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(c.default_object_id)) + ',','') +
ISNULL(check_constraints,'') +
' COLUMN ' + QUOTENAME(@ColumnNameUnQuoted)
FROM sys.columns c
CROSS APPLY (SELECT ' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(referencing_id)) + ','
FROM sys.sql_expression_dependencies
WHERE referenced_id = c.object_id
AND referenced_minor_id = c.column_id
AND OBJECTPROPERTYEX(referencing_id, 'BaseType') = 'C'
FOR XML PATH('')) ck(check_constraints)
WHERE c.object_id = object_id(@TwoPartTableNameQuoted)
AND c.name = @ColumnNameUnQuoted;
PRINT @DynSQL;
EXEC (@DynSQL);
You misread the documentation. You need to do two things:
Luckily urllib.parse.urlencode
does both those things in a single step, and that's the function you should be using.
from urllib.parse import urlencode, quote_plus
payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'
You can cast null
to any reference type without getting any exception.
The println
method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null"
. Otherwise it will call the toString
method of that object.
Adding more details: Internally print methods call String.valueOf(object)
method on the input object. And in valueOf
method, this check helps to avoid null pointer exception:
return (obj == null) ? "null" : obj.toString();
For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.
See this example, you want to add to the list conditionally. Without the word "return", all ifs will be executed and add to the ArrayList!
Arraylist<String> list = new ArrayList<>();
public void addingToTheList() {
if(isSunday()) {
list.add("Pray today")
return;
}
if(isMonday()) {
list.add("Work today"
return;
}
if(isTuesday()) {
list.add("Tr today")
return;
}
}
Something you can try is using the bind method, I think this achieves what you were asking for. If nothing else, it's still very useful.
function doClick(elem, func) {
var diffElem = document.getElementById('some_element'); //could be the same or different element than the element in the doClick argument
diffElem.addEventListener('click', func.bind(diffElem, elem))
}
function clickEvent(elem, evt) {
console.log(this);
console.log(elem);
// 'this' and elem can be the same thing if the first parameter
// of the bind method is the element the event is being attached to from the argument passed to doClick
console.log(evt);
}
var elem = document.getElementById('elem_to_do_stuff_with');
doClick(elem, clickEvent);
You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else.
By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment
in order to find the action.
git push --tags production
You need a smoothed average, the easiest way is to take the current answer (the time to draw the last frame) and combine it with the previous answer.
// eg.
float smoothing = 0.9; // larger=more smoothing
measurement = (measurement * smoothing) + (current * (1.0-smoothing))
By adjusting the 0.9 / 0.1 ratio you can change the 'time constant' - that is how quickly the number responds to changes. A larger fraction in favour of the old answer gives a slower smoother change, a large fraction in favour of the new answer gives a quicker changing value. Obviously the two factors must add to one!
If you are concerned about the speed then you could also consider WebGL.
For those using Catalina and Xcode-beta:
sudo xcode-select -s /Applications/Xcode-beta.app/Contents/Developer
Converting to datetime64[D]
:
df.dates.values.astype('M8[D]')
Though re-assigning that to a DataFrame col will revert it back to [ns].
If you wanted actual datetime.date
:
dt = pd.DatetimeIndex(df.dates)
dates = np.array([datetime.date(*date_tuple) for date_tuple in zip(dt.year, dt.month, dt.day)])
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th ng-repeat="header in headers | filter:headerFilter | orderBy:headerOrder" width="{{header.width}}">{{header.label}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" ng-class-odd="'trOdd'" ng-class-even="'trEven'" ng-dblclick="rowDoubleClicked(user)">
<td ng-repeat="(key,val) in user | orderBy:userOrder(key)">{{val}}</td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
refer this https://gist.github.com/ebellinger/4399082
First I don't want to start a war..
I haven't used TextMate but I have used its Windows equivalent, e-TextEditor and I could understand why people love it.
I've also tried many text editors and IDEs in my quest in finding the perfect text editor on Linux. I've tried jEdit, vim, emacs (although I used to love when I was at uni) and various others.
On Linux I've settled with gEdit. Although I do use Komodo Edit from time to time. When I'm in a hurry I use gEdit purely because it is quicker than Komodo Edit. gEdit has plenty of plugins and comes with some nice colour schemes. I reckon once gEdit has a proper code-tidy facility it'll be cool. I think the only reason I use Komodo Edit is the project file facility.
I have a friend who donated his 'Vi Improved' book in the hope that he can convert me to Vim. The book is over an inch thick and completely put me off in investing time in learning Vim..
Everytime I find an editor - I always find myself going back to gEdit. It is a frills-in-the-right-places editor. Give gEdit a go, it is the default text editor in Ubuntu and Linux Mint.
Here is a link to an excellent guide on how to get gEdit to look and behave (somewhat) like TextMate: http://grigio.org/pimp_my_gedit_was_textmate_linux
Hope that helps.
this in your callback function refers to the clicked element.
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
Ids is the array of object ids:
const ids = [
'4ed3ede8844f0f351100000c',
'4ed3f117a844e0471100000d',
'4ed3f18132f50c491100000e',
];
Using Mongoose with callback:
Model.find().where('_id').in(ids).exec((err, records) => {});
Using Mongoose with async function:
const records = await Model.find().where('_id').in(ids).exec();
Or more concise:
const records = await Model.find({ '_id': { $in: ids } });
Don't forget to change Model with your actual model.
We can use class Log
in our local component and define the methods as v/i/e/d.
Based on the need of we can make call further.
example is shown below.
public class Log{
private static boolean TAG = false;
public static void d(String enable_tag, String message,Object...args){
if(TAG)
android.util.Log.d(enable_tag, message+args);
}
public static void e(String enable_tag, String message,Object...args){
if(TAG)
android.util.Log.e(enable_tag, message+args);
}
public static void v(String enable_tag, String message,Object...args){
if(TAG)
android.util.Log.v(enable_tag, message+args);
}
}
if we do not need any print(s), at-all make TAG as false for all else
remove the check for type of Log (say Log.d).
as
public static void i(String enable_tag, String message,Object...args){
// if(TAG)
android.util.Log.i(enable_tag, message+args);
}
here message is for string
and and args
is the value you want to print.
I've refactored @Academy of Programmer's answer to shorter code and altered it so that it only hits https://
URLs:
public static string GetExternalIPAddress()
{
string result = string.Empty;
string[] checkIPUrl =
{
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com/",
"https://api.ipify.org",
"https://icanhazip.com",
"https://wtfismyip.com/text"
};
using (var client = new WebClient())
{
client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
foreach (var url in checkIPUrl)
{
try
{
result = client.DownloadString(url);
}
catch
{
}
if (!string.IsNullOrEmpty(result))
break;
}
}
return result.Replace("\n", "").Trim();
}
}
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update
:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']
There are 3 things I can think of off the top of my head:
Try using django.core.urlresolvers.reverse
at the command line for a (possibly) better error
>>> from django.core.urlresolvers import reverse
>>> reverse('products.views.filter_by_led')
Check to see if you have more than one url that points to that view
In general, multiple inserts will be slower because of the connection overhead. Doing multiple inserts at once will reduce the cost of overhead per insert.
Depending on which language you are using, you can possibly create a batch in your programming/scripting language before going to the db and add each insert to the batch. Then you would be able to execute a large batch using one connect operation. Here's an example in Java.
This feature is called XML Inclusions (XInclude). Some examples:
s3_sync:
bucket: ansible-harshika
file_root: "{{ pathoftsfiles }}"
validate_certs: false
mode: push
key_prefix: "{{ folder }}"
here the variables are being used named as 'pathoftsfiles' and 'folder'. Now the value to this variable can be given by the below command
sudo ansible-playbook multiadd.yml --extra-vars "pathoftsfiles=/opt/lampp/htdocs/video/uploads/tsfiles/$2 folder=nitesh"
Note: Don't use the inverted commas while passing the values to the variable in the shell command
Big O notation is most commonly used by programmers as an approximate measure of how long a computation (algorithm) will take to complete expressed as a function of the size of the input set.
Big O is useful to compare how well two algorithms will scale up as the number of inputs is increased.
More precisely Big O notation is used to express the asymptotic behavior of a function. That means how the function behaves as it approaches infinity.
In many cases the "O" of an algorithm will fall into one of the following cases:
Big O ignores factors that do not contribute in a meaningful way to the growth curve of a function as the input size increases towards infinity. This means that constants that are added to or multiplied by the function are simply ignored.
Here's the lazy iterator approach:
from itertools import tee
def split_on_condition(seq, condition):
l1, l2 = tee((condition(item), item) for item in seq)
return (i for p, i in l1 if p), (i for p, i in l2 if not p)
It evaluates the condition once per item and returns two generators, first yielding values from the sequence where the condition is true, the other where it's false.
Because it's lazy you can use it on any iterator, even an infinite one:
from itertools import count, islice
def is_prime(n):
return n > 1 and all(n % i for i in xrange(2, n))
primes, not_primes = split_on_condition(count(), is_prime)
print("First 10 primes", list(islice(primes, 10)))
print("First 10 non-primes", list(islice(not_primes, 10)))
Usually though the non-lazy list returning approach is better:
def split_on_condition(seq, condition):
a, b = [], []
for item in seq:
(a if condition(item) else b).append(item)
return a, b
Edit: For your more specific usecase of splitting items into different lists by some key, heres a generic function that does that:
DROP_VALUE = lambda _:_
def split_by_key(seq, resultmapping, keyfunc, default=DROP_VALUE):
"""Split a sequence into lists based on a key function.
seq - input sequence
resultmapping - a dictionary that maps from target lists to keys that go to that list
keyfunc - function to calculate the key of an input value
default - the target where items that don't have a corresponding key go, by default they are dropped
"""
result_lists = dict((key, []) for key in resultmapping)
appenders = dict((key, result_lists[target].append) for target, keys in resultmapping.items() for key in keys)
if default is not DROP_VALUE:
result_lists.setdefault(default, [])
default_action = result_lists[default].append
else:
default_action = DROP_VALUE
for item in seq:
appenders.get(keyfunc(item), default_action)(item)
return result_lists
Usage:
def file_extension(f):
return f[2].lower()
split_files = split_by_key(files, {'images': IMAGE_TYPES}, keyfunc=file_extension, default='anims')
print split_files['images']
print split_files['anims']
All Answer all well but I want to add one more point
If you encounter a problem when you have table cells, Deque a new cell there is a mismatch in shadow so in this case, you need to place your shadow code in a layoutSubviews method so that it will behave nicely in all conditions.
-(void)layoutSubviews{
[super layoutSubviews];
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
[VPShadow applyShadowView:self];
}
or in ViewControllers for specific view place shadow code inside the following method so that it's work well
-(void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
[self.viewShadow layoutIfNeeded];
[VPShadow applyShadowView:self.viewShadow];
}
I have modified my shadow implementation for new devs for more generalized form ex:
/*!
@brief Add shadow to a view.
@param layer CALayer of the view.
*/
+(void)applyShadowOnView:(CALayer *)layer OffsetX:(CGFloat)x OffsetY:(CGFloat)y blur:(CGFloat)radius opacity:(CGFloat)alpha RoundingCorners:(CGFloat)cornerRadius{
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRoundedRect:layer.bounds cornerRadius:cornerRadius];
layer.masksToBounds = NO;
layer.shadowColor = [UIColor blackColor].CGColor;
layer.shadowOffset = CGSizeMake(x,y);// shadow x and y
layer.shadowOpacity = alpha;
layer.shadowRadius = radius;// blur effect
layer.shadowPath = shadowPath.CGPath;
}
this is a utility function I've created to solve this problem
//define radio buttons, each with a common 'name' and distinct 'id'.
// eg- <input type="radio" name="storageGroup" id="localStorage">
// <input type="radio" name="storageGroup" id="sessionStorage">
//param-sGroupName: 'name' of the group. eg- "storageGroup"
//return: 'id' of the checked radioButton. eg- "localStorage"
//return: can be 'undefined'- be sure to check for that
function checkedRadioBtn(sGroupName)
{
var group = document.getElementsByName(sGroupName);
for ( var i = 0; i < group.length; i++) {
if (group.item(i).checked) {
return group.item(i).id;
} else if (group[0].type !== 'radio') {
//if you find any in the group not a radio button return null
return null;
}
}
}
for swift 5, I write a demo to verify it.
extension String {
/// convert JsonString to Dictionary
func convertJsonStringToDictionary() -> [String: Any]? {
if let data = data(using: .utf8) {
return (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any]
}
return nil
}
}
let str = "{\"name\":\"zgpeace\"}"
let dict = str.convertJsonStringToDictionary()
print("string > \(str)")
// string > {"name":"zgpeace"}
print("dicionary > \(String(describing: dict))")
// dicionary > Optional(["name": zgpeace])
It's almost the same, you just have to change to use the CONCAT() function instead of the + operator :
UPDATE tb_Company
SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)),
SUBSTRING(CompanyIndustry, 2));
This would turn hello
to Hello
, wOrLd
to WOrLd
, BLABLA
to BLABLA
, etc. If you want to upper-case the first letter and lower-case the other, you just have to use LCASE function :
UPDATE tb_Company
SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)),
LCASE(SUBSTRING(CompanyIndustry, 2)));
Note that UPPER and UCASE do the same thing.
An alternative to the answer provided by @Marc
SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
CHARINDEX(';', YOUR_FIELD) > 0;
This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.
Recommended solution is to install and trust a self-signed certificate (root). Assuming you created your own CA and the hierarchy of the certificated is correct you don't need to change the server trust evaluation. This is recommended because it doesn't require any changes in the code.
If it is not possible then you need to change server trust evaluation.
More info in this document: Technical Q&A QA1948 HTTPS and Test Servers
If you are reading directly from CSV file then do like this.
myDataFrame <- read.csv("path/to/file.csv", header = TRUE, stringsAsFactors = FALSE)
In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline()
. While by default it will read up to the next '\n'
(which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like =
in your example.
For simplicity, the following presumes that the =
are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws
before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.
const char config[] = "url=http://example.com\n"
"file=main.exe\n"
"true=0";
std::istringstream is_file(config);
std::string line;
while( std::getline(is_file, line) )
{
std::istringstream is_line(line);
std::string key;
if( std::getline(is_line, key, '=') )
{
std::string value;
if( std::getline(is_line, value) )
store_line(key, value);
}
}
(Adding error handling is left as an exercise to the reader.)
// TO CHECK WHETHER A FILE IS OPENED
// OR NOT (not for .txt files)
// the file we want to check
String fileName = "C:\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
I realized the permissions for the files and folders in your server also matter. I uploaded my files from a linux operating system and usually the permissions are limited for read and write. So when uploaded, the permission are still same as in the local machine.
I had the same error and i just changed the permissions for the folder i had uploaded and the error was gone.
Hope it helps someone.
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
A workspace is just a text file with a (.code-workspace) extension. You can look at it by opening it with a text editor. I too was frustrated by the idea of a workspace and how it is implemented in Visual Studio Code. I found a method that suits me.
Start with a single "project" folder.
Open Visual Studio Code and close any open workspaces or files or folders. You should see only "OPEN EDITORS" and "NO FOLDER OPENED" in the EXPLORER.
From the menu bar* → File → Open Folder.... Navigate to where you want to put your folder and right click to open a new folder. Name it whatever you want, then click on "Select Folder". It will appear in the *Visual Studio Code explorer.
Now from menu File → Save Workspace As.... Name the workspace and save it wherever you want to keep all your workspaces, (not necessarily where your project folders are). I put all mine in a folder called "Visual Studio Code workspace".
It will be saved as a (.code-workspace
) file and is just an index to all the files and folders it contains (or points to) wherever they may be on your hard drive. You can look at it by opening it with a text editor. Close the folder you created and close Visual Studio Code.
Now find your workspace "file" and double click on it. This will open Visual Studio Code with the folder you created in your workspace. Or you can open Visual Studio Code and use "Open Workspace".
Any folders you create from within your Visual Studio Code workspace will be inside your first folder. If you want to add any more top level folders, create them first wherever you want them and then use "Add To Workspace.." from Visual Studio Code.
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
As an alternative you can also query the information_schema
database and retrieve the data from the global_variables
(and global_status
of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.
For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size
in bytes and megabytes:
SELECT
variable_name,
variable_value AS innodb_log_buffer_size_bytes,
ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE 'innodb_log_buffer_size';
As a result you get:
+------------------------+------------------------------+---------------------------+
| variable_name | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456 | 256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)
When we want to get multiple elements from a List into a new list (filter using a predicate) and remove them from the existing list, I could not find a proper answer anywhere.
Here is how we can do it using Java Streaming API partitioning.
Map<Boolean, List<ProducerDTO>> classifiedElements = producersProcedureActive
.stream()
.collect(Collectors.partitioningBy(producer -> producer.getPod().equals(pod)));
// get two new lists
List<ProducerDTO> matching = classifiedElements.get(true);
List<ProducerDTO> nonMatching = classifiedElements.get(false);
// OR get non-matching elements to the existing list
producersProcedureActive = classifiedElements.get(false);
This way you effectively remove the filtered elements from the original list and add them to a new list.
Refer the 5.2. Collectors.partitioningBy section of this article.
System.out
is just an instance of PrintStream
. You can check its JavaDoc. Its variability is based on method overloading (multiple methods with the same name, but with different parameters).
This print stream is sending its output to so called standard output.
In your question you mention a technique called variadic functions (or varargs). Unfortunately that is not supported by PrintStream#print
, so you must be mistaking this with something else. However it is very easy to implement these in Java. Just check the documentation.
And if you are curious how Java knows how to concatenate non-string variables "foo" + 1 + true + myObj
, it is mainly responsibility of a Java compiler.
When there is no variable involved in the concatenation, the compiler simply concatenates the string. When there is a variable involved, the concatenation is translated into StringBuilder#append
chain. There is no concatenation instruction in the resulting byte code; i.e. the +
operator (when talking about string concatenation) is resolved during the compilation.
All types in Java can be converted to string (int
via methods in Integer
class, boolean
via methods in Boolean
class, objects via their own #toString
, ...). You can check StringBuilder's source code if you are interested.
UPDATE: I was curious myself and checked (using javap) what my example System.out.println("foo" + 1 + true + myObj)
compiles into. The result:
System.out.println(new StringBuilder("foo1true").append(myObj).toString());
Change the backend to automatic:
Tools > preferences > IPython console > Graphics > Graphics backend > Backend: Automatic
Then close and open Spyder.
Try
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here
This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.
First of all, the code you wrote isn't portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here's a version that uses just a single header file and is portable to any platform that implements the C standard library.
#include <stdio.h>
int main(int argc, char **argv)
{
FILE* sourceFile;
FILE* destFile;
char buf[50];
int numBytes;
if(argc!=3)
{
printf("Usage: fcopy source destination\n");
return 1;
}
sourceFile = fopen(argv[1], "rb");
destFile = fopen(argv[2], "wb");
if(sourceFile==NULL)
{
printf("Could not open source file\n");
return 2;
}
if(destFile==NULL)
{
printf("Could not open destination file\n");
return 3;
}
while(numBytes=fread(buf, 1, 50, sourceFile))
{
fwrite(buf, 1, numBytes, destFile);
}
fclose(sourceFile);
fclose(destFile);
return 0;
}
EDIT: The glibc reference has this to say:
In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).
If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.
For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:
USE master
go
DENY VIEW ANY DATABASE TO [user]
go
This will address exactly the requirement outlined above..
This is related to a known issue with logging found in the Xcode 8 Beta Release Notes (also asked an engineer at WWDC).
When debugging WatchOS applications in the Watch simulator, the OS may produce an excessive amount of unhelpful logging. (26652255)
There is currently no workaround available, you must wait for a new version of Xcode.
EDIT 7/5/16: This is supposedly fixed as of Xcode 8 Beta 2:
Resolved in Xcode 8 beta 2 – IDE
Debugging
- When debugging an app on the Simulator, logs are visible. (26457535)
I faced this issue a lot. I am not sure if this is the issue, but I think, when xCode saw that there is an app with the same bundle identifier as of the app, I am trying to install, it didn't allow me. So, I had to delete the older one and attempted to install and it worked. However sometimes for testing purpose, I needed multiple version of the same app and in that case, I would change the bundle identifier and try to install. It only works if, I am using an wildcard provisioning profile.
I think maybe you should go to check the official instruction about carousel, for me, i have not found answer above, because of multiple versions of bootstrap, I'm using b4-alpha and i want the autoplay effect stop.
$(document).ready({
pause:true,
interval:false
});
this script does not make any effect while mouse leave that page, exactly carousel area. go to official definition and find those :
So you will find why.if carousel page onmouseover event triggered, page will pause, while mouse out of that page, it'll resume again.
So, if you want a page stop forever and rotate manually, you can just set data-interval='false'
.
"OK, adding that XML to the Web.config works, but it doesn’t answer the question"
It should be there. By default the add references list seems to be ordered, but its not the case. Hit the name header and look again.
If I know exactly how many elements I'm going to need, say I need 5 elements and only ever 5 elements then I use an array. Otherwise I just use a List<T>.
It's simplest to just call the function yourself directly the first time:
foo();
setInterval(foo, delay);
However there are good reasons to avoid setInterval
- in particular in some circumstances a whole load of setInterval
events can arrive immediately after each other without any delay. Another reason is that if you want to stop the loop you have to explicitly call clearInterval
which means you have to remember the handle returned from the original setInterval
call.
So an alternative method is to have foo
trigger itself for subsequent calls using setTimeout
instead:
function foo() {
// do stuff
// ...
// and schedule a repeat
setTimeout(foo, delay);
}
// start the cycle
foo();
This guarantees that there is at least an interval of delay
between calls. It also makes it easier to cancel the loop if required - you just don't call setTimeout
when your loop termination condition is reached.
Better yet, you can wrap that all up in an immediately invoked function expression which creates the function, which then calls itself again as above, and automatically starts the loop:
(function foo() {
...
setTimeout(foo, delay);
})();
which defines the function and starts the cycle all in one go.
The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.
If you set fetchType=EAGER
This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.
If you set fetchType=LAZY
the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.
You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.
For the second part of the question - how to get hibernate to generate optimised SQL?
Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.
MultipartFile multipartFile = new MockMultipartFile("test.xlsx", new FileInputStream(new File("/home/admin/test.xlsx")));
This code works fine for me. May be you can have a try.
It's not really a bug, just a difference in implantation by the browser vendors.
As a rule avoid browser sniffing. There is a nifty jQuery fix which is hinted at in the answers.
This is what works for me: $('html:not(:animated),body:not(:animated)').scrollTop()
On windows 7, find
C:\Users\Simion\AppData\Roaming\Sublime Text 2\Packages\Color Scheme - Default
Find your color scheme file, open it, and find lineHighlight
.
Ex:
<key>lineHighlight</key>
<string>#ccc</string>
replace #ccc
with your preferred background color.
I resolved error copying the files class.phpmailer.php , class.smtp.php to the folder where the file is PHPMailerAutoload.php, of course there should be the file that we will use to send the email.
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
Check out this plugin that does exacly that - jquery.initialize
It works exacly like .each function, the difference is it takes selector you've entered and watch for new items added in future matching this selector and initialize them
Initialize looks like this
$(".some-element").initialize( function(){
$(this).css("color", "blue");
});
But now if new element matching .some-element
selector will appear on page, it will be instanty initialized.
The way new item is added is not important, you dont need to care about any callbacks etc.
So if you'd add new element like:
$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!
it will be instantly initialized.
Plugin is based on MutationObserver
A bit late, but whatever.
If you prefer parsing JSON to JavaScript-like constructs making use of Kotlin syntax, I recommend JSONKraken, of which I am the author.
Suggestions and opinions on the matter are much apreciated!
It seems that you want to use step parameter of range function. From documentation:
range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) [0, 3, 6, 9]
>>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0) []
>>> range(1, 0) []
In your case to get [0,2,4] you can use:
range(0,6,2)
OR in your case when is a var:
idx = None
for i in range(len(str1)):
if idx and i < idx:
continue
for j in range(len(str2)):
if str1[i+j] != str2[j]:
break
else:
idx = i+j
this question seem quite old but incase you come pass it, you can use the PHP inbuilt function array_push() to push data in an array using the example below.
<?php
$item = array();
foreach($group_membership as $i => $username) {
array_push($item, $username);
}
print_r($items);
?>
I think your port is probably open, but you don't have anything that listens on it.
The Apple Mac OS X operating system has SSH installed by default but the SSH daemon is not enabled. This means you can’t login remotely or do remote copies until you enable it.
To enable it, go to ‘System Preferences’. Under ‘Internet & Networking’ there is a ‘Sharing’ icon. Run that. In the list that appears, check the ‘Remote Login’ option. In OS X Yosemite and up, there is no longer an 'Internet & Networking' menu; it was moved to Accounts. The Sharing menu now has its own icon on the main System Preferences menu. (thx @AstroCB)
This starts the SSH daemon immediately and you can remotely login using your username. The ‘Sharing’ window shows at the bottom the name and IP address to use. You can also find this out using ‘whoami’ and ‘ifconfig’ from the Terminal application.
These instructions are copied from Enable SSH in Mac OS X, but I wanted to make sure they won't go away and to provide quick access.
make your class public
access modifier,
just add public
keyword infront of your class name
namespace Test
{
public class Delivery
{
private string name;
private string address;
private DateTime arrivalTime;
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public DateTime ArrivlaTime
{
get { return arrivalTime; }
set { arrivalTime = value; }
}
public string ToString()
{
{ return name + address + arrivalTime.ToString(); }
}
}
}
I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111
check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null
Use q
flag for quiet mode, and tell wget
to output to stdout with O-
(uppercase o) and redirect to /dev/null
to discard the output:
wget -qO- $url &> /dev/null
>
redirects application output (to a file). if >
is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >
. If you don't specify ampersand, then only normal output is redirected.
./app &> file # redirect error and standard output to file
./app > file # redirect standard output to file
./app 2> file # redirect error output to file
if file is /dev/null
then all is discarded.
This works as well, and simpler:
wget -O/dev/null -q $url
Another option as of 2017 is to use Date.parse()
. MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:
install webpack-dev-server
npm i -g webpack-dev-server
start webpack-dev-server with https
webpack-dev-server --https
Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:
foreach (var s in strings)
query = query.Where(i => i.Prop == s); // access to modified closure
I do:
foreach (var s in strings)
{
string search = s;
query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}
Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.
scanner.useDelimiter(",");
This should work.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("/Users/pankaj/abc.csv"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
System.out.print(scanner.next()+"|");
}
scanner.close();
}
}
For CSV File:
a,b,c d,e
1,2,3 4,5
X,Y,Z A,B
Output is:
a|b|c d|e
1|2|3 4|5
X|Y|Z A|B|
If you lost a keystore file, don't create/update the new one with another set of value. First do the thorough search. Because it will overwrite the old one, so it will not match to your previous apk.
If you use eclipse most probably it will store in default path. For MAC (eclipse) it will be in your elispse installation path something like:
/Applications/eclipse/Eclipse.app/Contents/MacOS/
then your keystore file without any extension. You need root privilege to access this path (file).
Bdizzle,
I would recommend that you read this link
You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.
Be happy, Julian
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
I just had to solve the same problem: json-encoding an entity ("User") having a One-To-Many Bidirectional Association to another Entity ("Location").
I tried several things and I think now I found the best acceptable solution. The idea was to use the same code as written by David, but somehow intercept the infinite recursion by telling the Normalizer to stop at some point.
I did not want to implement a custom normalizer, as this GetSetMethodNormalizer is a nice approach in my opinion (based on reflection etc.). So I've decided to subclass it, which is not trivial at first sight, because the method to say if to include a property (isGetMethod) is private.
But, one could override the normalize method, so I intercepted at this point, by simply unsetting the property that references "Location" - so the inifinite loop is interrupted.
In code it looks like this:
class GetSetMethodNormalizer extends \Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer {
public function normalize($object, $format = null)
{
// if the object is a User, unset location for normalization, without touching the original object
if($object instanceof \Leonex\MoveBundle\Entity\User) {
$object = clone $object;
$object->setLocations(new \Doctrine\Common\Collections\ArrayCollection());
}
return parent::normalize($object, $format);
}
}
Install alone didn't work for me.
mvn deploy:deploy-file -Durl=file:///home/me/project/lib/ \
-Dfile=target/jzmq-2.1.3-SNAPSHOT.jar -DgroupId=org.zeromq \
-DartifactId=zeromq -Dpackaging=jar -Dversion=2.1.3
The chosen solution doesn't actually work for me because I get a
"Unexpected Token <"
error in Chrome. This is because the error is thrown as soon as the parse comes across and unknown character. However, there is a way around this if you are returning only string values through ajax (which can be fairly useful if you are using PHP or ASPX to process ajax requests and might or might not return JSON depending on conditions)
The solution is quite simple, you can do the following to check if it was a valid JSON return
var IS_JSON = true;
try
{
var json = $.parseJSON(msg);
}
catch(err)
{
IS_JSON = false;
}
As I have said before, this is the solution for if you are either returning string type stuff from your AJAX request or if you are returning mixed type.
I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing }
character. What's the length of result1
versus result2
? I'll note that result2
as you've quoted it has 169 characters.
GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t
, \n
, \r
, and space count as whitespace. In particular, note that trailing NUL (\0
) characters do not count as whitespace and will cause this error.
If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);
ALTER TABLE allitems
CHANGE itemid itemid INT(10) AUTO_INCREMENT;
How about:
conditions = [a, b, c]
if any(conditions) and not all(conditions):
...
Other variant:
if 1 <= sum(map(bool, conditions)) <= 2:
...
While this question is premised by not caring about the data, sometimes maintenance of the data is essential.
If so, I wrote a list of steps on how to recover from Entity Framework nightmare when the database already has tables with the same name here: How to recover from Entity Framework nightmare - database already has tables with the same name
Apparently... a moderator saw fit to delete my post so I'll paste it here:
How to recover from Entity Framework nightmare - database already has tables with the same name
Description: If you're like us when your team is new to EF, you'll end up in a state where you either can't create a new local database or you can't apply updates to your production database. You want to get back to a clean EF environment and then stick to basics, but you can't. If you get it working for production, you can't create a local db, and if you get it working for local, your production server gets out of sync. And finally, you don't want to delete any production server data.
Symptom: Can't run Update-Database because it's trying to run the creation script and the database already has tables with the same name.
Error Message: System.Data.SqlClient.SqlException (0x80131904): There is already an object named '' in the database.
Problem Background: EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.
To understand this in more detail, I'd recommend watching both videos referenced here: https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx
Solution: What we need to do is to trick EF into thinking that the current database is up to date while not applying these CreateTable commands. At the same time, we still want those commands to exist so we can create new local databases.
Step 1: Production DB clean First, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts. Open your production database and delete/drop the dbo.__MigrationHistory table.
Step 2: Local environment clean Open your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.
Step 3: Recreate Initial In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts). Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code. If you had any seed operations in the previous Configuration.cs, then copy that across.
Step 4: Trick EF At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.
Step 5: Update-Database With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like. Now, uncomment that code and save. You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.
Step 6: Confirm EF is ACTUALLY up to date If you had code that hadn't yet had migrations applied to it, this is what I did...
Run "Add-Migration MissingMigrations" This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.
Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.
Step 7: Re-confirm and commit. Build, test, run. Ensure that everything is running then commit the changes.
Step 8: Let the rest of your team know how to proceed. When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.
A couple of months ago, Micro Focus released a free tool that allows you to record Selenium scripts in Chrome and Firefox. It's called Silk WebDriver, you can download it for free from https://www.microfocus.com/products/silk-portfolio/silk-webdriver/
Disclaimer: I work for Micro Focus.
Generally speaking, the cli/php.ini
file is used when the PHP binary is called from the command-line.
You can check that running php --ini
from the command-line.
fpm/php.ini
will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo()
from a php page served by your webserver.
cgi/php.ini
, in your situation, will most likely not be used.
Using two distinct php.ini
files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.
Typically, in the php.ini
file that's used by the web-server, you'll specify a rather short max_execution_time
: web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini
file that will be used is the one in cli/
. For those scripts, you'll specify a much longer max_execution_time
in cli/php.ini
than you did in fpm/php.ini
.
max_execution_time
is a common example ; you could do the same with several other configuration directives, of course.
You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See https://developer.mozilla.org/en/docs/Web/CSS/@keyframes for more detailed info.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
display: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
_x000D_
nav.main ul li:hover ul {_x000D_
display: block;_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
animation: fade 1s;_x000D_
}_x000D_
_x000D_
@keyframes fade {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a></li>_x000D_
<li><a href="">Dolor</a></li>_x000D_
<li><a href="">Sit</a></li>_x000D_
<li><a href="">Amet</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Here is an update on your fiddle. https://jsfiddle.net/orax9d9u/1/
select phone, phone2 from jewishyellow.users
where phone like '813%' and phone2 is not null
If you don't mind using an image instead of a background color(or possibly an image with your background color) the solution below has worked for me in FireFox,Chrome and even IE without any over-rides. Set the image somewhere on the page and hide it until the user prints.
The html on the page with the background image
<img src="someImage.png" class="background-print-img">
The Css
.background-print-img{
display: none;
}
@media print{
.background-print-img{
background:red;
display: block;
width:100%;
height:100%;
position:absolute;
left:0;
top:0;
z-index:-10;
}
}
Your two statements are equivalent.
Most people only use LEFT JOIN
since it seems more intuitive, and it's universal syntax - I don't think all RDBMS support RIGHT JOIN
.
It is possible to SSH to Travis CI environment via a bounce host. The feature isn't built in Travis CI, but it can be achieved by the following steps.
travis
user and ensure that you can SSH to it.Put these lines in the script:
section of your .travis.yml
(e.g. at the end).
- echo travis:$sshpassword | sudo chpasswd
- sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/' /etc/ssh/sshd_config
- sudo service ssh restart
- sudo apt-get install sshpass
- sshpass -p $sshpassword ssh -R 9999:localhost:22 -o StrictHostKeyChecking=no travis@$bouncehostip
Where $bouncehostip
is the IP/host of your bounce host, and $sshpassword
is your defined SSH password. These variables can be added as encrypted variables.
Push the changes. You should be able to make an SSH connection to your bounce host.
Source: Shell into Travis CI Build Environment.
Here is the full example:
# use the new container infrastructure
sudo: required
dist: trusty
language: python
python: "2.7"
script:
- echo travis:$sshpassword | sudo chpasswd
- sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/' /etc/ssh/sshd_config
- sudo service ssh restart
- sudo apt-get install sshpass
- sshpass -p $sshpassword ssh -R 9999:localhost:22 -o StrictHostKeyChecking=no travisci@$bouncehostip
See: c-mart/travis-shell
at GitHub.
See also: How to reproduce a travis-ci build environment for debugging
Try this :
I assume your text file is on sd card
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text.toString());
following links can also help you :
How can I read a text file from the SD card in Android?
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
You have to modify the code like:
in chart.Doughnut.defaults
labelFontFamily : "Arial",
labelFontStyle : "normal",
labelFontSize : 24,
labelFontColor : "#666"
and then in function drawPieSegments
ctx.fillText(data[0].value + "%", width/2 - 20, width/2, 200);
See this pull: https://github.com/nnnick/Chart.js/pull/35
here is a fiddle http://jsfiddle.net/mayankcpdixit/6xV78/ implementing the same.
Please also remember that ||=
isn't an atomic operation and so, it isn't thread safe. As rule of thumb, don't use it for class methods.
If you are interested in html formatted email, make sure to pass Content-type: text/html;
in the header. Example:
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
For more details, check php mail function.
i have created a php function which is used to upload multiple images, this function can upload multiple images in specific folder as well it can saves the records into the database in the following code $arrayimage is the array of images which is sent through form note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.
$dir is the directory in which you want to save the image $fields is the name of the field which you want to store in the database
database field must be in array formate example if you have database imagestore and fields name like id,name,address then you need to post data like
$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);
and then pass that field into function $fields
$table is the name of the table in which you want to store the data..
function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
//extracting extension of uploaded file
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $arrayimage["name"]);
$extension = end($temp);
//validating image
if ((($arrayimage["type"] == "image/gif")
|| ($arrayimage["type"] == "image/jpeg")
|| ($arrayimage["type"] == "image/jpg")
|| ($arrayimage["type"] == "image/pjpeg")
|| ($arrayimage["type"] == "image/x-png")
|| ($arrayimage["type"] == "image/png"))
//check image size
&& ($arrayimage["size"] < 20000000)
//check iamge extension in above created extension array
&& in_array($extension, $allowedExts))
{
if ($arrayimage["error"] > 0)
{
echo "Error: " . $arrayimage["error"] . "<br>";
}
else
{
echo "Upload: " . $arrayimage["name"] . "<br>";
echo "Type: " . $arrayimage["type"] . "<br>";
echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
echo "Stored in: ".$arrayimage['tmp_name']."<br>";
//check if file is exist in folder of not
if (file_exists($dir."/".$arrayimage["name"]))
{
echo $arrayimage['name'] . " already exists. ";
}
else
{
//extracting database fields and value
foreach($fields as $key=>$val)
{
$f[]=$key;
$v[]=$val;
$fi=implode(",",$f);
$value=implode("','",$v);
}
//dynamic sql for inserting data into any table
$sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
//echo $sql;
$imginsquery=mysql_query($sql);
move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
echo "<br> Stored in: " .$dir ."/ Folder <br>";
}
}
}
//if file not match with extension
else
{
echo "Invalid file";
}
}
//function imageUpload ends here
}
//imageFunctions class ends here
you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code
Always preferred using a connection service file (lookup/google 'psql connection service file')
Then simply:
psql service={yourservicename} < {myfile.sql}
Where yourservicename
is a section name from the service file.
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
you can use
empty($result)
to check if the main array is empty or not.
But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php
ex:
if (empty($result) || !isset($result['Tags'])) {
return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
return false;
}
return ($result['Tags']->count());
As mentioned above modern browsers have the The HTMLElement.dataset API.
That API gives you a DOMStringMap, and you can retrieve the list of data-*
attributes simply doing:
var dataset = el.dataset; // as you asked in the question
you can also retrieve a array with the data-
property's key names like
var data = Object.keys(el.dataset);
or map its values by
Object.keys(el.dataset).map(function(key){ return el.dataset[key];});
// or the ES6 way: Object.keys(el.dataset).map(key=>{ return el.dataset[key];});
and like this you can iterate those and use them without the need of filtering between all attributes of the element like we needed to do before.
Put them in brackets []
:
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
None of the suggestions here helped me with my situation, but I read something that did give me an answer. I have a ViewController with a fixed set of UI controls followed by a UIWebView. I wanted the entire page to scroll as though the UI controls were connected to the HTML content, so I disable scrolling on the UIWebView and must then set the content size of a parent scroll view correctly.
The important tip turned out to be that UIWebView does not report its size correctly until rendered to the screen. So when I load the content I set the content size to the available screen height. Then, in viewDidAppear I update the scrollview's content size to the correct value. This worked for me because I am calling loadHTMLString on local content. If you are using loadRequest you may need to update the contentSize in webViewDidFinishLoad also, depending on how quickly the html is retrieved.
There is no flickering, because only the invisible part of the scroll view is changed.
I had this problem but I solved it by installing the version of the ruby that is specified in my gem file using the RVM
rvm install (ruby version)
After the installation, I use the following command to use the the version that you installed.
rvm --default use (ruby version)
You have to install bundler by using the following command in order to use the latest version
gem install bundler
After the above steps, you can now run following command to install the gems specified on the gemfile
bundle install
If the user exists you can get the user in user_object
else user_object
will be None
.
try:
user_object = User.objects.get(email = cleaned_info['username'])
except User.DoesNotExist:
user_object = None
if user_object:
# user exist
pass
else:
# user does not exist
pass
(For completeness) If you want to remove columns by name, you can do this:
cols.dont.want <- "genome"
cols.dont.want <- c("genome", "region") # if you want to remove multiple columns
data <- data[, ! names(data) %in% cols.dont.want, drop = F]
Including drop = F
ensures that the result will still be a data.frame
even if only one column remains.
The floated elements do not add to the height of the container element, and hence if you don't clear them, container height won't increase...
I'll show you visually:
More Explanation:
<div>
<div style="float: left;"></div>
<div style="width: 15px;"></div> <!-- This will shift
besides the top div. Why? Because of the top div
is floated left, making the
rest of the space blank -->
<div style="clear: both;"></div>
<!-- Now in order to prevent the next div from floating beside the top ones,
we use `clear: both;`. This is like a wall, so now none of the div's
will be floated after this point. The container height will now also include the
height of these floated divs -->
<div></div>
</div>
You can also add overflow: hidden;
on container elements, but I would suggest you use clear: both;
instead.
Also if you might like to self-clear an element you can use
.self_clear:after {
content: "";
clear: both;
display: table;
}
The float
property is misunderstood by most beginners. Well, what exactly does float
do? Initially, the float
property was introduced to flow text around images, which are floated left
or right
. Here's another explanation by @Madara Uchicha.
So, is it wrong to use the float
property for placing boxes side by side? The answer is no; there is no problem if you use the float
property in order to set boxes side by side.
Floating an inline
or block
level element will make the element behave like an inline-block
element.
If you float an element left
or right
, the width
of the element will be limited to the content it holds, unless width
is defined explicitly ...
You cannot float
an element center
. This is the biggest issue I've always seen with beginners, using , which is not a valid value for the float: center;
float
property. float
is generally used to float
/move content to the very left or to the very right. There are only four valid values for float
property i.e left
, right
, none
(default) and inherit
.
Parent element collapses, when it contains floated child elements, in order to prevent this, we use clear: both;
property, to clear the floated elements on both the sides, which will prevent the collapsing of the parent element. For more information, you can refer my another answer here.
(Important) Think of it where we have a stack of various elements. When we use float: left;
or float: right;
the element moves above the stack by one. Hence the elements in the normal document flow will hide behind the floated elements because it is on stack level above the normal floated elements. (Please don't relate this to z-index
as that is completely different.)
Taking a case as an example to explain how CSS floats work, assuming we need a simple 2 column layout with a header, footer, and 2 columns, so here is what the blueprint looks like...
In the above example, we will be floating only the red boxes, either you can float
both to the left
, or you can float
on to left
, and another to right
as well, depends on the layout, if it's 3 columns, you may float
2 columns to left
where another one to the right
so depends, though in this example, we have a simplified 2 column layout so will float
one to left
and the other to the right
.
Markup and styles for creating the layout explained further down...
<div class="main_wrap">
<header>Header</header>
<div class="wrapper clear">
<div class="floated_left">
This<br />
is<br />
just<br />
a<br />
left<br />
floated<br />
column<br />
</div>
<div class="floated_right">
This<br />
is<br />
just<br />
a<br />
right<br />
floated<br />
column<br />
</div>
</div>
<footer>Footer</footer>
</div>
* {
-moz-box-sizing: border-box; /* Just for demo purpose */
-webkkit-box-sizing: border-box; /* Just for demo purpose */
box-sizing: border-box; /* Just for demo purpose */
margin: 0;
padding: 0;
}
.main_wrap {
margin: 20px;
border: 3px solid black;
width: 520px;
}
header, footer {
height: 50px;
border: 3px solid silver;
text-align: center;
line-height: 50px;
}
.wrapper {
border: 3px solid green;
}
.floated_left {
float: left;
width: 200px;
border: 3px solid red;
}
.floated_right {
float: right;
width: 300px;
border: 3px solid red;
}
.clear:after {
clear: both;
content: "";
display: table;
}
Let's go step by step with the layout and see how float works..
First of all, we use the main wrapper element, you can just assume that it's your viewport, then we use header
and assign a height
of 50px
so nothing fancy there. It's just a normal non floated block level element which will take up 100%
horizontal space unless it's floated or we assign inline-block
to it.
The first valid value for float
is left
so in our example, we use float: left;
for .floated_left
, so we intend to float a block to the left
of our container element.
And yes, if you see, the parent element, which is .wrapper
is collapsed, the one you see with a green border didn't expand, but it should right? Will come back to that in a while, for now, we have got a column floated to left
.
Coming to the second column, lets it float
this one to the right
Another column floated to the right
Here, we have a 300px
wide column which we float
to the right
, which will sit beside the first column as it's floated to the left
, and since it's floated to the left
, it created empty gutter to the right
, and since there was ample of space on the right
, our right
floated element sat perfectly beside the left
one.
Still, the parent element is collapsed, well, let's fix that now. There are many ways to prevent the parent element from getting collapsed.
clear: both;
before the parent element ends, which holds floated elements, now this one is a cheap solution to clear
your floating elements which will do the job for you but, I would recommend not to use this.Add, <div style="clear: both;"></div>
before the .wrapper
div
ends, like
<div class="wrapper clear">
<!-- Floated columns -->
<div style="clear: both;"></div>
</div>
Well, that fixes very well, no collapsed parent anymore, but it adds unnecessary markup to the DOM, so some suggest, to use overflow: hidden;
on the parent element holding floated child elements which work as intended.
Use overflow: hidden;
on .wrapper
.wrapper {
border: 3px solid green;
overflow: hidden;
}
That saves us an element every time we need to clear
float
but as I tested various cases with this, it failed in one particular one, which uses box-shadow
on the child elements.
Demo (Can't see the shadow on all 4 sides, overflow: hidden;
causes this issue)
So what now? Save an element, no overflow: hidden;
so go for a clear fix hack, use the below snippet in your CSS, and just as you use overflow: hidden;
for the parent element, call the class
below on the parent element to self-clear.
.clear:after {
clear: both;
content: "";
display: table;
}
<div class="wrapper clear">
<!-- Floated Elements -->
</div>
Here, shadow works as intended, also, it self-clears the parent element which prevents to collapse.
And lastly, we use footer after we clear
the floated elements.
When is float: none;
used anyways, as it is the default, so any use to declare float: none;
?
Well, it depends, if you are going for a responsive design, you will use this value a lot of times, when you want your floated elements to render one below another at a certain resolution. For that float: none;
property plays an important role there.
Few real-world examples of how float
is useful.
img
floated inside p
which will enable our content to flow around.Demo (Without floating img
)
Demo 2 (img
floated to the left
)
float
for creating horizontal menu - DemoLast but not the least, I want to explain this particular case where you float
only single element to the left
but you do not float
the other, so what happens?
Suppose if we remove float: right;
from our .floated_right
class
, the div
will be rendered from extreme left
as it isn't floated.
So in this case, either you can float
the to the left
as well
OR
You can use margin-left
which will be equal to the size of the left floated column i.e 200px
wide.
Unicode Property Escapes are among the features of ES2018.
With Unicode Property Escapes, you can match a letter from any language with the following simple regular expression:
/\p{Letter}/u
Or with the shorthand, even terser:
/\p{L}/u
Regarding the question's concrete use case (matching words), note that you can use Unicode Property Escapes in character classes, making it easy to match letters together with other word-characters like hyphens:
/[\p{L}-]/u
Stitching it all together, you could match words of all[1] languages with this beautifully short RegEx:
/[\p{L}-]+/ug
Example (shamelessly plugged from the answer above):
'Düsseldorf, Köln, ??????, ???, ??????? !@#$'.match(/[\p{L}-]+/ug)
// ["Düsseldorf", "Köln", "??????", "???", "???????"]
[1] Note that I'm not an expert on languages. You may still want to do your own research regarding other characters that might be parts of words besides letters and hyphens.
This feature is available in all major evergreen browsers.
If support for older browsers is needed, Unicode Property Escapes can be transpiled to ES5 with a tool called regexpu. There's an online demo available here. As you can see in the demo, you can in fact match non-latin letters today with the following (horribly long) ES5 regular expression:
/(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])/
If you're using Babel, there's also a regexpu-powered plugin for that (Babel v6 plugin, Babel v7 plugin).
Do it like this:
char s[256];
strcpy(s, "one two three");
char* token = strtok(s, " ");
while (token) {
printf("token: %s\n", token);
token = strtok(NULL, " ");
}
Note: strtok
modifies the string its tokenising, so it cannot be a const char*
.
It's hard to know how to help you without understanding the context / structure of your data, but I believe this might help you:
SELECT
SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count
,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count
,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count
FROM table
Use array_values(array_unique($array));
array_unique
: for unique array
array_values
: for reindexing
You simply select dates that are higher than the current time minus 1 day.
SELECT * FROM news WHERE date >= now() - INTERVAL 1 DAY;
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
Consider There are N items to be selected.
After adding these N items, add the hint text as (N+1)th item.
Set the selected item to Nth position [(N+1)th item].
In your OnItemSelected Listener, if the selected position is not N, pop the last item and call Adapter.notifyDataSetChanged() and set selected item as the selected position.
Something like this:
spinner.setItems("Daily", "One time", "Frequency"); // here "Frequency is the hint text"
spinner.setSelectedIndex(2);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(Spinner view, int position, long id, Object item) {
if (position != 2) {
view.setItems("Daily", "One time");
view.setSelectedIndex(position);
}else {
// This item is not a valid selection
}
}
});
To check for the NULL data for column1 and consider your datatype of it is String, you could use below command :
select * from tbl_name where column1 is null or column1 <> '';
I was having this exact problem, the above solutions didn't make much sense to me.
My Solution:
Turn of Bluetooth! Worked a treat ..
After connecting my macbook pro to iphone5 (hotspot) I started getting error message, after turning of bluetooth the error message is gone ..Hope that helps somebody!
Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException )
and then also use full path of file in which you are writing as
PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");
all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own. it should be as
import java.io.*;
public class PrintWriterClass {
public static void main(String arg[]) throws IOException{
PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
pw.println("hiiiiiii");
pw.close();
}
}
The following approach was inspired by this answer to a related (more general) question.
The approach is to read the MachineGuid
value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
. This value is generated during OS installation.
There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid
value.
However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.
public string GetMachineGuid()
{
string location = @"SOFTWARE\Microsoft\Cryptography";
string name = "MachineGuid";
using (RegistryKey localMachineX64View =
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
{
if (rk == null)
throw new KeyNotFoundException(
string.Format("Key Not Found: {0}", location));
object machineGuid = rk.GetValue(name);
if (machineGuid == null)
throw new IndexOutOfRangeException(
string.Format("Index Not Found: {0}", name));
return machineGuid.ToString();
}
}
}
You expose ports using the EXPOSE keyword in the Dockerfile or the --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.
Source: github commit
Do you want your function to react to an array argument or variable arguments? If the latter, try:
var func = function(...rest) {
alert(rest.length);
// In JS, don't use for..in with arrays
// use for..of that consumes array's pre-defined iterator
// or a more functional approach
rest.forEach((v) => console.log(v));
};
But if you wish to handle an array argument
var fn = function(arr) {
alert(arr.length);
for(var i of arr) {
console.log(i);
}
};
Here is another quick approach without using additional panel.
JFrame f = new JFrame("stackoverflow") {
private Image backgroundImage = ImageIO.read(new File("background.jpg"));
public void paint( Graphics g ) {
super.paint(g);
g.drawImage(backgroundImage, 0, 0, null);
}
};
Found this solution in Spring in Action 3rd Ed.
<img src="../resources/images/Image1.jpg" onerror="this.src='../resources/images/none.jpg'" />
Update:
This is not an HTML only solution... onerror
is javascript
You may remove the System.out
line. It is added for debug purposes.
WebDriver driver_;
public void waitForPageLoad() {
Wait<WebDriver> wait = new WebDriverWait(driver_, 30);
wait.until(new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver driver) {
System.out.println("Current Window State : "
+ String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState")));
return String
.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState"))
.equals("complete");
}
});
}
FWIW - Here's a directive I've used for a basic confirm/alert bootstrap modal, without the need for a <form>
(just switch out the jQuery click action for whatever you like, and add data-easy-dismiss
to your modal tag)
app.directive('easyDismiss', function() {
return {
restrict: 'A',
link: function ($scope, $element) {
var clickSubmit = function (e) {
if (e.which == 13) {
$element.find('[type="submit"]').click();
}
};
$element.on('show.bs.modal', function() {
$(document).on('keypress', clickSubmit);
});
$element.on('hide.bs.modal', function() {
$(document).off('keypress', clickSubmit);
});
}
};
});
Here is the alternative general solution - it sorts elements of a dict by keys and values.
The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.
def sort_key_func(item):
""" Helper function used to sort list of dicts
:param item: dict
:return: sorted list of tuples (k, v)
"""
pairs = []
for k, v in item.items():
pairs.append((k, v))
return sorted(pairs)
sorted(A, key=sort_key_func)
The following code sample, will match the pattern even in case of space characters in between. i.e. :
<td><a href='/path/to/file'>Name of File</a></td>
as well as:
<td> <a href='/path/to/file' >Name of File</a> </td>
Method returns true or false, depending on whether the input htmlTd string matches the pattern or no. If it matches, the out params contain the link and name respectively.
/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
link = null;
name = null;
string pattern = "<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>";
if (Regex.IsMatch(htmlTd, pattern))
{
Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
link = r.Match(htmlTd).Result("${link}");
name = r.Match(htmlTd).Result("${name}");
return true;
}
else
return false;
}
I have tested this and it works correctly.
All of
std::string s(1, c); std::cout << s << std::endl;
and
std::cout << std::string(1, c) << std::endl;
and
std::string s; s.push_back(c); std::cout << s << std::endl;
worked for me.
We automate the Chrome install and disable the auto update with Chef. When Chef tried to rename the entire Update directory, it failed with the "Access denied" error. Because Chef cannot click Yes when a security prompt comes up, the renaming of the entire Update directory does not work for us. We rename only the updater executable with
rename GoogleUpdate.exe GoogleUpdate_disabled.tmp
The entire Chef resource is
batch 'disable_chrome_update' do
code <<-EOF
cd "C:\\Program Files (x86)\\Google\\Update"
rename GoogleUpdate.exe GoogleUpdate_disabled.tmp
EOF
only_if {File.exists?("C:\\Program Files (x86)\\Google\\Update\\GoogleUpdate.exe")}
end
I tested 3 methods to do that...
Method1:
const FriendCard:any = require('./../pages/FriendCard')
Method2:
import * as FriendCard from './../pages/FriendCard';
Method3:
if you can find something like this in tsconfig.json:
{ "compilerOptions": { ..., "allowJs": true }
then you can write:
import FriendCard from './../pages/FriendCard';
I use Mutex in my solution for preventing multiple instances.
static Mutex mutex = null;
//A string that is the name of the mutex
string mutexName = @"Global\test";
//Prevent Multiple Instances of Application
bool onlyInstance = false;
mutex = new Mutex(true, mutexName, out onlyInstance);
if (!onlyInstance)
{
MessageBox.Show("You are already running this application in your system.", "Already Running..", MessageBoxButton.OK);
Application.Current.Shutdown();
}
you can use download attribute to force download a file:
<a href="https://test.com/aaa.exe" download>click here to download</a>
_x000D_
Another editor-based solution: text "rectangles" in Emacs.
Highlight the code you want to comment out, then C-x-r-t #
To un-comment the code: highlight, then C-x-r-k
I use this all-day, every day. (Assigned to hot-keys, of course.)
This and powerful regex search/replace is the reason I tolerate Emacs's other "eccentricities".
getPath()
returns the path used to create the File
object. This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere)
File f1 = new File("/some/path");
String path = f1.getPath(); // will return "\some\path"
File dir = new File("/basedir");
File f2 = new File(dir, "/some/path");
path = f2.getPath(); // will return "\basedir\some\path"
File f3 = new File("./some/path");
path = f3.getPath(); // will return ".\some\path"
getAbsolutePath()
will resolve the path based on the execution location or drive. So if run from c:\test
:
path = f1.getAbsolutePath(); // will return "c:\some\path"
path = f2.getAbsolutePath(); // will return "c:\basedir\some\path"
path = f3.getAbsolutePath(); // will return "c:\test\.\basedir\some\path"
getCanonicalPath()
is system dependent. It will resolve the unique location the path represents. So if you have any "."s in the path they will typically be removed.
As to when to use them. It depends on what you are trying to achieve. getPath()
is useful for portability. getAbsolutePath()
is useful to find the file system location, and getCanonicalPath()
is particularly useful to check if two files are the same.
Using Set and converting it to an array is very similar to copying an Array...
So you can use the same methods for copying an array which is very easy in ES6
For example, you can use ...
Imagine you have this Set below:
const a = new Set(["Alireza", "Dezfoolian", "is", "a", "developer"]);
You can simply convert it using:
const b = [...a];
and the result is:
["Alireza", "Dezfoolian", "is", "a", "developer"]
An array and now you can use all methods that you can use for an array...
Other common ways of doing it:
const b = Array.from(a);
or using loops like:
const b = [];
a.forEach(v => b.push(v));
You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps:
remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)
select *
from
(
select name, subject,
case subject
when 'Maths' then maths
when 'Science' then science
when 'English' then english
end as Marks
from studentmarks
Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject)
)as D
where marks is not null;
This doesn't sound intuitive but select the column you're having the issue with and use "text to column" and just press finish. This is the suggested answer from Excel help as well. For some reason in converts text to numbers.
Use pure js
async function saveFile() _x000D_
{_x000D_
let formData = new FormData(); _x000D_
formData.append("file", sortpicture.files[0]);_x000D_
await fetch('/uploads', {method: "POST", body: formData}); _x000D_
alert('works');_x000D_
}
_x000D_
<input id="sortpicture" type="file" name="sortpic" />_x000D_
<button id="upload" onclick="saveFile()">Upload</button>_x000D_
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
_x000D_
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp) _x000D_
{_x000D_
let user = { name:'john', age:34 };_x000D_
let formData = new FormData();_x000D_
let photo = inp.files[0]; _x000D_
_x000D_
formData.append("photo", photo);_x000D_
formData.append("user", JSON.stringify(user)); _x000D_
_x000D_
try {_x000D_
let r = await fetch('/upload/image', {method: "POST", body: formData}); _x000D_
console.log('HTTP response code:',r.status); _x000D_
alert('success');_x000D_
} catch(e) {_x000D_
console.log('Huston we have problem...:', e);_x000D_
}_x000D_
_x000D_
}
_x000D_
<input type="file" onchange="saveFile(this)" >_x000D_
<br><br>_x000D_
Before selecting the file Open chrome console > network tab to see the request details._x000D_
<br><br>_x000D_
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
_x000D_
Or, in order to avoid modifying slowFunc
(say you don't have access to the source code for instance):
var source = new CancellationTokenSource(); //original code
source.Token.Register(CancelNotification); //original code
source.CancelAfter(TimeSpan.FromSeconds(1)); //original code
var completionSource = new TaskCompletionSource<object>(); //New code
source.Token.Register(() => completionSource.TrySetCanceled()); //New code
var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token); //original code
//original code: await task;
await Task.WhenAny(task, completionSource.Task); //New code
You can also use nice extension methods from https://github.com/StephenCleary/AsyncEx and have it looks as simple as:
await Task.WhenAny(task, source.Token.AsTask());
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
I have tried like this
git rm --cached -r * -f
And it is working for me.
The Guava library contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.
Example:
ArrayList<String> list = newArrayList("a", "b", "c");
(This assumes import static com.google.common.collect.Lists.newArrayList;
)
If you are using PHP you can use file_get_contents()
to print the content:
<?php
$page = file_get_contents('https://www.google.com');
echo $page;
?>
This will print whatever content file_get_contents()
function gets in this url.
Please note that since you are displaying content as string instead as a actual web page, things like relative path images are not shown correctly, because /img/myimg.jpg is now loading from your server and not from google.com anymore.
However, you can play with some tricks like str_replace()
function to replace absolute urls in images:
<?php
$page = file_get_contents('https://www.google.com');
echo str_replace('src="img/','src="https://google.com/img/',$page);
?>
A very contentious subject that I seem to have stumbled along here. However sometimes it's nice to head dear little-bobby tables off at the pass and send little Robert to the headmasters office along with his semi-colons and SQL comment lines --.
This REGEX in VB.NET includes regular alphabetic characters and various circumflexed european characters. However poor old James Mc'Tristan-Smythe the 3rd will have to input his pedigree in as the Jim the Third.
<asp:RegularExpressionValidator ID="RegExValid1" Runat="server"
ErrorMessage="ERROR: Please enter a valid surname<br/>" SetFocusOnError="true" Display="Dynamic"
ControlToValidate="txtSurname" ValidationGroup="MandatoryContent"
ValidationExpression="^[A-Za-z'\-\p{L}\p{Zs}\p{Lu}\p{Ll}\']+$">
If you want the overflow to wrap: flex-flow: row wrap
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
This may also happen if you have a faulty or accidental equation in your csv file. i.e - One of the cells in your csv file starts with an equals sign (=) (An excel equation) which will, in turn throw an error. If you fix, or remove this equation by getting rid of the equals sign, it should solve the ORA-06502 error.
Use the put method: https://developer.android.com/reference/org/json/JSONObject.html
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied.
This is illustrated best with an example:
<div my-customer name="Customer XYZ"></div>
and the directive definition:
angular.module('myModule', [])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerName: '@name'
},
controllerAs: 'vm',
bindToController: true,
controller: ['$http', function($http) {
var vm = this;
vm.doStuff = function(pane) {
console.log(vm.customerName);
};
}],
link: function(scope, element, attrs) {
console.log(scope.customerName);
}
};
});
When the scope
property is used the directive is in the so called "isolated scope" mode, meaning it can not directly access the scope of the parent controller.
In very simple terms, the meaning of the binding symbols is:
someObject: '='
(two-way data binding)
someString: '@'
(passed directly or through interpolation with double curly braces notation {{}}
)
someExpression: '&'
(e.g. hideDialog()
)
This information is present in the AngularJS directive documentation page, although somewhat spread throughout the page.
The symbol >
is not part of the syntax.
However, <
does exist as part of the AngularJS component bindings and means one way binding.
LATE EDIT: Starting with Java 8 you should use neither java.util.Date
nor java.sql.Date
if you can at all avoid it, and instead prefer using the java.time
package (based on Joda) rather than anything else. If you're not on Java 8, here's the original response:
java.sql.Date
- when you call methods/constructors of libraries that use it (like JDBC). Not otherwise. You don't want to introduce dependencies to the database libraries for applications/modules that don't explicitly deal with JDBC.
java.util.Date
- when using libraries that use it. Otherwise, as little as possible, for several reasons:
It's mutable, which means you have to make a defensive copy of it every time you pass it to or return it from a method.
It doesn't handle dates very well, which backwards people like yours truly, think date handling classes should.
Now, because j.u.D doesn't do it's job very well, the ghastly Calendar
classes were introduced. They are also mutable, and awful to work with, and should be avoided if you don't have any choice.
There are better alternatives, like the Joda Time API (which might even make it into Java 7 and become the new official date handling API - a quick search says it won't).
If you feel it's overkill to introduce a new dependency like Joda, long
s aren't all that bad to use for timestamp fields in objects, although I myself usually wrap them in j.u.D when passing them around, for type safety and as documentation.
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter('output.mp4', fourcc, 20,(frame_width,frame_height),True )
print(int(cap.get(3)))
print(int(cap.get(4)))
while(cap.isOpened()):
ret,frame = cap.read()
if ret == True:
print(frame.shape)
out.write(frame)
cv2.imshow('Frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()`enter code here`
cv2.destroyAllWindows()
This works fine but the problem of having video size relatively very small means nothing is captured. So make sure the height and width of a video and the image that you are going to recorded is same. If you are using some manipulation after capturing a video than you must confirm the size (before and after). Hope it will save some1's hour
Because there are algorithms whose best-case is quick, and thus it's technically a big O, not a big Theta.
Big O is an upper bound, big Theta is an equivalence relation.
The difference between substring and slice - is how they work with negative and overlooking lines abroad arguments:
substring (start, end)
Negative arguments are interpreted as zero. Too large values ??are truncated to the length of the string: alert ( "testme" .substring (-2)); // "testme", -2 becomes 0
Furthermore, if start > end, the arguments are interchanged, i.e. plot line returns between the start and end:
alert ( "testme" .substring (4, -1)); // "test"
// -1 Becomes 0 -> got substring (4, 0)
// 4> 0, so that the arguments are swapped -> substring (0, 4) = "test"
slice
Negative values ??are measured from the end of the line:
alert ( "testme" .slice (-2)); // "me", from the end position 2
alert ( "testme" .slice (1, -1)); // "estm", from the first position to the one at the end.
It is much more convenient than the strange logic substring.
A negative value of the first parameter to substr supported in all browsers except IE8-.
If the choice of one of these three methods, for use in most situations - it will be slice: negative arguments and it maintains and operates most obvious.
You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.
My solution:
const setParams = (data) => {
if (typeof data !== 'undefined' && typeof data !== 'object') {
return
}
let url = new URL(window.location.href)
const params = new URLSearchParams(url.search)
for (const key of Object.keys(data)) {
if (data[key] == 0) {
params.delete(key)
} else {
params.set(key, data[key])
}
}
url.search = params
url = url.toString()
window.history.replaceState({ url: url }, null, url)
}
Then just call "setParams" and pass an object with data you want to set.
Example:
$('select').on('change', e => {
const $this = $(e.currentTarget)
setParams({ $this.attr('name'): $this.val() })
})
In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.
Hope this helps yall
The most simple way is..
if(window["myId"]){
// ..
}
This is also part of HTML5 specs: https://www.w3.org/TR/html5/single-page.html#accessing-other-browsing-contexts#named-access-on-the-window-object
window[name]
Returns the indicated element or collection of elements.
Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:
var http = require('http')
var fs = require('fs')
fs.readFile('image.jpg', function(err, data) {
if (err) throw err // Fail if the file can't be read.
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.end(data) // Send the file data to the browser.
}).listen(8124)
console.log('Server running at http://localhost:8124/')
})
Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg
.
[Edit] You could even embed the image in an HTML page directly by using an <img>
with a data URI source. For example:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body><img src="data:image/jpeg;base64,')
res.write(Buffer.from(data).toString('base64'));
res.end('"/></body></html>');
var dates = dates_as_int.map(function(dateStr) {
return new Date(dateStr).getTime();
});
=>
[1468959781804, 1469029434776, 1469199218634, 1469457574527]
Update: ES6 version:
const dates = dates_as_int.map(date => new Date(date).getTime())
As all answers posted above are well explained, I want to add something which I faced today.
When you export something using exports then you have to use it with variable. Like,
File1.js
exports.a = 5;
In another file
File2.js
const A = require("./File1.js");
console.log(A.a);
and using module.exports
File1.js
module.exports.a = 5;
In File2.js
const A = require("./File1.js");
console.log(A.a);
and default module.exports
File1.js
module.exports = 5;
in File2.js
const A = require("./File2.js");
console.log(A);
If you dont want to format a separate column with you normal dates pasted to it -- do the following -- add a column to the extreme left of your data and reverve your date ie if the date you had already entered was for example 11.5.16 enter int he new lefthand column 160511 ( notice that there are numbers only and no full stops . When you now sort there will be no mix ups as you have encountered.i have used this method for over 30 years and it never lets me down. And as you have placed the date by year, month and day you neednt include that column if you want or need tu print out your complete list.
<?php
$timestamp=1486830234542;
echo date('Y-m-d H:i:s', $timestamp/1000);
?>
If you're simply locking an object, I'd prefer to use synchronized
Example:
Lock.acquire();
doSomethingNifty(); // Throws a NPE!
Lock.release(); // Oh noes, we never release the lock!
You have to explicitly do try{} finally{}
everywhere.
Whereas with synchronized, it's super clear and impossible to get wrong:
synchronized(myObject) {
doSomethingNifty();
}
That said, Lock
s may be more useful for more complicated things where you can't acquire and release in such a clean manner. I would honestly prefer to avoid using bare Lock
s in the first place, and just go with a more sophisticated concurrency control such as a CyclicBarrier
or a LinkedBlockingQueue
, if they meet your needs.
I've never had a reason to use wait()
or notify()
but there may be some good ones.
OK, in case you want a normal remote repository, then create an extra branch and check it out. Push it into one branch (which is not checked out) and merge it with one which is currently active later after pushing from locally.
For example, on a remote server:
git branch dev
git checkout dev
On the local setup:
git push
On remote server:
git merge dev
Set Application pool to classic .NET appool and make sure that Classic .Net apppool working on Classic managed piple line .
For me, I always choose non-thread safe version because I always use nginx, or run PHP from the command line.
The non-thread safe version should be used if you install PHP as a CGI binary, command line interface or other environment where only a single thread is used.
A thread-safe version should be used if you install PHP as an Apache module in a worker MPM (multi-processing model) or other environment where multiple PHP threads run concurrently.
As of C++17 there's also std::from_chars. The following function takes a string of hex characters and returns a vector of T:
#include <charconv>
template<typename T>
std::vector<T> hexstr_to_vec(const std::string& str, unsigned char chars_per_num = 2)
{
std::vector<T> out(str.size() / chars_per_num, 0);
T value;
for (int i = 0; i < str.size() / chars_per_num; i++) {
std::from_chars<T>(
str.data() + (i * chars_per_num),
str.data() + (i * chars_per_num) + chars_per_num,
value,
16
);
out[i] = value;
}
return out;
}
Easy CSS properties can do the trick. The following is for a three-line ellipsis.
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
In Python, the 'null' object is the singleton None
.
The best way to check things for "Noneness" is to use the identity operator, is
:
if foo is None:
...
Try This
if (($val >= 1 && $val <= 10) || ($val >= 20 && $val <= 40))
This will return the value between 1 to 10 & 20 to 40.
IList<T> is an interface so you can inherit another class and still implement IList<T> while inheriting List<T> prevents you to do so.
For example if there is a class A and your class B inherits it then you can't use List<T>
class A : B, IList<T> { ... }
I had gone through this situation where textview marquee was not working. However follow this and I am sure it will work. :)
<TextView
android:id="@+id/tv_marquee"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:freezesText="true"
android:maxLines="1"
android:scrollHorizontally="true"
android:text="This is a sample code of marquee and it works"/>
and programmatically add these 2 lines...
tvMarquee.setHorizontallyScrolling(true);
tvMarquee.setSelected(true);
tvMarquee.setSelected(true) is required incase if any one of the view is already focused and setSelected will make it work. No need to use.
android:singleLine="true"
it is deprecated and above codes works.
I wrote a quick simple app recent that handle the management of various version of node and npm. It allows you to choose different version of node and npm to download and select which version to use. Check it out and see if it's something that's useful.
Yes, on the server side $_SERVER['DOCUMENT_ROOT']
is equivalent to /
on the client side.
For example: the value of "{$_SERVER['DOCUMENT_ROOT']}/images/thumbnail.png"
will be the string /var/www/html/images/thumbnail.png
on a server where it's local file at that path can be reached from the client side at the url http://example.com/images/thumbnail.png
No, in other words the value of $_SERVER['DOCUMENT_ROOT']
is not /
rather it is the server's local path to what the server shows the client at example.com/
note: $_SERVER['DOCUMENT_ROOT']
does not include a trailing /
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
I know this post is a bit old, but thought I would add the functions I use that take into account any filters and any <![CDATA[some stuff]]>
content you want to safely exclude.
Simply add to your functions.php file and use anywhere you would like, such as:
content(53);
or
excerpt(27);
Enjoy!
//limit excerpt
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'...';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
return $excerpt;
}
//limit content
function content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('/\[.+\]/','', $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
Check example link below and click on the div to get the color value in hex.
var color = '';_x000D_
$('div').click(function() {_x000D_
var x = $(this).css('backgroundColor');_x000D_
hexc(x);_x000D_
console.log(color);_x000D_
})_x000D_
_x000D_
function hexc(colorval) {_x000D_
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);_x000D_
delete(parts[0]);_x000D_
for (var i = 1; i <= 3; ++i) {_x000D_
parts[i] = parseInt(parts[i]).toString(16);_x000D_
if (parts[i].length == 1) parts[i] = '0' + parts[i];_x000D_
}_x000D_
color = '#' + parts.join('');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class='div' style='background-color: #f5b405'>Click me!</div>
_x000D_
Check working example at http://jsfiddle.net/DCaQb/
Answering my own question about 2 or something years later here but...
It uses a protocol extension so you can do it without any extra code for all classes.
/*
Prerequisites
-------------
- In IB set the view's class to the type hook up any IBOutlets
- In IB ensure the file's owner is blank
*/
public protocol CreatedFromNib {
static func createFromNib() -> Self?
static func nibName() -> String?
}
extension UIView: CreatedFromNib { }
public extension CreatedFromNib where Self: UIView {
public static func createFromNib() -> Self? {
guard let nibName = nibName() else { return nil }
guard let view = NSBundle.mainBundle().loadNibNamed(nibName, owner: nil, options: nil).last as? Self else { return nil }
return view
}
public static func nibName() -> String? {
guard let n = NSStringFromClass(Self.self).componentsSeparatedByString(".").last else { return nil }
return n
}
}
// Usage:
let myView = MyView().createFromNib()
From this documentation
pandas provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects:
merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True, suffixes=('_x', '_y'), copy=True, indicator=False)
And :
DataFrame.join
is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame. Here is a very basic example: The data alignment here is on the indexes (row labels). This same behavior can be achieved using merge plus additional arguments instructing it to use the indexes:result = pd.merge(left, right, left_index=True, right_index=True, how='outer')
Commenting both Fetch
and LazyCollection
sometimes helps to run project.
@Fetch(FetchMode.JOIN)
@LazyCollection(LazyCollectionOption.FALSE)
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
Eclipse automatically created the appcompat_v7.Because of Kitkat Api launched itself it adds automatically appcompat_v7
and fragment_main.xml
.
Best ways to solve these:
Firstly in project,Right click->properties->Android
.There you can
see the red marked appcompat
placed in Reference
. Click that and
Remove it.Then Tick the right target name in Project Build Target
.
Delete fragment_main.xml and Appcompat file created in your Eclipse.
Edit and change your activity_main.xml like these:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
In res/values/styles.xml:
<resources>
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
</style>
</resources>
In res/values-v11/styles.xml you have to change like these:
<resources>
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
</style>
</resources>
In res/values-v14/styles.xml you have to change like these:
<resources>
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<style name="AppTheme" parent="AppBaseTheme">
</style>
</resources>
Change your menu/main.xml like these:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
Finally change your MainActivity.java like these:
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
LikeWise you have to do it for creating a new project
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
If you are going to be programming an application to do all of this, the process will be something like this:
If you want the #header
to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).
Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:
#container {
position: relative;
width: 80%;
}
#header {
position: relative;
height: 50px;
padding: 10px;
}
You can see it in action here.
The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block
child with no width set.
Update
Another option for dealing with this is to use the box-sizing CSS rule:
#container {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
/* Since this element now uses border-box sizing, the 10px of horizontal
padding will be drawn inside the 80% width */
width: 80%;
padding: 0 10px;
}
Here's a post talking about how box-sizing works.
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
If you want to do this and control the server from which the base page or content is being served, you can use Cross Origin Resource Sharing (http://www.w3.org/TR/access-control/) to allow client-side JavaScript to load data into a <div>
via XMLHttpRequest()
:
// I safely ignore IE 6 and 5 (!) users
// because I do not wish to proliferate
// broken software that will hurt other
// users of the internet, which is what
// you're doing when you write anything
// for old version of IE (5/6)
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('displayDiv').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'http://api.google.com/thing?request=data', true);
xhr.send();
Now for the lynchpin of this whole operation, you need to write code for your server that will give clients the Access-Control-Allow-Origin
header, specifying which domains you want the client-side code to be able to access via XMLHttpRequest()
. The following is an example of PHP code you can include at the top of your page in order to send these headers to clients:
<?php
header('Access-Control-Allow-Origin: http://api.google.com');
header('Access-Control-Allow-Origin: http://some.example.com');
?>
>>> A = np.random.randint(5, size=(10,3))
>>> A
array([[1, 3, 0],
[3, 2, 0],
[0, 2, 1],
[1, 1, 4],
[3, 2, 2],
[0, 1, 0],
[1, 3, 1],
[0, 4, 1],
[2, 4, 2],
[3, 3, 1]])
>>> idx = np.random.randint(10, size=2)
>>> idx
array([7, 6])
>>> A[idx,:]
array([[0, 4, 1],
[1, 3, 1]])
Putting it together for a general case:
A[np.random.randint(A.shape[0], size=2), :]
For non replacement (numpy 1.7.0+):
A[np.random.choice(A.shape[0], 2, replace=False), :]
I do not believe there is a good way to generate random list without replacement before 1.7. Perhaps you can setup a small definition that ensures the two values are not the same.
As per OpenCV docs(1), below steps using OpenCV manager is the recommended way to use OpenCV for production runs. But, OpenCV manager(2) is an additional install from Google play store. So, if you prefer a self contained apk(not using OpenCV manager) or is currently in development/testing phase, I suggest answer at https://stackoverflow.com/a/27421494/1180117.
Recommended steps for using OpenCV in Android Studio with OpenCV manager.
File -> Import Module
, choose sdk/java
folder in the unzipped opencv archive. build.gradle
under imported OpenCV module to update 4 fields to match your project's build.gradle
a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and 4) targetSdkVersion. Application -> Module Settings
, and select the Dependencies
tab. Click +
icon at bottom(or right), choose Module Dependency
and select the imported OpenCV module.As the final step, in your Activity class, add snippet below.
public class SampleJava extends Activity {
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch(status) {
case LoaderCallbackInterface.SUCCESS:
Log.i(TAG,"OpenCV Manager Connected");
//from now onwards, you can use OpenCV API
Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
break;
case LoaderCallbackInterface.INIT_FAILED:
Log.i(TAG,"Init Failed");
break;
case LoaderCallbackInterface.INSTALL_CANCELED:
Log.i(TAG,"Install Cancelled");
break;
case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION:
Log.i(TAG,"Incompatible Version");
break;
case LoaderCallbackInterface.MARKET_ERROR:
Log.i(TAG,"Market Error");
break;
default:
Log.i(TAG,"OpenCV Manager Install");
super.onManagerConnected(status);
break;
}
}
};
@Override
protected void onResume() {
super.onResume();
//initialize OpenCV manager
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, mLoaderCallback);
}
}
Note: You could only make OpenCV calls after you receive success callback on onManagerConnected
method. During run, you will be prompted for installation of OpenCV manager from play store, if it is not already installed. During development, if you don't have access to play store or is on emualtor, use appropriate OpenCV manager apk present in apk
folder under downloaded OpenCV sdk archive .
Pros
Cons
Log in the Keycloak admin console website, select the realm and its client, then make sure all URIs of the client are prefixed with the protocol, that is, with http://
for example. An example would be http://localhost:8082/*
Another way to solve the issue, is to view the Keycloak server console output, locate the line stating the request was refused, copy from it the redirect_uri
displayed value and paste it in the * Valid Redirect URIs
field of the client in the Keycloak admin console website. The requested URI is then one of the acceptables.
My first answer!
This will set the safemode switch:
bcdedit /set {current} safeboot minimal
with networking:
bcdedit /set {current} safeboot network
then reboot the machine with
shutdown /r
to put back in normal mode via dos:
bcdedit /deletevalue {current} safeboot
For me the code:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
throws error, but I added name attribute to input:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
and it started to work.
As mentioned by Santosh, I think this query is suitably fast, while not querying all the table.
To return integer result of number of data records, for a specific tablename in a particular database:
select TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA = 'database'
AND table_name='tablename';
Json.NET probably serializes C# dictionaries adequately now, but when the OP originally posted this question, many MVC developers may have been using the JavaScriptSerializer class because that was the default option out of the box.
If you're working on a legacy project (MVC 1 or MVC 2), and you can't use Json.NET, I recommend that you use a List<KeyValuePair<K,V>>
instead of a Dictionary<K,V>>
. The legacy JavaScriptSerializer class will serialize this type just fine, but it will have problems with a dictionary.
Documentation: Serializing Collections with Json.NET
I haven't actually tried this, but this answer from the web sounds promising:
Wireshark can't actually capture local packets on windows XP due to the nature of the windows TCP stack. When packets are sent and received on the same machine they don't seem to cross the network boundary that wireshark monitors.
However there is a way around this, you can route the local traffic out via your network gateway (router) by setting up a (temporary) static route on your windows XP machine.
Say your XP IP address is 192.168.0.2 and your gateway (router) address is 192.168.0.1 you could run the following command from windows XP command line to force all local traffic out and back across the network boundary, so wireshark could then track the data (note that wireshark will report packets twice in this scenario, once when they leave your pc and once when they return).
route add 192.168.0.2 mask 255.255.255.255 192.168.0.1 metric 1
http://forums.whirlpool.net.au/archive/1037087, accessed just now.
I use for(;/*ever*/;)
.
It is easy to read and it takes a bit longer to type (due to the shifts for the asterisks), indicating I should be really careful when using this type of loop. The green text that shows up in the conditional is also a pretty odd sight—another indication this construct is frowned upon unless absolutely necessary.
We can add Unique key index by using fluent api. Below code worked for me
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(p => p.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));
}