After watching the answers and checking the recommendations, I end up having no clue what was going wrong.
I literally tried everything. So if you end up in the same situation, understand that the issue might be something else, completely irrelevant from swagger.
In my case was a OData
exception.
Here's the procedure:
1) Navigate to the localhost:xxxx/swagger
2) Open Developer tools
3) Click on the error shown in the console and you will see the inner exception that is causing the issue.
Here is how I did this.
I see that in some answers they are setting app.UserCors("xxxPloicy")
and putting [EnableCors("xxxPloicy")]
in controllers. You do not need to do both.
Here are the steps.
In Startup.cs inside the ConfigureServices add the following code.
services.AddCors(c=>c.AddPolicy("xxxPolicy",builder => {
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
If you want to apply all over the project then add the following code in Configure method in Startup.cs
app.UseCors("xxxPolicy");
Or
If you want to add it to the specific controllers then add enable cors code as shown below.
[EnableCors("xxxPolicy")]
[Route("api/[controller]")]
[ApiController]
public class TutorialController : ControllerBase {}
For more info: see this
I believe this can be solved by adding a project reference to Microsoft.EntityFrameworkCore.SqlServer.Design
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.SqlServer wasn't directly installed in my project, but the .Design package will install it anyway as a prerequisite.
To break down the error message:
Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.
That is saying that your application is trying to create an instance of BlogController
but it doesn't know how to create an instance of BloggerRepository
to pass into the constructor.
Now look at your startup:
services.AddScoped<IBloggerRepository, BloggerRepository>();
That is saying whenever a IBloggerRepository
is required, create a BloggerRepository
and pass that in.
However, your controller class is asking for the concrete class BloggerRepository
and the dependency injection container doesn't know what to do when asked for that directly.
I'm guessing you just made a typo, but a fairly common one. So the simple fix is to change your controller to accept something that the DI container does know how to process, in this case, the interface:
public BlogController(IBloggerRepository repository)
// ^
// Add this!
{
_repository = repository;
}
For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.
Example python implementation:
import sys
inner_loop = 0
def collatz_sequence(N, cache):
global inner_loop
l = [ ]
stop = False
n = N
tails = [ ]
while not stop:
inner_loop += 1
tmp = n
l.append(n)
if n <= 1:
stop = True
elif n in cache:
stop = True
elif n % 2:
n = 3*n + 1
else:
n = n // 2
tails.append((tmp, len(l)))
for key, offset in tails:
if not key in cache:
cache[key] = l[offset:]
return l
def gen_sequence(l, cache):
for elem in l:
yield elem
if elem in cache:
yield from gen_sequence(cache[elem], cache)
raise StopIteration
if __name__ == "__main__":
le_cache = {}
for n in range(1, 4711, 5):
l = collatz_sequence(n, le_cache)
print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))
print("inner_loop = {}".format(inner_loop))
I have to read own parameters by startup.
That has to be there before the WebHost is started (as I need the “to listen” url/IP and port from the parameter file and apply it to the WebHost). Further, I need the settings public in the whole application.
After searching for a while (no complete example found, only snippets) and after various try-and-error's, I have decided to do it the “old way" with an own .ini file.
So.. if you want to use your own .ini file and/or set the "to listen url/IP" your own and/or need the settings public, this is for you...
Complete example, valid for core 2.1 (mvc):
Create an .ini-file - example:
[Startup]
URL=http://172.16.1.201:22222
[Parameter]
*Dummy1=gew7623
Dummy1=true
Dummy2=1
whereby the Dummyx are only included as example for other date types than string (and also to test the case “wrong param” (see code below).
Added a code file in the root of the project, to store the global variables:
namespace MatrixGuide
{
public static class GV
{
// In this class all gobals are defined
static string _cURL;
public static string cURL // URL (IP + Port) on that the application has to listen
{
get { return _cURL; }
set { _cURL = value; }
}
static bool _bdummy1;
public static bool bdummy1 //
{
get { return _bdummy1; }
set { _bdummy1 = value; }
}
static int _idummy1;
public static int idummy1 //
{
get { return _idummy1; }
set { _idummy1 = value; }
}
static bool _bFehler_Ini;
public static bool bFehler_Ini //
{
get { return _bFehler_Ini; }
set { _bFehler_Ini = value; }
}
// add further GV variables here..
}
// Add further classes here...
}
Changed the code in program.cs (before CreateWebHostBuilder()):
namespace MatrixGuide
{
public class Program
{
public static void Main(string[] args)
{
// Read .ini file and overtake the contend in globale
// Do it in an try-catch to be able to react to errors
GV.bFehler_Ini = false;
try
{
var iniconfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddIniFile("matrixGuide.ini", optional: false, reloadOnChange: true)
.Build();
string cURL = iniconfig.GetValue<string>("Startup:URL");
bool bdummy1 = iniconfig.GetValue<bool>("Parameter:Dummy1");
int idummy2 = iniconfig.GetValue<int>("Parameter:Dummy2");
//
GV.cURL = cURL;
GV.bdummy1 = bdummy1;
GV.idummy1 = idummy2;
}
catch (Exception e)
{
GV.bFehler_Ini = true;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("!! Fehler beim Lesen von MatrixGuide.ini !!");
Console.WriteLine("Message:" + e.Message);
if (!(e.InnerException != null))
{
Console.WriteLine("InnerException: " + e.InnerException.ToString());
}
Console.ForegroundColor = ConsoleColor.White;
}
// End .ini file processing
//
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>() //;
.UseUrls(GV.cURL, "http://localhost:5000"); // set the to use URL from .ini -> no impact to IISExpress
}
}
This way:
To Configure exception handling behavior per exception type you can use Middleware from NuGet packages:
ASP.NET Core 2.0
ASP.NET Core 2.1+
. Code sample:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddExceptionHandlingPolicies(options =>
{
options.For<InitializationException>().Rethrow();
options.For<SomeTransientException>().Retry(ro => ro.MaxRetryCount = 2).NextPolicy();
options.For<SomeBadRequestException>()
.Response(e => 400)
.Headers((h, e) => h["X-MyCustomHeader"] = e.Message)
.WithBody((req,sw, exception) =>
{
byte[] array = Encoding.UTF8.GetBytes(exception.ToString());
return sw.WriteAsync(array, 0, array.Length);
})
.NextPolicy();
// Ensure that all exception types are handled by adding handler for generic exception at the end.
options.For<Exception>()
.Log(lo =>
{
lo.EventIdFactory = (c, e) => new EventId(123, "UnhandlerException");
lo.Category = (context, exception) => "MyCategory";
})
.Response(null, ResponseAlreadyStartedBehaviour.GoToNextHandler)
.ClearCacheHeaders()
.WithObjectResult((r, e) => new { msg = e.Message, path = r.Path })
.Handled();
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseExceptionHandlingPolicies();
app.UseMvc();
}
If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
The error message says your DbContext
(LogManagerContext
) needs a constructor which accepts a DbContextOptions
. But i couldn't find such a constructor in your DbContext
. So adding below constructor probably solves your problem.
public LogManagerContext(DbContextOptions options) : base(options)
{
}
Edit for comment
If you don't register IHttpContextAccessor
explicitly, use below code:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
All you need is width:100%
somewhere that applies to the tag as shown by the various answers here.
Using col-xs-12:
<!-- adds float:left, which is usually not a problem -->
<img class='img-responsive col-xs-12' />
Or inline CSS:
<img class='img-responsive' style='width:100%;' />
Or, in your own CSS file, add an additional definition for .img-responsive
.img-responsive {
width:100%;
}
THE ROOT OF THE PROBLEM
This is a known FF bug that <fieldset>
does not respect overflow rules:
https://bugzilla.mozilla.org/show_bug.cgi?id=261037
A CSS "FIX" to fix the FireFox bug would be to make the <fieldset>
display:table-column
. However, doing so, according to the following link, will cause the display of the fieldset to fail in Opera:
https://github.com/TryGhost/Ghost/issues/789
So, just set your tag to 100% width as described in one of the solutions above.
Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR
The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.
For example:
{ "things": ["a", "b", "c"] }
Would Unmarshal into a:
type Item struct {
Things []string
}
And not into:
type Item struct {
Things string
}
The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int
or float
field -- "1"
needs to Unmarshal into a string
, not into an int
like we saw with ShippingAdditionalCost int
Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).
If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel
public class ThisViewModel : ViewModelBase
{
TypeOfAncestorViewModel Parent { get; set; }
}
and bind against that directly instead.
<TextBox Text="{Binding Parent}" />
Two things. First, you must base64 decode the mykey.pem
file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey
ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec
, which is based on the SubjectPublicKeyInfo
ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
// ...
String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);
in my case, when I added Fragment I git this error.
When I opened THe app build.gradle
I saw id("kotlin-android")
this plugin in plugins.
just remove it!
import React from 'react'
import SvgUri from 'react-native-svg-uri';
export default function Splash() {
return (
<View style={styles.container}>
{/* provided the svg file is stored locally */}
<SvgUri
width="400"
height="200"
source={require('./logo.svg')}
/>
{/* if the svg is online */}
<SvgUri
width="200"
height="200"
source={{ uri: 'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg' }}
/>
<Text style={styles.logoText}>
Text
</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
logoText: {
fontSize: 50
}
});
Use:
SELECT oi.orderid,
SUM(oi.quantity * p.price) AS grand_total,
FROM ORDERITEM oi
JOIN PRODUCT p ON p.id = oi.productid
WHERE oi.orderid = @OrderId
GROUP BY oi.orderid
Mind that if either oi.quantity
or p.price
is null, the SUM will return NULL.
This is because the original A activity is already being destroyed by the time you start it from B, C or D. Therefore, onCreate will be called in stead of onNewIntent(). One way of solving this is to always destroy the existing A(using FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_NEW_TASK conjunction when startActivity) before starting a new A, so onCreate will always be called, and you put the code of onNewIntent() into onCreate by checking if getIntent() is the intent you started with.
Well, it's fairly simple to do.
On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.
Here's the code:
private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
{
myCanvas.Width = e.NewSize.Width;
myCanvas.Height = e.NewSize.Height;
double xChange = 1, yChange = 1;
if (e.PreviousSize.Width != 0)
xChange = (e.NewSize.Width/e.PreviousSize.Width);
if (e.PreviousSize.Height != 0)
yChange = (e.NewSize.Height / e.PreviousSize.Height);
foreach (FrameworkElement fe in myCanvas.Children )
{
/*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */
if (fe is Grid == false)
{
fe.Height = fe.ActualHeight * yChange;
fe.Width = fe.ActualWidth * xChange;
Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);
}
}
}
*<tr><a href="javascript:void(0);" class="remove">X</a></tr>*
<script type='text/javascript'>
$("table").on('click', '.remove', function () {
$(this).parent().parent('tr').remove();
});
localhost
will always redirect to 127.0.0.1
. You can trick this by naming your other VirtualHost to other local loop-back address, such as 127.0.0.2
. Make sure you also change the corresponding hosts
file to implement this.
For example, my httpd-vhosts.conf
looks like this:
<VirtualHost 127.0.0.2:80>
DocumentRoot "D:/6. App Data/XAMPP Shared/htdocs/intranet"
ServerName intranet.dev
ServerAlias www.intranet.dev
ErrorLog "logs/intranet.dev-error.log"
CustomLog "logs/intranet.dec-access.log" combined
<Directory "D:/6. App Data/XAMPP Shared/htdocs/intranet">
Options Indexes FollowSymLinks ExecCGI Includes
Order allow,deny
Allow from all
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
(Notice that in <VirtualHost>
section I typed 127.0.0.2:80
. It means that this block of VirtualHost will only affects requests to IP address 127.0.0.2
port 80
, which is the default port for HTTP.
To route the name intranet.dev
properly, my hosts
entry line is like this:
127.0.0.2 intranet.dev
This way, it will prevent you from creating another VirtualHost block for localhost
, which is unnecessary.
On Windows, downloading Node's MSI again and doing a 'Repair' worked for me.
Documentation is quite clear: https://docs.python.org/2/library/json.html
json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.
So load
is for a file, loads
for a string
I had same problem but later found adding any new interface and corresponding class requires it to be registered under Initializable Module for dependency injection. In my case it was inside code as follows:
[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class DependencyResolverInitialization : IConfigurableModule
{
public void ConfigureContainer(ServiceConfigurationContext context)
{
context.Container.Configure(ConfigureContainer);
var structureMapDependencyResolver = new StructureMapDependencyResolver(context.Container);
DependencyResolver.SetResolver(structureMapDependencyResolver);
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), structureMapDependencyResolver);
}
private void ConfigureContainer(ConfigurationExpression container)
{
container.For<IAppSettingService>().Use<AppSettingService>();
container.For<ISiteSettingService>().Use<SiteSettingService>();
container.For<IBreadcrumbBuilder>().Use<BreadcrumbBuilder>();
container.For<IFilterContentService>().Use<FilterContentService>().Singleton();
container.For<IDependecyFactoryResolver>().Use<DependecyFactoryResolver>();
container.For<IUserService>().Use<UserService>();
container.For<IGalleryVmFactory>().Use<GalleryVmFactory>();
container.For<ILanguageService>().Use<LanguageService>();
container.For<ILanguageBranchRepository>().Use<LanguageBranchRepository>();
container.For<ICacheService>().Use<CacheService>();
container.For<ISearchService>().Use<SearchService>();
container.For<IReflectionService>().Use<ReflectionService>();
container.For<ILocalizationService>().Use<LocalizationService>();
container.For<IBookingFormService>().Use<BookingFormService>();
container.For<IGeoService>().Use<GeoService>();
container.For<ILocationService>().Use<LocationService>();
RegisterEnterpriseAPIClient(container);
}
public void Initialize(InitializationEngine context)
{
}
public void Uninitialize(InitializationEngine context)
{
}
public void Preload(string[] parameters)
{
}
}
}
There are multiple ways of doing this, but if you’d prefer php
, I’d recommend the use of the header()
function.
Basically
$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();
If you want to kick it up a notch, it’s best to use it in functions. That way, you are able to add authentications and other checking elemnts in it.
Let’s try with by checking the user’s level.
So, suppose you have stored the user’s authority level in a session called u_auth
.
In the function.php
<?php
function authRedirect($get_auth_level,
$required_level,
$if_fail_link = “www.example.com/index.php”){
if ($get_auth_level != $required_level){
header(location : $if_fail_link);
return false;
exit();
}
else{
return true;
}
}
. . .
You’ll then call the function for every page that you want to authenticate.
Like in page.php
or any other page.
<?php
// page.php
require “function.php”
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 5
authRedirect($_SESSION[‘u_auth’], 5);
// Redirects to www.example.com/index.php if the
// user isn’t authentication level 4
authRedirect($_SESSION[‘u_auth’], 4);
// Redirects to www.someotherplace.com/somepage.php if the
// user isn’t authentication level 2
authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);
. . .
References;
You need to attach the Form1_Load
handler to the Load
event:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
Chart mych = new Chart();
mych.Height = 100;
mych.Width = 100;
mych.BackColor = SystemColors.Highlight;
mych.Series.Add("duck");
mych.Series["duck"].SetDefault(true);
mych.Series["duck"].Enabled = true;
mych.Visible = true;
for (int q = 0; q < 10; q++)
{
int first = rnd.Next(0, 10);
int second = rnd.Next(0, 10);
mych.Series["duck"].Points.AddXY(first, second);
Debug.WriteLine(first + " " + second);
}
Controls.Add(mych);
}
}
}
With the Apache 2 change KeepAliveTimeout
set it to 60 or above
And now something completely different...
Instead of using css tricks don't forget about solutions as simple as html entities:
▲
Result:
▲
Just another approach
function parseTimestamp(timestampStr) {_x000D_
return new Date(new Date(timestampStr).getTime() + (new Date(timestampStr).getTimezoneOffset() * 60 * 1000));_x000D_
};_x000D_
_x000D_
//Sun Jan 01 2017 12:00:00_x000D_
var timestamp = 1483272000000;_x000D_
date = parseTimestamp(timestamp);_x000D_
document.write(date);
_x000D_
Cheers!
I also was importing the wrong Entity import org.hibernate.annotations.Entity;
It should be import javax.persistence.Entity;
Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:
https://codepen.io/trusktr/pen/mdeQbKG?editors=0010
This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):
const winHtml = `<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Window with Blob</title>_x000D_
</head>_x000D_
<body>_x000D_
<h1>Hello from the new window!</h1>_x000D_
</body>_x000D_
</html>`;_x000D_
_x000D_
const winUrl = URL.createObjectURL(_x000D_
new Blob([winHtml], { type: "text/html" })_x000D_
);_x000D_
_x000D_
const win = window.open(_x000D_
winUrl,_x000D_
"win",_x000D_
`width=800,height=400,screenX=200,screenY=200`_x000D_
);
_x000D_
In the case of no repeats and no order, the following EqualityComparer can be used to allow collections as dictionary keys:
public class SetComparer<T> : IEqualityComparer<IEnumerable<T>>
where T:IComparable<T>
{
public bool Equals(IEnumerable<T> first, IEnumerable<T> second)
{
if (first == second)
return true;
if ((first == null) || (second == null))
return false;
return first.ToHashSet().SetEquals(second);
}
public int GetHashCode(IEnumerable<T> enumerable)
{
int hash = 17;
foreach (T val in enumerable.OrderBy(x => x))
hash = hash * 23 + val.GetHashCode();
return hash;
}
}
Here is the ToHashSet() implementation I used. The hash code algorithm comes from Effective Java (by way of Jon Skeet).
How I typically do it:
function name(arg1, arg2){
var args = arguments; // array: [arg1, arg2]
var objecArgOne = args[0].one;
}
name({one: "1", two: "2"}, "string");
You can even ref the args by the functions name like:
name.arguments;
Hope this helps!
Also, take a look at FrameLayout
, that's how the Camera's Gallery application implements the Zoom buttons overlay.
When having Typescript >= 2 the "lib" option in tsconfig.json will do the job. No need for Typings. https://www.typescriptlang.org/docs/handbook/compiler-options.html
{
"compilerOptions": {
"target": "es5",
"lib": ["es2016", "dom"] //or es6 instead of es2016(es7)
}
}
I know this isn't a 'replacement' WebBrowser control, but I was having some awful rendering issues whilst showing a page that was using BootStrap 3+ for layout etc, and then I found a post that suggested I use the following. Apparently, it's specific to IE and tells it to use the latest variation found on the client machine for rendering (so it won't use IE7, which I believe is the default).
So just put:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
somewhere in the head part of your document.
Obviously, if it's not your document, this won't help - though I personally consider it to be a security hole if you're reading pages not created by yourself through the WebBrowser control - why not just use a web browser!
You're not including the standard <string>
header.
You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<<
was not.
Use the -L
option to follow redirects:
curl -L https://github.com/pinard/Pymacs/tarball/v0.24-beta2 | tar zx
It seems impossible to prevent spinners from appearing in Opera. As a temporary workaround, you can make room for the spinners. As far as I can tell, the following CSS adds just enough padding, only in Opera:
noindex:-o-prefocus,
input[type=number] {
padding-right: 1.2em;
}
One thing you could change in your code very easily is the fontsize
you are using for the titles. However, I am going to assume that you don't just want to do that!
Some alternatives to using fig.subplots_adjust(top=0.85)
:
Usually tight_layout()
does a pretty good job at positioning everything in good locations so that they don't overlap. The reason tight_layout()
doesn't help in this case is because tight_layout()
does not take fig.suptitle() into account. There is an open issue about this on GitHub: https://github.com/matplotlib/matplotlib/issues/829 [closed in 2014 due to requiring a full geometry manager - shifted to https://github.com/matplotlib/matplotlib/issues/1109 ].
If you read the thread, there is a solution to your problem involving GridSpec
. The key is to leave some space at the top of the figure when calling tight_layout
, using the rect
kwarg. For your problem, the code becomes:
Using GridSpec
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure(1)
gs1 = gridspec.GridSpec(1, 2)
ax_list = [fig.add_subplot(ss) for ss in gs1]
ax_list[0].plot(f)
ax_list[0].set_title('Very Long Title 1', fontsize=20)
ax_list[1].plot(g)
ax_list[1].set_title('Very Long Title 2', fontsize=20)
fig.suptitle('Long Suptitle', fontsize=24)
gs1.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
plt.show()
The result:
Maybe GridSpec
is a bit overkill for you, or your real problem will involve many more subplots on a much larger canvas, or other complications. A simple hack is to just use annotate()
and lock the coordinates to the 'figure fraction'
to imitate a suptitle
. You may need to make some finer adjustments once you take a look at the output, though. Note that this second solution does not use tight_layout()
.
Simpler solution (though may need to be fine-tuned)
fig = plt.figure(2)
ax1 = plt.subplot(121)
ax1.plot(f)
ax1.set_title('Very Long Title 1', fontsize=20)
ax2 = plt.subplot(122)
ax2.plot(g)
ax2.set_title('Very Long Title 2', fontsize=20)
# fig.suptitle('Long Suptitle', fontsize=24)
# Instead, do a hack by annotating the first axes with the desired
# string and set the positioning to 'figure fraction'.
fig.get_axes()[0].annotate('Long Suptitle', (0.5, 0.95),
xycoords='figure fraction', ha='center',
fontsize=24
)
plt.show()
The result:
[Using Python
2.7.3 (64-bit) and matplotlib
1.2.0]
Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.
I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.
If you just want the content to scroll, you could leave out the part that limits the size of the modal body.
/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
margin: 2.5vh auto;
}
/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
max-height: 95vh;
overflow: scroll;
}
/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
max-height: 69vh;
}
try With this --- worked for me in Xcode-beta 4 7.0
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
Also one more option, if you want to disable ATS you can use this :
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
But this is not recommended at all. The server should have the SSL certificates and so that there is no privacy leaks.
Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.
HTML sample:
<body>
<ul class="nav-tabs">
<li><a id="btn-tab-business" class="btn-tab nav-tab-selected" onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
<li><a id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
<li><a id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
CSS sample:
.nav-tabs{
position: relative;
padding-bottom: 50px;
}
.nav-tabs li {
display: inline-block;
position: absolute;
list-style: none;
}
.nav-tabs li:first-child{
top: 0px;
left: 0px;
}
.nav-tabs li:last-child{
top: 0px;
right: 0px;
}
.nav-tabs li:nth-child(2){
top: 0px;
left: 50%;
transform: translate(-50%, 0%);
}
Two answers, both valid, depending on how sloppy you like to be:
1) No, it's not currently possible to inject audio into a phone conversation.
2) Yes, it's possible. It's also an ugly, ugly kludge. Turn on the hands free function of your phone. Create a media player, set the media source, set the volume to 1.0f (highest) and call player.start()
. If the microphone and speakers on the phone are of reasonable quality, the other party to the call will hear the music. He or she will also continue to hear anything you say, as well as ambient and other sounds in your immediate vicinity.
Instead of using -c, just pipe it to wc -l.
grep string * | wc -l
This will list each occurrence on a single line and then count the number of lines.
This will miss instances where the string occurs 2+ times on one line, though.
It's a useful convention for naming controls on a form (btnOK, txtLastName etc.), if the list of controls shows up in an alphabetized pull-down list in your IDE.
I think that this should work:
.element {
-webkit-transition: all .3s;
-moz-transition: all .3s;
-o-transition: all .3s;
transition: all .3s;
}
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array
, then it becomes a generic object.
This error occurs because the port, which is allocated for Apache, is used by another program. To check the application which uses the port, which we allocated for Apache, it can be had by clicking,
Netstat button.
This is the Netstat file,
At first, I have allocated port 8080 for Apache, and I recently installed Oracle DB.TNSLSNR.exe has used 8080 port now.
So, by looking at this file we can choose a port which is not clashing with other applications. In my case, port 8060 is not clashing with any application. By selecting that we can change the httpd.conf file (XAMPP control panel -> Config) as mentioned above.
One of the scenarios I found useful to use CTE is when you want to get DISTINCT rows of data based on one or more columns but return all columns in the table. With a standard query you might first have to dump the distinct values into a temp table and then try to join them back to the original table to retrieve the rest of the columns or you might write an extremely complex partition query that can return the results in one run but in most likelihood, it will be unreadable and cause performance issue.
But by using CTE (as answered by Tim Schmelter on Select the first instance of a record)
WITH CTE AS(
SELECT myTable.*
, RN = ROW_NUMBER()OVER(PARTITION BY patientID ORDER BY ID)
FROM myTable
)
SELECT * FROM CTE
WHERE RN = 1
As you can see, this is much easier to read and maintain. And in comparison to other queries, is much better at performance.
git config --global core.askpass
Run this first before cloning the same way, should be fixed!
Very simple, after defining args variable by 'args = parser.parse_args()' it contains all data of args subset variables too. To check if a variable is set or no assuming the 'action="store_true" is used...
if args.argument_name:
# do something
else:
# do something else
a) the method/function only reads the array argument => implicit (internal) reference
b) the method/function modifies the array argument => value
c) the method/function array argument is explicitly marked as a reference (with an ampersand) => explicit (user-land) reference
Or this:
- non-ampersand array param: passed by reference; the writing operations alter a new copy of the array, copy which is created on the first write;
- ampersand array param: passed by reference; the writing operations alter the original array.
Remember - PHP does a value-copy the moment you write to the non-ampersand array param. That's what copy-on-write
means. I'd love to show you the C source of this behaviour, but it's scary in there. Better use xdebug_debug_zval().
Pascal MARTIN was right. Kosta Kontos was even more so.
It depends.
I think I'm writing this down for myself. I should have a blog or something...
Whenever people talk of references (or pointers, for that matter), they usually end up in a logomachy (just look at this thread!).
PHP being a venerable language, I thought I should add up to the confusion (even though this a summary of the above answers). Because, although two people can be right at the same time, you're better off just cracking their heads together into one answer.
First off, you should know that you're not a pedant if you don't answer in a black-and-white manner. Things are more complicated than "yes/no".
As you will see, the whole by-value/by-reference thing is very much related to what exactly are you doing with that array in your method/function scope: reading it or modifying it?
The manual says this (emphasis mine):
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition
As far as I can tell, when big, serious, honest-to-God programmers talk about references, they usually talk about altering the value of that reference. And that's exactly what the manual talks about: hey, if you want to CHANGE the value in a function, consider that PHP's doing "pass-by-value"
.
There's another case that they don't mention, though: what if I don't change anything - just read?
What if you pass an array to a method which doesn't explicitly marks a reference, and we don't change that array in the function scope? E.g.:
<?php
function readAndDoStuffWithAnArray($array)
{
return $array[0] + $array[1] + $array[2];
}
$x = array(1, 2, 3);
echo readAndDoStuffWithAnArray($x);
Read on, my fellow traveller.
The same big and serious programmers, when they get even more serious, they talk about "memory optimizations" in regards to references. So does PHP. Because PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting
, that's why.
It wouldn't be ideal to pass HUGE arrays to various functions, and PHP to make copies of them (that's what "pass-by-value" does, after all):
<?php
// filling an array with 10000 elements of int 1
// let's say it grabs 3 mb from your RAM
$x = array_fill(0, 10000, 1);
// pass by value, right? RIGHT?
function readArray($arr) { // <-- a new symbol (variable) gets created here
echo count($arr); // let's just read the array
}
readArray($x);
Well now, if this actually was pass-by-value, we'd have some 3mb+ RAM gone, because there are two copies of that array, right?
Wrong. As long as we don't change the $arr
variable, that's a reference, memory-wise. You just don't see it. That's why PHP mentions user-land references when talking about &$someVar
, to distinguish between internal and explicit (with ampersand) ones.
So, when an array is passed as an argument to a method or function is it passed by reference?
I came up with three (yeah, three) cases:
a) the method/function only reads the array argument
b) the method/function modifies the array argument
c) the method/function array argument is explicitly marked as a reference (with an ampersand)
Firstly, let's see how much memory that array actually eats (run here):
<?php
$start_memory = memory_get_usage();
$x = array_fill(0, 10000, 1);
echo memory_get_usage() - $start_memory; // 1331840
That many bytes. Great.
Now let's make a function which only reads the said array as an argument and we'll see how much memory the reading logic takes:
<?php
function printUsedMemory($arr)
{
$start_memory = memory_get_usage();
count($arr); // read
$x = $arr[0]; // read (+ minor assignment)
$arr[0] - $arr[1]; // read
echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}
$x = array_fill(0, 10000, 1); // this is 1331840 bytes
printUsedMemory($x);
Wanna guess? I get 80! See for yourself. This is the part that the PHP manual omits. If the $arr
param was actually passed-by-value, you'd see something similar to 1331840
bytes. It seems that $arr
behaves like a reference, doesn't it? That's because it is a references - an internal one.
Now, let's write to that param, instead of reading from it:
<?php
function printUsedMemory($arr)
{
$start_memory = memory_get_usage();
$arr[0] = 1; // WRITE!
echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}
$x = array_fill(0, 10000, 1);
printUsedMemory($x);
Again, see for yourself, but, for me, that's pretty close to being 1331840. So in this case, the array is actually being copied to $arr
.
Now let's see how much memory a write operation to an explicit reference takes (run here) - note the ampersand in the function signature:
<?php
function printUsedMemory(&$arr) // <----- explicit, user-land, pass-by-reference
{
$start_memory = memory_get_usage();
$arr[0] = 1; // WRITE!
echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}
$x = array_fill(0, 10000, 1);
printUsedMemory($x);
My bet is that you get 200 max! So this eats approximately as much memory as reading from a non-ampersand param.
This is a very fast way. No external libaries needed.
final protected static char[] HEXARRAY = "0123456789abcdef".toCharArray();
public static String encodeHexString( byte[] bytes ) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEXARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEXARRAY[v & 0x0F];
}
return new String(hexChars);
}
Here's a simple way.
/**
* Add css to the document
* @param {string} css
*/
function addCssToDocument(css){
var style = document.createElement('style')
style.innerText = css
document.head.appendChild(style)
}
Changing between timezones
import pytz
from datetime import datetime
other_tz = pytz.timezone('Europe/Madrid')
# From random aware datetime...
aware_datetime = datetime.utcnow().astimezone(other_tz)
>> 2020-05-21 08:28:26.984948+02:00
# 1. Change aware datetime to UTC and remove tzinfo to obtain an unaware datetime
unaware_datetime = aware_datetime.astimezone(pytz.UTC).replace(tzinfo=None)
>> 2020-05-21 06:28:26.984948
# 2. Set tzinfo to UTC directly on an unaware datetime to obtain an utc aware datetime
aware_datetime_utc = unaware_datetime.replace(tzinfo=pytz.UTC)
>> 2020-05-21 06:28:26.984948+00:00
# 3. Convert the aware utc datetime into another timezone
reconverted_aware_datetime = aware_datetime_utc.astimezone(other_tz)
>> 2020-05-21 08:28:26.984948+02:00
# Initial Aware Datetime and Reconverted Aware Datetime are equal
print(aware_datetime1 == aware_datetime2)
>> True
Well, I faced a similar problem but on unit tests.
Using SharpTestsEx you can check if a property existis. I use this testing my controllers, because since the JSON object is dynamic, someone can change the name and forget to change it in the javascript or something, so testing for all properties when writing the controller should increase my safety.
Example:
dynamic testedObject = new ExpandoObject();
testedObject.MyName = "I am a testing object";
Now, using SharTestsEx:
Executing.This(delegate {var unused = testedObject.MyName; }).Should().NotThrow();
Executing.This(delegate {var unused = testedObject.NotExistingProperty; }).Should().Throw();
Using this, i test all existing properties using "Should().NotThrow()".
It's probably out of topic, but can be usefull for someone.
For positive integers as arguments and where argument order doesn't matter:
Here's an unordered pairing function:
<x, y> = x * y + trunc((|x - y| - 1)^2 / 4) = <y, x>
For x ? y, here's a unique unordered pairing function:
<x, y> = if x < y:
x * (y - 1) + trunc((y - x - 2)^2 / 4)
if x > y:
(x - 1) * y + trunc((x - y - 2)^2 / 4)
= <y, x>
Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int mWidthScreen = display.getWidth();
int mHeightScreen = display.getHeight();
Here is a hopefully helpful pointer, in a code example. Note how the initializer function is only called once.
Also, if you invert the calls to StaticClass::initializeStStateArr()
and $st = new StaticClass()
you'll get the same result.
$ cat static.php
<?php
class StaticClass {
public static $stStateArr = NULL;
public function __construct() {
if (!isset(self::$stStateArr)) {
self::initializeStStateArr();
}
}
public static function initializeStStateArr() {
if (!isset(self::$stStateArr)) {
self::$stStateArr = array('CA' => 'California', 'CO' => 'Colorado',);
echo "In " . __FUNCTION__. "\n";
}
}
}
print "Starting...\n";
StaticClass::initializeStStateArr();
$st = new StaticClass();
print_r (StaticClass::$stStateArr);
Which yields :
$ php static.php
Starting...
In initializeStStateArr
Array
(
[CA] => California
[CO] => Colorado
)
I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.
$('#txtbox').on('paste', function (e) {
var $this = $(this);
setTimeout(function (e) {
if (($this.val()).match(/[^0-9]/g))
{
$("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");
setTimeout(function (e) {
$this.val(null);
},2500);
}
}, 5);
});
In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.
General form of with:
with open(“file name”, “mode”) as file-var:
processing statements
note: no need to close the file by calling close() upon file-var.close()
with UnionTable as
(
SELECT a.id, a.time FROM dbo.a
UNION
SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id
using include 'page1.php'
in second page is one option but it can generate warnings and errors of undefined variables.
Three methods by which you can use variables of one php file in another php file:
use session to pass variable from one page to another
method:
first you have to start the session in both the files using php command
sesssion_start();
then in first file consider you have one variable
$x='var1';now assign value of $x to a session variable using this:
$_SESSION['var']=$x;
now getting value in any another php file:
$y=$_SESSION['var'];//$y is any declared variable
using get method and getting variables on clicking a link
method
<a href="page2.php?variable1=value1&variable2=value2">clickme</a>
getting values in page2.php file by $_GET function:$x=$_GET['variable1'];//value1 be stored in $x
$y=$_GET['variable2'];//vale2 be stored in $y
if you want to pass variable value using button then u can use it by following method:
$x='value1'
<input type="submit" name='btn1' value='.$x.'/>
in second php$var=$_POST['btn1'];
This,
public enum MySingleton {
INSTANCE;
}
has an implicit empty constructor. Make it explicit instead,
public enum MySingleton {
INSTANCE;
private MySingleton() {
System.out.println("Here");
}
}
If you then added another class with a main()
method like
public static void main(String[] args) {
System.out.println(MySingleton.INSTANCE);
}
You would see
Here
INSTANCE
enum
fields are compile time constants, but they are instances of their enum
type. And, they're constructed when the enum type is referenced for the first time.
The <f:viewParam>
manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>
, but then for GET parameters.
The following example
<f:metadata>
<f:viewParam name="id" value="#{bean.id}" />
</f:metadata>
does basically the following:
id
.required
, validator
and converter
attributes and nest a <f:converter>
and <f:validator>
in it like as with <h:inputText>
)#{bean.id}
value, or if the value
attribute is absent, then set it as request attribtue on name id
so that it's available by #{id}
in the view.So when you open the page as foo.xhtml?id=10
then the parameter value 10
get set in the bean this way, right before the view is rendered.
As to validation, the following example sets the param to required="true"
and allows only values between 10 and 20. Any validation failure will result in a message being displayed.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
</f:metadata>
<h:message for="id" />
You can use the <f:viewAction>
for this.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />
with
public void onload() {
// ...
}
The <f:viewAction>
is however new since JSF 2.2 (the <f:viewParam>
already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event>
instead.
<f:event type="preRenderView" listener="#{bean.onload}" />
This is however invoked on every request. You need to explicitly check if the request isn't a postback:
public void onload() {
if (!FacesContext.getCurrentInstance().isPostback()) {
// ...
}
}
When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:
public void onload() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
// ...
}
}
Using <f:event>
this way is in essence a workaround/hack, that's exactly why the <f:viewAction>
was introduced in JSF 2.2.
You can "pass-through" the view parameters in navigation links by setting includeViewParams
attribute to true
or by adding includeViewParams=true
request parameter.
<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">
which generates with the above <f:metadata>
example basically the following link
<a href="next.xhtml?id=10">
with the original parameter value.
This approach only requires that next.xhtml
has also a <f:viewParam>
on the very same parameter, otherwise it won't be passed through.
The <f:viewParam>
can also be used in combination with "plain HTML" GET forms.
<f:metadata>
<f:viewParam id="query" name="query" value="#{bean.query}" />
<f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
<label for="query">Query</label>
<input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
<input type="submit" value="Search" />
<h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
...
</h:dataTable>
With basically this @RequestScoped
bean:
private String query;
private List<Result> results;
public void search() {
results = service.search(query);
}
Note that the <h:message>
is for the <f:viewParam>
, not the plain HTML <input type="text">
! Also note that the input value displays #{param.query}
when #{bean.query}
is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).
var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World
That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.
Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:
alert($("<p>Hello, <b>World</b></p>").text());
Check out the text method.
I would suggest you to try
https://spark.apache.org/docs/latest/sql-programming-guide.html#rdds
JavaRDD<Person> people = sc.textFile("examples/src/main/resources/people.txt").map(
new Function<String, Person>() {
public Person call(String line) throws Exception {
String[] parts = line.split(",");
Person person = new Person();
person.setName(parts[0]);
person.setAge(Integer.parseInt(parts[1].trim()));
return person;
}
});
You have to have a class in this example person with the spec of your file header and associate your data to the schema and apply criteria like in mysql.. to get desired result
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
Update your connection string as shown below (without port
variable as well):
MysqlConn.ConnectionString = "Server=127.0.0.1;Database=patholabs;Uid=pankaj;Pwd=master;"
Hope this helps...
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
You can change style directly for scene using .root
class:
.root {
-fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}
Add this to CSS and load it as "Uluk Biy" described in his answer.
According to the above,i found three ways to solve the problem.
AnotherMongoDocument._id.toString()
JSON.stringify(AnotherMongoDocument._id)
results.userId.equals(AnotherMongoDocument._id)
if you are having dependency on some other project in work space and these projects are not build properly, such error might come. try building such dependent projects first, it may help
Strings are a great example of uses of double pointers. The string itself is a pointer, so any time you need to point to a string, you'll need a double pointer.
var time = "9:09:59AM"
var pmCheck =time.includes("PM");
var hrs=parseInt(time.split(":")[0]);
var newtime='';
// this is for between 12 AM to 12:59:59AM = 00:00:00
if( hrs == 12 && pmCheck == false){
newtime= "00" +':'+ time.split(":")[1] +':'+ time.split(":")[2].replace("AM",'');
}
//this is for between 12 PM to 12:59:59 =12:00:00
else if (hrs == 12 && pmCheck == true){
newtime= "12" +':'+ time.split(":")[1] +':'+ time.split(":")[2].replace("PM",'');
}
//this is for between 1 AM and 11:59:59 AM
else if (!pmCheck){
newtime= hrs +':'+ time.split(":")[1] +':'+ time.split(":")[2].replace("AM",'');
}
//this is for between 1 PM and 11:59:59 PM
else if(pmCheck){
newtime= (hrs +12)+':'+ time.split(":")[1] +':'+ time.split(":")[2].replace("PM",'');
}
console.log(newtime);
This is how I add to a string when needed:
string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
myList[i] = string.Format("List string : {0}", i);
}
The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA
) values. Here's an example:
> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
In your example this means that in your line plot(costs,pseudor2,type="l")
, costs
is completely NA
. You have to figure out why this is, but that's the explanation of your error.
From comments:
Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.
stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x)
)
Lol after months of using ?: I just find out that I can use this:
Column(
children: [
if (true) Text('true') else Text('false'),
],
)
Just saying: numpy
has this too. So no need to import math
if you already did import numpy as np
:
>>> np.exp(1)
2.718281828459045
I had a similar problem. The fontsquirel demo page was working in FF but not my own page even though all files were coming from the same domain!
It turned out that I was linking my stylesheet with an absolute URL (http://example.com/style.css) so FF thought it was coming from a different domain. Changing my stylesheet link href to /style.css instead fixed things for me.
Another mechanism for dynamic styling is to define it in the JSX for your component. For example, the following could be used to selectively style the current step in the React tic-tac-toe tutorial (one of the suggested extra credit enhancements:
return (
<li key={move}>
<button style={{fontWeight:(move === this.state.stepNumber ? 'bold' : '')}} onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
Granted, a cleaner approach would be to add/remove a 'selected' CSS class but this direct approach might be helpful in some cases.
Following Stored Procedure loop through the Table Variable and Prints it in Ascending ORDER. This example is using WHILE LOOP.
CREATE PROCEDURE PrintSequenceSeries
-- Add the parameters for the stored procedure here
@ComaSeperatedSequenceSeries nVarchar(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @SERIES_COUNT AS INTEGER
SELECT @SERIES_COUNT = COUNT(*) FROM PARSE_COMMA_DELIMITED_INTEGER(@ComaSeperatedSequenceSeries, ',') --- ORDER BY ITEM DESC
DECLARE @CURR_COUNT AS INTEGER
SET @CURR_COUNT = 1
DECLARE @SQL AS NVARCHAR(MAX)
WHILE @CURR_COUNT <= @SERIES_COUNT
BEGIN
SET @SQL = 'SELECT TOP 1 T.* FROM ' +
'(SELECT TOP ' + CONVERT(VARCHAR(20), @CURR_COUNT) + ' * FROM PARSE_COMMA_DELIMITED_INTEGER( ''' + @ComaSeperatedSequenceSeries + ''' , '','') ORDER BY ITEM ASC) AS T ' +
'ORDER BY T.ITEM DESC '
PRINT @SQL
EXEC SP_EXECUTESQL @SQL
SET @CURR_COUNT = @CURR_COUNT + 1
END;
Following Statement Executes the Stored Procedure:
EXEC PrintSequenceSeries '11,2,33,14,5,60,17,98,9,10'
The result displayed in SQL Query window is shown below:
The function PARSE_COMMA_DELIMITED_INTEGER() that returns TABLE variable is as shown below :
CREATE FUNCTION [dbo].[parse_comma_delimited_integer]
(
@LIST VARCHAR(8000),
@DELIMITER VARCHAR(10) = ',
'
)
-- TABLE VARIABLE THAT WILL CONTAIN VALUES
RETURNS @TABLEVALUES TABLE
(
ITEM INT
)
AS
BEGIN
DECLARE @ITEM VARCHAR(255)
/* LOOP OVER THE COMMADELIMITED LIST */
WHILE (DATALENGTH(@LIST) > 0)
BEGIN
IF CHARINDEX(@DELIMITER,@LIST) > 0
BEGIN
SELECT @ITEM = SUBSTRING(@LIST,1,(CHARINDEX(@DELIMITER, @LIST)-1))
SELECT @LIST = SUBSTRING(@LIST,(CHARINDEX(@DELIMITER, @LIST) +
DATALENGTH(@DELIMITER)),DATALENGTH(@LIST))
END
ELSE
BEGIN
SELECT @ITEM = @LIST
SELECT @LIST = NULL
END
-- INSERT EACH ITEM INTO TEMP TABLE
INSERT @TABLEVALUES
(
ITEM
)
SELECT ITEM = CONVERT(INT, @ITEM)
END
RETURN
END
The lazy/hurry alternative (Dotnet Core 2.2):
[HttpGet("method1-{item}")]
public string Method1(var item) {
return "hello" + item;}
[HttpGet("method2-{item}")]
public string Method2(var item) {
return "world" + item;}
Calling them :
localhost:5000/api/controllername/method1-42
"hello42"
localhost:5000/api/controllername/method2-99
"world99"
That should work. I am not sure why it's failing. You're quoting your variables properly. What happens if you use this script with double [[
]]
?
if [[ -d $PASSED ]]; then
echo "$PASSED is a directory"
elif [[ -f $PASSED ]]; then
echo "$PASSED is a file"
else
echo "$PASSED is not valid"
exit 1
fi
Double square brackets is a bash extension to [ ]
. It doesn't require variables to be quoted, not even if they contain spaces.
Also worth trying: -e
to test if a path exists without testing what type of file it is.
Same problem. This code doesn't work anymore.
I've corrected it, change clearMarkers method this way:
set_map(null) ---> setMap(null)
google.maps.Map.prototype.clearMarkers = function() {
for(var i=0; i < this.markers.length; i++){
this.markers[i].setMap(null);
}
this.markers = new Array();
};
Documentation has been updated to include details on the topic: https://developers.google.com/maps/documentation/javascript/markers#remove
this way worked for me
ng-disabled="(user.Role.ID != 1) && (user.Role.ID != 2)"
I am not sure I got you but this might be what you are looking for:
SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid
This would get you the amounts sums in case there are multiple payment rows for each invoice
on branchB do $git checkout branchA
to switch to branch A
on branchA do $git merge branchB
That's all you need.
The "Check for Modifications" command in tortoise will display a list of all changed files in the working copy. "Commit" will show all changed files as well (that you can then commit). "Revert" will also show changed files (that you can then revert).
I noticed that Google was stripping the src attribute from my img tags. I tried every answer on this page - with no luck.
What finally worked for me was replacing img tags with divs that have background images. For example, instead of:
<img style="height: 24px; width: 24px; display: block;" src="IMAGE SOURCE"/>
_x000D_
I replaced it with:
<div style="height: 24px; width: 24px; display: block; background: url(IMAGE SOURCE); background-size: contain;"></div>
_x000D_
Hope this helps others who spent way too long pulling their hair out over this.
Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.
My setup was as follows:
I put the following formula in cell A1 of Sheet3:
=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)
Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.
Notes:
In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.
A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.
After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)
and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.
Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.
Cells A2, A3, etc. will get these formulas:
=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)
Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.
SELECT @var = col1,
@var2 = col2
FROM Table
Here is some interesting information about SET / SELECT
- SET is the ANSI standard for variable assignment, SELECT is not.
- SET can only assign one variable at a time, SELECT can make multiple assignments at once.
- If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
- When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
- As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.
C++0x only:
vector<int> v; // and fill with data
int sum {}; // or = 0 ... :)
for (int n : v) sum += n;
This is similar to the BOOST_FOREACH mentioned elsewhere and has the same benefit of clarity in more complex situations, compared to stateful functors used with accumulate or for_each.
If you have to wait there is a method presenceOfNestedElementLocatedBy
that takes the "parent" element and a locator, e.g. a By.xpath
:
WebElement subNode = new WebDriverWait(driver,10).until(
ExpectedConditions.presenceOfNestedElementLocatedBy(
divA, By.xpath(".//div/span")
)
);
For me these steps worked
stop-all.sh
hadoop namenode -format
start-all.sh
I am going to go out on a limb and say that the following is what you are after.
Note, the following I believe was accidentally omitted in the question (see comment):
<div id="thumbnailwrapper"> <!-- <<< This opening element -->
<div id="artiststhumbnail">
...
So what you need is:
#artiststhumbnail {
width:120px;
height:108px;
margin: 0 auto; /* <<< This line here. */
...
}
Treat function as variable in your program so you can just pass them to other functions easily:
def test ():
print "test was invoked"
def invoker(func):
func()
invoker(test) # prints test was invoked
Easy solution if you don't want to code manually using Google Sheets Power Tools:
The most elegant way to do this is with a ByteArrayOutputStream
.
byte a[];
byte b[];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write( a );
outputStream.write( b );
byte c[] = outputStream.toByteArray( );
There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.
If performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days
is unintuitive because rounding will depend on the hour component of StartDate
and EndDate
.
(EndDate - StartDate).TotalDays
.(EndDate.Date - StartDate.Date).Days
(EndDate.Date - StartDate.Date).Days + 1
Did you check the string concatenation function? Something like:
update table_c set column_a = column_b || column_c
should work. More here
Regarding seek()
there's not too much to worry about.
First of all, it is useful when operating over an open file.
It's important to note that its syntax is as follows:
fp.seek(offset, from_what)
where fp
is the file pointer you're working with; offset
means how many positions you will move; from_what
defines your point of reference:
if omitted, from_what
defaults to 0.
Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek
will be useful to you when you need to walk
along that open file, just as a path you are traveling into.
The way I typically handle this is with a second piece of software. For Windows I use Notepad++, for OS X I use Sublime Text 2.
I've seen that problem when I'm writing to a filesystem which doesn't (properly) handle times -- I think SMB shares or FAT or something.
What is your target filesystem?
This lovely detailed error is still present in 2019!
I just want to add that if your web.config
is valid and accessible it most likely is a dependency issue.
As mentioned by the OP it was a AJAX
module, and as by others commonly the Rewrite
module.
Just keep your eyes open in your web.config what modules and libraries your tags are referencing to since the error code 0x8007000d can be about ANY dependency.
In my case I didn't realize the AspNetCore
bundle was missing and had to be installed! So happy I found this post!!
int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;
If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.
Hope, this code helps you.
Found a nice solution to this problem elsewhere, no messing around with tags on the button:
- (void)buttonPressedAction:(id)sender {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
// do stuff with the indexPath...
}
If your OS is Unix base use this code:
import os
def check_process(name):
output = []
cmd = "ps -aef | grep -i '%s' | grep -v 'grep' | awk '{ print $2 }' > /tmp/out"
os.system(cmd % name)
with open('/tmp/out', 'r') as f:
line = f.readline()
while line:
output.append(line.strip())
line = f.readline()
if line.strip():
output.append(line.strip())
return output
Then call it and pass it a process name to get all PIDs.
>>> check_process('firefox')
['499', '621', '623', '630', '11733']
dataframe[:n] - Will return first n-1 rows
"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.
The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.
In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo is the shared repo. If CI was on another box, it would have to use the "deploy" goal.
You can download the inf file from here - Introducing PowerShell Prompt Here
import logging
# Only show warnings
logging.getLogger("urllib3").setLevel(logging.WARNING)
# Disable all child loggers of urllib3, e.g. urllib3.connectionpool
logging.getLogger("urllib3").propagate = False
DateTime.Parse
is a much better bet. JS dates and C# dates do not start from the same root.
Sample:
DateTime dt = DateTime.ParseExact("Tue Jul 12 2011 16:00:00 GMT-0700",
"ddd MMM d yyyy HH:mm:ss tt zzz",
CultureInfo.InvariantCulture);
For the sake of completeness, you can also use eval():
$functionName = "foo()";
eval($functionName);
However, call_user_func()
is the proper way.
I would say that first and foremost: be consistent.
I reckon you are almost there with the conventions that you have outlined in your question. A couple of comments though:
Points 1 and 2 are good I reckon.
Point 3 - sadly this is not always possible. Think about how you would cope with a single table foo_bar
that has columns foo_id
and another_foo_id
both of which reference the foo
table foo_id
column. You might want to consider how to deal with this. This is a bit of a corner case though!
Point 4 - Similar to Point 3. You may want to introduce a number at the end of the foreign key name to cater for having more than one referencing column.
Point 5 - I would avoid this. It provides you with little and will become a headache when you want to add or remove columns from a table at a later date.
Some other points are:
Index Naming Conventions
You may wish to introduce a naming convention for indexes - this will be a great help for any database metadata work that you might want to carry out. For example you might just want to call an index foo_bar_idx1
or foo_idx1
- totally up to you but worth considering.
Singular vs Plural Column Names
It might be a good idea to address the thorny issue of plural vs single in your column names as well as your table name(s). This subject often causes big debates in the DB community. I would stick with singular forms for both table names and columns. There. I've said it.
The main thing here is of course consistency!
deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
$.ajax({
url: urlCall,
type: 'DELETE',
data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
success: callback || $.noop,
error: errorCallback || $.noop
});
}
Note: the use of headers
was introduced in JQuery 1.5.:
A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.
ul > li > a
selects only the direct children. In this case only the first level <a>
of the first level <li>
inside the <ul>
will be selected.
ul li a
on the other hand will select ALL <a>
-s in ALL <li>
-s in the unordered list
Example of ul > li
ul > li.bg {_x000D_
background: red;_x000D_
}
_x000D_
<ul>_x000D_
<li class="bg">affected</li>_x000D_
<li class="bg">affected</li> _x000D_
<li>_x000D_
<ol>_x000D_
<li class="bg">NOT affected</li>_x000D_
<li class="bg">NOT affected</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ul>
_x000D_
if you'd be using ul li
- ALL of the li
-s would be affected
UPDATE The order of more to less efficient CSS selectors goes thus:
#header
.promo
div
h2 + p
li > ul
ul a
*
[type="text"]
a:hover
So your better bet is to use the children
selector instead of just descendant
. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.
Javascript doesn't have it, as you point out.
A quick search came up with:
function strcmp ( str1, str2 ) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// + input by: Steve Hilder
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + revised by: gorthaur
// * example 1: strcmp( 'waldo', 'owald' );
// * returns 1: 1
// * example 2: strcmp( 'owald', 'waldo' );
// * returns 2: -1
return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/
Of course, you could just add localeCompare if needed:
if (typeof(String.prototype.localeCompare) === 'undefined') {
String.prototype.localeCompare = function(str, locale, options) {
return ((this == str) ? 0 : ((this > str) ? 1 : -1));
};
}
And use str1.localeCompare(str2)
everywhere, without having to worry wether the local browser has shipped with it. The only problem is that you would have to add support for locales
and options
if you care about that.
yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
and make sure there is no parent tags with position: relative in it
I may be a little late for this, but I would recommend Aptana Studio 3.x . Its a based on eclipse and has everything ready-to-go for python
. It has very good support for DJango, HTML5 and JQuery
. For me its a perfect web-development tool. I do HTML5 and Android
development too, this way I do not need to keep switching different IDE's. It my all-in-one solution.
Note: you need a good amount of RAM for this to be snazzy !! 4+ GB is awesome !!
session_start(); //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id']; //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);
//print_r($_SESSION['student']);
<table class="table"> //html part
<tr>
<th>Name</th>
<th>City</th>
</tr>
<tr>
<?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
echo '<td>'.$_SESSION['student'][$i].'</td>';
} ?>
</tr>
</table>
Golang is not OOP language in its official documents. All fields of Golang struct has a determined value(not like c/c++), so constructor function is not so necessary as cpp. If you need assign some fields some special values, use factory functions. Golang's community suggest New.. pattern names.
I just had to do this myself, you need to do it the other way around.
<div>
<span class="icon icon-2x icon-camera" style=" vertical-align: middle;"></span>
<span class="my-text">hello world</span>
</div>
Of course you could not use inline styles and target it with your own css class. But this works in a copy paste fashion.
See here: Vertical alignment of text and icon in button
If it were up to me however, I would not use the icon-2x. And simply specify the font-size myself, as in the following
<div class='my-fancy-container'>
<span class='my-icon icon-file-text'></span>
<span class='my-text'>Hello World</span>
</div>
.my-icon {
vertical-align: middle;
font-size: 40px;
}
.my-text {
font-family: "Courier-new";
}
.my-fancy-container {
border: 1px solid #ccc;
border-radius: 6px;
display: inline-block;
margin: 60px;
padding: 10px;
}
for a working example, please see JsFiddle
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
If you do not need the SSL security then you might want to switch it off.
/**
* disable SSL
*/
private void disableSslVerification() {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
} };
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
Probably way too late but this is another option:
$('body').popover({
selector: '[rel=popover]',
trigger: 'hover',
html: true,
content: function () {
return $(this).parents('.row').first().find('.metaContainer').html();
}
});
in case your Latitude and Longitude lists are large and lazily loaded:
from itertools import izip
for lat, lon in izip(latitudes, longitudes):
process(lat, lon)
or if you want to avoid the for-loop
from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))
I found that simply setting the line-height and height to the same pixel quantity produced the most consistent result. By "most consistent" I mean optimally consistent but of course it is not 100% "pixel-perfect" across browsers. Additionally I found that Firefox (v. 17.x) tends to crowd the option text to the right against the drop-down arrow; I alleviated this with a small amount of padding-right set on the OPTION element only. This setting does not affect appearance in IE 7-9.
My result:
select, option {
font-size:10px;
height:19px;
line-height: 19px;
padding:0;
margin:0;
}
option {
padding-right:6px; /* Firefox */
}
NOTE -- my SELECT element uses a smaller font, 10px. Obviously you will need to adjust proportions accordingly for your specific UI context.
The correct command for exclude directory from compression is :
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf backup.tar.gz backup/
Make sure to put --exclude before the source and destination items.
and you can check the contents of the tar.gz file without unzipping :
tar -tf backup.tar.gz
You need something like a full outer join. System.Linq.Enumerable has no method that implements a full outer join, so we have to do it ourselves.
var dict1 = list1.ToDictionary(l1 => l1.Name);
var dict2 = list2.ToDictionary(l2 => l2.Name);
//get the full list of names.
var names = dict1.Keys.Union(dict2.Keys).ToList();
//produce results
var result = names
.Select( name =>
{
Person p1 = dict1.ContainsKey(name) ? dict1[name] : null;
Person p2 = dict2.ContainsKey(name) ? dict2[name] : null;
//left only
if (p2 == null)
{
p1.Change = 0;
return p1;
}
//right only
if (p1 == null)
{
p2.Change = 0;
return p2;
}
//both
p2.Change = p2.Value - p1.Value;
return p2;
}).ToList();
You can set the figure size if you explicitly create the figure with
plt.figure(figsize=(3,4))
You need to set figure size before calling plt.plot()
To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff
steps to install maven :
In notepad++ you can set it for the file specifically by pressing
Edit --> EOL Conversion --> UNIX/OSX Format
package javaapplication4;
import java.text.*;
import java.util.*;
/**
*
* @author Stefan Wendelmann
*/
public class JavaApplication4
{
private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException
{
SimpleDateFormat parser = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss.SSS");
Date before = parser.parse("01.10.1990 07:00:00.000");
Date base = parser.parse("01.10.1990 08:00:00.000");
Date after = parser.parse("01.10.1990 09:00:00.000");
printCompare(base, base, "==");
printCompare(base, before, "==");
printCompare(base, before, "<");
printCompare(base, after, "<");
printCompare(base, after, ">");
printCompare(base, before, ">");
printCompare(base, before, "<=");
printCompare(base, base, "<=");
printCompare(base, after, "<=");
printCompare(base, after, ">=");
printCompare(base, base, ">=");
printCompare(base, before, ">=");
}
private static void printCompare (Date a, Date b, String operator){
System.out.println(sdf.format(b)+"\t"+operator+"\t"+sdf.format(a)+"\t"+compareTime(a, b, operator));
}
protected static boolean compareTime(Date a, Date b, String operator)
{
if (a == null)
{
return false;
}
try
{
//Zeit aus Datum holen
// The Magic happens here i only get the Time out of the Date Object
SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.SSS");
a = parser.parse(parser.format(a));
b = parser.parse(parser.format(b));
}
catch (ParseException ex)
{
System.err.println(ex);
}
switch (operator)
{
case "==":
return b.compareTo(a) == 0;
case "<":
return b.compareTo(a) < 0;
case ">":
return b.compareTo(a) > 0;
case "<=":
return b.compareTo(a) <= 0;
case ">=":
return b.compareTo(a) >= 0;
default:
throw new IllegalArgumentException("Operator " + operator + " wird für Feldart Time nicht unterstützt!");
}
}
}
run:
08:00:00.000 == 08:00:00.000 true
07:00:00.000 == 08:00:00.000 false
07:00:00.000 < 08:00:00.000 true
09:00:00.000 < 08:00:00.000 false
09:00:00.000 > 08:00:00.000 true
07:00:00.000 > 08:00:00.000 false
07:00:00.000 <= 08:00:00.000 true
08:00:00.000 <= 08:00:00.000 true
09:00:00.000 <= 08:00:00.000 false
09:00:00.000 >= 08:00:00.000 true
08:00:00.000 >= 08:00:00.000 true
07:00:00.000 >= 08:00:00.000 false
BUILD SUCCESSFUL (total time: 0 seconds)
Add the css:
html,body{
height:100%;
}
.bg-img {
background: url(image.jpg) no-repeat center top;
background-size: cover;
height:100%;
}
And html is:
<div class="bg-mg"></div>
CSS: stretching background image to 100% width and height of screen?
I ended up keeping Link and adding the reload to the Link's onClick event with a timeout like this:
function refreshPage() {
setTimeout(()=>{
window.location.reload(false);
}, 500);
console.log('page to reload')
}
<Link to={{pathname:"/"}} onClick={refreshPage}>Home</Link>
without the timeout, the refresh function would run first
In iOS7 the following matches UITextField border perfectly (to my eye at least):
textField.layer.borderColor = [[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor];
textField.layer.borderWidth = 0.5;
textField.layer.cornerRadius = 5;
textField.clipsToBounds = YES;
There is no need to import anything special.
Thanks to @uvieere and @hanumanDev whose answers go me almost there :)
If you happen to be working with a application which has a mix of Windows Forms and WPF you might have the additional complication of trying to convert a System.Drawing.Color to a System.Windows.Media.Color. I'm not sure if there is an easier way to do this, but I did it this way:
System.Drawing.Color MyColor = System.Drawing.Color.Red;
System.Windows.Media.Color = ConvertColorType(MyColor);
System.Windows.Media.Color ConvertColorType(System.Drawing.Color color)
{
byte AVal = color.A;
byte RVal = color.R;
byte GVal = color.G;
byte BVal = color.B;
return System.Media.Color.FromArgb(AVal, RVal, GVal, BVal);
}
Then you can use one of the techniques mentioned previously to convert to a Brush.
You might need to revise the data in the column, but anyway you can do one of the following:-
1- check if it is numeric then convert it else put another value like 0
Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA)
ELSE 0 END AS COLUMNA
2- select only numeric values from the column
SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1
One more thing - if You edited the shell script in some Windows text editor, which produces the \r\n
line-endings, cygwin's bash wouldn't accept those \r
. Just run dos2unix testit.sh
before executing the script:
C:\cygwin\bin\dos2unix testit.sh
C:\cygwin\bin\bash testit.sh
Try this:
ArrayList<Integer> arrlist = new ArrayList<Integer>(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
boolean retval = arrlist.contains(10);
if (retval == true) {
System.out.println("10 is contained in the list");
}
else {
System.out.println("10 is not contained in the list");
}
Try setting the system default encoding as utf-8
at the start of the script, so that all strings are encoded using that.
Example -
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
The above should set the default encoding as utf-8
.
You have two options to abruptly exit out of ForEach-Object
pipeline in PowerShell:
Where-Object
first, then pass objects to Foreach-Object
, orForeach-Object
into a standard Foreach
looping construct.Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":
Solution-1: use Where-Object
filter BEFORE Foreach-Object
:
[boolean]$exit = $false;
1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
if($_ -eq 2) {$exit = $true} #OR $exit = ($_ -eq 2);
$_;
}
OR
1..10 | Where-Object {$_ -le 2} | Foreach-Object {
$_;
}
Solution-2: Converted Foreach-Object
into standard Foreach
looping construct:
Foreach ($i in 1..10) {
if ($i -eq 3) {break;}
$i;
}
PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object
pipeline. Note: return
doesn't exit, it only skips specific iteration (similar to continue
in most programming languages), here is an example of return
:
Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
1..10 | Foreach-Object {
if ($_ -eq 3) {return;} #skips only 3rd iteration.
$_;
}
HTH
I've found that using this null comparison works well:
if (Combobox.SelectedItem != null){
//Do something
}
else{
MessageBox.show("Please select a item");
}
This will only accept the selected item and no other value which may have been entered manually by the user which could cause validation issues.
To run Java class file from the command line, the syntax is:
java -classpath /path/to/jars <packageName>.<MainClassName>
where packageName (usually starts with either com
or org
) is the folder name where your class file is present.
For example if your main class name is App and Java package name of your app is com.foo.app
, then your class file needs to be in com/foo/app
folder (separate folder for each dot), so you run your app as:
$ java com.foo.app.App
Note: $
is indicating shell prompt, ignore it when typing
If your class doesn't have any package
name defined, simply run as: java App
.
If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp
/-classpath
or using CLASSPATH
variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars
, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.
).
Given we've created sample project using Maven as:
$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
and we've compiled our project by mvn compile
in our my-app/
dir, it'll generate our class file is in target/classes/com/foo/app/App.class
.
To run it, we can either specify class path via -cp
or going to it directly, check examples below:
$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!
To double check your class and package name, you can use Java class file disassembler tool, e.g.:
$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
public com.foo.app.App();
public static void main(java.lang.String[]);
}
Note: javap
won't work if the compiled file has been obfuscated.
Alternate Bootstrap 4 solution (this way you can use divs which are smaller than col-6):
<div class="container">
<div class="row justify-content-center">
<div class="col-4">
One of two columns
</div>
<div class="col-4">
One of two columns
</div>
</div>
</div>
In the future the format might need to be changed which could be a small head ache having date.dateFromISO8601 calls everywhere in an app. Use a class and protocol to wrap the implementation, changing the date time format call in one place will be simpler. Use RFC3339 if possible, its a more complete representation. DateFormatProtocol and DateFormat is great for dependency injection.
class AppDelegate: UIResponder, UIApplicationDelegate {
internal static let rfc3339DateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
internal static let localeEnUsPosix = "en_US_POSIX"
}
import Foundation
protocol DateFormatProtocol {
func format(date: NSDate) -> String
func parse(date: String) -> NSDate?
}
import Foundation
class DateFormat: DateFormatProtocol {
func format(date: NSDate) -> String {
return date.rfc3339
}
func parse(date: String) -> NSDate? {
return date.rfc3339
}
}
extension NSDate {
struct Formatter {
static let rfc3339: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
formatter.locale = NSLocale(localeIdentifier: AppDelegate.localeEnUsPosix)
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.dateFormat = rfc3339DateFormat
return formatter
}()
}
var rfc3339: String { return Formatter.rfc3339.stringFromDate(self) }
}
extension String {
var rfc3339: NSDate? {
return NSDate.Formatter.rfc3339.dateFromString(self)
}
}
class DependencyService: DependencyServiceProtocol {
private var dateFormat: DateFormatProtocol?
func setDateFormat(dateFormat: DateFormatProtocol) {
self.dateFormat = dateFormat
}
func getDateFormat() -> DateFormatProtocol {
if let dateFormatObject = dateFormat {
return dateFormatObject
} else {
let dateFormatObject = DateFormat()
dateFormat = dateFormatObject
return dateFormatObject
}
}
}
After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution
- Right click on installer(.exe)
- Select properties option.
- Click on checkbox to check Unblock at the bottom of Properties.
This solution work for Heroku CLI (heroku-x64) installer(.exe)
You have to give a separate id to the label too.
<label for="foo" id="foo_label">text</label>
#foo_label {display: none;}
Or hide the whole row
<tr id="foo_row">/***/</tr>
#foo_row {display: none;}
#Single line
'''
multi-line
comment
'''
"""
also,
multi-line comment
"""
A couple of wires are crossed here. The various autoplay
settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.
However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.
Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)
You can also add 'active' class to the selected item.
$('.dropdown').on( 'click', '.dropdown-menu li a', function() {
var target = $(this).html();
//Adds active class to selected item
$(this).parents('.dropdown-menu').find('li').removeClass('active');
$(this).parent('li').addClass('active');
//Displays selected text on dropdown-toggle button
$(this).parents('.dropdown').find('.dropdown-toggle').html(target + ' <span class="caret"></span>');
});
See the jsfiddle example
Simple solution for all gaps:
public boolean isNowTimeBetween(String startTime, String endTime) {
LocalTime start = LocalTime.parse(startTime);//"22:00"
LocalTime end = LocalTime.parse(endTime);//"10:00"
LocalTime now = LocalTime.now();
if (start.isBefore(end))
return now.isAfter(start) && now.isBefore(end);
return now.isBefore(start)
? now.isBefore(start) && now.isBefore(end)
: now.isAfter(start) && now.isAfter(end);
}
First of all we should get clear that Hadoop was created as a faster alternative to RDBMS. To process large amount of data at a very fast rate which earlier took a lot of time in RDBMS.
Now one should know the two terms :
Structured Data : This is the data that we used in traditional RDBMS and is divided into well defined structures.
Unstructured Data : This is important to understand, about 80% of the world data is unstructured or semi structured. These are the data which are on its raw form and cannot be processed using RDMS. Example : facebook, twitter data. (http://www.dummies.com/how-to/content/unstructured-data-in-a-big-data-environment.html).
So, large amount of data was being generated in the last few years and the data was mostly unstructured, that gave birth to HADOOP. It was mainly used for very large amount of data that takes unfeasible amount of time using RDBMS. It had many drawbacks, that it could not be used for comparatively small data in real time but they have managed to remove its drawbacks in the newer version.
Before going further I would like to tell that a new Big Data tool is created when they see a fault on the previous tools. So, whichever tool you will see that is created has been done to overcome the problem of the previous tools.
Hadoop can be simply said as two things : Mapreduce and HDFS. Mapreduce is where the processing takes place and HDFS is the DataBase where data is stored. This structure followed WORM principal i.e. write once read multiple times. So, once we have stored data in HDFS, we cannot make changes. This led to the creation of HBASE, a NOSQL product where we can make changes in the data also after writing it once.
But with time we saw that Hadoop had many faults and for that we created different environment over the Hadoop structure. PIG and HIVE are two popular examples.
HIVE was created for people with SQL background. The queries written is similar to SQL named as HIVEQL. HIVE was developed to process completely structured data. It is not used for ustructured data.
PIG on the other hand has its own query language i.e. PIG LATIN. It can be used for both structured as well as unstructured data.
Moving to the difference as when to use HIVE and when to use PIG, I don't think anyone other than the architect of PIG could say. Follow the link : https://developer.yahoo.com/blogs/hadoop/comparing-pig-latin-sql-constructing-data-processing-pipelines-444.html
I'm surprised that no one thought of this simple non-recursive method, which can delete directories containing read only files, without needing to change read only attribute of each of them.
Process.Start("cmd.exe", "/c " + @"rmdir /s/q C:\Test\TestDirectoryContainingReadOnlyFiles");
(Change a bit to not to fire a cmd window momentarily, which is available all over the internet)
Set editable
to False
and default
to your default value.
http://docs.djangoproject.com/en/stable/ref/models/fields/#editable
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id
field is unnecessary. Django will add it automatically.
CREATE TABLE NEW_TABLENAME LIKE OLD_TABLENAME;
Works for DB2 V 9.7
Use \df
to list all the stored procedure in Postgres.
Nicolas solution is best. If you want in regex,
try this,
this will validate for, 01/01/1900 through 12/31/2099 Matches invalid dates such as February 31st Accepts dashes, spaces, forward slashes and dots as date separators
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}
you should declare label first use this :
Select Case parameter
Case "userID"
' does something here.
Case "packageID"
' does something here.
Case "mvrType"
If otherFactor Then
' does something here.
Else
GoTo else
End If
Case Else
else :
' does some processing...
Exit Select
End Select
Check out, http://laravel.com/docs/database/eloquent#to-array
You should be able to define which columns you do not want displayed in your api.
?vector
X <- vector(mode="character", length=10)
This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default
displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.
> X[5] <- "character element in 5th position"
> X
[1] "" ""
[3] "" ""
[5] "character element in 5th position" ""
[7] "" ""
[9] "" ""
> nchar(X)
[1] 0 0 0 0 33 0 0 0 0 0
> length(X)
[1] 10
Either:
SELECT u_name AS user_name
FROM users
WHERE u_name = "john";
or:
SELECT user_name
from
(
SELECT u_name AS user_name
FROM users
)
WHERE u_name = "john";
The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view.
I have found that, at least for "passcode"-like fields, doing something like <input type="tel" />
ends up producing the most authentic number-oriented field and it also has the benefit of no autoformatting. For example, in a mobile application I developed for Hilton recently, I ended up going with this:
... and my client was very impressed.
<form>_x000D_
<input type="tel" />_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
The correct way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Wish I had a dollar for every time I've posted that in a forum.
You have to add type="text/css"
you can also specify href="./style.css"
which the .
specifies the current directory
Or if you want a ripple pulse effect, you could use this:
http://jsfiddle.net/Fy8vD/3041/
.gps_ring {
border: 2px solid #fff;
-webkit-border-radius: 50%;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0;
}
.gps_ring:before {
content:"";
display:block;
border: 2px solid #fff;
-webkit-border-radius: 50%;
height: 30px;
width: 30px;
position: absolute;
left:-8px;
top:-8px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
-webkit-animation-delay: 0.1s;
opacity: 0.0;
}
.gps_ring:after {
content:"";
display:block;
border:2px solid #fff;
-webkit-border-radius: 50%;
height: 50px;
width: 50px;
position: absolute;
left:-18px;
top:-18px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
-webkit-animation-delay: 0.2s;
opacity: 0.0;
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
I would ensure all containers are docker-compose
'd to the same network by composing them together at the same time, using:
docker compose --file ~/front/docker-compose.yml --file ~/api/docker-compose.yml up -d
Close the window only when it is not IE:
function printDiv() {
var divToPrint = document.getElementById('printArea');
var newWin= window.open();
newWin.document.write(divToPrint.innerHTML);
newWin.print();
if (navigator.appName != 'Microsoft Internet Explorer') newWin.window.close();
}
Docker official position is explained in issue #11815 :
Issue 11815: Allow to specify default registries used in pull command
Resolution:
Like pointed out earlier (#11815), this would fragment the namespace, and hurt the community pretty badly, making dockerfiles no longer portable.
[the Maintainer] will close this for this reason.
Red Hat had a specific implementation that allowed it (see anwser, but it was refused by Docker upstream projet). It relied on --add-registry
argument, which was set in /etc/containers/registries.conf
on RHEL/CentOS 7.
EDIT:
Actually, Docker supports registry mirrors (also known as "Run a Registry as a pull-through cache"). https://docs.docker.com/registry/recipes/mirror/#configure-the-docker-daemon
You can do these in unix shell:
java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
You can do these in windows powershell:
java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main
*IntelliJ 13 * (its paid for) We found you have to have the cursor in the actual class before ctrl+Shift+T worked.
Which seems a bit restrictive if its the only way to generate a test class. Although in retrospect it would force developers to create a test class when they write a functional class.
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
I use a trigger as a workaround to set a datetime field to NOW() for new inserts:
CREATE TRIGGER `triggername` BEFORE INSERT ON `tablename`
FOR EACH ROW
SET NEW.datetimefield = NOW()
it should work for updates too
Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
public class JavaYoutubeDownloader {
public static String newline = System.getProperty("line.separator");
private static final Logger log = Logger.getLogger(JavaYoutubeDownloader.class.getCanonicalName());
private static final Level defaultLogLevelSelf = Level.FINER;
private static final Level defaultLogLevel = Level.WARNING;
private static final Logger rootlog = Logger.getLogger("");
private static final String scheme = "http";
private static final String host = "www.youtube.com";
private static final Pattern commaPattern = Pattern.compile(",");
private static final Pattern pipePattern = Pattern.compile("\\|");
private static final char[] ILLEGAL_FILENAME_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };
private static void usage(String error) {
if (error != null) {
System.err.println("Error: " + error);
}
System.err.println("usage: JavaYoutubeDownload VIDEO_ID DESTINATION_DIRECTORY");
System.exit(-1);
}
public static void main(String[] args) {
if (args == null || args.length == 0) {
usage("Missing video id. Extract from http://www.youtube.com/watch?v=VIDEO_ID");
}
try {
setupLogging();
log.fine("Starting");
String videoId = null;
String outdir = ".";
// TODO Ghetto command line parsing
if (args.length == 1) {
videoId = args[0];
} else if (args.length == 2) {
videoId = args[0];
outdir = args[1];
}
int format = 18; // http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
String encoding = "UTF-8";
String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
File outputDir = new File(outdir);
String extension = getExtension(format);
play(videoId, format, encoding, userAgent, outputDir, extension);
} catch (Throwable t) {
t.printStackTrace();
}
log.fine("Finished");
}
private static String getExtension(int format) {
// TODO
return "mp4";
}
private static void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable {
log.fine("Retrieving " + videoId);
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("video_id", videoId));
qparams.add(new BasicNameValuePair("fmt", "" + format));
URI uri = getUri("get_video_info", qparams);
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("User-Agent", userAgent);
log.finer("Executing " + uri);
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
InputStream instream = entity.getContent();
String videoInfo = getStringFromInputStream(encoding, instream);
if (videoInfo != null && videoInfo.length() > 0) {
List<NameValuePair> infoMap = new ArrayList<NameValuePair>();
URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding);
String token = null;
String downloadUrl = null;
String filename = videoId;
for (NameValuePair pair : infoMap) {
String key = pair.getName();
String val = pair.getValue();
log.finest(key + "=" + val);
if (key.equals("token")) {
token = val;
} else if (key.equals("title")) {
filename = val;
} else if (key.equals("fmt_url_map")) {
String[] formats = commaPattern.split(val);
for (String fmt : formats) {
String[] fmtPieces = pipePattern.split(fmt);
if (fmtPieces.length == 2) {
// in the end, download somethin!
downloadUrl = fmtPieces[1];
int pieceFormat = Integer.parseInt(fmtPieces[0]);
if (pieceFormat == format) {
// found what we want
downloadUrl = fmtPieces[1];
break;
}
}
}
}
}
filename = cleanFilename(filename);
if (filename.length() == 0) {
filename = videoId;
} else {
filename += "_" + videoId;
}
filename += "." + extension;
File outputfile = new File(outputdir, filename);
if (downloadUrl != null) {
downloadWithHttpClient(userAgent, downloadUrl, outputfile);
}
}
}
}
private static void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile) throws Throwable {
HttpGet httpget2 = new HttpGet(downloadUrl);
httpget2.setHeader("User-Agent", userAgent);
log.finer("Executing " + httpget2.getURI());
HttpClient httpclient2 = new DefaultHttpClient();
HttpResponse response2 = httpclient2.execute(httpget2);
HttpEntity entity2 = response2.getEntity();
if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
long length = entity2.getContentLength();
InputStream instream2 = entity2.getContent();
log.finer("Writing " + length + " bytes to " + outputfile);
if (outputfile.exists()) {
outputfile.delete();
}
FileOutputStream outstream = new FileOutputStream(outputfile);
try {
byte[] buffer = new byte[2048];
int count = -1;
while ((count = instream2.read(buffer)) != -1) {
outstream.write(buffer, 0, count);
}
outstream.flush();
} finally {
outstream.close();
}
}
}
private static String cleanFilename(String filename) {
for (char c : ILLEGAL_FILENAME_CHARACTERS) {
filename = filename.replace(c, '_');
}
return filename;
}
private static URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException {
URI uri = URIUtils.createURI(scheme, host, -1, "/" + path, URLEncodedUtils.format(qparams, "UTF-8"), null);
return uri;
}
private static void setupLogging() {
changeFormatter(new Formatter() {
@Override
public String format(LogRecord arg0) {
return arg0.getMessage() + newline;
}
});
explicitlySetAllLogging(Level.FINER);
}
private static void changeFormatter(Formatter formatter) {
Handler[] handlers = rootlog.getHandlers();
for (Handler handler : handlers) {
handler.setFormatter(formatter);
}
}
private static void explicitlySetAllLogging(Level level) {
rootlog.setLevel(Level.ALL);
for (Handler handler : rootlog.getHandlers()) {
handler.setLevel(defaultLogLevelSelf);
}
log.setLevel(level);
rootlog.setLevel(defaultLogLevel);
}
private static String getStringFromInputStream(String encoding, InputStream instream) throws UnsupportedEncodingException, IOException {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
instream.close();
}
String result = writer.toString();
return result;
}
}
/**
* <pre>
* Exploded results from get_video_info:
*
* fexp=90...
* allow_embed=1
* fmt_stream_map=35|http://v9.lscache8...
* fmt_url_map=35|http://v9.lscache8...
* allow_ratings=1
* keywords=Stefan Molyneux,Luke Bessey,anarchy,stateless society,giant stone cow,the story of our unenslavement,market anarchy,voluntaryism,anarcho capitalism
* track_embed=0
* fmt_list=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
* author=lukebessey
* muted=0
* length_seconds=390
* plid=AA...
* ftoken=null
* status=ok
* watermark=http://s.ytimg.com/yt/swf/logo-vfl_bP6ud.swf,http://s.ytimg.com/yt/swf/hdlogo-vfloR6wva.swf
* timestamp=12...
* has_cc=False
* fmt_map=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
* leanback_module=http://s.ytimg.com/yt/swfbin/leanback_module-vflJYyeZN.swf
* hl=en_US
* endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vflk19iTq.swf
* vq=auto
* avg_rating=5.0
* video_id=S6IZP3yRJ9I
* token=vPpcFNh...
* thumbnail_url=http://i4.ytimg.com/vi/S6IZP3yRJ9I/default.jpg
* title=The Story of Our Unenslavement - Animated
* </pre>
*/
rm should remove the symbolic link.
skrall@skrall-desktop:~$ mkdir bar
skrall@skrall-desktop:~$ ln -s bar foo
skrall@skrall-desktop:~$ ls -l foo
lrwxrwxrwx 1 skrall skrall 3 2008-10-16 16:22 foo -> bar
skrall@skrall-desktop:~$ rm foo
skrall@skrall-desktop:~$ ls -l foo
ls: cannot access foo: No such file or directory
skrall@skrall-desktop:~$ ls -l bar
total 0
skrall@skrall-desktop:~$
Most of the time your background color is different from the background of your table. Since there are spaces between the cells, those spaces will create the illusion of lines with the color of the background behind the table.
The solution is to get rid of those spaces.
Inside the table tag write:
cellspacing="0"
User Defined Class Array List Example
import java.util.*;
public class UserDefinedClassInArrayList {
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
Program Output:
1 AAA 13
2 BBB 14
3 CCC 15
For PostgreSQL... It didn't work for me with index; it gave me an error, so I did this:
alter table table_name
add unique(column_name_1,column_name_2);
PostgreSQL gave unique index its own name. I guess you can change the name of index in the options for the table, if it is needed to be changed...
I had same problem, for me npm install request --save
solved the problem. Hope it helps.
This error will also occur when we simply declare a virtual function without any definition in the base class.
For example:
class Base
{
virtual void method1(); // throws undefined reference error.
}
Change the above declaration to the below one, it will work fine.
class Base
{
virtual void method1()
{
}
}
Roger's answer was very helpful.
I had a little trouble using it, though, and kept getting the red "Windows can't verify the publisher of this driver software" error dialog. The key was to install the test root certificate with
certutil -addstore Root Demo_CA.cer
which Roger's answer didn't quite cover.
Here is a batch file that worked for me (with my .inf file, not included). It shows how to do it all from start to finish, with no GUI tools at all (except for a few password prompts).
REM Demo of signing a printer driver with a self-signed test certificate.
REM Run as administrator (else devcon won't be able to try installing the driver)
REM Use a single 'x' as the password for all certificates for simplicity.
PATH %PATH%;"c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin";"c:\Program Files\Microsoft SDKs\Windows\v7.0\Bin";c:\WinDDK\7600.16385.1\bin\selfsign;c:\WinDDK\7600.16385.1\Tools\devcon\amd64
makecert -r -pe -n "CN=Demo_CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature ^
-sv Demo_CA.pvk Demo_CA.cer
makecert -pe -n "CN=Demo_SPC" -a sha256 -cy end ^
-sky signature ^
-ic Demo_CA.cer -iv Demo_CA.pvk ^
-sv Demo_SPC.pvk Demo_SPC.cer
pvk2pfx -pvk Demo_SPC.pvk -spc Demo_SPC.cer ^
-pfx Demo_SPC.pfx ^
-po x
inf2cat /drv:driver /os:XP_X86,Vista_X64,Vista_X86,7_X64,7_X86 /v
signtool sign /d "description" /du "www.yoyodyne.com" ^
/f Demo_SPC.pfx ^
/p x ^
/v driver\demoprinter.cat
certutil -addstore Root Demo_CA.cer
rem Needs administrator. If this command works, the driver is properly signed.
devcon install driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
rem Now uninstall the test driver and certificate.
devcon remove driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
certutil -delstore Root Demo_CA
I have used graphviz ( https://www.graphviz.org/gallery ) together with LaTeX using dot command to generate graphs in PDF and includegraphics
to include those.
If graphviz produces what you are aiming at, this might be the best way to integrate: dot2tex: https://ctan.org/pkg/dot2tex?lang=en
pattern="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}"
This is pattern to enter the date for textbox in HTML5.
The first one[0-9]{1,2} will take only decimal number minimum 1 and maximum 2.
And other similarly.
Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....
Run again your problem will be solved
Differences
Use ArrayLists if there is no specific requirement to use Vectors.
Synchronization
If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
Collections.synchronizedList
is normally used at the time of creation of the list to avoid any accidental unsynchronized access to the list.
Data growth
Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
Use the below batch script which takes a process name as an argument and gives netstat
output for the process.
@echo off
set procName=%1
for /f "tokens=2 delims=," %%F in ('tasklist /nh /fi "imagename eq %1" /fo csv') do call :Foo %%~F
goto End
:Foo
set z=%1
echo netstat for : "%procName%" which had pid "%1"
echo ----------------------------------------------------------------------
netstat -ano |findstr %z%
goto :eof
:End
If you really need to do it in separate transaction you need to use REQUIRES_NEW
and live with the performance overhead. Watch out for dead locks.
I'd rather do it the other way:
I think the following is the easiest way to do it.
<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>
What is wrong with Date.parse
method?
str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10
It seems to work.
The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time
object, suppose we have string:
str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09
I couldn't find simpler method to convert Time
to Date
.
On Mac, I've tried the linecopypaste and it works great cmd+c -> Copy current (unselected) line, just like "yy" command in Vi/Vim cmd+v -> Paste it, like "p" command in Vi/Vim
Thank's Larsch for your work!
PD: Using Eclipse Luna 4.4.2 in Yosemite
This is way late but in-case someone finds this helpful.
You could use list comprehension.
rand = [random.randint(0, 100) for x in range(1, 11)]
print(rand)
Output:
[974, 440, 305, 102, 822, 128, 205, 362, 948, 751]
Cheers!
I think this is what you want:
REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'
echo "$1" | grep -P -q $REGEX_DATE
echo $?
I've used the -P switch to get perl regex.
If you have Gimp, I saw that exporting the image in .eps format would do the job.
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.
Given an array declared as:
byte[] array = new byte[4];
You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException
to be thrown. Remember this when you create and access an array.
Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1
(where Length
is total number of items in the array) so this code doesn't work:
array[array.Length] = 0;
Moreover please note that if you have a multidimensional array then you can't use Array.Length
for both dimension, you have to use Array.GetLength()
:
int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
for (int j=0; j < data.GetLength(1); ++j) {
data[i, j] = 1;
}
}
Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color
. Each item represents a pixel, indices are from (0, 0)
to (imageWidth - 1, imageHeight - 1)
.
Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
for (int y = 0; y <= imageHeight; ++y) {
pixels[x, y] = backgroundColor;
}
}
This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]
:
pixels[imageWidth, imageHeight] = Color.Black;
In another scenario you may get ArgumentOutOfRangeException
for this code (for example if you're using GetPixel
method on a Bitmap
class).
Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>()
, this example adds a new entry to an existing array:
Array.Resize(ref array, array.Length + 1);
Don't forget that valid indices are from 0
to Length - 1
. If you simply try to assign an item at Length
you'll get IndexOutOfRangeException
(this behavior may confuse you if you think they may increase with a syntax similar to Insert
method of other collections).
Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:
var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });
In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.
Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:
private static string[] RomanNumbers =
new string[] { "I", "II", "III", "IV", "V" };
public static string Romanize(int number)
{
return RomanNumbers[number];
}
Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:
// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.IndexOf(myArray, "Debug")]);
// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);
This will fail if no items in myArray
will satisfy search condition because Array.IndexOf()
will return -1 and then array access will throw.
Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):
static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
int[] result = new int[maximum + 1]; // Includes 0
foreach (int number in numbers)
++result[number];
return result;
}
Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum
.
How it applies to List<T>
?
Same cases as array - range of valid indexes - 0 (List
's indexes always start with 0) to list.Count
- accessing elements outside of this range will cause the exception.
Note that List<T>
throws ArgumentOutOfRangeException
for the same cases where arrays use IndexOutOfRangeException
.
Unlike arrays, List<T>
starts empty - so trying to access items of just created list lead to this exception.
var list = new List<int>();
Common case is to populate list with indexing (similar to Dictionary<int, T>
) will cause exception:
list[0] = 42; // exception
list.Add(42); // correct
IDataReader and Columns
Imagine you're trying to read data from a database with this code:
using (var connection = CreateConnection()) {
using (var command = connection.CreateCommand()) {
command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
ProcessData(reader.GetString(2)); // Throws!
}
}
}
}
GetString()
will throw IndexOutOfRangeException
because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).
Please note that this behavior is shared with most IDataReader
implementations (SqlDataReader
, OleDbDataReader
and so on).
You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with
var data = dr["Colum1"]; // Missing the n in Column1.
This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".
Others
There is another (documented) case when this exception is thrown: if, in DataView
, data column name being supplied to the DataViewSort
property is not valid.
In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0
with GetLowerBound(0)
and .Length
with GetUpperBound(0)
(of course if you have parameters of type System.Arra
y, it doesn't apply for T[]
). Please note that in this case, upper bound is inclusive then this code:
for (int i=0; i < array.Length; ++i) { }
Should be rewritten like this:
for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }
Please note that this is not allowed (it'll throw InvalidCastException
), that's why if your parameters are T[]
you're safe about custom lower bound arrays:
void foo<T>(T[] array) { }
void test() {
// This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}
Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException
or ArgumentOutOfRangeException
). In the next example, wrong parameters may cause IndexOutOfRangeException
, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:
static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
if (from < 0 || from>= array.Length)
throw new ArgumentOutOfRangeException("from");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (from + length > array.Length)
throw new ArgumentException("...");
for (int i=from; i < from + length; ++i)
array[i] = function(i);
}
If function is private you may simply replace if
logic with Debug.Assert()
:
Debug.Assert(from >= 0 && from < array.Length);
Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert()
, throw a proper exception (more descriptive about the problem) or handle that like in this example:
class Table {
public int SelectedIndex { get; set; }
public Row[] Rows { get; set; }
public Row SelectedRow {
get {
if (Rows == null)
throw new InvalidOperationException("...");
// No or wrong selection, here we just return null for
// this case (it may be the reason we use this property
// instead of direct access)
if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
return null;
return Rows[SelectedIndex];
}
}
Validate Return Values
In one of previous examples we directly used Array.IndexOf()
return value. If we know it may fail then it's better to handle that case:
int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }
In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.
You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:
array[index] = newValue;
You found your error, check how index
increases. Is it right? Check how array is allocated, is coherent with how index
increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!
A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.
If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).
Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.
In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.
' declares an array with space for 5 integer
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer
So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException
For i As Integer = 0 To 4
myArray(i) = i
Next
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration
Yes, should try reinstall mysql, but use the --reinstall
flag to force a package reconfiguration. So the operating system service configuration is not skipped:
sudo apt --reinstall install mysql-server
Use CompatPadding in CardView Item
If you are willing to use a 3rd party service, auth0.com supports this integration. The auth0 service exchanges a 3rd party SSO service authentication for an AWS temporary session token will limited permissions.
See:
https://github.com/auth0-samples/auth0-s3-sample/
and the auth0 documentation.
I made a new custom :pseudo selector for jQuery to test whether an item has one of the following css properties:
I wanted to find the closest scrollable parent of another element so I also wrote another little jQuery plugin to find the closest parent with overflow.
This solution probably doesn't perform the best, but it does appear to work. I used it in conjunction with the $.scrollTo plugin. Sometimes I need to know whether an element is inside another scrollable container. In that case I want to scroll the parent scrollable element vs the window.
I probably should have wrapped this up in a single plugin and added the psuedo selector as a part of the plugin, as well as exposing a 'closest' method to find the closest (parent) scrollable container.
Anywho....here it is.
$.isScrollable jQuery plugin:
$.fn.isScrollable = function(){
var elem = $(this);
return (
elem.css('overflow') == 'scroll'
|| elem.css('overflow') == 'auto'
|| elem.css('overflow-x') == 'scroll'
|| elem.css('overflow-x') == 'auto'
|| elem.css('overflow-y') == 'scroll'
|| elem.css('overflow-y') == 'auto'
);
};
$(':scrollable') jQuery pseudo selector:
$.expr[":"].scrollable = function(a) {
var elem = $(a);
return elem.isScrollable();
};
$.scrollableparent() jQuery plugin:
$.fn.scrollableparent = function(){
return $(this).closest(':scrollable') || $(window); //default to $('html') instead?
};
Implementation is pretty simple
//does a specific element have overflow scroll?
var somedivIsScrollable = $(this).isScrollable();
//use :scrollable psuedo selector to find a collection of child scrollable elements
var scrollableChildren = $(this).find(':scrollable');
//use $.scrollableparent to find closest scrollable container
var scrollableparent = $(this).scrollableparent();
UPDATE: I found that Robert Koritnik already came up with a much more powerful :scrollable pseudo selector that will identify the scrollable axes and height of scrollable containers, as a part of his $.scrollintoview() jQuery plugin. scrollintoview plugin
Here is his fancy pseudo selector (props):
$.extend($.expr[":"], {
scrollable: function (element, index, meta, stack) {
var direction = converter[typeof (meta[3]) === "string" && meta[3].toLowerCase()] || converter.both;
var styles = (document.defaultView && document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(element, null) : element.currentStyle);
var overflow = {
x: scrollValue[styles.overflowX.toLowerCase()] || false,
y: scrollValue[styles.overflowY.toLowerCase()] || false,
isRoot: rootrx.test(element.nodeName)
};
// check if completely unscrollable (exclude HTML element because it's special)
if (!overflow.x && !overflow.y && !overflow.isRoot)
{
return false;
}
var size = {
height: {
scroll: element.scrollHeight,
client: element.clientHeight
},
width: {
scroll: element.scrollWidth,
client: element.clientWidth
},
// check overflow.x/y because iPad (and possibly other tablets) don't dislay scrollbars
scrollableX: function () {
return (overflow.x || overflow.isRoot) && this.width.scroll > this.width.client;
},
scrollableY: function () {
return (overflow.y || overflow.isRoot) && this.height.scroll > this.height.client;
}
};
return direction.y && size.scrollableY() || direction.x && size.scrollableX();
}
});
playersList.get(0)
Java has limited operator polymorphism. So you use the get()
method on List
objects, not the array index operator ([]
)
MyClass
is a class not a namespace. So this code is wrong:
using MyClass //THIS CODE IS NOT CORRECT
You should check the namespace of the MyClass
(e.g: MyNamespace). Then call it in a proper way:
MyNamespace.MyClass myClass =new MyNamespace.MyClass();
If you indeed forgot the root password to the MySQL server, you need to start it with the option skip-grant-tables
. Search for the appropriate Ini-File my.ini
(C:\ProgramData\MySQL Server ...
or something like this) and add skip-grant-tables
to the section [mysqld]
like so:
[mysqld]
skip-grant-tables
Create a custom adapter with a custom layout for your spinner.
Spinner spinner = (Spinner) findViewById(R.id.pioedittxt5);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.travelreasons, R.layout.simple_spinner_item);
adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
R.layout.simple_spinner_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/spinnerItemStyle"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
R.layout.simple_spinner_dropdown_item
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/spinnerDropDownItemStyle"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="?android:attr/dropdownListPreferredItemHeight"
android:ellipsize="marquee" />
In styles add your custom dimensions and height as per your requirement.
<style name="spinnerItemStyle" parent="android:Widget.TextView.SpinnerItem">
</style>
<style name="spinnerDropDownItemStyle" parent="android:TextAppearance.Widget.TextView.SpinnerItem">
</style>
Echo the meta
tag like this:
URL is the one where the page should be redirected to after the refresh.
echo "<meta http-equiv=\"refresh\" content=\"0;URL=upload.php\">";
Used zoom-master/jquery.zoom.js. The zoom for the image worked perfectly. Here is a link to the page. http://www.jacklmoore.com/zoom/
<script>
$(document).ready(function(){
$('#ex1').zoom();
});
</script>
A simple code :
var homes = [_x000D_
{_x000D_
"h_id": "3",_x000D_
"city": "Dallas",_x000D_
"state": "TX",_x000D_
"zip": "75201",_x000D_
"price": "162500"_x000D_
}, {_x000D_
"h_id": "4",_x000D_
"city": "Bevery Hills",_x000D_
"state": "CA",_x000D_
"zip": "90210",_x000D_
"price": "319250"_x000D_
}, {_x000D_
"h_id": "5",_x000D_
"city": "New York",_x000D_
"state": "NY",_x000D_
"zip": "00010",_x000D_
"price": "962500"_x000D_
}_x000D_
];_x000D_
_x000D_
let sortByPrice = homes.sort(function (a, b) _x000D_
{_x000D_
return parseFloat(b.price) - parseFloat(a.price);_x000D_
});_x000D_
_x000D_
for (var i=0; i<sortByPrice.length; i++)_x000D_
{_x000D_
document.write(sortByPrice[i].h_id+' '+sortByPrice[i].city+' '_x000D_
+sortByPrice[i].state+' '_x000D_
+sortByPrice[i].zip+' '+sortByPrice[i].price);_x000D_
document.write("<br>");_x000D_
}
_x000D_
I have downloaded the datepicker from jqueryui.com/download and I got 1.7.2 version but still onSelect function didn't work. Here is what i had -
$("#datepicker").datepicker();
$("#datepicker").datepicker({
onSelect: function(value, date) {
alert('The chosen date is ' + value);
}
});
I found the solution in this page -- problem with jquery datepicker onselect . Removed the $("#datepicker").datepicker(); once and it worked.