As of R 3.3.0, one may use startsWith()
as a faster alternative to grepl()
:
which(startsWith(mydata_2$height_seca1, 1578))
Swift 5, Spacing Between UITableViewCell
1. Use sections instead of rows
2. Each section should return one row
3. Assign your cell data like this e.g [indexPath.section], instead of row
4. Use UITableView Method "heightForHeader" and return your desired spacing
5. Do rest things as you were doing it
Thanks!
Many of the posted solutions are incomplete or not to my taste.
My preferred solution, inspired by this gist, is to use an assets branch with permalinks to specific revisions.
git checkout --orphan assets
git reset --hard
cp /path/to/cat.png .
git add .
git commit -m 'Added cat picture'
git push -u origin assets
git rev-parse HEAD # Print the SHA, which is optional, you'll see below.
Construct a "permalink" to this revision of the image, and wrap it in Markdown.
Looking up the commit SHA by hand is inconvenient, however, so as a shortcut press Y to a permalink to a file in a specific commit as this help.github page says.
To always show the latest image on the assets branch, use the blob URL:
https://github.com/github/{repository}/blob/assets/cat.png
(From the same GitHub help page File views show the latest version on a branch)
I found another reason for this exception. When running the application from Spyder IDE (in my case it was Spyder3 on Raspbian) and the program terminated by ^C or an exception, the socket was still active:
sudo netstat -ap | grep 31416
tcp 0 0 0.0.0.0:31416 0.0.0.0:* LISTEN 13210/python3
Running the program again found the "Address already in use"; the IDE seems to start the new 'run' as a separate process which finds the socket used by the previous 'run'.
socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
did NOT help.
Killing process 13210 helped. Starting the python script from command-line like
python3 <app-name>.py
always worked well when SO_REUSEADDR was set to true. The new Thonny IDE or Idle3 IDE did not have this problem.
If you want to get client key from request header, u can try following:
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from apps.authentication.models import CerebroAuth
class CerebroAuthentication(BaseAuthentication):
def authenticate(self, request):
client_id = request.META.get('HTTP_AUTHORIZATION')
if not client_id:
raise exceptions.AuthenticationFailed('Client key not provided')
client_id = client_id.split()
if len(client_id) == 1 or len(client_id) > 2:
msg = ('Invalid secrer key header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
try:
client = CerebroAuth.objects.get(client_id=client_id[1])
except CerebroAuth.DoesNotExist:
raise exceptions.AuthenticationFailed('No such client')
return (client, None)
I found this related question on the topic, but if you want direct links, here they are:
I'm surprised node.js doesn't come with a shell, but I guess it's really more like an epoll/selector-based callback/event-oriented webserver, so perhaps it doesn't need the full JS feature set, but I'm not too familiar with its inner workings.
Since you seem interested in node.js and since it's based on V8, it might be best to follow those instructions on getting a V8 environment set up so you can have a consistent basis for your JavaScript programming (I should hope JSC and V8 are mostly the same, but I'm not sure).
if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
alert("option doesn't exist!");
}
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.
email.MIMEText sets up the "To:" header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)
SMTP.sendmail, on the other hand, sets up the "envelope" of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.
So, what you need to do is COMBINE the two replies you received. Set msg['To'] to a single string, but pass the raw list to sendmail:
emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails )
....
s.sendmail( msg['From'], emails, msg.as_string())
In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):
@Override
public void setFocusable(boolean b) {
super.setFocusable(b);
}
And by adding this to your constructor:
setFocusable(true);
Or, if you are calling the function from a parent class/container:
JComponent childComponent = new JComponent();
childComponent.setFocusable(true);
And then doing all the KeyListener stuff mentioned by others.
I made an installation guide for Egit on Eclipse so I thought I would share it.
INSTALL EGIT plugin in eclispe which is pretty easy. If EGit is missing in your Eclipse installation, you can install it via the Eclipse Update Manager via: Help ? Install new Software. EGit can be installed from the following URL: http://download.eclipse.org/egit/updates Under Eclipse Git Team Provider, tick ONLY "Eclipse EGit" and then download the plugin.
CONNECT TO YOUR LOCAL REPOSITORY. I right clicked on the project, selected "team > share project" and then ticked "use or create repository"
GIT IGNORE. Mark the "bin" folder as "ignored by Git", either by right-clicking on it and selecting Team > Ignore or by creating a .gitignore file. My file was generated for me, I just had to make it visible. Here's how in eclipse: In your package explorer, pull down the menu and select "Filters ...". You can adjust what types of files are shown/hidden there.
IDENTIFY YOURSELF. Click Preferences > Team > Git > Configuration and make sure your name & email are there so we know which user committed/pushed what.
NOW YOU ARE READY TO ADD/COMMIT/PUSH/PULL files with the plugin!
You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.
Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.
Whether or not YouTube videos play in HTML5 format depends on the setting at https://www.youtube.com/html5, per browser. Chrome prefers HTML5 playback automatically, but even the latest Firefox and Internet Explorer still use Flash if it is installed on the machine.
The parameter html5=1 does not do anything (anymore) now. (Note it is not even listed at https://developers.google.com/youtube/player_parameters.)
We use maven and svn. It was an mistaken checkin of target directory to SVN that cause this error. Removing that fixed everything, if this hint helps anyone.
This looks like valid Python code, so if the file is on your project's classpath (and not in some other directory or in arbitrary places) one way would be just to rename the file to "abc.py" and import it as a module, using import abc
. You can even update the values using the reload
function later. Then access the values as abc.path1
etc.
Of course, this can be dangerous in case the file contains other code that will be executed. I would not use it in any real, professional project, but for a small script or in interactive mode this seems to be the simplest solution.
Just put the abc.py
into the same directory as your script, or the directory where you open the interactive shell, and do import abc
or from abc import *
.
If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)
So I have to use the following method.
CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.
Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.
Step2:
[Situation A]: target commit is the latest one.
1) In the git command console, input
git commit --amend -m "new comment message"
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
[Situation B]: target commit is not the latest one.
1) In the git command console, input
git rebase -i HEAD~n
It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2.
This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq
to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq
to save&quit.
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
Finally: In the sourcetree main window, Press F5
to refresh.
You can find the setting here in IIS:
It can be found at the server level, web site level, or app level under "ASP".
I think you can set it at the web.config level here. Please confirm this for yourself.
<configuration>
<system.web>
<!-- Session Timeout in Minutes (Also in Global.asax) -->
<sessionState timeout="1440"/>
</system.web>
</configuration>
If it is on the stack, the contents of uninitialized members that don't have their own constructor will be random and undefined. Even if it is global, it would be a bad idea to rely on them being zeroed out. Whether it is on the stack or not, if a member has its own constructor, that will get called to initialize it.
So, if you have string* pname, the pointer will contain random junk. but for string name, the default constructor for string will be called, giving you an empty string. For your reference type variables, I'm not sure, but it'll probably be a reference to some random chunk of memory.
Using Angular 4 and the cli that came with it I was able to start the server with $npm start -- --port 8000
. That worked ok: ** NG Live Development Server is listening on localhost:8000, open your browser on http://localhost:8000 **
Got the tip from Here
dplyr::as_data_frame(df, rownames = "your_row_name")
will give you even simpler result.
The default size of the arraylist is 10. When we add the 11th ....arraylist increases the size (n*2). The values stored in old arraylist are copied into the new arraylist whose size is 20.
There is no direct function to get yesterday's date.
To get yesterday's date, you need to use Calendar
by subtracting -1
.
Avro is a row-based storage format for Hadoop.
Parquet is a column-based storage format for Hadoop.
If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.
If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.
@DawidDrozd's answer above is excellent.
I would add one point. Recent versions of the Clang compiler complain about requiring a "bridging cast" if attempting to use his code.
This seems reasonable: using a trampoline creates a potential bug: since Objective-C classes are reference counted, if we pass their address around as a void *, we risk having a hanging pointer if the class is garbage collected up while the callback is still active.
Solution 1) Cocoa provides CFBridgingRetain and CFBridgingRelease macro functions which presumably add and subtract one from the reference count of the Objective-C object. We should therefore be careful with multiple callbacks, to release the same number of times as we retain.
// C++ Module
#include <functional>
void cppFnRequiringCallback(std::function<void(void)> callback) {
callback();
}
//Objective-C Module
#import "CppFnRequiringCallback.h"
@interface MyObj : NSObject
- (void) callCppFunction;
- (void) myCallbackFn;
@end
void cppTrampoline(const void *caller) {
id callerObjC = CFBridgingRelease(caller);
[callerObjC myCallbackFn];
}
@implementation MyObj
- (void) callCppFunction {
auto callback = [self]() {
const void *caller = CFBridgingRetain(self);
cppTrampoline(caller);
};
cppFnRequiringCallback(callback);
}
- (void) myCallbackFn {
NSLog(@"Received callback.");
}
@end
Solution 2) The alternative is to use the equivalent of a weak reference (ie. no change to the retain count), without any additional safety.
The Objective-C language provides the __bridge cast qualifier to do this (CFBridgingRetain and CFBridgingRelease seem to be thin Cocoa wrappers over the Objective-C language constructs __bridge_retained and release respectively, but Cocoa does not appear to have an equivalent for __bridge).
The required changes are:
void cppTrampoline(void *caller) {
id callerObjC = (__bridge id)caller;
[callerObjC myCallbackFn];
}
- (void) callCppFunction {
auto callback = [self]() {
void *caller = (__bridge void *)self;
cppTrampoline(caller);
};
cppFunctionRequiringCallback(callback);
}
None of the above mentioned solution worked for me due to some reason. Here is my solution. It's pretty basic.
curl -X GET API_ENDPOINT -H 'Content-Type: application/json' -d 'JSON_DATA'
API_ENDPOINT is your api endpoint e.g: http://127.0.0.1:80/api
-H has been used to added header content.
JSON_DATA is your request body it can be something like :: {"data_key": "value"} . ' ' surrounding JSON_DATA are important.
Anything after -d is the data which you need to send in the GET request
The following script solved my problem:
// Fake localStorage implementation.
// Mimics localStorage, including events.
// It will work just like localStorage, except for the persistant storage part.
var fakeLocalStorage = function() {
var fakeLocalStorage = {};
var storage;
// If Storage exists we modify it to write to our fakeLocalStorage object instead.
// If Storage does not exist we create an empty object.
if (window.Storage && window.localStorage) {
storage = window.Storage.prototype;
} else {
// We don't bother implementing a fake Storage object
window.localStorage = {};
storage = window.localStorage;
}
// For older IE
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
var dispatchStorageEvent = function(key, newValue) {
var oldValue = (key == null) ? null : storage.getItem(key); // `==` to match both null and undefined
var url = location.href.substr(location.origin.length);
var storageEvent = document.createEvent('StorageEvent'); // For IE, http://stackoverflow.com/a/25514935/1214183
storageEvent.initStorageEvent('storage', false, false, key, oldValue, newValue, url, null);
window.dispatchEvent(storageEvent);
};
storage.key = function(i) {
var key = Object.keys(fakeLocalStorage)[i];
return typeof key === 'string' ? key : null;
};
storage.getItem = function(key) {
return typeof fakeLocalStorage[key] === 'string' ? fakeLocalStorage[key] : null;
};
storage.setItem = function(key, value) {
dispatchStorageEvent(key, value);
fakeLocalStorage[key] = String(value);
};
storage.removeItem = function(key) {
dispatchStorageEvent(key, null);
delete fakeLocalStorage[key];
};
storage.clear = function() {
dispatchStorageEvent(null, null);
fakeLocalStorage = {};
};
};
// Example of how to use it
if (typeof window.localStorage === 'object') {
// Safari will throw a fit if we try to use localStorage.setItem in private browsing mode.
try {
localStorage.setItem('localStorageTest', 1);
localStorage.removeItem('localStorageTest');
} catch (e) {
fakeLocalStorage();
}
} else {
// Use fake localStorage for any browser that does not support it.
fakeLocalStorage();
}
It checks if localStorage exists and can be used and in the negative case, it creates a fake local storage and uses it instead of the original localStorage. Please let me know if you need further information.
Should work on every modern browser and without jQuery or any dependency, here my implementation :
// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ',') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Then add your download button/link :
<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>
CSV file is timedated and compatible with default Excel format.
Update after comments: Added second parameter "separator", it can be used to configure another character like ;
, it's useful if you have user downloading your csv in different region of the world because they can use another default separator for Excel, for more information see : https://superuser.com/a/606274/908273
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301
results
is now an object.
SqlCommand yourCommand = new SqlCommand();
yourCommand.Connection = yourSqlConn;
yourCommand.Parameters.Add("@yourParam");
yourCommand.Parameters["@yourParam"].Direction = ParameterDirection.Output;
// execute your query successfully
int yourResult = yourCommand.Parameters["@yourParam"].Value;
Oops, there were typing errors in my previous post.
header("Content-Type: application/force-download");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"".$name."\";");
If you don't want the browser to prompt the user then use "inline" for the third string instead of "attachment". Inline works very well. The PDF display immediately without asking the user to click on Open. I've used "attachment" and this will prompt the user for Open, Save. I've tried to change the browser setting nut it doesn't prevent the prompt.
I assume you are looking to use mysql client, which is a good thing and much more efficient to use than any phpMyAdmin alternatives.
The proper way to log in with the commandline client is by typing:
mysql -u username -p
Notice I did not type the password. Doing so would of made the password visible on screen, that is not good in multi-user environnment!
After typing this hit enter key, mysql will ask you for your password.
Once logged in, of course you will need:
use databaseName;
to do anything.
Good-luck.
This is a well-known issue and based on this answer you could add setLenient
:
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Now, if you add this to your retrofit, it gives you another error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:
{
android:[
{ ver:"1.5", name:"Cupcace", api:"Api Level 3" }
...
]
}
For better comprehension, compare your response with Github api.
Suggestion: to find out what's going on to your request/response
add HttpLoggingInterceptor
in your retrofit.
Based on this answer your ServiceHelper would be:
private ServiceHelper() {
httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.interceptors().add(interceptor);
Retrofit retrofit = createAdapter().build();
service = retrofit.create(IService.class);
}
Also don't forget to add:
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
Use the (ngModelChange)
event to detect changes on the model
How about something like this: http://jsfiddle.net/EgLKV/3/
Its done by using position:absolute
and z-index
to place the text over the image.
#container {_x000D_
height: 400px;_x000D_
width: 400px;_x000D_
position: relative;_x000D_
}_x000D_
#image {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
}_x000D_
#text {_x000D_
z-index: 100;_x000D_
position: absolute;_x000D_
color: white;_x000D_
font-size: 24px;_x000D_
font-weight: bold;_x000D_
left: 150px;_x000D_
top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
<img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
<p id="text">_x000D_
Hello World!_x000D_
</p>_x000D_
</div>
_x000D_
The ISO file that suggested in the accepted answer is still not complete. The very complete offline installer is about 24GB! There is only one way to get it. follow these steps:
temp
folderC:\VS Community\
C:\VS
Community\
with this argument: /Layout .
Good Luck
On Linux/Unix (note: Mac OS is a Unix) use top
and press M (Shift+M) to sort processes by memory usage.
On Windows use the Task Manager.
I also had the similar issue. Logs were not creating.
Please check logger attribute name should match with your LogManager.GetLogger("name")
<logger name="Mylog">
<level value="All"></level>
<appender-ref ref="RollingLogFileAppender" />
</logger>
private static readonly ILog Log = LogManager.GetLogger("Mylog");
There are already answers for Deleting row by LIMIT
. Ideally you should have primary key in your table. But if there is not.
I will give other ways:
I see id_users and id_product should be unique in your example.
ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)
These will delete duplicate rows with same data.
But if you still get an error, even if you use IGNORE clause, try this:
ALTER TABLE orders ENGINE MyISAM;
ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)
ALTER TABLE orders ENGINE InnoDB;
If there are multiple rows who have duplicate values, then you can also recreate table
RENAME TABLE `orders` TO `orders2`;
CREATE TABLE `orders`
SELECT * FROM `orders2` GROUP BY id_users, id_product;
<roleManager
enabled="true"
cacheRolesInCookie="false"
cookieName=".ASPXROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
defaultProvider="AspNetSqlRoleProvider"
createPersistentCookie="false"
maxCachedResults="25">
<providers>
<clear />
<add
connectionStringName="MembershipConnection"
applicationName="Mvc3"
name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add
applicationName="Mvc3"
name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
To select data in numerical range you can use BETWEEN
which is inclusive.
SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;
use .NET3.5 it worked for me for similar issue.
If you want to just uncommit the last commit use this:
git reset HEAD~
work like charm for me.
I have tried the code of Ramana and I found out on Ubuntu you have to write sudo
for each command. Here is my script which works fine on Ubuntu 13.10 (Saucy Salamander):
#!/usr/bin/env python
import pip
from subprocess import call
for dist in pip.get_installed_distributions():
call("sudo pip install --upgrade " + dist.project_name, shell=True)
These days, there's a better solution for importing an existing PHP project. The PDT plugin now has an option on the New PHP Project dialog just for this. So:
From File->New->PHP Project:
In Java 8, if you want to have a list
of non-repeating N
random integers in range (a, b)
, where b
is exclusive, you can use something like this:
Random random = new Random();
List<Integer> randomNumbers = random.ints(a, b).distinct().limit(N).boxed().collect(Collectors.toList());
This code is used to multiply the values of one column
select exp(sum(log(column))) from table
In this part of your SP:
IF @DateFirst <> '' and @DateLast <> ''
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + @DateFirst
+ ' and convert (Date,DateLog) <=''' + @DateLast
you are trying to concatenate strings and datetimes.
As the datetime
type has higher priority than varchar
/nvarchar
, the +
operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= '''
and others) to datetime or numeric values. And fails.
That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.
To amend the situation, you need to add explicit casting of your datetime variables to strings:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst)
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)
You'll also need to add closing single quotes:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst) + ''''
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''
If you set a static height for your header, you can use that in a calculation for the size of your wrapper.
http://jsfiddle.net/ske5Lqyv/5/
Using your example code, you can add this CSS:
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
#container {
height: 100%;
}
.header {
height: 64px;
background-color: lightblue;
}
.wrapper {
height: calc(100% - 64px);
overflow-y: auto;
}
Or, you can use flexbox for a more dynamic approach http://jsfiddle.net/19zbs7je/3/
<div id="container">
<div class="section">
<div class="header">Heading</div>
<div class="wrapper">
<p>Large Text</p>
</div>
</div>
</div>
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
#container {
display: flex;
flex-direction: column;
height: 100%;
}
.section {
flex-grow: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.header {
height: 64px;
background-color: lightblue;
flex-shrink: 0;
}
.wrapper {
flex-grow: 1;
overflow: auto;
min-height: 100%;
}
And if you'd like to get even fancier, take a look at my response to this question https://stackoverflow.com/a/52416148/1513083
This solved my problem: Kotlin Code:
val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
fragmentTransaction.add(dialogFragment, tag)
fragmentTransaction.commitAllowingStateLoss()
How is commitAllowingStateLoss()
is different than commit()
?
As per documentation:
Like commit()
but allows the commit to be executed after an activity's state is saved.
https://developer.android.com/reference/android/app/FragmentTransaction#commitAllowingStateLoss()
P.S: you can show Fragment Dialogs or can load fragments by this method. Applicable for both.
You could also put your JSON content in a file and pass it to curl using the --upload-file
option via standard input, like this:
echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -
You're searching for gc_maxlifetime, see http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime for a description.
Your session will last 1440 seconds which is 24 minutes (default).
Note: The following method will work on windows.
An alternative method (if it is ok to run a single version of PHP at a time) is to define multiple Apache services, each of which will use a different PHP version.
First of all use conditions in the Apache configuration file:
<ifdefine php54>
SetEnv PHPRC C:/apache/php54/
ScriptAlias /php/ "C:/apache/php54/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>
<ifdefine php55>
SetEnv PHPRC C:/apache/php55/
ScriptAlias /php/ "C:/apache/php55/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>
Now using the httpd.exe create two separate services from command line (elevated to administrator):
httpd.exe -k install -n Apache224_php54 -D php54
httpd.exe -k install -n Apache224_php55 -D php55
Now you can start one of the above services at a time (should shutdown one before starting the other).
If you have previously installed Apache as service you can remove that using below command (replace the service name with the one you have used):
apache -k uninstall -n Apache224
One further note is that I personally use a "notification area icon program" called "Seobiseu" to start and stop services as needed. I have added the two above services to it.
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
I use the third, but of the other two the first seems less odd. string is an alias for String, but seeing them across an assignment feels off.
mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)
mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM tin3;
+----+------------+
| id | val |
+----+------------+
| 1 | 0000000012 |
| 2 | 0000000007 |
| 4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)
mysql>
mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
| 10 |
+-------------+
1 row in set (0.01 sec)
mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
| 8 |
+-------+
1 row in set (0.00 sec)
My solution: String str = String.format ("%.0f", yourDouble);
Ah, the following works and does what I want:
configurations {
runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"
}
It seems that an Exclude Rule only has two attributes - group
and module
. However, the above syntax doesn't prevent you from specifying any arbitrary property as a predicate. When trying to exclude from an individual dependency you cannot specify arbitrary properties. For example, this fails:
dependencies {
compile ('org.springframework.data:spring-data-hadoop-core:2.0.0.M4-hadoop22') {
exclude group: "org.slf4j", name: "slf4j-log4j12"
}
}
with
No such property: name for class: org.gradle.api.internal.artifacts.DefaultExcludeRule
So even though you can specify a dependency with a group:
and name:
you can't specify an exclusion with a name:
!?!
Perhaps a separate question, but what exactly is a module then? I can understand the Maven notion of groupId:artifactId:version, which I understand translates to group:name:version in Gradle. But then, how do I know what module (in gradle-speak) a particular Maven artifact belongs to?
It really depends what you are going for, and specifically, what kind of performance you really need to offer.
I've seen admirable solutions for strongly-typed HTML development (complete control models, be it ASP.NET Web Controls, or similar to it) that just add amazing complexity to a project. In other situations, it is perfect.
In order of preference in the C# world,
You have to look I the folder C:\Program Files\MySQL\MySQL Server 5.5
but there is a problem. When you perform an MSI install of MySQL, my.ini is not created. There will be sample .ini files in that folder. In order to use one of them, say my-medium.ini
, you need to do the following before a MySQL restart:
cd C:\Program Files\MySQL\MySQL Server 5.5
copy my-medium.ini my.ini
net stop mysql
net start mysql
Once, you do this, my.ini
can be read by C:\Program Files\MySQL\MySQL Server 5.5\bin\mysql.exe
.
I'm having the same warnings. I'm not sure it's a matter of 32 vs 64 bits. Just loaded the new symbols and some problems were solved, but the ones regarding OpenCV still persist. This is an extract of the output with solved vs unsolved issue:
'OpenCV_helloworld.exe': Loaded 'C:\OpenCV2.2\bin\opencv_imgproc220d.dll', Cannot find or open the PDB file
'OpenCV_helloworld.exe': Loaded 'C:\WINDOWS\system32\imm32.dll', Symbols loaded (source information stripped).
The code is exiting 0 in case someone will ask.
The program '[4424] OpenCV_helloworld.exe: Native' has exited with code 0 (0x0).
i had similar problem and my gui reported problem with cache, i change it zabbix-server.conf to 32M and now is ok, zabbix is an intelligent tool, please if it possible check problems in gui first. I had to much hosts ... for default cache.
The COLLATE keyword specify what kind of character set and rules (order, confrontation rules) you are using for string values.
For example in your case you are using Latin rules with case insensitive (CI) and accent sensitive (AS)
You can refer to this Documentation
A simple solution might be to just store the drawable id in a temporary variable. I'm not sure how practical this would be for your situation but it's definitely a quick fix.
I got here looking for a way to add a key/value pair(s) as a group - in my case it was the output of a function call, so adding the pair using dictionary[key] = value
would require me to know the name of the key(s).
In this case, you can use the update method:
dictionary.update(function_that_returns_a_dict(*args, **kwargs)))
Beware, if dictionary
already contains one of the keys, the original value will be overwritten.
Perhaps you don't have to include the single quotes:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"
Update: Reading curl's manual, you could actually separate both fields with two --data:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"
You could also try --data-binary:
curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"
And --data-urlencode:
curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"
To see the difference between:
Your working copy and staging area:
% git diff
Staging area and the latest commit:
% git diff --staged
Your working copy and commit 4ac0a6733:
% git diff 4ac0a6733
Commit 4ac0a6733 and the latest commit:
% git diff 4ac0a6733 HEAD
Commit 4ac0a6733 and commit 826793951
% git diff 4ac0a6733 826793951
For more explanation see the official documentation.
EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday
I found this a while back when learning python
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
# create figure window
gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns
ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]
ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)
fig.add_subplot(ax) #add 'ax' to figure
you can make different sizes in one figure as well, use slices in that case:
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns
consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)
Here's a nice way using a bit of reflection to get a version of a DLL containing a particular class:
var ver = System.Reflection.Assembly.GetAssembly(typeof(!Class!)).GetName().Version;
Just replace !Class! with the name of a class which is defined in the DLL you wish to get the version of.
This is my preferred method because if I move the DLLs around for different deploys I don't have to change the filepath.
For someone looking for a NEST JS TYPESCRIPT
version of the above:
/**
* to fetch a signed URL of a file
* @param key key of the file to be fetched
* @param bucket name of the bucket containing the file
*/
public getFileUrl(key: string, bucket?: string): Promise<string> {
var scopeBucket: string = bucket ? bucket : this.defaultBucket;
var params: any = {
Bucket: scopeBucket,
Key: key,
Expires: signatureTimeout // const value: 30
};
return this.account.getSignedUrlPromise(getSignedUrlObject, params);
}
/**
* to get the downloadable file buffer of the file
* @param key key of the file to be fetched
* @param bucket name of the bucket containing the file
*/
public async getFileBuffer(key: string, bucket?: string): Promise<Buffer> {
var scopeBucket: string = bucket ? bucket : this.defaultBucket;
var params: GetObjectRequest = {
Bucket: scopeBucket,
Key: key
};
var fileObject: GetObjectOutput = await this.account.getObject(params).promise();
return Buffer.from(fileObject.Body.toString());
}
/**
* to upload a file stream onto AWS S3
* @param stream file buffer to be uploaded
* @param key key of the file to be uploaded
* @param bucket name of the bucket
*/
public async saveFile(file: Buffer, key: string, bucket?: string): Promise<any> {
var scopeBucket: string = bucket ? bucket : this.defaultBucket;
var params: any = {
Body: file,
Bucket: scopeBucket,
Key: key,
ACL: 'private'
};
var uploaded: any = await this.account.upload(params).promise();
if (uploaded && uploaded.Location && uploaded.Bucket === scopeBucket && uploaded.Key === key)
return uploaded;
else {
throw new HttpException("Error occurred while uploading a file stream", HttpStatus.BAD_REQUEST);
}
}
If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;
If the data is a local variable or a heap-allocated zone, clear it with memset
like:
memset(&m, 0, sizeof(myStruct));
Current compilers (e.g. recent versions of gcc
) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).
You could perhaps code myStruct m = {};
or myStruct m = {0};
(even if the first member of myStruct
is not a scalar).
My feeling is that using memset
for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).
it clears stdin
buffer before reading. From the man page:
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.
Note: This is Linux-specific, using fflush()
on input streams is undefined by the standard, however, most implementations behave the same as in Linux.
You can use the LIKE operator to compare the content of a T-SQL string, e.g.
SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.
The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".
Checksum all files, including both content and their filenames
grep -ar -e . /your/dir | md5sum | cut -c-32
Same as above, but only including *.py files
grep -ar -e . --include="*.py" /your/dir | md5sum | cut -c-32
You can also follow symlinks if you want
grep -aR -e . /your/dir | md5sum | cut -c-32
Other options you could consider using with grep
-s, --no-messages suppress error messages
-D, --devices=ACTION how to handle devices, FIFOs and sockets;
-Z, --null print 0 byte after FILE name
-U, --binary do not strip CR characters at EOL (MSDOS/Windows)
Some "Advanced" features
Here's how to do it:
var myVideo = document.getElementById("my-video")
myVideo.controls = false;
Working example: https://jsfiddle.net/otnfccgu/2/
See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp
<?php
$sessionDetails = $this->Session->read('Auth.User');
if (!empty($sessionDetails)) {
$loginFlag = 1;
# code...
}else{
$loginFlag = 0;
}
?>
<script type="text/javascript">
var sessionValue = '<?php echo $loginFlag; ?>';
if (sessionValue = 0) {
//model show
}
</script>
If using function onclick DIV and then want to disable click it again you can use this :
for (var i=0;i<document.getElementsByClassName('ads').length;i++){
document.getElementsByClassName('ads')[i].onclick = false;
}
Example :
HTML
<div id='mybutton'>Click Me</div>
Javascript
document.getElementById('mybutton').onclick = function () {
alert('You clicked');
this.onclick = false;
}
When you want svn-like behavior of git commit, use this in your git aliases in your .gitconfig
commit = "!f() { git commit \"$@\" && git push; };f"
Workaround simple and quick. Upload file/photo on cloud (from outside the emulator) and download with browser on the emulator.
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
Just add this code in your ImageView:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@color/white"/>
<size
android:width="20dp"
android:height="20dp"/>
<stroke
android:width="4dp" android:color="@android:color/black"/>
<padding android:left="1dp" android:top="1dp" android:right="1dp"
android:bottom="1dp" />
</shape>
I found that even after following all the steps above, I was still getting errors saying that my Maven dependencies (i.e. pom.xml) were pointing to jar files that didn't exist.
Viewing the errors in the Problems tab, for some reason these were still pointing to the old location of my repository. This was probably because I'd changed the location of my Maven repository since creating the workspace and project.
This can be easily solved by deleting the project from the Eclipse workspace, and re-adding it again through Package Explorer -> R/Click -> Import... -> Existing Projects.
UPDATE
T1
SET
T1.Inci = T2.Inci
FROM
T1
INNER JOIN
T2
ON
T1.Brands = T2.Brands
AND
T1.Category= T2.Category
AND
T1.Date = T2.Date
We need the primary key of that particular model that you want to update. For example:
private fun update(Name: String?, Brand: String?) {
val deviceEntity = remoteDao?.getRemoteId(Id)
if (deviceEntity == null)
remoteDao?.insertDevice(DeviceEntity(DeviceModel = DeviceName, DeviceBrand = DeviceBrand))
else
DeviceDao?.updateDevice(DeviceEntity(deviceEntity.id,remoteDeviceModel = DeviceName, DeviceBrand = DeviceBrand))
}
In this function, I am checking whether a particular entry exists in the database if exists pull the primary key which is id over here and perform update function.
This is the for fetching and update records:
@Query("SELECT * FROM ${DeviceDatabase.DEVICE_TABLE_NAME} WHERE ${DeviceDatabase.COLUMN_DEVICE_ID} = :DeviceId LIMIT 1")
fun getRemoteDeviceId(DeviceId: String?): DeviceEntity
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updatDevice(item: DeviceEntity): Int
<img id="uxcMyImageId" src"myImage" width="100" height="100" />
specifying width and height in the image tag is a good practice..this way when the page loads there is space allocated for the image and the layout does not suffer any jerks even if the image takes a long time to load.
I agree with @kent that this is well suited for grep -o
. If you need to extract a group within a pattern, you can do it with a 2nd grep.
# To extract \1 from /xx([0-9]+)yy/
$ echo "aa678bb xx123yy xx4yy aa42 aa9bb" | grep -Eo 'xx[0-9]+yy' | grep -Eo '[0-9]+'
123
4
# To extract \1 from /a([0-9]+)b/
$ echo "aa678bb xx123yy xx4yy aa42 aa9bb" | grep -Eo 'a[0-9]+b' | grep -Eo '[0-9]+'
678
9
I generally cringe when I see 2 calls to grep/sed/awk piped together, but it's not always wrong. While we should exercise our skills of doing things efficiently, "A foolish consistency is the hobgoblin of little minds", and "Real artists ship".
Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after
method and binding a change method allows you to change color and do other operations.
Label.destroy
is another example of the after method.
def export_win():
//Some Operation
orig_color = export_finding_graph.cget("background")
export_finding_graph.configure(background = "green")
tt = "Exported"
label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)
def change(orig_color):
export_finding_graph.configure(background = orig_color)
tab1_closed_observations.after(1000, lambda: change(orig_color))
tab1_closed_observations.after(500, label.destroy)
export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)
You can also revert to the original color.
You cannot add AM / PM to a TimeSpan
. You'll anyway have to associate the TimaSpan
value with DateTime
if you want to display the time in 12-hour clock format.
TimeSpan
is not intended to use with a 12-hour clock format, because we are talking about a time interval here.
As it says in the documentation;
A
TimeSpan
object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. TheTimeSpan
structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, theDateTime
orDateTimeOffset
structure should be used instead.
Also Microsoft Docs describes as follows;
A
TimeSpan
value can be represented as[-]d.hh:mm:ss.ff
, where the optional minus sign indicates a negative time interval, thed
component is days,hh
is hours as measured on a 24-hour clock,mm
is minutes,ss
is seconds, andff
is fractions of a second.
So in this case, you can display using AM/PM as follows.
TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");
Side note :
Also should note that the TimeOfDay property of DateTime
is a TimeSpan
, where it represents
a time interval that represents the fraction of the day that has elapsed since midnight.
I've found a way to get only the Contacts application:
git clone https://android.googlesource.com/platform/packages/apps/Contacts
which is good enough for me for now, but doesn't answer the question of browsing the code on the web.
Semantically there is no difference between these cases in LDAP.
MSDN seems to indicate that the Cxxx casts for specific types can improve performance in VB .NET because they are converted to inline code. For some reason, it also suggests DirectCast as opposed to CType in certain cases (the documentations states it's when there's an inheritance relationship; I believe this means the sanity of the cast is checked at compile time and optimizations can be applied whereas CType always uses the VB runtime.)
When I'm writing VB .NET code, what I use depends on what I'm doing. If it's prototype code I'm going to throw away, I use whatever I happen to type. If it's code I'm serious about, I try to use a Cxxx cast. If one doesn't exist, I use DirectCast if I have a reasonable belief that there's an inheritance relationship. If it's a situation where I have no idea if the cast should succeed (user input -> integers, for example), then I use TryCast so as to do something more friendly than toss an exception at the user.
One thing I can't shake is I tend to use ToString instead of CStr but supposedly Cstr is faster.
Below could be the better way:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
//your code to implement
cursor.moveToNext();
}
}
cursor.close();
The above code would insure that it would go through entire iteration and won't escape first and last iteration.
You also have the Apache Commons CSV library, maybe it does what you need. See the guide. Updated to Release 1.1 in 2014-11.
Also, for the foolproof edition, I think you'll need to code it yourself...through SimpleDateFormat
you can choose your formats, and specify various types, if the Date
isn't like any of your pre-thought types, it isn't a Date.
I would opt for NOT EXISTS
in this case.
SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
(SELECT 'X'
FROM Domain2 D2
WHERE D2.ShortCode = D1.ShortCode
)
Short answer was provided here already: use <div [innerHTML]="yourHtml">
binding.
However the rest of the advices mentioned here might be misleading. Angular has a built-in sanitizing mechanism when you bind to properties like that. Since Angular is not a dedicated sanitizing library, it is overzealous towards suspicious content to not take any risks. For example, it sanitizes all SVG content into empty string.
You might hear advices to "sanitize" your content by using DomSanitizer
to mark content as safe with bypassSecurityTrustXXX
methods. There are also suggestions to use pipe to do that and that pipe is often called safeHtml
.
All of this is misleading because it actually bypasses sanitizing, not sanitizing your content. This could be a security concern because if you ever do this on user provided content or on anything that you are not sure about — you open yourself up for a malicious code attacks.
If Angular removes something that you need by its built-in sanitization — what you can do instead of disabling it is delegate actual sanitization to a dedicated library that is good at that task. For example — DOMPurify.
I've made a wrapper library for it so it could be easily used with Angular: https://github.com/TinkoffCreditSystems/ng-dompurify
It also has a pipe to declaratively sanitize HTML:
<div [innerHtml]="value | dompurify"></div>
The difference to pipes suggested here is that it actually does do the sanitization through DOMPurify and therefore work for SVG.
One thing to keep in mind is DOMPurify is great for sanitizing HTML/SVG, but not CSS. So you can provider Angular's CSS sanitizer to handle CSS:
import {NgModule, ?_sanitizeStyle} from '@angular/core';
import {SANITIZE_STYLE} from '@tinkoff/ng-dompurify';
@NgModule({
// ...
providers: [
{
provide: SANITIZE_STYLE,
useValue: ?_sanitizeStyle,
},
],
// ...
})
export class AppModule {}
It's internal — hense ?
prefix, but this is how Angular team use it across their own packages as well anyway. That library also works for Angular Universal and server side renedring environment.
Use slideToggle(500) function with a duration in milliseconds for getting a better effect.
Sample Html
<body>
<div class="growth-step js--growth-step">
<div class="step-title">
<div class="num">2.</div>
<h3>How Can Aria Help Your Business</h3>
</div>
<div class="step-details ">
<p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
management organization with expertise. </p>
</div>
</div>
<div class="growth-step js--growth-step">
<div class="step-title">
<div class="num">3.</div>
<h3>How Can Aria Help Your Business</h3>
</div>
<div class="step-details">
<p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
management organization with expertise. </p>
</div>
</div>
</body>
In your js file, if you need child propagation for the animation then remove the second click event function and its codes.
$(document).ready(function(){
$(".js--growth-step").click(function(event){
$(this).children(".step-details").slideToggle(500);
return false;
});
//for stoping child to manipulate the animation
$(".js--growth-step .step-details").click(function(event) {
event.stopPropagation();
});
});
You should make tags their own table with a linking table.
items:
id object
1 lamp
2 table
3 stool
4 bench
tags:
id tag
1 furniture
2 chair
items_tags:
item_id tag_id
1 1
2 1
3 1
4 1
3 2
4 2
Not really programming related, but I found this on Google, there is not a direct keyboard shortcut, but makes it a little quicker.
Simply use
sp_restoredb 'Your Database Name' ,'Location From you want to restore'
Example: sp_restoredb 'omDB','D:\abc.bak'
If you have tomcat on the classpath, it's as simple as:
TomcatURLStreamHandlerFactory.register();
This will register handlers for "war" and "classpath" protocols.
will give you info about the currently logged-in user, but you'll need to supply an oauth token. See:
Alternatively, cv2.merge()
can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1)
into (height, width, 3)
To address your problem
I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.
This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
Example
We create a color image with dimensions (200,200,3)
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
Next we convert it to grayscale and create another image using cv2.merge()
with three gray channels
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1)
and the three channel grayscale image with shape (200,200,3)
(right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
Full code
import cv2
import numpy as np
# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])
# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()
This is actually a lot easier using a dataURI, because you can just call print on the returned window object.
// file is a File object, this will also take a blob
const dataUrl = window.URL.createObjectURL(file);
// Open the window
const pdfWindow = window.open(dataUrl);
// Call print on it
pdfWindow.print();
This opens the pdf in a new tab and then pops the print dialog up.
The following correct answer was provided in the comment section of the question by Felix Kling:
if (!$.trim(data)){
alert("What follows is blank: " + data);
}
else{
alert("What follows is not blank: " + data);
}
If you want the font you chose to be applied and not the one in bootstrap without modifying the original bootstrap files you can rearrange the tags in your HTML documents so your CSS files that applies the font called after the bootstrap one. In this way since the browser reads the documents line after line first it will read the bootstrap files and apply it roles then it will read your file and override the roles in the bootstrap and replace it with the ones in your file.
let gameBoard: [
[null, null, null],
[null, null, null],
[null, null, null]
]
const SYMBOLS = {
X:'X',
O:'O'
}
const RESULT = {
INCOMPLETE: "incomplete",
PLAYER_X_WON: SYMBOLS.x,
PLAYER_O_WON: SYMBOLS.o,
tie: "tie"
}
We'll need a function that can check for the result. The function will check for a succession of chars. What ever the state of the board is, the result is one of 4 options: either Incomplete, player X won, Player O won or a tie.
function checkSuccession (line){_x000D_
if (line === SYMBOLS.X.repeat(3)) return SYMBOLS.X_x000D_
if (line === SYMBOLS.O.repeat(3)) return SYMBOLS.O_x000D_
return false _x000D_
}_x000D_
_x000D_
function getResult(board){_x000D_
_x000D_
let result = RESULT.incomplete_x000D_
if (moveCount(board)<5){_x000D_
return result_x000D_
}_x000D_
_x000D_
let lines_x000D_
_x000D_
//first we check row, then column, then diagonal_x000D_
for (var i = 0 ; i<3 ; i++){_x000D_
lines.push(board[i].join(''))_x000D_
}_x000D_
_x000D_
for (var j=0 ; j<3; j++){_x000D_
const column = [board[0][j],board[1][j],board[2][j]]_x000D_
lines.push(column.join(''))_x000D_
}_x000D_
_x000D_
const diag1 = [board[0][0],board[1][1],board[2][2]]_x000D_
lines.push(diag1.join(''))_x000D_
const diag2 = [board[0][2],board[1][1],board[2][0]]_x000D_
lines.push(diag2.join(''))_x000D_
_x000D_
for (i=0 ; i<lines.length ; i++){_x000D_
const succession = checkSuccesion(lines[i])_x000D_
if(succession){_x000D_
return succession_x000D_
}_x000D_
}_x000D_
_x000D_
//Check for tie_x000D_
if (moveCount(board)==9){_x000D_
return RESULT.tie_x000D_
}_x000D_
_x000D_
return result_x000D_
}
_x000D_
Our getBestMove function will receive the state of the board, and the symbol of the player for which we want to determine the best possible move. Our function will check all possible moves with the getResult function. If it is a win it will give it a score of 1. if it's a loose it will get a score of -1, a tie will get a score of 0. If it is undetermined we will call the getBestMove function with the new state of the board and the opposite symbol. Since the next move is of the oponent, his victory is the lose of the current player, and the score will be negated. At the end possible move receives a score of either 1,0 or -1, we can sort the moves, and return the move with the highest score.
const copyBoard = (board) => board.map( _x000D_
row => row.map( square => square ) _x000D_
)_x000D_
_x000D_
function getAvailableMoves (board) {_x000D_
let availableMoves = []_x000D_
for (let row = 0 ; row<3 ; row++){_x000D_
for (let column = 0 ; column<3 ; column++){_x000D_
if (board[row][column]===null){_x000D_
availableMoves.push({row, column})_x000D_
}_x000D_
}_x000D_
}_x000D_
return availableMoves_x000D_
}_x000D_
_x000D_
function applyMove(board,move, symbol) {_x000D_
board[move.row][move.column]= symbol_x000D_
return board_x000D_
}_x000D_
_x000D_
function getBestMove (board, symbol){_x000D_
_x000D_
let availableMoves = getAvailableMoves(board)_x000D_
_x000D_
let availableMovesAndScores = []_x000D_
_x000D_
for (var i=0 ; i<availableMoves.length ; i++){_x000D_
let move = availableMoves[i]_x000D_
let newBoard = copyBoard(board)_x000D_
newBoard = applyMove(newBoard,move, symbol)_x000D_
result = getResult(newBoard,symbol).result_x000D_
let score_x000D_
if (result == RESULT.tie) {score = 0}_x000D_
else if (result == symbol) {_x000D_
score = 1_x000D_
}_x000D_
else {_x000D_
let otherSymbol = (symbol==SYMBOLS.x)? SYMBOLS.o : SYMBOLS.x_x000D_
nextMove = getBestMove(newBoard, otherSymbol)_x000D_
score = - (nextMove.score)_x000D_
}_x000D_
if(score === 1) // Performance optimization_x000D_
return {move, score}_x000D_
availableMovesAndScores.push({move, score})_x000D_
}_x000D_
_x000D_
availableMovesAndScores.sort((moveA, moveB )=>{_x000D_
return moveB.score - moveA.score_x000D_
})_x000D_
return availableMovesAndScores[0]_x000D_
}
_x000D_
Algorithm in action, Github, Explaining the process in more details
A problem I was running into was that I was using the webpack-simple install for VueJS which didn't seem to include an Environment variable config folder. So I wasn't able to edit the env.test,development, and production.js config files. Creating them didn't help either.
Other answers weren't detailed enough for me, so I just "fiddled" with webpack.config.js. And the following worked just fine.
So to get Environment Variables to work, the webpack.config.js should have the following at the bottom:
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Based on the above, in production, you would be able to get the NODE_ENV variable
mounted() {
console.log(process.env.NODE_ENV)
}
Now there may be better ways to do this, but if you want to use Environment Variables in Development you would do something like the following:
if (process.env.NODE_ENV === 'development') {
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
})
]);
}
Now if you want to add other variables with would be as simple as:
if (process.env.NODE_ENV === 'development') {
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"',
ENDPOINT: '"http://localhost:3000"',
FOO: "'BAR'"
}
})
]);
}
I should also note that you seem to need the "''" double quotes for some reason.
So, in Development, I can now access these Environment Variables:
mounted() {
console.log(process.env.ENDPOINT)
console.log(process.env.FOO)
}
Here is the whole webpack.config.js just for some context:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
if (process.env.NODE_ENV === 'development') {
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"',
ENDPOINT: '"http://localhost:3000"',
FOO: "'BAR'"
}
})
]);
}
netcat
(nc.exe
) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as "OK" in your antivirus software (how you do this will depend on what type of antivirus software you use).
Of course you will also need to configure your sysadmin to accept that you're not trying to do anything illegal...
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
In c++ you could use std::string to get repeated character
printf("%s",std::string(count,char).c_str());
For example:
printf("%s",std::string(5,'a').c_str());
output:
aaaaa
In order to downgrade, i had to recompile from source (MacOS Mojave)
$ wget https://ssl.icu-project.org/files/icu4c/62.1/icu4c-62_1-src.tgz
$ tar xvfz icu4c-62_1-src.tgz
$ cd icu/sources
$ ./configure
$ make
$ make install
In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
count := 10
then := now.Add(time.Duration(-count) * time.Minute)
// if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
// then := now.Add(-10 * time.Minute)
fmt.Println("10 minutes ago:", then)
}
Produces:
now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
Not to mention, you can also use time.Hour
or time.Second
instead of time.Minute
as per your needs.
Playground: https://play.golang.org/p/DzzH4SA3izp
This is the simple Console Application to convert List to Datatable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;
namespace ConvertListToDataTable
{
public static class Program
{
public static void Main(string[] args)
{
List<MyObject> list = new List<MyObject>();
for (int i = 0; i < 5; i++)
{
list.Add(new MyObject { Sno = i, Name = i.ToString() + "-KarthiK", Dat = DateTime.Now.AddSeconds(i) });
}
DataTable dt = ConvertListToDataTable(list);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine();
for (int x = 0; x < dt.Columns.Count; x++)
{
Console.Write(row[x].ToString() + " ");
}
}
Console.ReadLine();
}
public class MyObject
{
public int Sno { get; set; }
public string Name { get; set; }
public DateTime Dat { get; set; }
}
public static DataTable ConvertListToDataTable<T>(this List<T> iList)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor propertyDescriptor = props[i];
Type type = propertyDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = Nullable.GetUnderlyingType(type);
dataTable.Columns.Add(propertyDescriptor.Name, type);
}
object[] values = new object[props.Count];
foreach (T iListItem in iList)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
}
If you understand stack very well then you will understand how memory works in program and if you understand how memory works in program you will understand how function store in program and if you understand how function store in program you will understand how recursive function works and if you understand how recursive function works you will understand how compiler works and if you understand how compiler works your mind will works as compiler and you will debug any program very easily
Let me explain how stack works:
First you have to know how functions are represented in stack :
Heap stores dynamically allocated values.
Stack stores automatic allocation and deletion values.
Let's understand with example :
def hello(x):
if x==1:
return "op"
else:
u=1
e=12
s=hello(x-1)
e+=1
print(s)
print(x)
u+=1
return e
hello(4)
Now understand parts of this program :
Now let's see what is stack and what are stack parts:
Allocation of the stack :
Remember one thing: if any function's return condition gets satisfied, no matter it has loaded the local variables or not, it will immediately return from stack with it's stack frame. It means that whenever any recursive function get base condition satisfied and we put a return after base condition, the base condition will not wait to load local variables which are located in the “else” part of program. It will immediately return the current frame from the stack following which the next frame is now in the activation record.
See this in practice:
Deallocation of the block:
So now whenever a function encounters return statement, it delete the current frame from the stack.
While returning from the stack, values will returned in reverse of the original order in which they were allocated in stack.
In my case, the mysql.com downloaded Connector/J 5.1.29 .jar had this error whereas the 5.1.29 .jar downloaded from the MvnRepository did not.
This happened when building a Google appengine application in Android Studio (gradle, Windows x64), communicating to a Linux MySQL server on the local network/local VM.
yan.kun was on the right track but this is much much easier.
public FileContentResult DownloadCSV()
{
string csv = "Charlie, Chaplin, Chuckles";
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");
}
Hopes this makes it find the tables as you're reading through the thing:
mysql> show columns from colors;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| color | varchar(15) | YES | | NULL | |
| paint | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
With Visual Studio 2017
, It now comes with a much better version, named “Go To All”
and is bound to the keyboard shortcut CTRL + T
as well as CTRL +,
and includes inline filtering and “fuzzy search”
CTRL + T
CTRL + ,
Based on solution by Pavel Cerný here we can make an universal typed implementation of this pattern. To to it, we need to introduce NamedService interface:
public interface NamedService {
String name();
}
and add abstract class:
public abstract class AbstractFactory<T extends NamedService> {
private final Map<String, T> map;
protected AbstractFactory(List<T> list) {
this.map = list
.stream()
.collect(Collectors.toMap(NamedService::name, Function.identity()));
}
/**
* Factory method for getting an appropriate implementation of a service
* @param name name of service impl.
* @return concrete service impl.
*/
public T getInstance(@NonNull final String name) {
T t = map.get(name);
if(t == null)
throw new RuntimeException("Unknown service name: " + name);
return t;
}
}
Then we create a concrete factory of specific objects like MyService:
public interface MyService extends NamedService {
String name();
void doJob();
}
@Component
public class MyServiceFactory extends AbstractFactory<MyService> {
@Autowired
protected MyServiceFactory(List<MyService> list) {
super(list);
}
}
where List the list of implementations of MyService interface at compile time.
This approach works fine if you have multiple similar factories across app that produce objects by name (if producing objects by a name suffice you business logic of course). Here map works good with String as a key, and holds all the existing implementations of your services.
if you have different logic for producing objects, this additional logic can be moved to some another place and work in combination with these factories (that get objects by name).
To add to what Jonathan said: use the -print0
option for find
in conjunction with xargs
as follows:
find test/* -type d -print0 | xargs -0 command
That will execute the command command
with the proper arguments; directories with spaces in them will be properly quoted (i.e. they'll be passed in as one argument).
As others have said, use ArrayList
. Here's how:
public class t
{
private List<Integer> x = new ArrayList<Integer>();
public void add(int num)
{
this.x.add(num);
}
}
As you can see, your add
method just calls the ArrayList
's add method. This is only useful if your variable is private (which it is).
Imports System.Data
Imports System.Data.SqlClient
Public Class Form2
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim dr1 As SqlDataReader
Dim ra As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")
'you need to provide password for sql server
myconnection.Open()
mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)
mycommand.ExecuteNonQuery()
MessageBox.Show("New Row Inserted" & ra)
myconnection.Close()
End Sub
End Class
this query will auto-update the nulls
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) DEFAULT 'whatever' NOT NULL;
You could combine 2 formats:
3 dd/mm/yy (British/French)
8 hh:mm:ss
according to CONVERT()
function, and using +
operator:
SELECT CONVERT(varchar(10),GETDATE(),3) + ' ' + CONVERT(varchar(10),GETDATE(),8)
This is another way to specify the range of the bit-vector.
x +: N, The start position of the vector is given by x and you count up from x by N.
There is also
x -: N, in this case the start position is x and you count down from x by N.
N is a constant and x is an expression that can contain iterators.
It has a couple of benefits -
It makes the code more readable.
You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.
I would suggest a slight change in your logic. It may or may not work, depending on what you need to accomplish.
handle_event() can still do the "boring default code" but instead of being virtual, at the point where you want it to do the "new exciting code" have the base class call an abstract method (i.e. must-be-overridden) method that will be supplied by your descendant class.
EDIT: And if you later decide that some of your descendant classes do not need to provide "new exciting code" then you can change the abstract to virtual and supply an empty base class implementation of that "inserted" functionality.
Did you try this?
UPDATE table
SET col1 = NULL
WHERE col1 = ''
As the commenters point out, you don't have to do ltrim()
or rtrim()
, and NULL
columns will not match ''
.
for my example:
Windows XP ---> Synology:DS218+
Step2:
Enable Telnet service (?? Telnet ??)
or Enable SSH Service (?? SSH ??)
Step3: Launch the terminal on Windows (or via executing cmd
to launch the terminal)
Step4: type: telnet your_nas_ip_or_domain_name, like below telnet 192.168.1.104
Fzz login: tsungjung411 Password: # shows the current working directory (?????????) $ pwd /var/services/homes/tsungjung411 # edit a Java file (via vi), then compile and run it # (?? vi ?? Java ??,???????) $ vi Main.java # show the file content (??????) $ cat Main.java public class Main { public static void main(String [] args) { System.out.println("hello, World!"); } } # compiles the Java file (?? Java ??) javac Main.java # executes the Java file (?? Java ??) $ java Main hello, World! # shows the file list (??????) $ ls CloudStation Main.class Main.java www
# shows the JRE version on this Synology Disk Station $ java -version openjdk version "1.8.0_151" OpenJDK Runtime Environment (IcedTea 3.6.0) (linux-gnu build 1.8.0_151-b12) OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
$ python Python 2.7.12 (default, Nov 10 2017, 20:30:30) [GCC 4.9.3 20150311 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import sys >>> >>> # shows the the python version >>> print(sys.version) 2.7.12 (default, Nov 10 2017, 20:30:30) [GCC 4.9.3 20150311 (prerelease)] >>> >>> import os >>> >>> # shows the current working directory >>> print(os.getcwd()) /volume1/homes/tsungjung411
$ # launch Python 3 $ python3 Python 3.5.1 (default, Dec 9 2016, 00:20:03) [GCC 4.9.3 20150311 (prerelease)] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
Forgetting to set up relationships between the tables. I remember having to clean this up when I first started working at my current employer.
@gbtimmon's answer is great, but way, way too complicated. I've simplified his code as much as I could.
#answer,
#show,
#hide:target {
display: none;
}
#hide:target + #show,
#hide:target ~ #answer {
display: inherit;
}
_x000D_
<a href="#hide" id="hide">Show</a>
<a href="#/" id="show">Hide</a>
<div id="answer"><p>Answer</p></div>
_x000D_
There are some predefined formats in date_d.php
to use with format
like:
define ('DATE_ATOM', "Y-m-d\TH:i:sP");
define ('DATE_COOKIE', "l, d-M-y H:i:s T");
define ('DATE_ISO8601', "Y-m-d\TH:i:sO");
define ('DATE_RFC822', "D, d M y H:i:s O");
define ('DATE_RFC850', "l, d-M-y H:i:s T");
define ('DATE_RFC1036', "D, d M y H:i:s O");
define ('DATE_RFC1123', "D, d M Y H:i:s O");
define ('DATE_RFC2822', "D, d M Y H:i:s O");
define ('DATE_RFC3339', "Y-m-d\TH:i:sP");
define ('DATE_RSS', "D, d M Y H:i:s O");
define ('DATE_W3C', "Y-m-d\TH:i:sP");
Use like this:
$date = new \DateTime();
$string = $date->format(DATE_RFC2822);
A simple loop should be working:
for file in /var/*
do
#whatever you need with "$file"
done
This solution checks all the possible formats before throwing an exception. This solution is more convenient if you are trying to test for multiple date formats.
Date extractTimestampInput(String strDate){
final List<String> dateFormats = Arrays.asList("yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd");
for(String format: dateFormats){
SimpleDateFormat sdf = new SimpleDateFormat(format);
try{
return sdf.parse(strDate);
} catch (ParseException e) {
//intentionally empty
}
}
throw new IllegalArgumentException("Invalid input for date. Given '"+strDate+"', expecting format yyyy-MM-dd HH:mm:ss.SSS or yyyy-MM-dd.");
}
This task is very easy use following code in html header section
<head> <meta http-equiv="refresh" content="30" /> </head>
It will refresh your page after 30 seconds.
hg strip
will completely remove a revision (and any descendants) from the repository.
To use strip you'll need to install MqExtension by adding the following lines to your .hgrc (or mercurial.ini):
[extensions]
mq =
In TortoiseHg the strip command is available in the workbench. Right click on a revision and choose 'Modify history' -> 'Strip'.
Since strip
changes the the repository's history you should only use it on revisions which haven't been shared with anyone yet. If you are using mercurial 2.1+ you can uses phases to track this information. If a commit is still in the draft phase it hasn't been shared with other repositories so you can safely strip it. (Thanks to Zasurus for pointing this out).
You can use onSelect
event
$("#date-daily").datepicker({
onSelect: function(dateText) {
alert($('#dp3').val());
}
});
It is Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. this refers to the associated input field.
$var = preg_replace( "/return=[^&]+/", "", $var ); $var = preg_replace( "/&{2,}/", "&", $var );
Second line will just replace && to &
Non of these solutions worked for my case:
notes:
import { keyBy, values } from 'lodash';
interface IStringTMap<T> {
[key: string]: T;
}
type IIdentified = {
id?: string | number;
};
export function mergeArrayById<T extends IIdentified>(
array1: T[],
array2: T[]
): T[] {
const mergedObjectMap: IStringTMap<T> = keyBy(array1, 'id');
const finalArray: T[] = [];
for (const object of array2) {
if (object.id && mergedObjectMap[object.id]) {
mergedObjectMap[object.id] = {
...mergedObjectMap[object.id],
...object,
};
} else {
finalArray.push(object);
}
}
values(mergedObjectMap).forEach(object => {
finalArray.push(object);
});
return finalArray;
}
This worked for my purposes. Pretty basic and simple, but it did what I needed (which was to get a personal photo of mine onto the internet so I could use its URL).
Go to photos.google.com and open any image that you wish to embed in your website.
Tap the Share Icon and then choose "Get Link" to generate a shareable link for that image.
Go to j.mp/EmbedGooglePhotos, paste that link and it will instantly generate the embed code for that picture.
Open your website template, paste the generated code and save. The image will now serve directly from your Google Photos account.
Check this video tutorial out if you have trouble.
select cast((1*1.00)/3 AS DECIMAL(16,2)) as Result
Here in this sql first convert to float or multiply by 1.00 .Which output will be a float number.Here i consider 2 decimal places. You can choose what you need.
The already-mentioned list comprehension approach is probably your best bet. But if you absolutely want to do it in-place (for example if x
is really large), here's one way:
x = ["ok", "jj", "uy", "poooo", "fren"]
index=0
while index < len(x):
if len(x[index]) != 2:
print "length of %s is: %s" %(x[index], len(x[index]))
del x[index]
continue
index+=1
For those who don't know how to get index_name
which mentioned in Devart's answer, or key_name
which mentioned in Uday Sawant's answer, you can get it like this:
SHOW INDEX FROM table_name;
This will show all indexes for the given table, then you can pick name of the index or unique key that you want to remove.
I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)
But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this:
jdbc:sqlserver://localhost;integratedSecurity=true;
And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver)
MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL
I had, pretty much, the same problem. I was able to see that PDO was enabled but I had no available drivers (using PHP 7-RC4). I managed to resolve the issue by adding the php_pdo_mysql extension to those which were enabled.
Hope this helps!
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
Why not create a class Book with properties: Number, Title, and Price. Then store them in a single dimensional array? That way instead of calling
Book[i][j]
..to get your books title, call
Book[i].Title
Seems to me like it would be a bit more manageable and code friendly.
Remove 'javascript:' from your code and it should work.
Do you happen to use FireFox? I have learned from someone else that FireFox no longer accepts the 'javascript:' string. However, for the life of me, I cannot find the original source (though I believe it was somewhere in FF update notes).
I think refilling the same adapter with different data would be more or most better technique. Put this method in your Adapter class with right argument (the data list you want to display as names in my case) Call this where u update the data of list with updated list (names in my case)
public void refill(ArrayList<BeanDatabase> names) {
list.clear();
list.addAll(names);
list.notifyDataSetChanged();
}
If you change the adapter or set the adapter again and again on when the list updates, then force close error would surely cause problems at some point. (Error:List data been updated but adapter doesn't notify the List View)
Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>
struct Foo
{
Foo() : _i(0) {};
int _i;
friend std::ostream& operator<<(std::ostream& os, const Foo& f)
{
os << f._i;
return os;
};
};
typedef std::vector<Foo> VectorT;
std::string toString(const VectorT& v)
{
std::stringstream ss;
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
return ss.str();
};
int main()
{
VectorT v(10);
std::for_each(v.begin(), v.end(),
[](Foo& f)
{
f._i = rand() % 100;
});
std::cout << "before sort: " << toString(v) << "\n";
sort(v.begin(), v.end(),
[](const Foo& a, const Foo& b)
{
return a._i > b._i;
});
std::cout << "after sort: " << toString(v) << "\n";
return 1;
};
The output is:
before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort: 93, 92, 86, 86, 83, 77, 49, 35, 21, 15,
Log.v("blah", "blah blah");
You need to add the android Log view in eclipse to see them. There are also other methods depending on the severity of the message (error, verbose, warning, etc..).
NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&url=https://xxxxxx.com/rest/images/apps/ipa/dev/xyz.plist"]];
[[UIApplication sharedApplication] openURL:url];
openUrl method was deprecated.
[[UIApplication sharedApplication] openURL: url options:@{} completionHandler:nil];
This method latest openUrl method and it will display prompt dialog.The dialog will show
xxxxxx.com would like to install "YOUR_APP_NAME"
this messages. If you click the "install" button application will close and ipa will download.
If the file is only numerical values separated by tabs, try using the csv library: http://docs.python.org/library/csv.html (you can set the delimiter to '\t')
If you have a textual file in which every line represents a row in a matrix and has integers separated by spaces\tabs, wrapped by a 'arrayname = [...]' syntax, you should do something like:
import re
f = open("your-filename", 'rb')
result_matrix = []
for line in f.readlines():
match = re.match(r'\s*\w+\s+\=\s+\[(.*?)\]\s*', line)
if match is None:
pass # line syntax is wrong - ignore the line
values_as_strings = match.group(1).split()
result_matrix.append(map(int, values_as_strings))
To save a bit time:
1) You can mark your app icon images all in finder and drag them into your Assets catalog all at once by dragging into one of the empty slots of the app icon imageset. When you hold your drag over the slot, several of the other slots look selected and when you drop those all will be filled up at once. Note that this works in XCode 8 (I haven't tried XCode 7), but in XCode 9 beta not yet.
2) The "Technical Q&A QA1686" apple documentation site has the sizes per app icon slot already calculated for you in a nice image and also contains the correct image names conventions.
In Linux, there is different escape sequences for control terminal. For example, there is special escape sequence for erase whole line: \33[2K
and for move cursor to previous line: \33[1A
. So all you need is to print this every time you need to refresh the line. Here is the code which prints Line 1 (second variant)
:
System.out.println("Line 1 (first variant)");
System.out.print("\33[1A\33[2K");
System.out.println("Line 1 (second variant)");
There are codes for cursor navigation, clearing screen and so on.
I think there are some libraries which helps with it (ncurses
?).
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect
call. For example,
con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
connect_timeout=1000)
Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.
For detail about different arguments that you can pass to _mysql.connect
, see MySQLdb API documentation
I'm not sure why your breakpoints aren't hitting, but one sure-fire way to step into your code is to type
debugger;
where you want the code to halt, and then run again with the chrome developer tools window open.
Just one small thing to be aware of, be sure to clean up after you done and remove the debugger lines. If you ever run JavaScript files through YUI compressor, the existence of a debugger;
line will cause it to error out.
You can try something like this....
Dim cbTime
Set cbTime = ActiveSheet.CheckBoxes.Add(100, 100, 50, 15)
With cbTime
.Name = "cbTime"
.Characters.Text = "Time"
End With
If ActiveSheet.CheckBoxes("cbTime").Value = 1 Then 'or just cbTime.Value
'checked
Else
'unchecked
End If
I'm also coming from Ruby so I love the syntax foo ||= 7
.
This is the closest thing I can find.
foo = foo if 'foo' in vars() else 7
I've seen people do this for a dict:
try:
foo['bar']
except KeyError:
foo['bar'] = 7
Upadate: However, I recently found this gem:
foo['bar'] = foo.get('bar', 7)
If you like that, then for a regular variable you could do something like this:
vars()['foo'] = vars().get('foo', 7)
If you want to remove all whitespace:
$str = preg_replace('/\s+/', '', $str);
See the 5th example on the preg_replace documentation. (Note I originally copied that here.)
Edit: commenters pointed out, and are correct, that str_replace
is better than preg_replace
if you really just want to remove the space character. The reason to use preg_replace
would be to remove all whitespace (including tabs, etc.).
You can achieve this using XML notation and the MethodInvokingFactoryBean
. For an example look here.
private static StaticBean staticBean;
public void setStaticBean(StaticBean staticBean) {
StaticBean.staticBean = staticBean;
}
You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.
Note testing can also be more difficult with this approach.
These are extended operations (e.g., sort, reverse) for one dimensional and two dimensional arrays in Twig framework:
{% for key, value in array_one_dimension %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key, value in array_one_dimension|keys|sort %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key, value in array_one_dimension|keys|sort|reverse %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key_a, value_a in array_two_dimension %}
{% for key_b, value_b in array_two_dimension[key_a] %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a] %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
I was getting this error because I did release that my ant release
was failing because I ran out of disk space.
@Jason S: your "fmod" variant will not work on a standards-compliant implementation. The C standard is explicit and clear (7.12.10.1, "the fmod functions"):
if y is nonzero, the result has the same sign as x
thus,
fmod(atan2(y,x)/M_PI*180,360)
is actually just a verbose rewriting of:
atan2(y,x)/M_PI*180
Your third suggestion, however, is spot on.
We should first read the documentation on proxy_pass carefully and fully.
The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /
. Absense of trailing slash means hat URI is absent.
Proxy_pass with URI:
location /some_dir/ {
proxy_pass http://some_server/;
}
With the above, there's the following proxy:
http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/ some_subdir/some_file
Basically, /some_dir/
gets replaced by /
to change the request path from /some_dir/some_subdir/some_file
to /some_subdir/some_file
.
Proxy_pass without URI:
location /some_dir/ {
proxy_pass http://some_server;
}
With the second (no trailing slash): the proxy goes like this:
http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file
Basically, the full original request path gets passed on without changes.
So, in your case, it seems you should just drop the trailing slash to get what you want.
Caveat
Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:
location /some_dir/ {
rewrite /some_dir/(.*) /$1 break;
proxy_pass $upstream_server;
}
There are other cases where rewrite wouldn't work, that's why reading documentation is a must.
Reading your question again, it seems I may have missed that you just want to edit the html output.
For that, you can use the sub_filter directive. Something like ...
location /admin/ {
proxy_pass http://localhost:8080/;
sub_filter "http://your_server/" "http://your_server/admin/";
sub_filter_once off;
}
Basically, the string you want to replace and the replacement string
Add list-style-position: inside
to the ul
element. (example)
The default value for the list-style-position
property is outside
.
ul {_x000D_
text-align: center;_x000D_
list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>
_x000D_
Another option (which yields slightly different results) would be to center the entire ul
element:
.parent {_x000D_
text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>_x000D_
</div>
_x000D_
If you run sudo apt-get install lib32z1 lib32ncurses5 libbz2-1.0 lib32stdc++6
and got a message like: "The following packages have unmet dependencies: lib32stdc++6 : Depends: lib32gcc1 (>= 1:4.1.1)
".
You can do something like this tut: https://askubuntu.com/questions/671791/lib32stdc6-package-depends-on-gcc-base-but-my-installed-version-is-newer
Short answer: No practical, performance, or storage, difference.
Long answer:
There is essentially no difference (in MySQL) between VARCHAR(3000)
(or any other large limit) and TEXT
. The former will truncate at 3000 characters; the latter will truncate at 65535 bytes. (I make a distinction between bytes and characters because a character can take multiple bytes.)
For smaller limits in VARCHAR
, there are some advantages over TEXT
.
CHARACTER SET
.INDEXes
are limited in how big a column can be indexed. (767 or 3072 bytes; this is version and settings dependent)SELECTs
are handled in two different ways -- MEMORY (faster) or MyISAM (slower). When 'large' columns are involved, the slower technique is automatically picked. (Significant changes coming in version 8.0; so this bullet item is subject to change.)TEXT
datatypes (as opposed to VARCHAR
) jump straight to MyISAM. That is, TINYTEXT
is automatically worse for generated temp tables than the equivalent VARCHAR
. (But this takes the discussion in a third direction!)VARBINARY
is like VARCHAR
; BLOB
is like TEXT
.Rebuttal to other answers
The original question asked one thing (which datatype to use); the accepted answer answered something else (off-record storage). That answer is now out of date.
When this thread was started and answered, there were only two "row formats" in InnoDB. Soon afterwards, two more formats (DYNAMIC
and COMPRESSED
) were introduced.
The storage location for TEXT
and VARCHAR()
is based on size, not on name of datatype. For an updated discussion of on/off-record storage of large text/blob columns, see this .
Stole this from here. I found it very useful!
DECLARE @DB_USers TABLE
(DBName sysname, UserName sysname, LoginType sysname, AssociatedRole varchar(max),create_date datetime,modify_date datetime)
INSERT @DB_USers
EXEC sp_MSforeachdb
'
use [?]
SELECT ''?'' AS DB_Name,
case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName,
prin.type_desc AS LoginType,
isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole ,create_date,modify_date
FROM sys.database_principals prin
LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id
WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and
prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%'''
SELECT
dbname,username ,logintype ,create_date ,modify_date ,
STUFF(
(
SELECT ',' + CONVERT(VARCHAR(500),associatedrole)
FROM @DB_USers user2
WHERE
user1.DBName=user2.DBName AND user1.UserName=user2.UserName
FOR XML PATH('')
)
,1,1,'') AS Permissions_user
FROM @DB_USers user1
GROUP BY
dbname,username ,logintype ,create_date ,modify_date
ORDER BY DBName,username
try
int words = 0;
int lines = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
chars += line.length();
words += new StringTokenizer(line, " ,").countTokens();
}
You can pass the necessary variables from the parent scope into the closure with the use
keyword.
For example:
DB::table('users')->where(function ($query) use ($activated) {
$query->where('activated', '=', $activated);
})->get();
More on that here.
PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.
An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):
DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();
Differences compared to the regular syntax:
fn
keyword instead of function
.use
keyword in the latter example.void
return type when declaring them.return
keyword must be omitted.You can also do:
obj = ClassModel.get_by_id(object_id)
This works, but there may I'm not sure if it's supported in Django 2.
The "compile project(':volley')" line was giving me this error:
Error:Execution failed for task ':volley:processDebugResources'. > com.android.ide.common.process.ProcessException: Failed to execute aapt
It was caused because the compileSdk and buildTools versions of module volley were currently on"22" and "22.0.1" and I my project was working with newer ones ("24" and "24.0.1").
SOLUTION:
Open your build.gradle (Module:volley) file and change the version of "compileSdk" and "buildTools", for example I changed this:
android {
compileSdkVersion 22
buildToolsVersion = '22.0.1'
}
for this:
android {
compileSdkVersion 24
buildToolsVersion = '24.0.1'
}
You should no longer have this error, I hope it helps:)
Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).
Remove the directory (basically a copy of https://stackoverflow.com/a/38201611/1695680), Ansible does this operation with rmtree
under the hood.
- name: remove files and directories
file:
state: "{{ item }}"
path: "/srv/deleteme/"
owner: 1000 # set your owner, group, and mode accordingly
group: 1000
mode: '0777'
with_items:
- absent
- directory
If you don't have the luxury of removing the whole directory and recreating it, you can scan it for files, (and directories), and delete them one by one. Which will take a while. You probably want to make sure you have [ssh_connection]\npipelining = True
in your ansible.cfg on.
- block:
- name: 'collect files'
find:
paths: "/srv/deleteme/"
hidden: True
recurse: True
# file_type: any # Added in ansible 2.3
register: collected_files
- name: 'collect directories'
find:
paths: "/srv/deleteme/"
hidden: True
recurse: True
file_type: directory
register: collected_directories
- name: remove collected files and directories
file:
path: "{{ item.path }}"
state: absent
with_items: >
{{
collected_files.files
+ collected_directories.files
}}
I'm sure you are using a old version. You must use the last version available at master branch:
edit my.cnf file:
vi /etc/my.cnf
:
make sure that:
bind-address=YOUR-SERVER-IP
and if you have the line:
skip-networking
make sure to comment it:
#skip-networking
don't forget to restart:
/etc/init.d/mysqld restart
context.getImageData(x, y, 1, 1).data;
returns an rgba array. e.g. [50, 50, 50, 255]
Here's a version of @lwburk's rgbToHex function that takes the rgba array as an argument.
function rgbToHex(rgb){
return '#' + ((rgb[0] << 16) | (rgb[1] << 8) | rgb[2]).toString(16);
};
The function returns a FileStream
object. So you could use it's return value to open your StreamWriter
or close it using the proper method of the object:
File.Create(myPath).Close();
You should set it with C:\Program Files\Java\jdk1.8.0_12
.
\bin
is not required.
If your arrays are character arrays(which seems to be the case), You need a strcat().
Your destination array should have enough space to accommodate the appended data though.
In C++, You are much better off using std::string and then you can use std::string::append()
You can do it with the options
echo $form->field($model, 'hidden1',
['options' => ['value'=> 'your value'] ])->hiddenInput()->label(false);
It is a library from SSL. You need to install openssl.
You might also meet missing readline()
function in python. You have to install pyreadline Lib.
You can use Process.Start:
Dim url As String = “http://www.example.com“
Process.Start(url)
This should open whichever browser is set as default on the system.
Try this, it should work for what you need:
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff f
return true;
}
return false;
}
});
For checking out only a given tag for deployment, I use e.g.:
git clone -b 'v2.0' --single-branch --depth 1 https://github.com/git/git.git
This seems to be the fastest way to check out code from a remote repository if one has only interest in the most recent code instead of in a complete repository. In this way, it resembles the 'svn co' command.
Note: Per the Git manual, passing the --depth
flag implies --single-branch
by default.
--depth
Create a shallow clone with a history truncated to the specified number of commits. Implies --single-branch unless --no-single-branch is given to fetch the histories near the tips of all branches. If you want to clone submodules shallowly, also pass --shallow-submodules.
If you want to make it easier for yourself by only having tabs, replace the spaces with tabs:
tr " " "\t" < <file> | sort <options>
Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.
Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.
Namespaces are packages essentially. They can be used like this:
namespace MyNamespace
{
class MyClass
{
};
}
Then in code:
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
Or, if you want to always use a specific namespace, you can do this:
using namespace MyNamespace;
MyClass* pClass = new MyClass();
Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
And as you asked below, you can use as many namespaces as you like.
Try something like this. The first row builds your URL and the rest check if it contains the word "car".
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'car') !== false) {
echo 'Car exists.';
} else {
echo 'No cars.';
}
And if you mean select the ID of the last record inserted, its
SELECT @@IDENTITY FROM table
If you want multiple lines consider this:
<textarea rows="2"></textarea>
Specify rows as needed.
You can also generate in a range [min, max] with something like
float float_rand( float min, float max )
{
float scale = rand() / (float) RAND_MAX; /* [0, 1.0] */
return min + scale * ( max - min ); /* [min, max] */
}
As of TypeScript 2.7.2, you are required to initialise a property in the constructor if it was not assigned to at the point of declaration.
If you are coming from Vue, you can try the following:
Add "strictPropertyInitialization": true
to your tsconfig.json
If you are unhappy with disabling it you could also try this makes: any[] | undefined
. Doing this requires that you access the properties with null check (?.
) operator i.e. this.makes?.length
makes!: any[];
, this tells TS that the value will be assigned at runtime.This might help for people ending up here searching how to sort list alphabetically.
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class SortService {
public static void main(String[] args) {
List<TestData> test = new ArrayList<>();
test.add(prepareTestData("Asmin",1));
test.add(prepareTestData("saurav",4));
test.add(prepareTestData("asmin",2));
test.add(prepareTestData("Saurav",3));
test.forEach(data-> System.out.println(data));
/** Output
* TestData(name=Asmin, id=1)
* TestData(name=saurav, id=4)
* TestData(name=asmin, id=2)
* TestData(name=Saurav, id=3)
*/
test.sort(Comparator.comparing(TestData::getName,String::compareToIgnoreCase));
test.forEach(data-> System.out.println(data));
/**Sorted Output
* TestData(name=Asmin, id=1)
* TestData(name=asmin, id=2)
* TestData(name=saurav, id=4)
* TestData(name=Saurav, id=3)
*/
}
private static TestData prepareTestData(String name, int id){
TestData testData= new TestData();
testData.setId(id);
testData.setName(name);
return testData;
}
}
@Getter
@Setter
@ToString
class TestData{
private String name;
private int id;
}
I was trying to work with that solutions but it doesn't work. But later I was realize that the function it wasn't declared so I watch in to the dropzone.com page and take the example to call events. So finally work on my site. For those like me who don't understand JavaScript very well, I leave you the example.
<script type="text/javascript" src="/js/dropzone.js"></script>
<script type="text/javascript">
// This example uses jQuery so it creates the Dropzone, only when the DOM has
// loaded.
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
// or disable for specific dropzone:
// Dropzone.options.myDropzone = false;
$(function() {
// Now that the DOM is fully loaded, create the dropzone, and setup the
// event listeners
var myDropzone = new Dropzone(".dropzone");
myDropzone.on("queuecomplete", function(file, res) {
if (myDropzone.files[0].status != Dropzone.SUCCESS ) {
alert('yea baby');
} else {
alert('cry baby');
}
});
});
</script>
I used the code below to create a Button and it worked for me.
<input type="button" value="PDF" onclick="location.href='@Url.Action("Export","tblOrder")'"/>