I used this way in my code
$(function(){
$('.block').affix();
})
Its not mentioned on doc, but Left sidebar on Bootstrap 3 is possible using "Collapse" method.
As mentioned by bootstrap.js :
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
This mean, adding class "width" into target, will expand by width instead of height :
Position absolute, top:0 and bottom:0 for the sidebar and position relative for the wrapper (or container) witch content all the elements and it's done !
The best way to enhance your experience and change the sidebar and theme of the sublime text UI is to install two packages to control it:
After you've installed those two, just change the color scheme (text editor) and then with the Theme Menu Switcher you'll switch to whatever UI you use.
Remember: It's required that the theme you install to have UI inside the package.
you can make a function that do this job and use it
#include <stdio.h>
void repeat (char input , int count )
{
for (int i=0; i != count; i++ )
{
printf("%c", input);
}
}
int main()
{
repeat ('#', 5);
return 0;
}
This will output
#####
Write code in this manner ...
<canvas id="canvas" width="640" height="480"></canvas>
<script>
var Grid = function(width, height) {
...
this.draw = function() {
var canvas = document.getElementById("canvas");
if(canvas.getContext) {
var context = canvas.getContext("2d");
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
if(isLive(i, j)) {
context.fillStyle = "lightblue";
}
else {
context.fillStyle = "yellowgreen";
}
context.fillRect(i*15, j*15, 14, 14);
}
}
}
}
}
First write canvas tag and then write script tag. And write script tag in body.
I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.
First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.
public class UserProfile : Profile, IProfile
{
public UserProfile()
{
CreateMap<User, UserModel>();
CreateMap<UserModel, User>();
}
}
Now create a separate class e.g Mappings
public class Mappings
{
public static void RegisterMappings()
{
var all =
Assembly
.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.SelectMany(x => x.DefinedTypes)
.Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
var t = ti.AsType();
if (t.Equals(typeof(IProfile)))
{
Mapper.Initialize(cfg =>
{
cfg.AddProfiles(t); // Initialise each Profile classe
});
}
}
}
}
Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application loading.
Mappings.RegisterMappings();
If you have PHP on the back-end, you can use this code:
$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="'.$src.'">';
On Windows, you can use the following command to find out the defaults on the system where your applications runs.
java -XX:+PrintFlagsFinal -version | findstr HeapSize
Look for the options MaxHeapSize
(for -Xmx
) and InitialHeapSize
for -Xms
.
On a Unix/Linux system, you can do
java -XX:+PrintFlagsFinal -version | grep HeapSize
I believe the resulting output is in bytes.
.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.
.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).
There are two ways of solving this issue:
Now I don't see the error anymore, and the code completion feature works as well with "bottle".
re install your java. First check your OS version.
If the application is not doing anything in that 10 seconds, this will form a bad design only to make the user wait for 10 seconds doing nothing.
If there is something going on in that, or if you wish to implement 10 seconds delay splash screen,Here is the Code :
ProgressDialog pd;
pd = ProgressDialog.show(this,"Please Wait...", "Loading Application..", false, true);
pd.setCanceledOnTouchOutside(false);
Thread t = new Thread()
{
@Override
public void run()
{
try
{
sleep(10000) //Delay of 10 seconds
}
catch (Exception e) {}
handler.sendEmptyMessage(0);
}
} ;
t.start();
//Handles the thread result of the Backup being executed.
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
pd.dismiss();
//Start the Next Activity here...
}
};
I like Rink.Attendant.6 answer. I actually want to check for multiple strings and did it this way:
First the situation: Names that can be home builders or community names and I need to bucket the builders as one group. To do this I am looking for the word "builder" or "construction", etc. So -
=IF(OR(COUNTIF(A1,"*builder*"),COUNTIF(A1,"*builder*")),"Builder","Community")
This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd
to another (existing) directory and then cd
back; the simplest would be: cd; cd -
.
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}
This worked for me, can also be "borrowed" from the design view, make changes -> right click -> generate change script.
BEGIN TRANSACTION
GO
ALTER TABLE dbo.YOURTABLE ADD
YOURCOLUMN bit NOT NULL CONSTRAINT DF_YOURTABLE_YOURCOLUMN DEFAULT 0
GO
COMMIT
If you are using a nodejs backend you can use the following code I found here
var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''"
+ encodeRFC5987ValueChars(fileName);
function encodeRFC5987ValueChars (str) {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
}
How to filter (skip) non-UTF8 charachers from array?
To address this comment in @uname01's post and the OP, ignore the errors:
Code
>>> b'\x80abc'.decode("utf-8", errors="ignore")
'abc'
Details
From the docs, here are more examples using the same errors
parameter:
>>> b'\x80abc'.decode("utf-8", "replace")
'\ufffdabc'
>>> b'\x80abc'.decode("utf-8", "backslashreplace")
'\\x80abc'
>>> b'\x80abc'.decode("utf-8", "strict")
Traceback (most recent call last):
...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
invalid start byte
The errors argument specifies the response when the input string can’t be converted according to the encoding’s rules. Legal values for this argument are
'strict'
(raise aUnicodeDecodeError
exception),'replace'
(useU+FFFD
,REPLACEMENT CHARACTER
), or'ignore'
(just leave the character out of the Unicode result).
I had this issue after restoring a hard drive from a backup.
My problem: I could check & see my remote (using git remote -v), but when I executed git push origin master, it returned : Permission denied (publickey). fatal: Could not read from remote repository.
I already had an SSH folder and SSH keys, and adding them via Terminal (ssh-add /path/to/my-ssh-folder/id_rsa
) successfully added my identity, but I still couldn't push and still got the same error. Generating a new key was a bad idea for me, because it was tied to other very secure permissions on AWS.
It turned out the link between the key and my Github profile had broken.
Solution: Re-adding the key to Github in Profile > Settings > SSH and GPG keys resolved the issue.
Also: My account had 2-factor authentication set up. When this is the case, if Terminal requests credentials, use your username - but NOT your Github password. For 2-factor authentication, you need to use your authentication code (for me, this was generated by Authy on my phone, and I had to copy it into Terminal for the pw).
You can do this with one simple command:
npm ci
Documentation:
npm ci
Install a project with a clean slate
Update: OP uses Python 3. So adding an example using httplib2
import httplib2
h = httplib2.Http(".cache")
h.add_credentials('name', 'password') # Basic authentication
resp, content = h.request("https://host/path/to/resource", "POST", body="foobar")
The below works for python 2.6:
I use pycurl
a lot in production for a process which does upwards of 10 million requests per day.
You'll need to import the following first.
import pycurl
import cStringIO
import base64
Part of the basic authentication header consists of the username and password encoded as Base64.
headers = { 'Authorization' : 'Basic %s' % base64.b64encode("username:password") }
In the HTTP header you will see this line Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
. The encoded string changes depending on your username and password.
We now need a place to write our HTTP response to and a curl connection handle.
response = cStringIO.StringIO()
conn = pycurl.Curl()
We can set various curl options. For a complete list of options, see this. The linked documentation is for the libcurl API, but the options does not change for other language bindings.
conn.setopt(pycurl.VERBOSE, 1)
conn.setopt(pycurlHTTPHEADER, ["%s: %s" % t for t in headers.items()])
conn.setopt(pycurl.URL, "https://host/path/to/resource")
conn.setopt(pycurl.POST, 1)
If you do not need to verify certificate. Warning: This is insecure. Similar to running curl -k
or curl --insecure
.
conn.setopt(pycurl.SSL_VERIFYPEER, False)
conn.setopt(pycurl.SSL_VERIFYHOST, False)
Call cStringIO.write
for storing the HTTP response.
conn.setopt(pycurl.WRITEFUNCTION, response.write)
When you're making a POST request.
post_body = "foobar"
conn.setopt(pycurl.POSTFIELDS, post_body)
Make the actual request now.
conn.perform()
Do something based on the HTTP response code.
http_code = conn.getinfo(pycurl.HTTP_CODE)
if http_code is 200:
print response.getvalue()
According to the Docker Getting Started guide "your built image" is "in your machine’s local Docker image registry."
This is still strange to me, because now it leads to the question. Where is my machine's local Docker image registry?
Nevertheless, I definitely think this info is worth sharing as an answer.
This should fix it:
jQuery(document).ready(function($){
//you can now use $ as your jQuery object.
var body = $( 'body' );
});
Put simply, WordPress runs their own scripting before you can and they release the $
var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.
From their documentation:
The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.
In the noConflict() mode, the global $ shortcut for jQuery is not available...
Here's something based on accepted answer. I removed the try/catch to make sure all the exceptions are not swallowed and not dealt with. Also made sure that the return variable (in accepted answer) is never initialized twice for nothing.
public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
if (!string.IsNullOrWhiteSpace(s))
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
return (T)conv.ConvertFrom(s);
}
return default(Nullable<T>);
}
If you can't use box-sizing (e.g. when you convert HTML to PDF using iText). Try this:
CSS
.input-wrapper { border: 1px solid #ccc; padding: 0 5px; min-height: 20px; }
.input-wrapper input[type=text] { border: none; height: 20px; width: 100%; padding: 0; margin: 0; }
HTML
<div class="input-wrapper">
<input type="text" value="" name="city"/>
</div>
xCode 7.3.1 iOS 9.3.2
_siteLabel.layer.masksToBounds = true;
_siteLabel.layer.cornerRadius = 8;
If you have run ng build --prod
- you shouldn't have vendor
files at all.
If I run just ng build
- I get these files:
The total size of the folder is ~14MB. Waat! :D
But if I run ng build --prod
- I get these files:
The total size of the folder is 584K.
One and the same code. I have enabled Ivy in both cases. Angular is 8.2.13.
So - I guess you didn't add --prod
to your build command?
in my case, the file
command tells a wrong encoding, so i tried converting with all the possible encodings, and found out the right one.
execute this script and check the result file.
for i in `iconv -l`
do
echo $i
iconv -f $i -t UTF-8 yourfile | grep "hint to tell converted success or not"
done &>/tmp/converted
Just use plain objects:
var map = { key1: "value1", key2: "value2" }
function get(k){
return map[k];
}
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
From you own project.
npx nodemon [your-app.js]
With a local installation, nodemon will not be available in your system path. Instead, the local installation of nodemon can be run by calling it from within an npm script (such as npm start
) or using npx nodemon
.
OR
Create a simple symbolik link
ln -s /Users/YourUsername/.npm-global/bin/nodemon /usr/local/bin
ln -s [from: where is you install 'nodemon'] [to: folder where are general module for node]
node : v12.1.0
npm : 6.9.0
Due to the fact that I answered this in 2014, I have updated my answer to account for more recent versions of ansible.
Yes, you can do it at the host/inventory level (Which became possible on newer ansible versions) or global level:
inventory:
Add the following.
ansible_ssh_common_args='-o StrictHostKeyChecking=no'
host:
Add the following.
ansible_ssh_extra_args='-o StrictHostKeyChecking=no'
hosts/inventory options will work with connection type ssh
and not paramiko
. Some people may strongly argue that inventory and hosts is more secure because the scope is more limited.
global:
Ansible User Guide - Host Key Checking
You can do it either in the /etc/ansible/ansible.cfg
or ~/.ansible.cfg
file:
[defaults]
host_key_checking = False
Or you can setup and env variable (this might not work on newer ansible versions):
export ANSIBLE_HOST_KEY_CHECKING=False
char[] chars = s.toCharArray();
HashSet<Character> charz = new HashSet<Character>();
for(Character c : s.toCharArray() )
{
if(!charz.contains(c))
{
charz.add(c);
//System.out.print(c);
}
}
for(Character c : charz)
{
System.out.print(c);
}
Any definition is valid. As long as you are consistent in your implementation (always put equal nodes to the right, always put them to the left, or never allow them) then you're fine. I think it is most common to not allow them, but it is still a BST if they are allowed and place either left or right.
If you want to debug your flask app then just go to the folder where flask app is. Don't forget to activate your virtual environment and paste the lines in the console change "mainfilename" to flask main file.
export FLASK_APP="mainfilename.py"
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0
After you enable your debugger for flask app almost every error will be printed on the console or on the browser window. If you want to figure out what's happening, you can use simple print statements or you can also use console.log() for javascript code.
This is ancient history but I just ran into this issue and the fix for me was recycling the application pool of the website in IIS. Easy fix, for once.
This an old question, but I have had to explain it to someone recently and I thought recording the answer here would be helpful at least in understanding how C works.
String literals like
"a"
or
"This is a string"
are put in the text or data segments of your program.
A string in C is actually a pointer to a char, and the string is understood to be the subsequent chars in memory up until a NUL char is encountered. That is, C doesn't really know about strings.
So if I have
char *s1 = "This is a string";
then s1 is a pointer to the first byte of the string.
Now, if I have
char *s2 = "This is a string";
this is also a pointer to the same first byte of that string in the text or data segment of the program.
But if I have
char *s3 = malloc( 17 );
strcpy(s3, "This is a string");
then s3 is a pointer to another place in memory into which I copy all the bytes of the other strings.
Illustrative examples:
Although, as your compiler rightly points out, you shouldn't do this, the following will evaluate to true:
s1 == s2 // True: we are comparing two pointers that contain the same address
but the following will evaluate to false
s1 == s3 // False: Comparing two pointers that don't hold the same address.
And although it might be tempting to have something like this:
struct Vehicle{
char *type;
// other stuff
}
if( type == "Car" )
//blah1
else if( type == "Motorcycle )
//blah2
You shouldn't do it because it's not something that is guarantied to work. Even if you know that type will always be set using a string literal.
I have tested it and it works. If I do
A.type = "Car";
then blah1 gets executed and similarly for "Motorcycle". And you'd be able to do things like
if( A.type == B.type )
but this is just terrible. I'm writing about it because I think it's interesting to know why it works, and it helps understand why you shouldn't do it.
Solutions:
In your case, what you want to do is use strcmp(a,b) == 0
to replace a == b
In the case of my example, you should use an enum.
enum type {CAR = 0, MOTORCYCLE = 1}
The preceding thing with string was useful because you could print the type, so you might have an array like this
char *types[] = {"Car", "Motorcycle"};
And now that I think about it, this is error prone since one must be careful to maintain the same order in the types array.
Therefore it might be better to do
char *getTypeString(int type)
{
switch(type)
case CAR: return "Car";
case MOTORCYCLE: return "Motorcycle"
default: return NULL;
}
Fairly new to using PowerShell, think I might be able to help. Could you try this?
I believe you're not getting the correct parameters to your script block:
param([string]$one, [string]$two)
$res = Invoke-Command -Credential $migratorCreds -ScriptBlock {Get-LocalUsers -parentNodeXML $args[0] -migratorUser $args[1] } -ArgumentList $xmlPRE, $migratorCreds
your_dict = {}
To add new key:
your_dict[key]=value
your_dict.update(key=value)
Here is the correct implementation using numpy (np.log()
is the natural logarithm)
import numpy as np
p = 100
r = 0.06 / 12
FV = 4000
n = np.log(1 + FV * r/ p) / np.log(1 + r)
print ("Number of periods = " + str(n))
Output:
Number of periods = 36.55539635919235
There is no difference. The $_SERVER['PHP_SELF'] just makes the execution time slower by like 0.000001 second.
How is it noone has mentioned..
document.activeElement.id
I am using IE8, and have not tested it on any other browser. In my case, I am using it to make sure a field is a minimum of 4 characters and focused before acting. Once you enter the 4th number, it triggers. The field has an id of 'year'. I am using..
if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
// action here
}
If for some reason xcode is not installed under
/usr/bin/xcodebuild
execute the following command
which xcodebuild
and if it is installed, you'll be prompted with it's location.
Please read the Threading Model in UI applications (old VB link is here) in order to understand basic concepts. The link navigates to page that describes the WPF threading model. However, Windows Forms utilizes the same idea.
Read answers on question How to update the GUI from another thread in C#?. For C# 5.0 and .NET 4.5 the recommended solution is here.
I stopped using datetime
in my applications after facing many problems and bugs related to time zones. IMHO using timestamp
is better than datetime
in most of the cases.
When you ask what is the time ? and the answer comes as something like '2019-02-05 21:18:30', that is not completed, not defined answer because it lacks another part, in which timezone ? Washington ? Moscow ? Beijing ?
Using datetimes without the timezone means that your application is dealing with only 1 timezone, however timestamps give you the benefits of datetime
plus the flexibility of showing the same exact point of time in different timezones.
Here are some cases that will make you regret using datetime
and wish that you stored your data in timestamps.
For your clients comfort you want to show them the times based on their preferred time zones without making them doing the math and convert the time to their meaningful timezone. all you need is to change the timezone and all your application code will be the same.(Actually you should always define the timezone at the start of the application, or request processing in case of PHP applications)
SET time_zone = '+2:00';
you changed the country you stay in, and continue your work of maintaining the data while seeing it in a different timezone (without changing the actual data).
datetime
= application supports 1 timezone (for both inserting and selecting)
timestamp
= application supports any timezone (for both inserting and selecting)
This answer is only for putting some highlight on the flexibility and ease of timestamps when it comes to time zones , it is not covering any other differences like the column size or range or fraction.
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
Call $watch
with true
as the third argument:
$scope.$watch('form', function(newVal, oldVal){
console.log('changed');
}, true);
By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal.
Per the Angular documentation, the third parameter is for objectEquality
:
When
objectEquality == true
, inequality of the watchExpression is determined according to theangular.equals
function. To save the value of the object for later comparison, theangular.copy
function is used. This therefore means that watching complex objects will have adverse memory and performance implications.
I have managed to get this to work using the following...
function resetFileElement(ele)
{
ele.val('');
ele.wrap('<form>').parent('form').trigger('reset');
ele.unwrap();
ele.prop('files')[0] = null;
ele.replaceWith(ele.clone());
}
This has been tested in IE10, FF, Chrome & Opera.
There are two caveats...
Still doesn't work properly in FF, if you refresh the page, the file element gets re-populated with the selected file. Where it is getting this info from is beyond me. What else related to a file input element could I possible try to clear?
Remember to use delegation on any events you had attached to the file input element, so they still work when the clone is made.
What I don't understand is who on earth thought not allowing you to clear an input field from an invalid unacceptable file selection was a good idea?
OK, don't let me dynamically set it with a value so I can't leach files from a user's OS, but let me clear an invalid selection without resetting an entire form.
It's not like 'accept' does anything other than a filter anyhow and in IE10, it doesn't even understand MS Word mime types, it's a joke!
I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact
DateTime.ParseExact(dateString, format, provider);
source: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
You could use dots: ...
in your function definition.
myfun <- function(a, b, ...){
cat(a,b)
}
myfun(a=4,b=7,hello=3)
# 4 7
It can be retrieved using REST, see Version API :
curl --header "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" https://gitlab.example.com/api/v4/version
For authentication see Personal access tokens documentation.
Following up on sas's answer, PHP 5.4, Symfony 2.8, I had to use
ini_set('date.timezone','<whatever timezone string>');
instead of date_default_timezone_set
. I also added a call to ini_set
to the top of a custom web/config.php
to get that check to succeed.
Another solution is using vue-router-back-mixin
import BackMixin from `vue-router-back-mixin`
export default {
...
mixins: [BackMixin],
methods() {
goBack() {
this.backMixin_handleBack()
}
}
...
}
The C99 way is
#include <inttypes.h>
int64_t my_int = 999999999999999999;
printf("%" PRId64 "\n", my_int);
Or you could cast!
printf("%ld", (long)my_int);
printf("%lld", (long long)my_int); /* C89 didn't define `long long` */
printf("%f", (double)my_int);
If you're stuck with a C89 implementation (notably Visual Studio) you can perhaps use an open source <inttypes.h>
(and <stdint.h>
): http://code.google.com/p/msinttypes/
If you are using boost libs you can obtain a random generator in this way:
#include <iostream>
#include <string>
// Used in randomization
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>
using namespace std;
using namespace boost;
int current_time_nanoseconds(){
struct timespec tm;
clock_gettime(CLOCK_REALTIME, &tm);
return tm.tv_nsec;
}
int main (int argc, char* argv[]) {
unsigned int dice_rolls = 12;
random::mt19937 rng(current_time_nanoseconds());
random::uniform_int_distribution<> six(1,6);
for(unsigned int i=0; i<dice_rolls; i++){
cout << six(rng) << endl;
}
}
Where the function current_time_nanoseconds()
gives the current time in nanoseconds which is used as a seed.
Here is a more general class to get random integers and dates in a range:
#include <iostream>
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/gregorian/gregorian.hpp"
using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace boost::gregorian;
class Randomizer {
private:
static const bool debug_mode = false;
random::mt19937 rng_;
// The private constructor so that the user can not directly instantiate
Randomizer() {
if(debug_mode==true){
this->rng_ = random::mt19937();
}else{
this->rng_ = random::mt19937(current_time_nanoseconds());
}
};
int current_time_nanoseconds(){
struct timespec tm;
clock_gettime(CLOCK_REALTIME, &tm);
return tm.tv_nsec;
}
// C++ 03
// ========
// Dont forget to declare these two. You want to make sure they
// are unacceptable otherwise you may accidentally get copies of
// your singleton appearing.
Randomizer(Randomizer const&); // Don't Implement
void operator=(Randomizer const&); // Don't implement
public:
static Randomizer& get_instance(){
// The only instance of the class is created at the first call get_instance ()
// and will be destroyed only when the program exits
static Randomizer instance;
return instance;
}
bool method() { return true; };
int rand(unsigned int floor, unsigned int ceil){
random::uniform_int_distribution<> rand_ = random::uniform_int_distribution<> (floor,ceil);
return (rand_(rng_));
}
// Is not considering the millisecons
time_duration rand_time_duration(){
boost::posix_time::time_duration floor(0, 0, 0, 0);
boost::posix_time::time_duration ceil(23, 59, 59, 0);
unsigned int rand_seconds = rand(floor.total_seconds(), ceil.total_seconds());
return seconds(rand_seconds);
}
date rand_date_from_epoch_to_now(){
date now = second_clock::local_time().date();
return rand_date_from_epoch_to_ceil(now);
}
date rand_date_from_epoch_to_ceil(date ceil_date){
date epoch = ptime(date(1970,1,1)).date();
return rand_date_in_interval(epoch, ceil_date);
}
date rand_date_in_interval(date floor_date, date ceil_date){
return rand_ptime_in_interval(ptime(floor_date), ptime(ceil_date)).date();
}
ptime rand_ptime_from_epoch_to_now(){
ptime now = second_clock::local_time();
return rand_ptime_from_epoch_to_ceil(now);
}
ptime rand_ptime_from_epoch_to_ceil(ptime ceil_date){
ptime epoch = ptime(date(1970,1,1));
return rand_ptime_in_interval(epoch, ceil_date);
}
ptime rand_ptime_in_interval(ptime floor_date, ptime ceil_date){
time_duration const diff = ceil_date - floor_date;
long long gap_seconds = diff.total_seconds();
long long step_seconds = Randomizer::get_instance().rand(0, gap_seconds);
return floor_date + seconds(step_seconds);
}
};
I would simply do this, which literally follows what your desired logic was:
df.groupby(['org']).mean().groupby(['cluster']).mean()
Its simply means that you have an array of values and you want record except that values/records.
you can simply pass a array into whereNotIn() laravel function.
With query builder
$users = DB::table('applications')
->whereNotIn('id', [1,3,5])
->get(); //will return without applications which contain this id's
With eloquent.
$result = ModelClassName::select('your_column_name')->whereNotIn('your_column_name', ['satatus1', 'satatus2']); //return without application which contain this status.
I tried almost all of the above options, but was not able to install google play services, however just found from the faq section of genymotion that the only way to access google play services is to use the packages provided by OpenGapps.
I tried and this worked:
formatDateTime(sDate,FormatType) {
var lDate = new Date(sDate)
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var hh = lDate.getHours() < 10 ? '0' +
lDate.getHours() : lDate.getHours();
var mi = lDate.getMinutes() < 10 ? '0' +
lDate.getMinutes() : lDate.getMinutes();
var ss = lDate.getSeconds() < 10 ? '0' +
lDate.getSeconds() : lDate.getSeconds();
var d = lDate.getDate();
var dd = d < 10 ? '0' + d : d;
var yyyy = lDate.getFullYear();
var mon = eval(lDate.getMonth()+1);
var mm = (mon<10?'0'+mon:mon);
var monthName=month[lDate.getMonth()];
var weekdayName=weekday[lDate.getDay()];
if(FormatType==1) {
return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi;
} else if(FormatType==2) {
return weekdayName+', '+monthName+' '+
dd +', ' + yyyy;
} else if(FormatType==3) {
return mm+'/'+dd+'/'+yyyy;
} else if(FormatType==4) {
var dd1 = lDate.getDate();
return dd1+'-'+Left(monthName,3)+'-'+yyyy;
} else if(FormatType==5) {
return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi+':'+ss;
} else if(FormatType == 6) {
return mon + '/' + d + '/' + yyyy + ' ' +
hh + ':' + mi + ':' + ss;
} else if(FormatType == 7) {
return dd + '-' + monthName.substring(0,3) +
'-' + yyyy + ' ' + hh + ':' + mi + ':' + ss;
}
}
You aren't building your formula right.
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = "=SUM(H5:H" & var1a & ")"
This does the same as the following lines do:
Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"
which is what you are trying to do.
Also, you want to have the =
at the beginning of the formala.
In Windows server 2012. Go to ISS -> Modules -> Remove the ServiceModel3-0.
I think you can use Step 1: Select text Step 2: Ctrl + Shift + P Step 3: Enter Uppercae
Use File.ReadAllText passing file location as an argument.
However, if your real goal is to parse html then I would recommend using Html Agility Pack.
For security reasons, your local drive is declared to be "other-domain" and will taint the canvas.
(That's because your most sensitive info is likely on your local drive!).
While testing try these workarounds:
Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders).
Post your images to a site that supports cross-domain sharing (like dropbox.com). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...)
Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).
You can just loop over your array:
var doc = { /* your json */ };
function getById(arr, id) {
for (var d = 0, len = arr.length; d < len; d += 1) {
if (arr[d].id === id) {
return arr[d];
}
}
}
var doc_id_2 = getById(doc.results, 2);
If you don't want to write this messy loops, you can consider using underscore.js or Lo-Dash (example in the latter):
var doc_id_2 = _.filter(doc.results, {id: 2})[0]
For Visual Studio users: Right click on the npm folder and "Restore Packages".
This function will return the caller's function name.
def func_name():
import traceback
return traceback.extract_stack(None, 2)[0][2]
It is like Albert Vonpupp's answer with a friendly wrapper.
Filestash is the perfect tool for that:
Also Filestash is open source. (Disclaimer: I am the author)
Note that some zip programs have trouble unzipping a CRX like sathish described - if this is the case, try using 7-Zip - http://www.7-zip.org/
Call startOf
before isoWeekday
.
var begin = moment(date).startOf('week').isoWeekday(1);
In Java 8, Arrays.parallelSetAll
seems ready made for this purpose:
import java.util.Arrays;
Arrays.parallelSetAll(array, (i) -> array[i].trim());
This will modify the original array in place, replacing each element with the result of the lambda expression.
I use this class to handle database.I hope it will help some one in future.
Happy coding.
public class Database {
private static class DBHelper extends SQLiteOpenHelper {
/**
* Database name
*/
private static final String DB_NAME = "db_name";
/**
* Table Names
*/
public static final String TABLE_CART = "DB_CART";
/**
* Cart Table Columns
*/
public static final String CART_ID_PK = "_id";// Primary key
public static final String CART_DISH_NAME = "dish_name";
public static final String CART_DISH_ID = "menu_item_id";
public static final String CART_DISH_QTY = "dish_qty";
public static final String CART_DISH_PRICE = "dish_price";
/**
* String to create reservation tabs table
*/
private final String CREATE_TABLE_CART = "CREATE TABLE IF NOT EXISTS "
+ TABLE_CART + " ( "
+ CART_ID_PK + " INTEGER PRIMARY KEY, "
+ CART_DISH_NAME + " TEXT , "
+ CART_DISH_ID + " TEXT , "
+ CART_DISH_QTY + " TEXT , "
+ CART_DISH_PRICE + " TEXT);";
public DBHelper(Context context) {
super(context, DB_NAME, null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_CART);
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CART);
onCreate(db);
}
}
/**
* CART handler
*/
public static class Cart {
/**
* Check if Cart is available or not
*
* @param context
* @return
*/
public static boolean isCartAvailable(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
boolean exists = false;
try {
String query = "SELECT * FROM " + DBHelper.TABLE_CART;
Cursor cursor = db.rawQuery(query, null);
exists = (cursor.getCount() > 0);
cursor.close();
db.close();
} catch (SQLiteException e) {
db.close();
}
return exists;
}
/**
* Insert values in cart table
*
* @param context
* @param dishName
* @param dishPrice
* @param dishQty
* @return
*/
public static boolean insertItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.CART_DISH_ID, "" + itemId);
values.put(DBHelper.CART_DISH_NAME, "" + dishName);
values.put(DBHelper.CART_DISH_PRICE, "" + dishPrice);
values.put(DBHelper.CART_DISH_QTY, "" + dishQty);
try {
db.insert(DBHelper.TABLE_CART, null, values);
db.close();
return true;
} catch (SQLiteException e) {
db.close();
return false;
}
}
/**
* Check for specific record by name
*
* @param context
* @param dishName
* @return
*/
public static boolean isItemAvailable(Context context, String dishName) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
boolean exists = false;
String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE "
+ DBHelper.CART_DISH_NAME + " = '" + String.valueOf(dishName) + "'";
try {
Cursor cursor = db.rawQuery(query, null);
exists = (cursor.getCount() > 0);
cursor.close();
} catch (SQLiteException e) {
e.printStackTrace();
db.close();
}
return exists;
}
/**
* Update cart item by item name
*
* @param context
* @param dishName
* @param dishPrice
* @param dishQty
* @return
*/
public static boolean updateItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.CART_DISH_ID, itemId);
values.put(DBHelper.CART_DISH_NAME, dishName);
values.put(DBHelper.CART_DISH_PRICE, dishPrice);
values.put(DBHelper.CART_DISH_QTY, dishQty);
try {
String[] args = new String[]{dishName};
db.update(DBHelper.TABLE_CART, values, DBHelper.CART_DISH_NAME + "=?", args);
db.close();
return true;
} catch (SQLiteException e) {
db.close();
return false;
}
}
/**
* Get cart list
*
* @param context
* @return
*/
public static ArrayList<CartModel> getCartList(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
ArrayList<CartModel> cartList = new ArrayList<>();
try {
String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";
Cursor cursor = db.rawQuery(query, null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
cartList.add(new CartModel(
cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_ID)),
cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_NAME)),
cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)),
Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE)))
));
}
db.close();
} catch (SQLiteException e) {
db.close();
}
return cartList;
}
/**
* Get total amount of cart items
*
* @param context
* @return
*/
public static String getTotalAmount(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
double totalAmount = 0.0;
try {
String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";
Cursor cursor = db.rawQuery(query, null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
totalAmount = totalAmount + Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE))) *
Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)));
}
db.close();
} catch (SQLiteException e) {
db.close();
}
if (totalAmount == 0.0)
return "";
else
return "" + totalAmount;
}
/**
* Get item quantity
*
* @param context
* @param dishName
* @return
*/
public static String getItemQty(Context context, String dishName) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = null;
String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE " + DBHelper.CART_DISH_NAME + " = '" + dishName + "';";
String quantity = "0";
try {
cursor = db.rawQuery(query, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
quantity = cursor.getString(cursor
.getColumnIndex(DBHelper.CART_DISH_QTY));
return quantity;
}
} catch (SQLiteException e) {
e.printStackTrace();
}
return quantity;
}
/**
* Delete cart item by name
*
* @param context
* @param dishName
*/
public static void deleteCartItem(Context context, String dishName) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
try {
String[] args = new String[]{dishName};
db.delete(DBHelper.TABLE_CART, DBHelper.CART_DISH_NAME + "=?", args);
db.close();
} catch (SQLiteException e) {
db.close();
e.printStackTrace();
}
}
}//End of cart class
/**
* Delete database table
*
* @param context
*/
public static void deleteCart(Context context) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
try {
db.execSQL("DELETE FROM " + DBHelper.TABLE_CART);
} catch (SQLiteException e) {
e.printStackTrace();
}
}
}
Usage:
if(Database.Cart.isCartAvailable(context)){
Database.deleteCart(context);
}
I got into this mess twice and after searching long and hard and following what others did absolutely nothing worked for me but to uninstall and install IIS back once on Windows 7 machine and then on Windows server 2012 R2.
Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);
it also provides some safety:
try{
std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
...
}
It seems to be this function
h_url=document.getElementById("u").value;
You can help yourself using some 'console.log' to see what object is Null.
To have greater control of the track color (no API
controlled alpha changes), I extended SwitchCompat
and style the elements programmatically:
public class CustomizedSwitch extends SwitchCompat {
public CustomizedSwitch(Context context) {
super(context);
initialize(context);
}
public CustomizedSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
public CustomizedSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context);
}
public void initialize(Context context) {
// DisplayMeasurementConverter is just a utility to convert from dp to px and vice versa
DisplayMeasurementConverter displayMeasurementConverter = new DisplayMeasurementConverter(context);
// Sets the width of the switch
this.setSwitchMinWidth(displayMeasurementConverter.dpToPx((int) getResources().getDimension(R.dimen.tp_toggle_width)));
// Setting up my colors
int mediumGreen = ContextCompat.getColor(context, R.color.medium_green);
int mediumGrey = ContextCompat.getColor(context, R.color.medium_grey);
int alphaMediumGreen = Color.argb(127, Color.red(mediumGreen), Color.green(mediumGreen), Color.blue(mediumGreen));
int alphaMediumGrey = Color.argb(127, Color.red(mediumGrey), Color.green(mediumGrey), Color.blue(mediumGrey));
// Sets the tints for the thumb in different states
DrawableCompat.setTintList(this.getThumbDrawable(), new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
mediumGreen,
ContextCompat.getColor(getContext(), R.color.light_grey)
}));
// Sets the tints for the track in different states
DrawableCompat.setTintList(this.getTrackDrawable(), new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
alphaMediumGreen,
alphaMediumGrey
}));
}
}
Whenever I want to use the CustomizedSwitch
, I just add one to my xml
file.
Use CURRENT_TIMESTAMP (or GETDATE() on archaic versions of SQL Server).
EDIT: An unofficial Bootstrap Modal modification has been built to address responsive/mobile issues. This is perhaps the simplest and easiest way to remedy the problem.
There has since been a fix found in one of the issues you discussed earlier
in bootstrap-responsive.css
.modal {
position: fixed;
top: 3%;
right: 3%;
left: 3%;
width: auto;
margin: 0;
}
.modal-body {
height: 60%;
}
and in bootstrap.css
.modal-body {
max-height: 350px;
padding: 15px;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson()
method.
For example:
class Response {
Map<String, App> descriptor;
// standard getters & setters...
}
class App {
String name;
int age;
String[] messages;
// standard getters & setters...
}
Then just use:
Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);
Where yourJson
can be a String
, any Reader
, a JsonReader
or a JsonElement
.
Finally, if you want to access any particular field, you just have to do:
String name = response.getDescriptor().get("app3").getName();
You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.
The snippet below does the job as expected!
<input type="text" name="AUS" pattern="[0-9]{10}" title="You can enter only 10 digits..." />
//type="text" <!-- always -->
//name="AUS" <!-- for Australia -->
//pattern="[0-9]{10}" <!-- 10 digits from 0 to 9 -->
//title="You can enter only 10 digits..." <!-- Pops a warning when input mismatches -->
The Javadoc generation can be skipped by setting the property maven.javadoc.skip
to true [1], i.e.
-Dmaven.javadoc.skip=true
(and not false)
I set it to automatically clean up on check-in, which is usually good enough for me. If something is too ugly, I'll just hit the shortcut (Ctrl-Alt-L, Return). And I see they have an option for auto-formatting pasted code, although I've never used that.
Also you can have the selected value using following code:
alert("Selected option value is: "+$('#SelectelementId').select2("val"));
probably not the way you are thinking. the iframe would have to <link>
in the css file too. AND you can't do it even with javascript if it's on a different domain.
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];
In your case, to fast-forward, run:
$ git merge --ff-only origin/master
This uses the --ff-only
option of git merge
, as the question specifically asks for "fast-forward".
Here is an excerpt from git-merge(1)
that shows more fast-forward options:
--ff, --no-ff, --ff-only
Specifies how a merge is handled when the merged-in history is already a descendant of the current history. --ff is the default unless merging an annotated
(and possibly signed) tag that is not stored in its natural place in the refs/tags/ hierarchy, in which case --no-ff is assumed.
With --ff, when possible resolve the merge as a fast-forward (only update the branch pointer to match the merged branch; do not create a merge commit). When
not possible (when the merged-in history is not a descendant of the current history), create a merge commit.
With --no-ff, create a merge commit in all cases, even when the merge could instead be resolved as a fast-forward.
With --ff-only, resolve the merge as a fast-forward when possible. When not possible, refuse to merge and exit with a non-zero status.
I fast-forward often enough that it warranted an alias:
$ git config --global alias.ff 'merge --ff-only @{upstream}'
Now I can run this to fast-forward:
$ git ff
Methods in other answers throw OverflowException
if the float value is outside the Int range. https://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_Single_
int result = 0;
try {
result = Convert.ToInt32(value);
}
catch (OverflowException) {
if (value > 0) result = int.MaxValue;
else result = int.Minvalue;
}
Just create a new DWORD(32) under the Fusion key. Name the DWORD to EnableLog, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.
You may do it by using following code:
var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);
To get mod_rewrite to work for me in Apache 2.4, I had to add the "Require all granted" line below.
<Directory /var/www>
# Required if running apache > 2.4
Require all granted
RewriteEngine on
RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L]
</Directory>
supposedly a similar requirement exists for Apache 2.2 as well, if you're using that:
<Directory /var/www>
# Required if running apache 2.2
Order allow,deny
Allow from all
RewriteEngine on
RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L]
</Directory>
Note that an ErrorDocument 404
directive can sometimes override these things as well, so if it's not working try commenting out your ErrorDocument directive and see if it works. The above example can be used to ensure a site isn't served from cache by including a subfolder in the path, though the files reside at the root of the server.
You can use either length property and length
is better on performance than size
.
$('#input1 option').length;
OR you can use size function like (removed in jQuery v3)
$('#input1 option').size();
$(document).ready(function(){
console.log($('#input1 option').size());
console.log($('#input1 option').length);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select data-attr="dropdown" id="input1">
<option value="Male" id="Male">Male</option>
<option value="Female" id="Female">Female</option>
</select>
_x000D_
print "Matched!\n" if ($str1 eq $str2)
Perl has seperate string comparison and numeric comparison operators to help with the loose typing in the language. You should read perlop for all the different operators.
I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )
Anyway, coming to the solution, this is what I was required to do:
su -
gedit /etc/phpMyAdmin/config.inc.php
if not found... try phpmyadmin - all small caps.
gedit /etc/phpmyadmin/config.inc.php
Locate
$cfg['Servers'][$i]['AllowNoPassword']
and set it to:
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
Save it.
Here is a solution using Microsoft's System.Text.Json library:
static string FormatJsonText(string jsonString)
{
using var doc = JsonDocument.Parse(
jsonString,
new JsonDocumentOptions
{
AllowTrailingCommas = true
}
);
MemoryStream memoryStream = new MemoryStream();
using (
var utf8JsonWriter = new Utf8JsonWriter(
memoryStream,
new JsonWriterOptions
{
Indented = true
}
)
)
{
doc.WriteTo(utf8JsonWriter);
}
return new System.Text.UTF8Encoding()
.GetString(memoryStream.ToArray());
}
If you're working in js on a server, just a little more gymnastics goes a long way... Here's my ppos (pretty-print-on-server):
ppos = (object, space = 2) => JSON.stringify(object, null, space).split('\n').forEach(s => console.log(s));
which does a bang-up job of creating something I can actually read when I'm writing server code.
The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:
cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012
UML Studio does this quite well in my experience, and will run in "freeware mode" for small projects.
Patrick's (accepted) answer is right: if not a:
is the right way to do it. Harley Holcombe's answer is right that this is in the PEP 8 style guide. But what none of the answers explain is why it's a good idea to follow the idiom—even if you personally find it's not explicit enough or confusing to Ruby users or whatever.
Python code, and the Python community, has very strong idioms. Following those idioms makes your code easier to read for anyone experienced in Python. And when you violate those idioms, that's a strong signal.
It's true that if not a:
doesn't distinguish empty lists from None
, or numeric 0, or empty tuples, or empty user-created collection types, or empty user-created not-quite-collection types, or single-element NumPy array acting as scalars with falsey values, etc. And sometimes it's important to be explicit about that. And in that case, you know what you want to be explicit about, so you can test for exactly that. For example, if not a and a is not None:
means "anything falsey except None", while if len(a) != 0:
means "only empty sequences—and anything besides a sequence is an error here", and so on. Besides testing for exactly what you want to test, this also signals to the reader that this test is important.
But when you don't have anything to be explicit about, anything other than if not a:
is misleading the reader. You're signaling something as important when it isn't. (You may also be making the code less flexible, or slower, or whatever, but that's all less important.) And if you habitually mislead the reader like this, then when you do need to make a distinction, it's going to pass unnoticed because you've been "crying wolf" all over your code.
if(!empty($youtube) && empty($link)) {
}
else if(empty($youtube) && !empty($link)) {
}
else if(empty($youtube) && empty($link)) {
}
In C and C++ you have these least requirements (i.e actual implementations can have larger magnitudes)
signed char: -2^07+1 to +2^07-1
short: -2^15+1 to +2^15-1
int: -2^15+1 to +2^15-1
long: -2^31+1 to +2^31-1
long long: -2^63+1 to +2^63-1
Now, on particular implementations, you have a variety of bit ranges. The wikipedia article describes this nicely.
Why does it implement its methods? How can it implement its methods when an interface can't contain method body? How can it implement the methods when it extends the other interface and not implement it? What is the purpose of an interface implementing another interface?
Interface does not implement the methods of another interface but just extends them.
One example where the interface extension is needed is: consider that you have a vehicle interface with two methods moveForward
and moveBack
but also you need to incorporate the Aircraft which is a vehicle but with some addition methods like moveUp
, moveDown
so
in the end you have:
public interface IVehicle {
bool moveForward(int x);
bool moveBack(int x);
};
and airplane:
public interface IAirplane extends IVehicle {
bool moveDown(int x);
bool moveUp(int x);
};
Try this as root (maybe you can use sudo
or su
):
/etc/init.d/postgresql restart
Without any argument the script also gives you a hint on how to restart a specific version
[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]
Similarly, in case you have it, you can also use the service
tool:
[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]
Please, pay attention to the optional [version ...]
trailing argument.
That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.
Finally, in case you are running systemd, then you can use systemctl
like this:
[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...
You can replace status
with stop
, start
or restart
as well as other actions. Please refer to the documentation for full details.
In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12
and reload v13
you can run:
systemctl stop postgresql-12.service
systemctl reload postgresql-13.service
Thanks to @Jojo for pointing me to this very one.
Finally Keep in mind that root
permissions may be needed for non-informative tasks as in the other cases seen earlier.
VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.
Here is how to install it:
C:\Windows
called MSJAVA.DLL
. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.SETUP.EXE
, select Run As Administrator
.C:\Program Files\Microsoft Visual Studio\VB98\
After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.
Edit: Updated dead link to point to a different page with the same instructions
Edit: Updated the answer with the actual instructions in the post as the link kept dying
This simple thing worked for me!
If it says it can't do 2 things at same time, separate them.
git branch branch_name origin/branch_name
git checkout branch_name
try this:
var result = from r in myDataTable.AsEnumerable()
where r.Field<string>("Name") != "n/a" &&
r.Field<string>("Name") != "" select r;
DataTable dtResult = result.CopyToDataTable();
Nice question/answers.
Just want to point out that C pointers and arrays are not the same, although in this case the difference is not essential.
Consider the following declarations:
int a[10];
int* p = a;
In a.out
, the symbol a
is at an address that's the beginning of the array, and symbol p
is at an address where a pointer is stored, and the value of the pointer at that memory location is the beginning of the array.
I ran into the same issue. This code sets the font size for the entire segmented control. Something similar might work for setting the font type. Note that this is only available for iOS5+
Obj C:
UIFont *font = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName];
[segmentedControl setTitleTextAttributes:attributes
forState:UIControlStateNormal];
EDIT: UITextAttributeFont
has been deprecated - use NSFontAttributeName
instead.
EDIT #2: For Swift 4 NSFontAttributeName
has been changed to NSAttributedStringKey.font
.
Swift 5:
let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
Swift 4:
let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: font],
for: .normal)
Swift 3:
let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font],
for: .normal)
Swift 2.2:
let font = UIFont.systemFontOfSize(16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font],
forState: UIControlState.Normal)
Thanks to the Swift implementations from @audrey-gordeev
HTML with JavaScript:
<p id="myid">My long long looooong text cut cut cut cut cut</p>
<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>
The result will be:
My long lo...
Cheers
G.
"MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format." This is from mysql site. You can store only this type, but you can use one of the many time format functions to change it, when you need to display it.
For example, one of those functions is the DATE_FORMAT, which can be used like so:
SELECT DATE_FORMAT(column_name, '%m/%d/%Y %H:%i') FROM tablename
Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:
int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;
for vectors, you just declare it and add elements
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...
at times you wont know the number of elements needed so a vector would be ideal for such a situation.
buildScript {
...
dependencies {
...
classpath 'com.android.tools.build:gradle:4.0.0-rc01'
}
}
...
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
Some libraries require the updated gradle. Such as:
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines"
GL
conda
is both a command line tool, and a python package.
Miniconda installer = Python + conda
Anaconda installer = Python + conda
+ meta package anaconda
meta Python pkg anaconda
= about 160 Python pkgs for daily use in data science
Anaconda installer = Miniconda installer + conda install anaconda
conda
is a python manager and an environment manager, which makes it possible to
conda install flake8
conda create -n myenv python=3.6
Miniconda installer = Python + conda
conda
, the package manager and environment manager, is a Python package. So Python is installed. Cause conda distribute Python interpreter with its own libraries/dependencies but not the existing ones on your operating system, other minimal dependencies like openssl
, ncurses
, sqlite
, etc are installed as well.
Basically, Miniconda is just conda
and its minimal dependencies. And the environment where conda
is installed is the "base" environment, which is previously called "root" environment.
Anaconda installer = Python + conda
+ meta package anaconda
meta Python package anaconda
= about 160 Python pkgs for daily use in data science
Meta packages, are packages that do NOT contain actual softwares and simply depend on other packages to be installed.
Download an anaconda
meta package from Anaconda Cloud and extract the content from it. The actual 160+ packages to be installed are listed in info/recipe/meta.yaml
.
package:
name: anaconda
version: '2019.07'
build:
ignore_run_exports:
- '*'
number: '0'
pin_depends: strict
string: py36_0
requirements:
build:
- python 3.6.8 haf84260_0
is_meta_pkg:
- true
run:
- alabaster 0.7.12 py36_0
- anaconda-client 1.7.2 py36_0
- anaconda-project 0.8.3 py_0
# ...
- beautifulsoup4 4.7.1 py36_1
# ...
- curl 7.65.2 ha441bb4_0
# ...
- hdf5 1.10.4 hfa1e0ec_0
# ...
- ipykernel 5.1.1 py36h39e3cac_0
- ipython 7.6.1 py36h39e3cac_0
- ipython_genutils 0.2.0 py36h241746c_0
- ipywidgets 7.5.0 py_0
# ...
- jupyter 1.0.0 py36_7
- jupyter_client 5.3.1 py_0
- jupyter_console 6.0.0 py36_0
- jupyter_core 4.5.0 py_0
- jupyterlab 1.0.2 py36hf63ae98_0
- jupyterlab_server 1.0.0 py_0
# ...
- matplotlib 3.1.0 py36h54f8f79_0
# ...
- mkl 2019.4 233
- mkl-service 2.0.2 py36h1de35cc_0
- mkl_fft 1.0.12 py36h5e564d8_0
- mkl_random 1.0.2 py36h27c97d8_0
# ...
- nltk 3.4.4 py36_0
# ...
- numpy 1.16.4 py36hacdab7b_0
- numpy-base 1.16.4 py36h6575580_0
- numpydoc 0.9.1 py_0
# ...
- pandas 0.24.2 py36h0a44026_0
- pandoc 2.2.3.2 0
# ...
- pillow 6.1.0 py36hb68e598_0
# ...
- pyqt 5.9.2 py36h655552a_2
# ...
- qt 5.9.7 h468cd18_1
- qtawesome 0.5.7 py36_1
- qtconsole 4.5.1 py_0
- qtpy 1.8.0 py_0
# ...
- requests 2.22.0 py36_0
# ...
- sphinx 2.1.2 py_0
- sphinxcontrib 1.0 py36_1
- sphinxcontrib-applehelp 1.0.1 py_0
- sphinxcontrib-devhelp 1.0.1 py_0
- sphinxcontrib-htmlhelp 1.0.2 py_0
- sphinxcontrib-jsmath 1.0.1 py_0
- sphinxcontrib-qthelp 1.0.2 py_0
- sphinxcontrib-serializinghtml 1.1.3 py_0
- sphinxcontrib-websupport 1.1.2 py_0
- spyder 3.3.6 py36_0
- spyder-kernels 0.5.1 py36_0
# ...
The pre-installed packages from meta pkg anaconda
are mainly for web scraping and data science. Like requests
, beautifulsoup
, numpy
, nltk
, etc.
If you have a Miniconda installed, conda install anaconda
will make it same as an Anaconda installation, except that the installation folder names are different.
Miniconda2 v.s. Miniconda. Anaconda2 v.s. Anaconda.
2
means the bundled Python interpreter for conda
in the "base" environment is Python 2, but not Python 3.
they are some needs i can't see to dome thing like Keith or Marcos Placona did instead of just doing
using System;
using System.Windows.Forms;
namespace WFsimulateMouseClick
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1_Click(button1, new MouseEventArgs(System.Windows.Forms.MouseButtons.Left, 1, 1, 1, 1));
//by the way
//button1.PerformClick();
// and
//button1_Click(button1, new EventArgs());
// are the same
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("clicked");
}
}
}
I use git from cygwin on Windows, the git apply
solution doesn't work for me. Here is my solution, run chmod
on every file to reset its permissions.
#!/bin/bash
IFS=$'\n'
for c in `git diff -p |sed -n '/diff --git/{N;s/diff --git//g;s/\n/ /g;s# a/.* b/##g;s/old mode //g;s/\(.*\) 100\(.*\)/chmod \2 \1/g;p}'`
do
eval $c
done
unset IFS
It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.
var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true
These errors are usually generated from an ad blocking plugin, such as Adblock Plus. To test this use either a different browser or uninstall the ad blocking plugin (right clicking the extension by the URL bar and clicking "Remove from Chrome...").
There is an easier way to temporarily disable an extension. In Chrome, opening an Incognito tab will usually stop extensions running (unless you have specifically told Chrome which ones to run in Incognito).
According to the latest doc you can do the following-
Add a day
moment().add(1, 'days').calendar();
Add Year
moment().add(1, 'years').calendar();
Add Month
moment().add(1, 'months').calendar();
Function imageMorph
will create a new img element therefore the id is removed.
Changed to
$("#wrapper > img")
You should use live() function for click event if you want you rocket lanch again.
Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/
This is here:
<button onClick="window.location='page_name.php';" value="click here" />
Here it is some code:
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();
See more examples in this article, you may need to take a look to impersonation.
Code snippet above provides incorrect byte order in string, so I fixed it a bit.
char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B','C','D','E','F'};
std::string byte_2_str(char* bytes, int size) {
std::string str;
for (int i = 0; i < size; ++i) {
const char ch = bytes[i];
str.append(&hex[(ch & 0xF0) >> 4], 1);
str.append(&hex[ch & 0xF], 1);
}
return str;
}
You don't need 2 style attributes - just use one:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
style="height:100px;width:100px;" alt="25"/>
Consider, however, using a CSS class instead:
CSS:
.100pxSquare
{
width: 100px;
height: 100px;
}
HTML:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
class="100pxSquare" alt="25"/>
On the (more general) question in title - to prevent Jenkins from failing you can prevent it from seeing exit code 1. Example for ping:
bash -c "ping 1.2.3.9999 -c 1; exit 0"
And now you can e.g. get output of ping:
output=`bash -c "ping 1.2.3.9999 -c 1; exit 0"`
Of course instead of ping ...
You can use any command(s) - including git commit
.
After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!
table.setDefaultEditor(Object.class, null);
I use this simple one: https://www.npmjs.com/package/csv-parser
Very simple to use:
const csv = require('csv-parser')
const fs = require('fs')
const results = [];
fs.createReadStream('./CSVs/Update 20191103C.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
console.log(results);
console.log(results[0]['Lowest Selling Price'])
});
Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two schemas instead - in that case you don't need anything special to query across them.
postgres_fdw
Use postgres_fdw
(foreign data wrapper) to connect to tables in any Postgres database - local or remote.
Note that there are foreign data wrappers for other popular data sources. At this time, only postgres_fdw
and file_fdw
are part of the official Postgres distribution.
Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called dblink
.
I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib.
If you set up a click binding in Knockout the event is passed as the second parameter. You can use the event to obtain the element that the click occurred on and perform whatever action you want.
Here is a fiddle that demonstrates: http://jsfiddle.net/jearles/xSKyR/
Alternatively, you could create your own custom binding, which will receive the element it is bound to as the first parameter. On init you could attach your own click event handler to do any actions you wish.
http://knockoutjs.com/documentation/custom-bindings.html
HTML
<div>
<button data-bind="click: clickMe">Click Me!</button>
</div>
Js
var ViewModel = function() {
var self = this;
self.clickMe = function(data,event) {
var target = event.target || event.srcElement;
if (target.nodeType == 3) // defeat Safari bug
target = target.parentNode;
target.parentNode.innerHTML = "something";
}
}
ko.applyBindings(new ViewModel());
You can find the codes in the DB2 Information Center. Here's a definition of the -302
from the z/OS Information Center:
THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE
On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW
, if it's negative, you'll look for SQLxxxxN
, where xxxx is the code you're looking up.
This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?
Much simpler: use sudo
to run a shell and use a heredoc to feed it commands.
#!/usr/bin/env bash
whoami
sudo -i -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
(answer originally on SuperUser)
You will need wrapper classes:
public class SomeIntInfo
{
[XmlAttribute]
public int Value { get; set; }
}
public class SomeStringInfo
{
[XmlAttribute]
public string Value { get; set; }
}
public class SomeModel
{
[XmlElement("SomeStringElementName")]
public SomeStringInfo SomeString { get; set; }
[XmlElement("SomeInfoElementName")]
public SomeIntInfo SomeInfo { get; set; }
}
or a more generic approach if you prefer:
public class SomeInfo<T>
{
[XmlAttribute]
public T Value { get; set; }
}
public class SomeModel
{
[XmlElement("SomeStringElementName")]
public SomeInfo<string> SomeString { get; set; }
[XmlElement("SomeInfoElementName")]
public SomeInfo<int> SomeInfo { get; set; }
}
And then:
class Program
{
static void Main()
{
var model = new SomeModel
{
SomeString = new SomeInfo<string> { Value = "testData" },
SomeInfo = new SomeInfo<int> { Value = 5 }
};
var serializer = new XmlSerializer(model.GetType());
serializer.Serialize(Console.Out, model);
}
}
will produce:
<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SomeStringElementName Value="testData" />
<SomeInfoElementName Value="5" />
</SomeModel>
When you are opening the project in the android studio instead of opening android directory open app directory
First find the version you are using for GIT.
using this command : git --version
if you have a newer version than 1.7.10.
Then simply use this this command.
Windows:
git config --global credential.helper wincred
MAC
git config --global credential.helper osxkeychain
I found that JavaScript can return a correct date when you use new Date(nYear, nMonth, nDate);
with the over days of that month.
Try to see the result of a dDate
variable when you use this:
var dDate = new Date(2012, 0, 34); // the result is 3 Feb 2012
I have a SkipDate function to share:
function DaysOfMonth(nYear, nMonth) {
switch (nMonth) {
case 0: // January
return 31; break;
case 1: // February
if ((nYear % 4) == 0) {
return 29;
}
else {
return 28;
};
break;
case 2: // March
return 31; break;
case 3: // April
return 30; break;
case 4: // May
return 31; break;
case 5: // June
return 30; break;
case 6: // July
return 31; break;
case 7: // August
return 31; break;
case 8: // September
return 30; break;
case 9: // October
return 31; break;
case 10: // November
return 30; break;
case 11: // December
return 31; break;
}
};
function SkipDate(dDate, skipDays) {
var nYear = dDate.getFullYear();
var nMonth = dDate.getMonth();
var nDate = dDate.getDate();
var remainDays = skipDays;
var dRunDate = dDate;
while (remainDays > 0) {
remainDays_month = DaysOfMonth(nYear, nMonth) - nDate;
if (remainDays > remainDays_month) {
remainDays = remainDays - remainDays_month - 1;
nDate = 1;
if (nMonth < 11) { nMonth = nMonth + 1; }
else {
nMonth = 0;
nYear = nYear + 1;
};
}
else {
nDate = nDate + remainDays;
remainDays = 0;
};
dRunDate = Date(nYear, nMonth, nDate);
}
return new Date(nYear, nMonth, nDate);
};
According to the docs numpy.loadtxt
is
a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.
so there are only a few options to handle more complicated files.
As mentioned numpy.genfromtxt
has more options. So as an example you could use
import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['x', 'y', 'z'])
to read the data and assign names to the columns (or read a header line from the file with names=True
) and than plot it with
ax1.plot(data['x'], data['y'], color='r', label='the data')
I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython
or by using an IDE like spider
if you prefer to read them rendered as HTML.
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle
I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.
A double quote character ("
) can be escaped as "
, but here's the rest of the story...
In XML attributes delimited by double quotes:
<EscapeNeeded name="Pete "Maverick" Mitchell"/>
In XML textual content:
<NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
In XML attributes delimited by single quotes ('
):
<NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
Similarly, ('
) require no escaping if ("
) are used for the attribute value delimiters:
<NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
You can simply use "findViewHolderForAdapterPosition" method of recycler view and you will get a viewHolder object from that then typecast that viewholder into your adapter viewholder so you can directly access your viewholder's views
following is the sample code for kotlin
val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
val textview=(viewHolder as YourViewHolder).yourTextView
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
Are you specifically trying to rotate the links only? Because doing it on the LI tags seems to work fine.
According to Snook transforms require the elements affected be block. He's also got some code there to make this work for IE using filters, if you care to add it on(though there appears to be some limitation on values).
Mockito is not a DI framework and even DI frameworks encourage constructor injections over field injections.
So you just declare a constructor to set dependencies of the class under test :
@Mock
private SomeService serviceMock;
private Demo demo;
/* ... */
@BeforeEach
public void beforeEach(){
demo = new Demo(serviceMock);
}
Using Mockito spy
for the general case is a terrible advise. It makes the test class brittle, not straight and error prone : What is really mocked ? What is really tested ?
@InjectMocks
and @Spy
also hurts the overall design since it encourages bloated classes and mixed responsibilities in the classes.
Please read the spy()
javadoc before using that blindly (emphasis is not mine) :
Creates a spy of the real object. The spy calls real methods unless they are stubbed. Real spies should be used carefully and occasionally, for example when dealing with legacy code.
As usual you are going to read the
partial mock warning
: Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.
See my jsFiddle here: http://jsfiddle.net/fuDBL/
Whenever you change the email field, the link is updated automatically. This requires a small amount of jQuery. So now your form will work as needed, but your link will be updated dynamically so that when someone clicks on it, it contains what they entered in the email field. You should validate the input on the receiving page.
$('input[name="email"]').change(function(){
$('#regLink').attr('href')+$('input[name="email"]').val();
});
Currently experienced this problem with my Nexus 5, when attempting to sideload latest 4.4.1 OTA update via stock recovery.
Solution:
You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-
If you can produce a small demo showing the onMouseEnter / onMouseLeave or onMouseDown / onMouseUp bug, it would be worthwhile to post it to ReactJS's issues page or mailing list, just to raise the question and hear what the developers have to say about it.
In your use case, you seem to imply that CSS :hover and :active states would be enough for your purposes, so I suggest you use them. CSS is orders of magnitude faster and more reliable than Javascript, because it's directly implemented in the browser.
However, :hover and :active states cannot be specified in inline styles. What you can do is assign an ID or a class name to your elements and write your styles either in a stylesheet, if they are somewhat constant in your application, or in a dynamically generated <style>
tag.
Here's an example of the latter technique: https://jsfiddle.net/ors1vos9/
To read the files from src/resources folder then try this :
DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg"));
public static File getFileHandle(String fileName){
return new File(YourClassName.class.getClassLoader().getResource(fileName).getFile());
}
in case of non static reference:
return new File(getClass().getClassLoader().getResource(fileName).getFile());
I had this issue when I added react-router-dom
to the new CRA app using typescript. After I added @types/react-router
, the issue was fixed.
Update: this answer works with both ,Visual Sudio 2017 and 2019
For me it worked by the following three steps:
Adding Report viewer control by:
Going to NuGet Package Manager.
Installing Microsoft.ReportingServices.ReportViewerControl.Winforms
For WebForms applications:
Adding Report viewer control by:
Going to NuGet Package Manager.
Installing Microsoft.ReportingServices.ReportViewerControl.WebForms
That's all!
You need to retrieve and disect the information into what you need.
while($row = mysql_fetch_array($result)) {
echo "img src='",$row['filename'],"' width='175' height='200' />";
}
These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.
Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.
Local Storage does the same thing, but persists even when the browser is closed and reopened.
You can set and retrieve stored data as follows:
sessionStorage.setItem('key', 'value');
var data = sessionStorage.getItem('key');
Similarly for localStorage.
In Servlet do:
String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);
Then in JSP do:
<select name="roleName">
<c:forEach items="${roleNames}" var="role">
<option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
</c:forEach>
</select>
It will print the selected
attribute of the HTML <option>
element so that you end up like:
<select name="roleName">
<option value="cat">cat</option>
<option value="rat" selected>rat</option>
<option value="unicorn">unicorn</option>
</select>
Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.
You can try: .order_by(ClientTotal.id.desc())
session = Session()
auth_client_name = 'client3'
result_by_auth_client = session.query(ClientTotal).filter(ClientTotal.client ==
auth_client_name).order_by(ClientTotal.id.desc()).all()
for rbac in result_by_auth_client:
print(rbac.id)
session.close()
public void Empty(System.IO.DirectoryInfo directory)
{
try
{
logger.DebugFormat("Empty directory {0}", directory.FullName);
foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
catch (Exception ex)
{
ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture));
throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex);
}
}
The "{{ ... }}"-delimiter can also be used within strings:
"http://{{ app.request.host }}"
you could use ⊕ or ⊗
First use:
yarn application -list
Note down the application id Then to kill use:
yarn application -kill application_id
It looks like a 32/64 bit mismatch. The ldd output shows that mainly libraries from /lib64
are chosen. That would indicate that you have installed a 64 bit version of the Oracle client and have created a 64 bit executable. But libaio.so
is probably a 32 bit library and cannot be used for your application.
So you either need a 64 bit version of libaio or you create a 32 bit version of your application.
One approach is to strip object and functions from main object. And stringify the simpler form
function simpleStringify (object){
var simpleObject = {};
for (var prop in object ){
if (!object.hasOwnProperty(prop)){
continue;
}
if (typeof(object[prop]) == 'object'){
continue;
}
if (typeof(object[prop]) == 'function'){
continue;
}
simpleObject[prop] = object[prop];
}
return JSON.stringify(simpleObject); // returns cleaned up JSON
};
You can't, and you shouldn't. That's what polymorphism is for, so that each object has its own way of doing some "base" things.
2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine
exec getlist 47,1,0
create procedure getlist
@convId int,
@SortOrder int,
@contestantsOnly bit = 0
as
Web API works very nicely if you accept the fact that you are using HTTP. It's when you start trying to pretend that you are sending objects over the wire that it starts to get messy.
public class TextController : ApiController
{
public HttpResponseMessage Post(HttpRequestMessage request) {
var someText = request.Content.ReadAsStringAsync().Result;
return new HttpResponseMessage() {Content = new StringContent(someText)};
}
}
This controller will handle a HTTP request, read a string out of the payload and return that string back.
You can use HttpClient to call it by passing an instance of StringContent. StringContent will be default use text/plain as the media type. Which is exactly what you are trying to pass.
[Fact]
public void PostAString()
{
var client = new HttpClient();
var content = new StringContent("Some text");
var response = client.PostAsync("http://oak:9999/api/text", content).Result;
Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);
}
After finding this StackOverflow question/answer
Complex type is getting null in a ApiController parameter
the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.
I think you set the marquee width related to 5 images total width. It works fine
ex: <marquee style="width:700px"></marquee>
Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.
NB - You need to do this first on a test copy of your table!
When I did it, I found that unless I also included AND n1.id <> n2.id
, it deleted every row in the table.
If you want to keep the row with the lowest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
If you want to keep the row with the highest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
I used this method in MySQL 5.1
Not sure about other versions.
Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE
, please be advised that using INSERT
and DISTINCT
is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE
, it took more than 2 hours and yet didn't complete.
INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
SELECT DISTINCT cellId,attributeId,entityRowId,value
FROM tableName;
Use
System.getProperty("java.class.path")
see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
You can also split it into it's elements easily
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2:
data<- rbind(c(480, 780, 431, 295, 670, 360, 190),
c(720, 350, 377, 255, 340, 615, 345),
c(460, 480, 179, 560, 60, 735, 1260),
c(220, 240, 876, 789, 820, 100, 75))
a <- cbind(data[, 1], 1, c(1:4))
b <- cbind(data[, 2], 2, c(1:4))
c <- cbind(data[, 3], 3, c(1:4))
d <- cbind(data[, 4], 4, c(1:4))
e <- cbind(data[, 5], 5, c(1:4))
f <- cbind(data[, 6], 6, c(1:4))
g <- cbind(data[, 7], 7, c(1:4))
data <- as.data.frame(rbind(a, b, c, d, e, f, g))
colnames(data) <-c("Time", "Type", "Group")
data$Type <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))
library(ggplot2)
ggplot(data = data, aes(x = Type, y = Time, fill = Group)) +
geom_bar(stat = "identity") +
opts(legend.position = "none")
Did you try this?
UPDATE table
SET col1 = NULL
WHERE col1 = ''
As the commenters point out, you don't have to do ltrim()
or rtrim()
, and NULL
columns will not match ''
.
You can use the .not() method:
$(".content_box a").not(".button")
Alternatively, you can also use the :not() selector:
$(".content_box a:not('.button')")
There is little difference between the two approaches, except .not()
is more readable (especially when chained) and :not()
is very marginally faster. See this Stack Overflow answer for more info on the differences.
Create a class like this:
public class Data
{
public string Id {get; set;}
public string Name {get; set;}
public string First_Name {get; set;}
public string Last_Name {get; set;}
public string Username {get; set;}
public string Gender {get; set;}
public string Locale {get; set;}
}
(I'm not 100% sure, but if that doesn't work you'll need use [DataContract]
and [DataMember]
for DataContractJsonSerializer
.)
Then create JSonSerializer
:
private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));
and deserialize object:
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
(Data)Serializer.ReadObject(stream);
}
You can also use .$delete:
remove (index) {
this.$delete(this.finds, index)
}
sources:
This is the RegKey I used:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"DisableUNCCheck"=dword:00000001
I improve Sai Sunder answer because OP uses ID which allows to avoid getElementById:
elementId.remove();
box2.remove(); // remove BOX 2_x000D_
_x000D_
this["box-3"].remove(); // remove BOX 3 (for Id with 'minus' character)
_x000D_
<div id="box1">My BOX 1</div>_x000D_
<div id="box2">My BOX 2</div>_x000D_
<div id="box-3">My BOX 3</div>_x000D_
<div id="box4">My BOX 4</div>
_x000D_
Yes, the first means "match all strings that start with a letter", the second means "match all strings that contain a non-letter". The caret ("^") is used in two different ways, one to signal the start of the text, one to negate a character match inside square brackets.
json_decode() is used to decode a json string to an array/data object. json_encode() creates a json string from an array or data. You are using the wrong function my friend, try json_encode();
'Ctrl + m' works for Windows in the Android emulator to bring up the React-Native developer menu.
Couldn't find that documented anywhere. Found my way here, guessed the rest... Good grief.
By the way: OP: You didn't mention what OS you were on.
you can write a hoc for this purpose and write a method call redirect, here is the code:
import React, {useState} from 'react';
import {Redirect} from "react-router-dom";
const RedirectHoc = (WrappedComponent) => () => {
const [routName, setRoutName] = useState("");
const redirect = (to) => {
setRoutName(to);
};
if (routName) {
return <Redirect to={"/" + routName}/>
}
return (
<>
<WrappedComponent redirect={redirect}/>
</>
);
};
export default RedirectHoc;
I usually put all my files like that into an "assets" folder in the application root, and then I make sure to use an Asset_Helper to point to those files for me. This is what CodeIgniter suggests.
There is a CocoaPods to facilitate the observation on NSNotificationCentr
for the keyboard's visibility here: https://github.com/levantAJ/Keyhi
pod 'Keyhi'
If you can convert .xls to .csv before processing, you can use the query below to import the csv to the database:
load data local infile 'FILE.CSV' into table TABLENAME fields terminated by ',' enclosed by '"' lines terminated by '\n' (FIELD1,FIELD2,FIELD3)
I'd use the accepted answer, but another possibility is to use a table variable to hold a numbered set of values (in this case just the ID field of a table) and loop through those by Row Number with a JOIN to the table to retrieve whatever you need for the action within the loop.
DECLARE @RowCnt int; SET @RowCnt = 0 -- Loop Counter
-- Use a table variable to hold numbered rows containg MyTable's ID values
DECLARE @tblLoop TABLE (RowNum int IDENTITY (1, 1) Primary key NOT NULL,
ID INT )
INSERT INTO @tblLoop (ID) SELECT ID FROM MyTable
-- Vars to use within the loop
DECLARE @Code NVarChar(10); DECLARE @Name NVarChar(100);
WHILE @RowCnt < (SELECT COUNT(RowNum) FROM @tblLoop)
BEGIN
SET @RowCnt = @RowCnt + 1
-- Do what you want here with the data stored in tblLoop for the given RowNum
SELECT @Code=Code, @Name=LongName
FROM MyTable INNER JOIN @tblLoop tL on MyTable.ID=tL.ID
WHERE tl.RowNum=@RowCnt
PRINT Convert(NVarChar(10),@RowCnt) +' '+ @Code +' '+ @Name
END
It works fine. I tested it like this:
String command = @"C:\Doit.bat";
ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
// ProcessInfo.CreateNoWindow = true;
I commented out turning off the window so I could SEE it run.
Server.UrlEncode() is there to provide backward compatibility with Classic ASP,
Server.UrlEncode(str);
Is equivalent to:
HttpUtility.UrlEncode(str, Response.ContentEncoding);
It is important to note the following difference between the two techniques:
$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT
From this you can see that the string.split()
method:
While the -split
operator:
Bass can do just this. Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play as soon as you have enough data to start the playback..
You can use this: http://vikku.info/codesnippets/javascript/print-div-content-print-only-the-content-of-an-html-element-and-not-the-whole-document/
Or use visibility:visible
and visibility:hidden
css property together with @media print{}
'display:none' will hide all nested 'display:block'. That is not solution.
I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.
Bootstrap requires a specific file structure to work. I see from your code you have this:
<link href="bootstrap.css" rel="stylesheet" media="screen">
Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.
But first, let me recommend you setup your folder structure like so:
/css <-- Bootstrap.css here
/fonts <-- Bootstrap fonts here
/img
/js <-- Bootstrap JavaScript here
index.html
If you notice, this is also how Bootstrap structures its files in its download ZIP.
You then include your Bootstrap file like so:
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">
Depending on your server structure or what you're going for.
The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).
The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.
So, why do this?
Bootstrap.css has this specific line for Glyphfonts:
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
What you can see is that that Glyphfonts are loaded by going up one directory ../
and then looking for a folder called /fonts
and THEN loading the font file.
The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:
/fonts
Bootstrap.css
index.html
The CSS file is going one level deeper than looking for a /fonts
folder.
So, let's say the actual location of these files are:
C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html
The CSS file would technically be looking for a folder at:
C:\fonts
but your folder is actually in:
C:\www\fonts
So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.
When you get that fixed, your HTML should simply be:
<span class="glyphicon glyphicon-comment"></span>
Note, you need both classes. The first class glyphicon
sets up the basic styles while glyphicon-comment
sets the specific image.
decimal RoundTotal = Total - (int)Total;
if ((double)RoundTotal <= .50)
Total = (int)Total;
else
Total = (int)Total + 1;
lblTotal.Text = Total.ToString();
You can add an event listener with 'ended' as first param
Like this :
<video src="video.ogv" id="myVideo">
video not supported
</video>
<script type='text/javascript'>
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler(e) {
// What you want to do after the event
}
</script>
mysqli_error()
As in:
$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);
Trigger error is better than die because you can use it for development AND production, it's the permanent solution.
Use the CSS :overflow
property
.noscroll {
width: 150px;
height: 150px;
overflow: auto; /* Or hidden, or visible */
}
Here are some more examples:
I put my version of Singleton below:
public class SingletonDemo {
private static SingletonDemo instance = null;
private static Context context;
/**
* To initialize the class. It must be called before call the method getInstance()
* @param ctx The Context used
*/
public static void initialize(Context ctx) {
context = ctx;
}
/**
* Check if the class has been initialized
* @return true if the class has been initialized
* false Otherwise
*/
public static boolean hasBeenInitialized() {
return context != null;
}
/**
* The private constructor. Here you can use the context to initialize your variables.
*/
private SingletonDemo() {
// Use context to initialize the variables.
}
/**
* The main method used to get the instance
*/
public static synchronized SingletonDemo getInstance() {
if (context == null) {
throw new IllegalArgumentException("Impossible to get the instance. This class must be initialized before");
}
if (instance == null) {
instance = new SingletonDemo();
}
return instance;
}
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Clone is not allowed.");
}
}
Note that the method initialize could be called in the main class(Splash) and the method getInstance could be called from other classes. This will fix the problem when the caller class requires the singleton but it does not have the context.
Finally the method hasBeenInitialized is uses to check if the class has been initialized. This will avoid that different instances have different contexts.
using System;
using System.Threading;
using System.Threading.Tasks;
...
var cts = new CancellationTokenSource();
var task = Task.Run(() => { while (true) { } });
Parallel.Invoke(() =>
{
task.Wait(cts.Token);
}, () =>
{
Thread.Sleep(1000);
cts.Cancel();
});
This is a simple snippet to abort a never-ending task with CancellationTokenSource.
I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect
call. For example,
con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
connect_timeout=1000)
Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.
For detail about different arguments that you can pass to _mysql.connect
, see MySQLdb API documentation
I've decided to post a new answer, because some existing answers are outdated or incomplete.
First of all: there is nothing like JUnit XML Format Specification
, simply because JUnit doesn't produce any kind of XML or HTML report.
The XML report generation itself comes from the Ant JUnit task/ Maven Surefire Plugin/ Gradle (whichever you use for running your tests). The XML report format was first introduced by Ant and later adapted by Maven (and Gradle).
If somebody just needs an official XML format then:
Hope it will help somebody.
Just complementing Hovercraft Full Of Eels's solution:
I reworked his code, tweaked it a bit, adding a grid, axis labels and now the Y-axis goes from the minimum value present up to the maximum value. I planned on adding a couple of getters/setters but I didn't need them, you can add them if you want.
Here is the Gist link, I'll also paste the code below: GraphPanel on Gist
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GraphPanel extends JPanel {
private int width = 800;
private int heigth = 400;
private int padding = 25;
private int labelPadding = 25;
private Color lineColor = new Color(44, 102, 230, 180);
private Color pointColor = new Color(100, 100, 100, 180);
private Color gridColor = new Color(200, 200, 200, 200);
private static final Stroke GRAPH_STROKE = new BasicStroke(2f);
private int pointWidth = 4;
private int numberYDivisions = 10;
private List<Double> scores;
public GraphPanel(List<Double> scores) {
this.scores = scores;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1);
double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore());
List<Point> graphPoints = new ArrayList<>();
for (int i = 0; i < scores.size(); i++) {
int x1 = (int) (i * xScale + padding + labelPadding);
int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding);
graphPoints.add(new Point(x1, y1));
}
// draw white background
g2.setColor(Color.WHITE);
g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding);
g2.setColor(Color.BLACK);
// create hatch marks and grid lines for y axis.
for (int i = 0; i < numberYDivisions + 1; i++) {
int x0 = padding + labelPadding;
int x1 = pointWidth + padding + labelPadding;
int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding);
int y1 = y0;
if (scores.size() > 0) {
g2.setColor(gridColor);
g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1);
g2.setColor(Color.BLACK);
String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + "";
FontMetrics metrics = g2.getFontMetrics();
int labelWidth = metrics.stringWidth(yLabel);
g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
}
g2.drawLine(x0, y0, x1, y1);
}
// and for x axis
for (int i = 0; i < scores.size(); i++) {
if (scores.size() > 1) {
int x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding;
int x1 = x0;
int y0 = getHeight() - padding - labelPadding;
int y1 = y0 - pointWidth;
if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) {
g2.setColor(gridColor);
g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding);
g2.setColor(Color.BLACK);
String xLabel = i + "";
FontMetrics metrics = g2.getFontMetrics();
int labelWidth = metrics.stringWidth(xLabel);
g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
}
g2.drawLine(x0, y0, x1, y1);
}
}
// create x and y axes
g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding);
g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding);
Stroke oldStroke = g2.getStroke();
g2.setColor(lineColor);
g2.setStroke(GRAPH_STROKE);
for (int i = 0; i < graphPoints.size() - 1; i++) {
int x1 = graphPoints.get(i).x;
int y1 = graphPoints.get(i).y;
int x2 = graphPoints.get(i + 1).x;
int y2 = graphPoints.get(i + 1).y;
g2.drawLine(x1, y1, x2, y2);
}
g2.setStroke(oldStroke);
g2.setColor(pointColor);
for (int i = 0; i < graphPoints.size(); i++) {
int x = graphPoints.get(i).x - pointWidth / 2;
int y = graphPoints.get(i).y - pointWidth / 2;
int ovalW = pointWidth;
int ovalH = pointWidth;
g2.fillOval(x, y, ovalW, ovalH);
}
}
// @Override
// public Dimension getPreferredSize() {
// return new Dimension(width, heigth);
// }
private double getMinScore() {
double minScore = Double.MAX_VALUE;
for (Double score : scores) {
minScore = Math.min(minScore, score);
}
return minScore;
}
private double getMaxScore() {
double maxScore = Double.MIN_VALUE;
for (Double score : scores) {
maxScore = Math.max(maxScore, score);
}
return maxScore;
}
public void setScores(List<Double> scores) {
this.scores = scores;
invalidate();
this.repaint();
}
public List<Double> getScores() {
return scores;
}
private static void createAndShowGui() {
List<Double> scores = new ArrayList<>();
Random random = new Random();
int maxDataPoints = 40;
int maxScore = 10;
for (int i = 0; i < maxDataPoints; i++) {
scores.add((double) random.nextDouble() * maxScore);
// scores.add((double) i);
}
GraphPanel mainPanel = new GraphPanel(scores);
mainPanel.setPreferredSize(new Dimension(800, 600));
JFrame frame = new JFrame("DrawGraph");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
It looks like this:
The top voted answer is right and simplest. However, sometimes you may find that not working for some font, but working for others.(Which problem I just came across when dealing with Chinese.)
Solution is do not use "WRAP_CONTENT" only for your TextView, cause there is no extra space for drawing the line. You may set fixed height to your TextView, or use android:paddingVertical with WRAP_CONTENT.
Another option that enforces exact matching (i.e. no partial matching) would be:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
You can read more about the Match method and its arguments at http://msdn.microsoft.com/en-us/library/office/ff835873(v=office.15).aspx
With PostgreSQL 8.4 or newer there is no need to specify the WITH 1
anymore. The start value that was recorded by CREATE SEQUENCE
or last set by ALTER SEQUENCE START WITH
will be used (most probably this will be 1).
Reset the sequence:
ALTER SEQUENCE seq RESTART;
Then update the table's ID column:
UPDATE foo SET id = DEFAULT;
Source: PostgreSQL Docs
You may be running out of space either in the partition where the mysql tables are stored (usually /var/lib/mysql) or in where the temporary tables are stored (usually /tmp).
You may want to: - monitor your free space during the index creation. - point the tmpdir MySQL variable to a different location. This requires a server restart.