The Structure101 slice perspective will give a list (and dependency graph) of any "orphans" or "orphan groups" of classes or packages that have no dependencies to or from the "main" cluster.
You could use a Dictionary<TKey, List<TValue>>
.
That would allow each key to reference a list of values.
Your first problem was you weren't using your compare symbols correctly.
< less than
> greater than
<= less than or equal to
>= greater than or equal to
To answer your other questions; get the condition to work on every cell in the column and what about blanks?
What about blanks?
Add an extra IF
condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())
Condition on every cell in column
Use Calendar.getInstance().get(Calendar.MONTH)+1
to get current month.
use 127.0.0.1
instead of localhost
In the repository, click Admin
, then go to the Collaborators
tab.
- (UIImage*)screenshotForView:(UIView *)view
{
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// hack, helps w/ our colors when blurring
NSData *imageData = UIImageJPEGRepresentation(image, 1); // convert to jpeg
image = [UIImage imageWithData:imageData];
return image;
}
My experience with windows client and linux/mysql server:
When sqldev is used in a windows client and mysql is installed in a linux server meaning, sqldev network access to mysql.
Assuming mysql is already up and running and the databases to be accessed are up and functional:
• Ensure the version of sqldev (32 or 64). If 64 and to avoid dealing with path access copy a valid 64 version of msvcr100.dll into directory ~\sqldeveloper\jdev\bin.
a. Open the file msvcr100.dll in notepad and search for first occurrence of “PE “
i. “PE d” it is 64.
ii. “PE L” it is 32.
b. Note: if sqldev is 64 and msvcr100.dll is 32, the application gets stuck at startup.
• For sqldev to work with mysql there is need of the JDBC jar driver. Download it from mysql site.
a. Driver name = mysql-connector-java-x.x.xx
b. Copy it into someplace related to your sqldeveloper directory.
c. Set it up in menu sqldev Tools/Preferences/Database/Third Party JDBC Driver (add entry)
• In Linux/mysql server change file /etc/mysql/mysql.conf.d/mysqld.cnf look for
bind-address = 127.0.0.1 (this linux localhost)
and change to
bind-address = xxx.xxx.xxx.xxx (this linux server real IP or machine name if DNS is up)
• Enter to linux mysql and grant needed access for example
# mysql –u root -p
GRANT ALL ON . to root@'yourWindowsClientComputerName' IDENTIFIED BY 'mysqlPasswd';
flush privileges;
restart mysql - sudo /etc/init.d/mysql restart
• Start sqldev and create a new connection
a. user = root
b. pass = (your mysql pass)
c. Choose MySql tab
i. Hostname = the linux IP hostname
ii. Port = 3306 (default for mysql)
iii. Choose Database = (from pull down the mysql database you want to use)
iv. save and connect
That is all I had to do in my case.
Thank you,
Ale
This is my first post which support only a single page http://www.techumber.com/html-to-pdf-conversion-using-javascript/
Now, the second one will support the multiple pages. http://www.techumber.com/how-to-convert-html-to-pdf-using-javascript-multipage/
If you give the following command you'll get the list of activities including commits, merges.
git reflog
Your last commit should probably be at 'HEAD@{0}'
. You can check the same with your commit message.
To go to that point, use the command
git reset --hard 'HEAD@{0}'
Your merge will be reverted. If in case you have new files left, discard those changes from the merge.
"BypassTraverseChecking" means that you can directly access any deep-level subdirectory even if you don't have all the intermediary access privileges to directories in between, i.e. all directories above it towards root level .
A somewhat late answer, but with pandas, it is possible to get directly a column of an excel file:
import pandas
df = pandas.read_excel('sample.xls')
#print the column names
print df.columns
#get the values for a given column
values = df['Arm_id'].values
#get a data frame with selected columns
FORMAT = ['Arm_id', 'DSPName', 'Pincode']
df_selected = df[FORMAT]
Make sure you have installed xlrd and pandas:
pip install pandas xlrd
I had the same issue. I got resolved setting up correctly the environment variables in windows, for instance:
JAVA_HOME -> C:\Program Files\Java\jdk1.6.0_45
path -> C:\Program Files\Java\jdk1.6.0_45\bin
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
addNewUser();
return true;
}
}
Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.
No hardcoded value other than the scroll time, best suited for small scroll spaces
.marquee {_x000D_
width: 100%;_x000D_
margin: 0 auto;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
box-sizing: border-box;_x000D_
display: inline-flex; _x000D_
}_x000D_
_x000D_
.marquee span {_x000D_
display: flex; _x000D_
flex-basis: 100%;_x000D_
animation: marquee-reset;_x000D_
animation-play-state: paused; _x000D_
}_x000D_
_x000D_
.marquee:hover> span {_x000D_
animation: marquee 2s linear infinite;_x000D_
animation-play-state: running;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
0% {_x000D_
transform: translate(0%, 0);_x000D_
} _x000D_
50% {_x000D_
transform: translate(-100%, 0);_x000D_
}_x000D_
50.001% {_x000D_
transform: translate(100%, 0);_x000D_
}_x000D_
100% {_x000D_
transform: translate(0%, 0);_x000D_
}_x000D_
}_x000D_
@keyframes marquee-reset {_x000D_
0% {_x000D_
transform: translate(0%, 0);_x000D_
} _x000D_
}
_x000D_
<span class="marquee">_x000D_
<span>This is the marquee text</span>_x000D_
</span>
_x000D_
Or you might have something like this (redeclaring a variable):
var data = [];
var data =
None of the answers here worked for me unfortunately.
I ended up using Custom Model Binding and used a third-party Sanitizer.
See my self-answered question here.
one obvious solution is to run 2 separate queries, first select all items that have count=1 and run your insert, then select the items with count>1 and run the second insert.
as a second step if the two inserts are similar you can probably combine them into one query.
another possibility is to use a cursor to loop thru your recordset and do whatever logic you need for each line.
Add intl
package to your pubspec.yaml
file.
import 'package:intl/intl.dart';
DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");
Converting DateTime object to String
String string = dateFormat.format(DateTime.now());
Converting String to DateTime object
DateTime dateTime = dateFormat.parse("2019-07-19 8:40:23");
Try... for YUI
Dom.get("gadget_url").set("value","");
with normal Javascript
document.getElementById('gadget_url').value = '';
with JQuery
$("#gadget_url").val("");
There's a few things with your code as it stands:
The first thing we are going to do is to declare your variable as let
, as we are not going to modify it later.
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")! // We can force unwrap because we are 100% certain the constructor will not return nil in this case.
Then we need to download the contents of that URL. We can do this with the URLSession
object. When the completion handler is called, we will have a UIImage
downloaded from the web.
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
Finally you need to call resume
on the download task, otherwise your task will never start:
downloadPicTask.resume()
.
All this code may look a bit intimidating at first, but the URLSession
APIs are block based so they can work asynchronously - If you block your UI thread for a few seconds, the OS will kill your app.
Your full code should look like this:
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
Over a serial console all the vi and sed solutions didn't work for me. I had to:
cat inputfilename | tr -d '\r' > outputfilename
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/} Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
It is possible to have multiple or nested views. But not by ng-view.
The primary routing module in angular does not support multiple views. But you can use ui-router. This is a third party module which you can get via Github, angular-ui/ui-router, https://github.com/angular-ui/ui-router . Also a new version of ngRouter (ngNewRouter) currently, is being developed. It is not stable at the moment. So I provide you a simple start up example with ui-router. Using it you can name views and specify which templates and controllers should be used for rendering them. Using $stateProvider you should specify how view placeholders should be rendered for specific state.
<body ng-app="main">
<script type="text/javascript">
angular.module('main', ['ui.router'])
.config(['$locationProvider', '$stateProvider', function ($locationProvider, $stateProvider) {
$stateProvider
.state('home', {
url: '/',
views: {
'header': {
templateUrl: '/app/header.html'
},
'content': {
templateUrl: '/app/content.html'
}
}
});
}]);
</script>
<a ui-sref="home">home</a>
<div ui-view="header">header</div>
<div ui-view="content">content</div>
<div ui-view="bottom">footer</div>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.js">
</body>
You need referencing angularjs, and angular-ui.router for this sample.
$ bower install angular-ui-router
yum -y remove php*
to remove all php packages then you can install the 5.6 ones.
You could do:
sh scriptname.sh
This is my working solution:
vbFILEOPEN = "your_utf8_file.csv"
Workbooks.OpenText Filename:=vbFILEOPEN, DataType:=xlDelimited, Semicolon:=True, Local:=True, Origin:=65001
The key is Origin:=65001
To run function onLoad
jQuery(window).on("load", function(){
..code..
});
To run code onDOMContentLoaded (also called onready)
jQuery(document).ready(function(){
..code..
});
or the recommended shorthand for onready
jQuery(function($){
..code.. ($ is the jQuery object)
});
onready fires when the document has loaded
onload fires when the document and all the associated content, like the images on the page have loaded.
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
If you are familiar with Maven there also rpm-maven-plugin
which simplifies making RPMs: you have to write only pom.xml
which will be then used to build RPM. RPM build environment is created implicitly by the plugin.
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return = 0 And Level = 0 Then GoTo NextIteration
'Go to the next iteration
Else
End If
' This is how you make a line label in VBA - Do not use keyword or
' integer and end it in colon
NextIteration:
Next
-(NSString *)returnPreferredLanguage { //as written text
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSArray *preferredLanguages = [defaults objectForKey:@"AppleLanguages"];
NSString *preferredLanguageCode = [preferredLanguages objectAtIndex:0]; //preferred device language code
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"]; //language name will be in English (or whatever)
NSString *languageName = [enLocale displayNameForKey:NSLocaleIdentifier value:preferredLanguageCode]; //name of language, eg. "French"
return languageName;
}
You can stablish specific toolbar for div
div::-webkit-scrollbar {
width: 12px;
}
div::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}
see demo in jsfiddle.net
Global import is safe to go with.
import 'rxjs/Rx';
Cygwin's setup accepts command-line arguments to install packages from the command-line.
e.g. setup-x86.exe -q -P packagename1,packagename2
to install packages without any GUI interaction ('unattended setup mode').
(Note that you need to use setup-x86.exe
or setup-x86_64.exe
as appropriate.)
See http://cygwin.com/packages/ for the package list.
If you were asking how to remove the empty strings, you can do it like this (where l
is an ArrayList<String>
) - this removes all null
references and strings of length 0:
Iterator<String> i = l.iterator();
while (i.hasNext())
{
String s = i.next();
if (s == null || s.isEmpty())
{
i.remove();
}
}
Don't confuse an ArrayList
with arrays, an ArrayList
is a dynamic data-structure that resizes according to it's contents. If you use the code above, you don't have to do anything to get the result as you've described it -if your ArrayList
was ["","Hi","","How","are","you"], after removing as above, it's going to be exactly what you need - ["Hi","How","are","you"]
.
However, if you must have a 'sanitized' copy of the original list (while leaving the original as it is) and by 'store it back' you meant 'make a copy', then krmby's code in the other answer will serve you just fine.
What does $rootScope.$broadcast do?
It broadcasts the message to respective listeners all over the angular app, a very powerful means to transfer messages to scopes at different hierarchical level(be it parent , child or siblings)
Similarly, we have $rootScope.$emit, the only difference is the former is also caught by $scope.$on while the latter is caught by only $rootScope.$on .
refer for examples :- http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
I had the same problem and solved it adding "es5" library to tsconfig.json like this:
{
"compilerOptions": {
"target": "es5", //defines what sort of code ts generates, es5 because it's what most browsers currently UNDERSTANDS.
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true, //for angular to be able to use metadata we specify in our components.
"experimentalDecorators": true, //angular needs decorators like @Component, @Injectable, etc.
"removeComments": false,
"noImplicitAny": false,
"lib": [
"es2016",
"dom",
"es5"
]
}
}
The previous answers all state that you can do the following:
var d = eval(net_datetime.slice(1, -1));
However, this doesn't work in either Chrome or FF because what's getting evaluated literally is:
// returns the current timestamp instead of the specified epoch timestamp
var d = Date([epoch timestamp]);
The correct way to do this is:
var d = eval("new " + net_datetime.slice(1, -1)); // which parses to
var d = new Date([epoch timestamp]);
This worked for me:
& 'D:\Server\PSTools\PsExec.exe' @('\\1.1.1.1', '-accepteula', '-d', '-i', $id, '-h', '-u', 'domain\user', '-p', 'password', '-w', 'C:\path\to\the\app', 'java', '-jar', 'app.jar')
Just put paths or connection strings in one array item and split the other things in one array item each.
There are a lot of other options here: https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx
Microsoft should make this way simpler and compatible with command prompt syntax.
Copies a directory named html & all its contents to a destination directory in silent mode. If the destination directory is not present it will still create it.
@echo off
TITLE Copy Folder with Contents
set SOURCE=C:\labs
set DESTINATION=C:\Users\MyUser\Desktop\html
xcopy %SOURCE%\html\* %DESTINATION%\* /s /e /i /Y >NUL
/S Copies directories and subdirectories except empty ones.
/E Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.
/I If destination does not exist and copying more than one file, assumes that destination must be a directory.
Example 2 on w3schools shows what you are trying to achieve.
<?php header("Content-type:application/pdf"); // It will be called downloaded.pdf header("Content-Disposition:attachment;filename='downloaded.pdf'"); // The PDF source is in original.pdf readfile("original.pdf"); ?>
Also remember that,
It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)
This was the order I got everything working. The second point is the most important one. Scipy needs Numpy+MKL
, not just vanilla Numpy
.
pip install "file path"
(download Numpy+MKL wheel from here http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)pip install scipy
I wanted "key" & "value" pair of a first dictionary item. I used the following code.
key, val = next(iter(my_dict.items()))
One way to do this that correctly uses group by
:
select l.*
from table l
inner join (
select
m_id, max(timestamp) as latest
from table
group by m_id
) r
on l.timestamp = r.latest and l.m_id = r.m_id
order by timestamp desc
How this works:
m_id
in the subquerytable
that match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious)From your ant buildfile, I assume that what you want is to create a single JAR archive that will contain not only your application classes, but also the contents of other JARs required by your application.
However your build-jar
file is just putting required JARs inside your own JAR; this will not work as explained here (see note).
Try to modify this:
<jar destfile="${jar.file}"
basedir="${build.dir}"
manifest="${manifest.file}">
<fileset dir="${classes.dir}" includes="**/*.class" />
<fileset dir="${lib.dir}" includes="**/*.jar" />
</jar>
to this:
<jar destfile="${jar.file}"
basedir="${build.dir}"
manifest="${manifest.file}">
<fileset dir="${classes.dir}" includes="**/*.class" />
<zipgroupfileset dir="${lib.dir}" includes="**/*.jar" />
</jar>
More flexible and powerful solutions are the JarJar or One-Jar projects. Have a look into those if the above does not satisfy your requirements.
Try this:
var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();
Possible duplicate with: How do I use jQuery to ignore case when selecting
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
From python >= 3.5 onward, you can use **
, glob.iglob(path/**, recursive=True)
and it seems the most pythonic solution, i.e.:
import glob, os
for filename in glob.iglob('/pardadox-music/**', recursive=True):
if os.path.isfile(filename): # filter dirs
print(filename)
Output:
/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...
Notes:
1 - glob.iglob
glob.iglob(pathname, recursive=False)
Return an iterator which yields the same values as
glob()
without actually storing them all simultaneously.
2 - If recursive is True
, the pattern '**'
will match any files and
zero or more directories
and subdirectories
.
3 - If the directory contains files starting with .
they won’t be matched by default. For example, consider a directory containing card.gif
and .card.gif
:
>>> import glob
>>> glob.glob('*.gif') ['card.gif']
>>> glob.glob('.c*')['.card.gif']
4 - You can also use rglob(pattern)
,
which is the same as calling glob()
with **/
added in front of the given relative pattern.
It turns out that if you don't specify the Model to the View method within your controller, it doesn't create a object for you with the default values.
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Loads default values
Instructor i = new Instructor();
return View("Create", i);
}
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Does not load default values from instructor
return View("Create");
}
Wouldn't establishing a connection to the database do this for you? If the database isn't up you won't be able to establish a connection.
I used this statement and it worked for me:
setListAdapter(null)
This one calls a default constructor that does nothing in a class extends BaseAdapter.
You may also need the following directive to be set before the first "sub_filter" for backend-servers with data compression:
proxy_set_header Accept-Encoding "";
Otherwise it may not work. For your example it will look like:
location /admin/ {
proxy_pass http://localhost:8080/;
proxy_set_header Accept-Encoding "";
sub_filter "http://your_server/" "http://your_server/admin/";
sub_filter_once off;
}
I recently needed to create a date string with UTC and DST, and based on Sheldon's answer I put this together:
Date.prototype.getTimezone = function(showDST) {_x000D_
var jan = new Date(this.getFullYear(), 0, 1);_x000D_
var jul = new Date(this.getFullYear(), 6, 1);_x000D_
_x000D_
var utcOffset = new Date().getTimezoneOffset() / 60 * -1;_x000D_
var dstOffset = (jan.getTimezoneOffset() - jul.getTimezoneOffset()) / 60;_x000D_
_x000D_
var utc = "UTC" + utcOffset.getSign() + (utcOffset * 100).preFixed(1000);_x000D_
var dst = "DST" + dstOffset.getSign() + (dstOffset * 100).preFixed(1000);_x000D_
_x000D_
if (showDST) {_x000D_
return utc + " (" + dst + ")";_x000D_
}_x000D_
_x000D_
return utc;_x000D_
}_x000D_
Number.prototype.preFixed = function (preCeiling) {_x000D_
var num = parseInt(this, 10);_x000D_
if (preCeiling && num < preCeiling) {_x000D_
num = Math.abs(num);_x000D_
var numLength = num.toString().length;_x000D_
var preCeilingLength = preCeiling.toString().length;_x000D_
var preOffset = preCeilingLength - numLength;_x000D_
for (var i = 0; i < preOffset; i++) {_x000D_
num = "0" + num;_x000D_
}_x000D_
}_x000D_
return num;_x000D_
}_x000D_
Number.prototype.getSign = function () {_x000D_
var num = parseInt(this, 10);_x000D_
var sign = "+";_x000D_
if (num < 0) {_x000D_
sign = "-";_x000D_
}_x000D_
return sign;_x000D_
}_x000D_
_x000D_
document.body.innerHTML += new Date().getTimezone() + "<br>";_x000D_
document.body.innerHTML += new Date().getTimezone(true);
_x000D_
<p>Output for Turkey (UTC+0200) and currently in DST: UTC+0300 (DST+0100)</p>_x000D_
<hr>
_x000D_
This goes also for statements like this (auto-formatted by PyCharm):
return combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
Which will give the same style-warning. In order to get rid of it I had to rewrite it to:
return \
combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
You can use the str.format
method. Examples:
>>> print('{0:.16f}'.format(1.6))
1.6000000000000001
>>> print('{0:.15f}'.format(1.6))
1.600000000000000
Note the 1
at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.
You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):
>>> print '%.16f' % 1.6
1.6000000000000001
>>> print '%.15f' % 1.6
1.600000000000000
In my case, this error was caused by the lack of a mere space. I had this if block in my makefile:
if($(METHOD),opt)
CFLAGS=
endif
which should have been:
if ($(METHOD),opt)
CFLAGS=
endif
with a space after if.
.navbar-nav > li > a {padding-top:7px !important; padding-bottom:7px !important;}
.navbar {min-height:32px !important;}
.navbar-brand{padding-top:7px !important; max-height: 24px; }
.navbar .navbar-toggle { margin-top: 0px; margin-bottom: 0px; padding: 8px 9px; }
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
What about injecting the class attribute after the class definition?
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
def method(self):
ret = Klass.stat_func()
return ret
Klass._ANS = Klass.stat_func() # inject the class attribute with static method value
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
Here's what I'm using to deal with a similar problem I encountered while trying to access MailChimp's API. This does the same thing, just formatted nicer.
import urllib2
import base64
chimpConfig = {
"headers" : {
"Content-Type": "application/json",
"Authorization": "Basic " + base64.encodestring("hayden:MYSECRETAPIKEY").replace('\n', '')
},
"url": 'https://us12.api.mailchimp.com/3.0/'}
#perform authentication
datas = None
request = urllib2.Request(chimpConfig["url"], datas, chimpConfig["headers"])
result = urllib2.urlopen(request)
And here is a simple Send-MailMessage
example with username/password for anyone looking for just that
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
STATEMENT:
A Statement is a action or a command that does something. Ex: If-Else,Loops..etc
val a: Int = 5
If(a>5) print("Hey!") else print("Hi!")
EXPRESSION:
A Expression is a combination of values, operators and literals which yields something.
val a: Int = 5 + 5 #yields 10
Iv'e noticed this recently with all new macs here at my office. Atom will be installed via an image for the developers but we found the Atom is never in the Application folder.
When doing a ls on the /usr/local/bin folder the path for atom will show something like "/private/var/folders/cs" . To resolve this, we just located atom.app and copied it into the application folder, then ran the system link commands provided by nwinkler which resoled the issue. Developers can now open atom from the command line with "atom" or open the current projects from their working director with "atom ."
The problem with this question is that "opening" the app isn't well-defined. An app is either cold-launched from a not-running state, or it's reactivated from an inactive state (e.g. from switching back to it from another app). Here's my solution to distinguish all of these possible states:
typedef NS_ENUM(NSInteger, MXAppState) {
MXAppStateActive = 0,
MXAppStateReactivated = 1,
MXAppStateLaunched = 2
};
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// ... your custom launch stuff
[[MXDefaults instance] setDateOfLastLaunch:[NSDate date]];
// ... more custom launch stuff
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Through a lot of trial and error (by showing alerts), I can confirm that on iOS 10
// this method is only called when the app has been launched from a push notification
// or when the app is already in the Active state. When you receive a push
// and then launch the app from the icon or apps view, this method is _not_ called.
// So with 99% confidence, it means this method is called in one of the 3 mutually exclusive cases
// 1) we are active in the foreground, no action was taken by the user
// 2) we were 'launched' from an inactive state (so we may already be in the main section) by a tap
// on a push notification
// 3) we were truly launched from a not running state by a tap on a push notification
// Beware that cases (2) and (3) may both show UIApplicationStateInactive and cant be easily distinguished.
// We check the last launch date to distinguish (2) and (3).
MXAppState appState = [self mxAppStateFromApplicationState:[application applicationState]];
//... your app's logic
}
- (MXAppState)mxAppStateFromApplicationState:(UIApplicationState)state {
if (state == UIApplicationStateActive) {
return MXAppStateActive;
} else {
NSDate* lastLaunchDate = [[MXDefaults instance] dateOfLastLaunch];
if (lastLaunchDate && [[NSDate date] timeIntervalSinceDate:lastLaunchDate] < 0.5f) {
return MXAppStateLaunched;
} else {
return MXAppStateReactivated;
}
}
return MXAppStateActive;
}
And MXDefaults
is just a little wrapper for NSUserDefaults
.
You can use QTextCodec to convert the bytearray to a string:
QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);
(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)
From your example we can see that the string "test"
is encoded as "t\0 e\0 s\0 t\0 \0 \0"
in your encoding, i.e. every ascii character is followed by a \0
-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).
function isCapital(ch){
return ch.charCodeAt() >= 65 && ch.charCodeAt() <= 90;
}
Did you check the gsl
package in your system. Try with this:
ldconfig-p | grep gsl
If gsl
is installed, it will display the configuration path. If it is not in the standard path /usr/lib/
then you need to do the following in bash:
export PATH=$PATH:/your/path/to/gsl-config
If gsl
is not installed, simply do
sudo apt-get install libgsl0ldbl
sudo apt-get install gsl-bin libgsl0-dev
I had a problem with the mvabund
package and this fixed the error
Cheers!
You can also do ORDER BY TITLE COLLATE NOCASE
.
Edit: If you need to specify ASC
or DESC
, add this after NOCASE
like
ORDER BY TITLE COLLATE NOCASE ASC
or
ORDER BY TITLE COLLATE NOCASE DESC
After the long time research i have found the solution for above:
Firstly you change the wp-config.php> Database DB_CHARSET default to "utf8"
Click the "Export" tab for the database
Click the "Custom" radio button
Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.
Scroll to the bottom and click go
Then you are on.
If you want to open inside the app itself instead of leaving the app you can import SafariServices and work it out.
import UIKit
import SafariServices
let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
Right click on project -> maven -> download sources
Since there is not anything else that was more intricate, I wanted to share this as it helped me out.
This is what I originally used:
import requests
import re
url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
print("{}".format(r.content))
Undesired Result:
b'<!DOCTYPE html>\r\n\r\n\r\n <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive">\r\n\r\n <head>\r\n\r\n <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>\r\n <link
This is what I changed it to:
import requests
import re
url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
regex = r'\s+'
print("CNT: {}".format(re.sub(regex, " ", r.content.decode('utf-8'))))
Desired Result:
<!DOCTYPE html> <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive"> <head> <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>
The precise regex that @MattH had mentioned, was what worked for me in fitting it into my code. Thanks!
Note: This is python3
If you can't find your problem and you're code should work, it may be that your request is just reaching the maximum of time heroku allows you to make a request. Heroku cancels requests if it takes more than 30 seconds.
Reference: https://devcenter.heroku.com/articles/request-timeout
you can declare a Numpy array dynamically for 1 dimension as shown below:
import numpy as np
n = 2
new_table = np.empty(shape=[n,1])
new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)
The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)
output is shown below:
[[2.] [3.]]
Try this
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");
You can do this in plain JavaScript, use Array.prototype.join
:
arrayName.join(delimiter);
Just add this to your ~/.bash_profile to switch between default keys for github.com
# Git SSH keys swap
alias work_git="ssh-add -D && ssh-add -K ~/.ssh/id_rsa_work"
alias personal_git="ssh-add -D && ssh-add -K ~/.ssh/id_rsa"
This is a new tool: oxygene which you can use to build apps for iOS/Mac, Windows RT/8 or Android. It uses a specific language derived from Object Pascal and Visual Studio (and uses .net or java.). It seem to be really powerful, but is not free.
If all your files are named similarly you could simply do:
cat *.log >> output.log
Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).
Jquery:
$(document).on('click','#test-element',function(){
alert("You clicked the element with and ID of 'test-element'");
});
As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-element
but not for any that follow.
If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual document
instead of test-element
. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different document
s and therefore you are clicking the document.
If neither of these are the answer, posting HTML will go a long way toward figuring it out.
If you are not wanting to use async
you can add .Result
to force the code to execute synchronously:
private string GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
var contents = response.Content.ReadAsStringAsync().Result;
return contents;
}
Bootstrap by default can scale up to 12 columns? This means if we want to create a 12-column layout of equal width, we would write inside div class="col-md-1" twelve times.
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2">1</div>
<div class="col-md-2">2</div>
<div class="col-md-2">3</div>
<div class="col-md-2">4</div>
<div class="col-md-2">5</div>
<div class="col-md-1"></div>
</div>
Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this
<category name="org.springframework.beans">
<priority value="debug" />
</category>
or
<category name="org.springframework">
<priority value="debug" />
</category>
I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest
{
@Autowired
private SpringDAO dao;
@Autowired
private ApplicationContext appContext;
@Test
public void checkConfig()
{
AnySpringBean bean = appContext.getBean(AnySpringBean.class);
Assert.assertNotNull(bean);
}
}
I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
UPDATE log4j config file
I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
</layout>
</appender>
<appender name="springAppender" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="C:/tomcatLogs/webApp/spring-details.log" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" />
</layout>
</appender>
<category name="org.springframework">
<priority value="debug" />
</category>
<category name="org.springframework.beans">
<priority value="debug" />
</category>
<category name="org.springframework.security">
<priority value="debug" />
</category>
<category
name="org.springframework.beans.CachedIntrospectionResults">
<priority value="debug" />
</category>
<category name="org.springframework.jdbc.core">
<priority value="debug" />
</category>
<category name="org.springframework.transaction.support.TransactionSynchronizationManager">
<priority value="debug" />
</category>
<root>
<priority value="debug" />
<appender-ref ref="springAppender" />
<!-- <appender-ref ref="STDOUT"/> -->
</root>
</log4j:configuration>
Use max-width on modal-dialog for angular 5
.mod-class .modal-dialog {
max-width: 1000px;
}
and use windowClass as others recommended, TS eg:
this.modalService.open(content, { windowClass: 'mod-class' }).result.then(
(result) => {
// this.closeResult = `Closed with: ${result}`;
}, (reason) => {
// this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
Also, I had to put the css code in global styles > styles.css.
Your second way is correct.
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
this outputs
{'opts': <class 'dict'>}
It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.
I strongly advise against using mutable keyword arguments. More information here.
From the @param wiki page:
If a parameter is expected to have a particular property, you can document that immediately after the @param tag for that parameter, like so:
/**
* @param userInfo Information about the user.
* @param userInfo.name The name of the user.
* @param userInfo.email The email of the user.
*/
function logIn(userInfo) {
doLogIn(userInfo.name, userInfo.email);
}
There used to be a @config tag which immediately followed the corresponding @param, but it appears to have been deprecated (example here).
<table style="width:100%;">
<tbody ><tr><td align="center">
<img src="axe.JPG" />
</td>
</tr>
</tbody>
</table>
or
td
{
text-align:center;
}
in the CSS file
For many years I used the command:
ps aux | grep postgres
On one hand it is useful (for any process) and gives useful info (but from process POV). But on the other hand it is for checking if the server you know, you already installed is running.
At some point I found this tutorial, where the usage of the locate command is shown. It looks like this command is much more to the point for this case.
(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))
Try this one
getActivity().finish();
==========Advise==========
@martin clayton Answer is correct, But this is an advise only.
Please avoid the use of ambiguous variable in the stored procedure.
Example :
SELECT Id, dateCreated
INTO id, datecreated
FROM products
WHERE pName = iName
The above example will cause an error (null value error)
Example give below is correct. I hope this make sense.
Example :
SELECT Id, dateCreated
INTO val_id, val_datecreated
FROM products
WHERE pName = iName
You can also make them unambiguous by referencing the table, like:
[ Credit : maganap ]
SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p
WHERE pName = iName
Even if the generics problems are fixed in 1.3
the great thing about this method is it works on any class that has an isEmpty()
method! Not just Collections
!
For example it will work on String
as well!
/* Matches any class that has an <code>isEmpty()</code> method
* that returns a <code>boolean</code> */
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
@Factory
public static <T> Matcher<T> empty()
{
return new IsEmpty<T>();
}
@Override
protected boolean matchesSafely(@Nonnull final T item)
{
try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
catch (final NoSuchMethodException e) { return false; }
catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
}
@Override
public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}
For me it was a permission problem.
enter:
mysqld --verbose --help | grep -A 1 "Default options"
[Warning] World-writable config file '/etc/mysql/my.cnf' is ignored.
So try to execute the following, and then restart the server
chmod 644 '/etc/mysql/my.cnf'
It will give mysql access to read and write to the file.
Quick sort is typically faster than merge sort when the data is stored in memory. However, when the data set is huge and is stored on external devices such as a hard drive, merge sort is the clear winner in terms of speed. It minimizes the expensive reads of the external drive and also lends itself well to parallel computing.
I want to share with you one more solution if you have absolute part in the URL
SharePoint solution with ${_spPageContextInfo.webAbsoluteUrl}
HTML:
<button (click)="onNavigate()">Google</button>
TypeScript:
onNavigate()
{
let link = `${_spPageContextInfo.webAbsoluteUrl}/SiteAssets/Pages/help.aspx#/help`;
window.open(link, "_blank");
}
and url will be opened in new tab.
This might be impossible or at least very hard. The DLL's contents don't depend (a lot) on it being written in C++; it's all machine code. That code might have been optimized so a lot of information that was present in the original source code is simply gone.
That said, here is one article that goes through a lot of material about doing this.
Considering filter:expression is a Microsoft extension to CSS, so it will only work in Internet Explorer. If you want to grey it out, I would recommend that you set it's opacity to 50% using a bit of javascript.
http://lyxus.net/mv would be a good place to start, because it discusses an opacity script that works with Firefox, Safari, KHTML, Internet Explorer and CSS3 capable browsers.
You might also want to give it a grey border.
l[index] if index < len(l) else default
To support negative indices we can use:
l[index] if -len(l) <= index < len(l) else default
The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.
It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.
So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.
Otherwise, some users may not enjoy the smooth scrolling of your website / platform.
I can give a simpler example on how it can be applicable.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
// Add smooth scrolling to all links_x000D_
$("a").on('click', function(event) {_x000D_
// Make sure this.hash has a value before overriding default behavior_x000D_
if (this.hash !== "") {_x000D_
// Prevent default anchor click behavior_x000D_
event.preventDefault();_x000D_
// Store hash_x000D_
var hash = this.hash;_x000D_
// Using jQuery's animate() method to add smooth page scroll_x000D_
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area_x000D_
$('html, body').animate({_x000D_
scrollTop: $(hash).offset().top_x000D_
}, 800, function(){_x000D_
// Add hash (#) to URL when done scrolling (default click behavior)_x000D_
window.location.hash = hash;_x000D_
});_x000D_
} // End if_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
<style>_x000D_
#section1 {_x000D_
height: 600px;_x000D_
background-color: pink;_x000D_
}_x000D_
#section2 {_x000D_
height: 600px;_x000D_
background-color: yellow;_x000D_
}_x000D_
</style>
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<h1>Smooth Scroll</h1>_x000D_
<div class="main" id="section1">_x000D_
<h2>Section 1</h2>_x000D_
<p>Click on the link to see the "smooth" scrolling effect.</p>_x000D_
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>_x000D_
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>_x000D_
</div>_x000D_
<div class="main" id="section2">_x000D_
<h2>Section 2</h2>_x000D_
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Press Ctrl + KM and then type in (or click) the language you want.
Alternatively, to access it from the command palette, look for "Change Language Mode" as seen below:
Here is a more robust implementation that handles abnormal input and race conditions.
It deliberately uses character arrays instead of the String
type, to be more efficient and to avoid memory problems. It also avoids using the readStringUntil()
function, to not timeout before the input arrives.
The original question did not say how the variable length strings are defined, but I'll assume they are terminated by a single newline character - which turns this into a line reading problem.
int read_line(char* buffer, int bufsize)
{
for (int index = 0; index < bufsize; index++) {
// Wait until characters are available
while (Serial.available() == 0) {
}
char ch = Serial.read(); // read next character
Serial.print(ch); // echo it back: useful with the serial monitor (optional)
if (ch == '\n') {
buffer[index] = 0; // end of line reached: null terminate string
return index; // success: return length of string (zero if string is empty)
}
buffer[index] = ch; // Append character to buffer
}
// Reached end of buffer, but have not seen the end-of-line yet.
// Discard the rest of the line (safer than returning a partial line).
char ch;
do {
// Wait until characters are available
while (Serial.available() == 0) {
}
ch = Serial.read(); // read next character (and discard it)
Serial.print(ch); // echo it back
} while (ch != '\n');
buffer[0] = 0; // set buffer to empty string even though it should not be used
return -1; // error: return negative one to indicate the input was too long
}
Here is an example of it being used to read commands from the serial monitor:
const int LED_PIN = 13;
const int LINE_BUFFER_SIZE = 80; // max line length is one less than this
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
Serial.print("> ");
// Read command
char line[LINE_BUFFER_SIZE];
if (read_line(line, sizeof(line)) < 0) {
Serial.println("Error: line too long");
return; // skip command processing and try again on next iteration of loop
}
// Process command
if (strcmp(line, "off") == 0) {
digitalWrite(LED_PIN, LOW);
} else if (strcmp(line, "on") == 0) {
digitalWrite(LED_PIN, HIGH);
} else if (strcmp(line, "") == 0) {
// Empty line: no command
} else {
Serial.print("Error: unknown command: \"");
Serial.print(line);
Serial.println("\" (available commands: \"off\", \"on\")");
}
}
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
you should register for BOOT_COMPLETE as well as REBOOT
<receiver android:name=".Services.BootComplete">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.REBOOT"/>
</intent-filter>
</receiver>
var markerArray = [];
markerArray.push(L.marker([51.505, -0.09]));
...
var group = L.featureGroup(markerArray).addTo(map);
map.fitBounds(group.getBounds());
Well,
Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!
This will do the trick :-
new Date().valueOf()
The mysql
deamon should be running.
If not try this:
#/etc/init.d/mysql start
Or this:
#service mysqld start
And if you want to add mysql on boot:
# chkconfig --add mysqld
# chkconfig -- level 235 mysqld on
If yes, and it is still not working try this:
Uncomment the following lines in /etc/php/php.ini
extension=mysqli.so
extension=mysql.so
And please check your post above '/usr/lib64/php/modules/msql.so'. It should be mysql.so (if it's mistyped ignore it...)
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
Thanks @Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
public class JSONParsing {
public static void main(String[] args) throws Exception {
File f = new File("file.json");
if (f.exists()){
InputStream is = new FileInputStream("file.json");
String jsonTxt = IOUtils.toString(is, "UTF-8");
System.out.println(jsonTxt);
JSONObject json = new JSONObject(jsonTxt);
String a = json.getString("1000");
System.out.println(a);
}
}
}
I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.
If you can switch the ENGINE and use MyISAM instead of InnoDB, that should help:
ENGINE=MyISAM
There are two caveats with MyISAM (arguably more):
Delete then reset auto-increment:
delete from tablename;
then
ALTER TABLE tablename AUTO_INCREMENT = 1;
The important part is this:
Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];
due to:
nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
According to this log, Spring could not find your MemberPointSummaryDAOImpl
class.
So you did some work and pushed it, lets call them commits A and B. Your coworker did some work as well, commits C And D. You merged your coworkers work into yours (merge commit E), then continued working, committed that, too (commit F), and discovered that your coworker changed some things he shouldn't have.
So your commit history looks like this:
A -- B -- C -- D -- D' -- E -- F
You really want to get rid of C, D, and D'. Since you say you merged your coworkers work into yours, these commits already "out there", so removing the commits using e.g. git rebase is a no-no. Believe me, I've tried.
Now, I see two ways out:
if you haven't pushed E and F to your coworker or anyone else (typically your "origin" server) yet, you could still remove those from the history for the time being. This is your work that you want to save. This can be done with a
git reset D'
(replace D' with the actual commit hash that you can obtain from a git log
At this point, commits E and F are gone and the changes are uncommitted changes in your local workspace again. At this point I would move them to a branch or turn them into a patch and save it for later. Now, revert your coworker's work, either automatically with a git revert
or manually. When you've done that, replay your work on top of that. You may have merge conflicts, but at least they'll be in the code you wrote, instead of your coworker's code.
If you've already pushed the work you did after your coworker's commits, you can still try and get a "reverse patch" either manually or using git revert
, but since your work is "in the way", so to speak you'll probably get more merge conflicts and more confusing ones. Looks like that's what you ended up in...
If you are able to send the payload in JSON, this is a most convenient way to read the playload:
Example data class:
public class Person {
String firstName;
String lastName;
// Getters and setters ...
}
Example payload (request body):
{ "firstName" : "John", "lastName" : "Doe" }
Code to read payload in servlet (requires com.google.gson.*):
Person person = new Gson().fromJson(request.getReader(), Person.class);
That's all. Nice, easy and clean. Don't forget to set the content-type header to application/json.
With the stable release of Android Material Components in Nov 2018, Google has moved the material components from namespace
android.support.design
tocom.google.android.material
.
Material Component library is replacement for Android’s Design Support Library.
Add the dependency to your build.gradle
:
dependencies { implementation ‘com.google.android.material:material:1.0.0’ }
Then add the MaterialButton
to your layout:
<com.google.android.material.button.MaterialButton
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
app:strokeColor="@color/colorAccent"
app:strokeWidth="6dp"
app:layout_constraintStart_toStartOf="parent"
app:shapeAppearance="@style/MyShapeAppearance"
/>
You can check the full documentation here and API here.
To change the background color you have 2 options.
backgroundTint
attribute.Something like:
<style name="MyButtonStyle"
parent="Widget.MaterialComponents.Button">
<item name="backgroundTint">@color/button_selector</item>
//..
</style>
materialThemeOverlay
attribute.Something like:
<style name="MyButtonStyle"
parent="Widget.MaterialComponents.Button">
<item name=“materialThemeOverlay”>@style/GreenButtonThemeOverlay</item>
</style>
<style name="GreenButtonThemeOverlay">
<!-- For filled buttons, your theme's colorPrimary provides the default background color of the component -->
<item name="colorPrimary">@color/green</item>
</style>
The option#2 requires the 'com.google.android.material:material:1.1.0'.
OLD Support Library:
With the new Support Library 28.0.0, the Design Library now contains the MaterialButton
.
You can add this button to our layout file with:
<android.support.design.button.MaterialButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YOUR TEXT"
android:textSize="18sp"
app:icon="@drawable/ic_android_white_24dp" />
By default this class will use the accent colour of your theme for the buttons filled background colour along with white for the buttons text colour.
You can customize the button with these attributes:
app:rippleColor
: The colour to be used for the button ripple effectapp:backgroundTint
: Used to apply a tint to the background of the button. If you wish to change the background color of the button, use this attribute instead of background.
app:strokeColor
: The color to be used for the button stroke
app:strokeWidth
: The width to be used for the button strokeapp:cornerRadius
: Used to define the radius used for the corners of the buttonYou can add subject added to the mailto command using either one of the following ways. Add ?subject out mailto to the mailto tag.
<a href="mailto:[email protected]?subject=testing out mailto">First Example</a>
We can also add text into the body of the message by adding &body to the end of the tag as shown in the below example.
<a href="mailto:[email protected]?subject=testing out mailto&body=Just testing">Second Example</a>
In addition to body, a user may also type &cc or &bcc to fill out the CC and BCC fields.
<a href="mailto:[email protected]?subject=testing out mailto&body=Just testing&[email protected]&[email protected]">Third
Example</a>
You can also use the shorter format
From the man page:
%F full date; same as %Y-%m-%d
Example:
#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)
I had this same problem, because my line of code was:
txtTotalInvoice.setText(var1.divide(var2).doubleValue() + "");
I change to this, reading previous Answer, because I was not writing decimal precision:
txtTotalInvoice.setText(var1.divide(var2,4, RoundingMode.HALF_UP).doubleValue() + "");
4 is Decimal Precison
AND RoundingMode are Enum constants, you could choose any of this
UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP
In this Case HALF_UP, will have this result:
2.4 = 2
2.5 = 3
2.7 = 3
You can check the RoundingMode
information here: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/
This answer doesn't require that you know the what type of display (inline, etc.) the hideable element is supposed to be when being shown:
.hoverable:not(:hover) + .show-on-hover {_x000D_
display: none;_x000D_
}
_x000D_
<a class="hoverable">Hover over me!</a>_x000D_
<div class="show-on-hover">I'm a block element.</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<a class="hoverable">Hover over me also!</a>_x000D_
<span class="show-on-hover">I'm an inline element.</span>
_x000D_
This uses the adjacent sibling selector and the not selector.
If you want to get a long-as-possible (not sure what limits there are), similar to Solaris' pargs, you can use this on Linux & OSX:
ps -ww -o pid,command [-p <pid> ... ]
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.
With this prototype you can simply call
.hashCode()
on any string, e.g."some string".hashCode()
, and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) {
return hash;
}
for (var i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
...\Program Files\Microsoft SQL Server\MSSQL 1.0\MSSQL\Backup
For parsing do this-
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
$scope.data=data;
}).
Or you can use `$scope.data=JSON.Stringify(data);
In Angular template you can use it as
{{data}}
print( "hello " +k+ " " +ln);
where k
and ln
are variables
I recently came across Python 3 interpreter at CompileOnline.
4 GB minus what is in use by the system if you link with /LARGEADDRESSAWARE.
Of course, you should be even more careful with pointer arithmetic if you set that flag.
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.
Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.
Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.
On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)
The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.
Jake
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
use
console.log(variable)
and if you using google chrome open Console by using Ctrl+Shift+j
Goto >> Console
Since Multiple SCMs Plugin is deprecated.
With Jenkins Pipeline its possible to checkout multiple git repos and after building it using gradle
node {
def gradleHome
stage('Prepare/Checkout') { // for display purposes
git branch: 'develop', url: 'https://github.com/WtfJoke/Any.git'
dir('a-child-repo') {
git branch: 'develop', url: 'https://github.com/WtfJoke/AnyChild.git'
}
env.JAVA_HOME="${tool 'JDK8'}"
env.PATH="${env.JAVA_HOME}/bin:${env.PATH}" // set java home in jdk environment
gradleHome = tool '3.4.1'
}
stage('Build') {
// Run the gradle build
if (isUnix()) {
sh "'${gradleHome}/bin/gradle' clean build"
} else {
bat(/"${gradleHome}\bin\gradle" clean build/)
}
}
}
You might want to consider using git submodules instead of a custom pipeline like this.
The main concept of partial view is returning the HTML code rather than going to the partial view it self.
[HttpGet]
public ActionResult Calendar(int year)
{
var dates = new List<DateTime>() { /* values based on year */ };
HolidayViewModel model = new HolidayViewModel {
Dates = dates
};
return PartialView("HolidayPartialView", model);
}
this action return the HTML code of the partial view ("HolidayPartialView").
To refresh partial view replace the existing item with the new filtered item using the jQuery below.
$.ajax({
url: "/Holiday/Calendar",
type: "GET",
data: { year: ((val * 1) + 1) }
})
.done(function(partialViewResult) {
$("#refTable").html(partialViewResult);
});
Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).
The code I am looking for is adjusting the savefig call to:
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable
This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.
import matplotlib.pyplot as plt
import numpy as np
plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')
This produces:
[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm.
I think I got there in the end.
The task is like this:
- name: Populate genders
set_fact:
genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
with_items: "{{ people.results }}"
It loops through each of the dicts (item
) in the people.results
array, each time creating a new dict like {Bob: "male"}
, and combine()
s that new dict in the genders
array, which ends up like:
{
"Bob": "male",
"Thelma": "female"
}
It assumes the keys (the name
in this case) will be unique.
I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items
:
- name: Populate genders
set_fact:
genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
with_items: "{{ people.results }}"
This keeps combining the existing list with a list containing a single dict. We end up with a genders
array like this:
[
{'name': 'Bob', 'gender': 'male'},
{'name': 'Thelma', 'gender': 'female'}
]
well i found out the mistake i was committing i was adding a group to the project instead of adding real directory for more instructions
Try to use single quotes (') to avoid shell escaping of your string. Remember that the expression needs to match the whole path, i.e. needs to look like:
find . -regex '\./[a-f0-9-]*.jpg'
Apart from that, it seems that my find (GNU 4.4.2) only knows basic regular expressions, especially not the {36} syntax. I think you'll have to make do without it.
The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR
. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?
To find the values that are causing issues (so you (or whoever designed this table) can fix them):
SELECT GRADUATION_DATE FROM mydb
WHERE ISDATE(GRADUATION_DATE) = 0;
Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.
ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;
Now you don't have to worry about the formatting - you can always format as YYYYMMDD
or YYYY-MM-DD
on the client, or using CONVERT
in SQL. When you have a valid date as a string literal, you can use:
SELECT CONVERT(CHAR(10), '20120101', 120);
...but this is better done on the client (if at all).
There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.
You can groupby
on cols 'A' and 'B' and call size
and then reset_index
and rename
the generated column:
In [26]:
df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})
Out[26]:
A B count
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
update
A little explanation, by grouping on the 2 columns, this groups rows where A and B values are the same, we call size
which returns the number of unique groups:
In[202]:
df1.groupby(['A','B']).size()
Out[202]:
A B
no no 1
yes 2
yes no 4
yes 3
dtype: int64
So now to restore the grouped columns, we call reset_index
:
In[203]:
df1.groupby(['A','B']).size().reset_index()
Out[203]:
A B 0
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
This restores the indices but the size aggregation is turned into a generated column 0
, so we have to rename this:
In[204]:
df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})
Out[204]:
A B count
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
groupby
does accept the arg as_index
which we could have set to False
so it doesn't make the grouped columns the index, but this generates a series
and you'd still have to restore the indices and so on....:
In[205]:
df1.groupby(['A','B'], as_index=False).size()
Out[205]:
A B
no no 1
yes 2
yes no 4
yes 3
dtype: int64
Another way:
SELECT *
FROM TABLE A
WHERE EXISTS (
SELECT 1 FROM TABLE
WHERE COLUMN_NAME = A.COLUMN_NAME
AND ROWID < A.ROWID
)
Works fine (quick enough) when there is index on column_name
. And it's better way to delete or update duplicate rows.
All will get executed and On first Called first run basis!!
<div id="target"></div>
<script>
$(document).ready(function(){
jQuery('#target').append('target edit 1<br>');
});
$(document).ready(function(){
jQuery('#target').append('target edit 2<br>');
});
$(document).ready(function(){
jQuery('#target').append('target edit 3<br>');
});
</script>
Demo As you can see they do not replace each other
Also one thing i would like to mention
in place of this
$(document).ready(function(){});
you can use this shortcut
jQuery(function(){
//dom ready codes
});
I stumbled on this while looking for a better way than what I had arrived at. Having read the answers and trying them out I thought it was worth posting what I was doing as the other answers didn't feel as succinct for me. It was important for me to only have to write a short amount of code each time I set up a new interface. I settled on...
Using a custom generic deepCopy function:
deepCopy = <T extends {}>(input: any): T => {
return JSON.parse(JSON.stringify(input));
};
Define your interface
interface IX {
a: string;
b: any;
c: AnotherType;
}
... and define the defaults in a separate const.
const XDef : IX = {
a: '',
b: null,
c: null,
};
Then init like this:
let x : IX = deepCopy(XDef);
That's all that's needed..
.. however ..
If you want to custom initialise any root element you can modify the deepCopy function to accept custom default values. The function becomes:
deepCopyAssign = <T extends {}>(input: any, rootOverwrites?: any): T => {
return JSON.parse(JSON.stringify({ ...input, ...rootOverwrites }));
};
Which can then be called like this instead:
let x : IX = deepCopyAssign(XDef, { a:'customInitValue' } );
Any other preferred way of deep copy would work. If only a shallow copy is needed then Object.assign would suffice, forgoing the need for the utility deepCopy
or deepCopyAssign
function.
let x : IX = object.assign({}, XDef, { a:'customInitValue' });
Known Issues
deepCopyAssign
to iterate and check types before assigning.How do I manually throw/raise an exception in Python?
Use the most specific Exception constructor that semantically fits your issue.
Be specific in your message, e.g.:
raise ValueError('A very specific bad thing happened.')
Avoid raising a generic Exception
. To catch it, you'll have to catch all other more specific exceptions that subclass it.
raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
For example:
def demo_bad_catch():
try:
raise ValueError('Represents a hidden bug, do not catch this')
raise Exception('This is the exception you expect to handle')
except Exception as error:
print('Caught this error: ' + repr(error))
>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)
And more specific catches won't catch the general exception:
def demo_no_catch():
try:
raise Exception('general exceptions not caught by specific handling')
except ValueError as e:
print('we will not catch exception: Exception')
>>> demo_no_catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
raise
statementInstead, use the most specific Exception constructor that semantically fits your issue.
raise ValueError('A very specific bad thing happened')
which also handily allows an arbitrary number of arguments to be passed to the constructor:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
These arguments are accessed by the args
attribute on the Exception
object. For example:
try:
some_code_that_may_raise_our_value_error()
except ValueError as err:
print(err.args)
prints
('message', 'foo', 'bar', 'baz')
In Python 2.5, an actual message
attribute was added to BaseException
in favor of encouraging users to subclass Exceptions and stop using args
, but the introduction of message
and the original deprecation of args has been retracted.
except
clauseWhen inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:
logger = logging.getLogger(__name__)
try:
do_something_in_app_that_breaks_easily()
except AppError as error:
logger.error(error)
raise # just this!
# raise AppError # Don't do this, you'll lose the stack trace!
You can preserve the stacktrace (and error value) with sys.exc_info()
, but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare raise
to re-raise.
To explain - the sys.exc_info()
returns the type, value, and traceback.
type, value, traceback = sys.exc_info()
This is the syntax in Python 2 - note this is not compatible with Python 3:
raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
If you want to, you can modify what happens with your new raise - e.g. setting new args
for the instance:
def error():
raise ValueError('oops!')
def catch_error_modify_message():
try:
error()
except ValueError:
error_type, error_instance, traceback = sys.exc_info()
error_instance.args = (error_instance.args[0] + ' <modification>',)
raise error_type, error_instance, traceback
And we have preserved the whole traceback while modifying the args. Note that this is not a best practice and it is invalid syntax in Python 3 (making keeping compatibility much harder to work around).
>>> catch_error_modify_message()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in catch_error_modify_message
File "<stdin>", line 2, in error
ValueError: oops! <modification>
In Python 3:
raise error.with_traceback(sys.exc_info()[2])
Again: avoid manually manipulating tracebacks. It's less efficient and more error prone. And if you're using threading and sys.exc_info
you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.)
In Python 3, you can chain Exceptions, which preserve tracebacks:
raise RuntimeError('specific message') from error
Be aware:
These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, but not the one intended!
Valid in Python 2, but not in Python 3 is the following:
raise ValueError, 'message' # Don't do this, it's deprecated!
Only valid in much older versions of Python (2.4 and lower), you may still see people raising strings:
raise 'message' # really really wrong. don't do this.
In all modern versions, this will actually raise a TypeError
, because you're not raising a BaseException
type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.
I raise Exceptions to warn consumers of my API if they're using it incorrectly:
def api_func(foo):
'''foo should be either 'baz' or 'bar'. returns something very useful.'''
if foo not in _ALLOWED_ARGS:
raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))
"I want to make an error on purpose, so that it would go into the except"
You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
and usage:
if important_key not in resource_dict and not ok_to_be_missing:
raise MyAppLookupError('resource is missing, and that is not ok.')
You would use an expression when you want to treat your function as data and not as code. You can do this if you want to manipulate the code (as data). Most of the time if you don't see a need for expressions then you probably don't need to use one.
No. the pointer will be deleted. You should call the delete on A explicit in the destructor of B.
I know it's late, but I take the original code and change some stuff to control easily the css. So I made a code with the addClass() and the removeClass()
Here the full code : http://jsfiddle.net/e5qaD/4837/
if( bottom_of_window > bottom_of_object ){
$(this).addClass('showme');
}
if( bottom_of_window < bottom_of_object ){
$(this).removeClass('showme');
I had the same problem in various different situations, and the solutions i have found work in some but dont work in others so here is a combine solution that works in most situations i have found:
public static void showVirtualKeyboard(Context context, final View view) {
if (context != null) {
final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.clearFocus();
if(view.isShown()) {
imm.showSoftInput(view, 0);
view.requestFocus();
} else {
view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
view.post(new Runnable() {
@Override
public void run() {
view.requestFocus();
imm.showSoftInput(view, 0);
}
});
view.removeOnAttachStateChangeListener(this);
}
@Override
public void onViewDetachedFromWindow(View v) {
view.removeOnAttachStateChangeListener(this);
}
});
}
}
}
For us VBers:
TrimEnd(New Char() {ControlChars.Cr, ControlChars.Lf})
Use This its is very useful for your solution:
I use __dict__
Example:
class MyObj(object):
def __init__(self):
self.name = 'Chuck Norris'
self.phone = '+6661'
obj = MyObj()
print(obj.__dict__)
# Output:
# {'phone': '+6661', 'name': 'Chuck Norris'}
if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use
\d+
This code works for me:
<?php
$date = "21.12.2015";
$newDate = date("d.m.Y",strtotime($date."+2 day"));
echo $newDate; // print 23.12.2015
?>
The property event.which
is added when using jQuery to avoid browser differences. See docs.
The which
property will be undefined if you are not using jQuery.
One thing that caught me out and surprised me was, in an inherited project, the files it was referring to were referred to on a relative path outside of the project folder but yet existed in the project folder.
In solution explorer, single click each file with the error, bring up the Properties window (right-click, Properties), and ensure the "Relative Path" is just the file name (e.g. MyMissingFile.cpp
) if it is in the project folder. In my case it was set to: ..\..\Some Other Folder\MyMissingFile.cpp
.
In my case I forgot to add the return type to a function in my inherited class from RoomDatabase:
abstract class LocalDb : RoomDatabase() {
abstract fun progressDao(): ProgressDao
}
The ProgressDao return type was missing.
It is possible to use the data field name, if not the title so easily, which solved the problem for me. For ASP.NET & VB:
e.g. For a string:
Dim Encoding = e.Row.DataItem("Encoding").ToString().Trim()
e.g. For an integer:
Dim MsgParts = Convert.ToInt32(e.Row.DataItem("CalculatedMessageParts").ToString())
This is now trivial in tidyr with replace_na(). The function appears to work for data.tables as well as data.frames:
tidyr::replace_na(x, list(a=0, b=0))
You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.
USE OurDatabaseName
GO
SELECT
sc.name AS [Columne Name],
st1.name AS [User Type],
st2.name AS [Base Type]
FROM dbo.syscolumns sc
INNER JOIN dbo.systypes st1 ON st1.xusertype = sc.xusertype
INNER JOIN dbo.systypes st2 ON st2.xusertype = sc.xtype
-- STEP TWO: Change OurTableName to the table name
WHERE sc.id = OBJECT_ID('OurTableName')
ORDER BY sc.colid
Or:
SELECT COLUMN_NAME AS ColumnName, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS CharacterLength
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'OurTableName'
I recommend checking out Microsoft's SQL Server sample databases: https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks
The AdventureWorks sample uses a very clear and consistent naming convention that uses schema names for the organization of database objects.
Looking at:
No public installers with the RunInstallerAttribute.Yes attribute could be found in the C:\Users\myusername\Documents\Visual Studio 2010\Projects\TestService\TestSe rvice\obj\x86\Debug\TestService.exe assembly.
It looks like you may not have an installer class in your code. This is a class that inherits from Installer
that will tell installutil
how to install your executable as a service.
P.s. I have my own little self-installing/debuggable Windows Service template here which you can copy code from or use: Debuggable, Self-Installing Windows Service
If you just need to output the date in ISO8601 format including the trailing Z and you are on at least SQL Server 2012, then you may use FORMAT
:
SELECT FORMAT(GetUtcDate(),'yyyy-MM-ddTHH:mm:ssZ')
This will give you something like:
2016-02-18T21:34:14Z
Just as @Pxtl points out in a comment FORMAT may have performance implications, a cost that has to be considered compared to any flexibility it brings.
Easiest way: select the TARGET name, double click on it, rename. You'll see your app's new name underneath the icon on your device or Simulator.
See: Local dependency in package.json
It looks like the answer is npm link
: https://docs.npmjs.com/cli/link
The way to do it without projection:
StudentsGrades.OrderBy(student => student.Name).
ThenBy(student => student.Grade);
Like so many others, but with explanation in the css.
/* select all <a> elements with class "button" */
a.button {
/* use inline-block because it respects padding */
display: inline-block;
/* padding creates clickable area around text (top/bottom, left/right) */
padding: 1em 3em;
/* round corners */
border-radius: 5px;
/* remove underline */
text-decoration: none;
/* set colors */
color: white;
background-color: #4E9CAF;
}
_x000D_
<a class="button" href="#">Add a problem</a>
_x000D_
Because it's not.
Indexing is covered by IList
. IEnumerable
means "I have some of the powers of IList, but not all of them."
Some collections (like a linked list), cannot be indexed in a practical way. But they can be accessed item-by-item. IEnumerable
is intended for collections like that. Note that a collection can implement both IList & IEnumerable (and many others). You generally only find IEnumerable
as a function parameter, meaning the function can accept any kind of collection, because all it needs is the simplest access mode.
roenving is correct BUT you need to change the test to:
if(element.nodeType == 1) { //code }
because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
var myPieChart=null;
function drawChart(objChart,data){
if(myPieChart!=null){
myPieChart.destroy();
}
// Get the context of the canvas element we want to select
var ctx = objChart.getContext("2d");
myPieChart = new Chart(ctx).Pie(data, {animateScale: true});
}
This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.
On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !
Inside activities on back pressed put this:
Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");
if (home instanceof FragmentDetailedPizza && home.isVisible()) {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
} else {
//Primary fragment
moveTaskToBack(true);
}
And launch the other fragment like this:
Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, someFragment, "DetailedPizza");
transaction.addToBackStack("DetailedPizza");
transaction.commit();
What errors are you seeing in the browser? I can understand why your code doesn't work if what you posted was incomplete, but without knowing that I can't know for sure.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
} else {
$('#charNum').text(500 - len);
}
};
</script>
</head>
<body>
<textarea id="field" onkeyup="countChar(this)"></textarea>
<div id="charNum"></div>
</body>
</html>
... works fine for me.
Edit: You should probably clear the charNum div, or write something, if they are over the limit.
If I remember well, I had the same kind of issue when loading stuff from the asset folder but with a database. It seems that the stuff in your asset folder can have 2 stats : compressed or not.
If it is compressed, then you are allowed 1 Mo of memory to uncompress it, otherwise you will get this kind of exception. There are several bug reports about that because the documentation is not clear. So if you still want to to use your format, you have to either use an uncompressed version, or give an extension like .mp3 or .png to your file. I know it's a bit crazy but I load a database with a .mp3 extension and it works perfectly fine. This other solution is to package your application with a special option to tell it not to compress certain extension. But then you need to build your app manually and add "zip -0" option.
The advantage of an uncompressed assest is that the phase of zip-align before publication of an application will align the data correctly so that when loaded in memory it can be directly mapped.
To follow up on the previous answer using mail :
Often times one's html output is interpreted by the client mailer, which may not format things using a fixed-width font. Thus your nicely formatted ascii alignment gets all messed up. To send old-fashioned fixed-width the way the God intended, try this:
{ echo -e "<pre>"
echo "Descriptive text here."
shell_command_1_here
another_shell_command
cat <<EOF
This is the ending text.
</pre><br>
</div>
EOF
} | mail -s "$(echo -e 'Your subject.\nContent-Type: text/html')" [email protected]
You don't necessarily need the "Descriptive text here." line, but I have found that sometimes the first line may, depending on its contents, cause the mail program to interpret the rest of the file in ways you did not intend. Try the script with simple descriptive text first, before fine tuning the output in the way that you want.
The advantages of EditorFor
is that your code is not tied to an <input type="text"
. So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div
you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml
) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor
you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.
I've been having the same problem (well I hope the same). Anyways it turned out to be my version of ntwdblib.dll, which was out of date in my PHP folder.
http://dba.fyicenter.com/faq/sql_server_2/Finding_ntwdblib_dll_Version_2000_80_194_0.html
Here is the script in Python.
You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.
element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)
You build the object before encoding it to a JSON string:
import json
data = {}
data['key'] = 'value'
json_data = json.dumps(data)
JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
Consider Moshi's JsonWriter class (source). It has a wonderful API and it reduces copying to a minimum, everything is nicely streamed to the OutputStream.
OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.sink(os));
json
.beginObject()
.name("id").value(userID)
.name("type").value(methodn)
...
.endObject();
A device might have several IP addresses, and the one in use in a particular app might not be the IP that servers receiving the request will see. Indeed, some users use a VPN or a proxy such as Cloudflare Warp.
If your purpose is to get the IP address as shown by servers that receive requests from your device, then the best is to query an IP geolocation service such as Ipregistry (disclaimer: I work for the company) with its Java client:
https://github.com/ipregistry/ipregistry-java
IpregistryClient client = new IpregistryClient("tryout");
RequesterIpInfo requesterIpInfo = client.lookup();
requesterIpInfo.getIp();
In addition to being really simple to use, you get additional information such as country, language, currency, the time zone for the device IP and you can identify whether the user is using a proxy.
Chrome 56 is not accepting this kind of patterns (Chrome 56 is accpeting 11.11. an additional .) with type number, use type as text as progress.
Complementing the answer from @Nishant,the best way to return the activity result is:
Intent returnIntent = getIntent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
I was having problem with
new Intent();
Then I found out that the correct way is using
getIntent();
to get the current intent
server.session.timeout=1200
server.servlet.session.timeout=10m
I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??
This depends strongly on the crypto algorithm you use:
Addition to the Usage from the ORM layer in the accepted answer: count(*) can be done for ORM using the query.with_entities(func.count())
, like this:
session.query(MyModel).with_entities(func.count()).scalar()
It can also be used in more complex cases, when we have joins and filters - the important thing here is to place with_entities
after joins, otherwise SQLAlchemy could raise the Don't know how to join
error.
For example:
User
model (id
, name
) and Song
model (id
, title
, genre
)UserSong
model (user_id
, song_id
, is_liked
) where user_id
+ song_id
is a primary key)We want to get a number of user's liked rock songs:
SELECT count(*)
FROM user_song
JOIN song ON user_song.song_id = song.id
WHERE user_song.user_id = %(user_id)
AND user_song.is_liked IS 1
AND song.genre = 'rock'
This query can be generated in a following way:
user_id = 1
query = session.query(UserSong)
query = query.join(Song, Song.id == UserSong.song_id)
query = query.filter(
and_(
UserSong.user_id == user_id,
UserSong.is_liked.is_(True),
Song.genre == 'rock'
)
)
# Note: important to place `with_entities` after the join
query = query.with_entities(func.count())
liked_count = query.scalar()
Complete example is here.
For me, the simplest way to do this is
1) Download and unzip bootstrap into vendor
2) Add the bootstrap path to your config
config.assets.paths << Rails.root.join("vendor/bootstrap-3.3.6-dist")
3) Require them
in css *= require css/bootstrap
in js //= require js/bootstrap
Done!
This methods makes the fonts load without any other special configuration and doesn't require moving the bootstrap files out of their self-contained directory.
This a very basic solution (maybe I'm missing the full point of the question). ActiveSheet.Name will RETURN the string of the current tab name (and will reflect any future changes by the user). I just call the active sheet, set the variable and then use it as the Worksheets' object. Here I'm retrieving data from a table to set up a report for a division. This macro will work on any sheet in my workbook that is formatted for the same filter (criteria and copytorange) - each division gets their own sheet and can alter the criteria and update using this single macro.
Dim currRPT As String
ActiveSheet.Select
currRPT = (ActiveSheet.Name)
Range("A6").Select
Selection.RemoveSubtotal
Selection.AutoFilter
Range("PipeData").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=Range _
("C1:D2"), CopyToRange:=Range("A6:L9"), Unique:=True
Worksheets(currRPT).AutoFilter.Sort.SortFields.Clear
Worksheets(currRPT).AutoFilter.Sort.SortFields.Add Key:= _
Range("C7"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
You can try as follows it works for me.
Start server:
sudo service mysql start
Now, Go to sock folder:
cd /var/run
Back up the sock:
sudo cp -rp ./mysqld ./mysqld.bak
Stop server:
sudo service mysql stop
Restore the sock:
sudo mv ./mysqld.bak ./mysqld
Start mysqld_safe:
sudo mysqld_safe --skip-grant-tables --skip-networking &
Init mysql shell:
mysql -u root
Change password:
Hence, First choose the database
mysql> use mysql;
Now enter below two queries:
mysql> update user set authentication_string=password('123456') where user='root';
mysql> update user set plugin="mysql_native_password" where User='root';
Now, everything will be ok.
mysql> flush privileges;
mysql> quit;
For checking:
mysql -u root -p
done!
N.B, After login please change the password again from phpmyadmin
Now check hostname/phpmyadmin
Username: root
Password: 123456
For more details please check How to reset forgotten password phpmyadmin in Ubuntu
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
Do you want your function to react to an array argument or variable arguments? If the latter, try:
var func = function(...rest) {
alert(rest.length);
// In JS, don't use for..in with arrays
// use for..of that consumes array's pre-defined iterator
// or a more functional approach
rest.forEach((v) => console.log(v));
};
But if you wish to handle an array argument
var fn = function(arr) {
alert(arr.length);
for(var i of arr) {
console.log(i);
}
};
use
sudo find / -name file.txt
It's stupid (because you elevate the search) and nonsecure, but far shorter to write.
All you need is this:
#ffffff00
Here the ffffff
is the color and 00
is the transparency
Also, if you want 50% transparent color, then sure you can do...
#ffffff80
Where 80
is the hexadecimal equivalent of 50%
.
Since the scale is 0-255 in RGB Colors, the half would be 255/2 = 128
, which when converted to hex becomes 80
And since in transparent we want 0 opacity, we write 00
see there link was very nice and simple. its working fine... u don't want any library its working fine. click here
OnTouchListener gestureListener = new View.OnTouchListener() {
private int padding = 0;
private int initialx = 0;
private int currentx = 0;
private ViewHolder viewHolder;
public boolean onTouch(View v, MotionEvent event) {
if ( event.getAction() == MotionEvent.ACTION_DOWN) {
padding = 0;
initialx = (int) event.getX();
currentx = (int) event.getX();
viewHolder = ((ViewHolder) v.getTag());
}
if ( event.getAction() == MotionEvent.ACTION_MOVE) {
currentx = (int) event.getX();
padding = currentx - initialx;
}
if ( event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
padding = 0;
initialx = 0;
currentx = 0;
}
if(viewHolder != null) {
if(padding == 0) {
v.setBackgroundColor(0xFF000000 );
if(viewHolder.running)
v.setBackgroundColor(0xFF058805);
}
if(padding > 75) {
viewHolder.running = true;
v.setBackgroundColor(0xFF00FF00 );
viewHolder.icon.setImageResource(R.drawable.clock_running);
}
if(padding < -75) {
viewHolder.running = false;
v.setBackgroundColor(0xFFFF0000 );
}
v.setPadding(padding, 0,0, 0);
}
return true;
}
};
In SQL Server, you would say:
Select name from users
UNION [ALL]
SELECT 'JASON'
In Oracle, you would say
Select name from user
UNION [ALL]
Select 'JASON' from DUAL
Underscore-java library has json builder.
String json = U.objectBuilder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", U.objectBuilder()
.add("innerKey1", "value3"))
.toJson();