After writing
header('HTTP/1.0 404 Not Found');
add one more header for any inexisting page on your site. It works, for sure.
header("Location: http://yoursite/nowhere");
die;
If you are using PHP's curl
bindings, you can check the error code using curl_getinfo
as such:
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
/* Handle 404 here. */
}
curl_close($handle);
/* Handle $response here. */
This is the only answer that worked for me...
I had a similar issue... It seemed like no matter what I did, nothing was getting redirected and my global file was just being ignored. I seriously considered just ending it all before I found this answer. I hope this link helps somebody else.
Adding the following to the web.config file worked for me:
<system.webServer>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
</system.webServer>
system.webServer tag was already there of course but I added the modules tag to it and then the remove & add tags to modules tag.
You could also use the render file:
render file: "#{Rails.root}/public/404.html", layout: false, status: 404
Where you can choose to use the layout or not.
Another option is to use the Exceptions to control it:
raise ActiveRecord::RecordNotFound, "Record not found."
I had the same problem, but believe it or not is was a case of case sensitivity.
This on localhost: http://localhost/.../getdata.php?id=3
Did not behave the same as this on the server: http://server/.../getdata.php?id=3
Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3
You can try and do a simple GET on the page, if you get a 200 back it means the page exists. Try this (using jQuery), the function is the success callback function on a successful page load. Note this will only work on sites within your domain to prevent XSS. Other domains will have to be handled server side
$.get(
yourURL,
function(data, textStatus, jqXHR) {
//load the iframe here...
}
);
What you're doing will work, and the browser will receive a 404 code. What it won't do is display the "not found" page that you might be expecting, e.g.:
The requested URL /test.php was not found on this server.
That's because the web server doesn't send that page when PHP returns a 404 code (at least Apache doesn't). PHP is responsible for sending all its own output. So if you want a similar page, you'll have to send the HTML yourself, e.g.:
<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>
You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:
ErrorDocument 404 /notFound.php
You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like
@WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
//rest of the class
Then you can just go to the localhost:8080/yourApp/hello
and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml
file like
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
It seems to me that the standard CustomErrors
configuration should just work however, due to the reliance on Server.Transfer
it seems that the internal implementation of ResponseRewrite
isn't compatible with MVC.
This feels like a glaring functionality hole to me, so I decided to re-implement this feature using a HTTP module. The solution below allows you to handle any HTTP status code (including 404) by redirecting to any valid MVC route just as you would do normally.
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="404.aspx" />
<error statusCode="500" redirect="~/MVCErrorPage" />
</customErrors>
This has been tested on the following platforms;
Benefits
The Solution
namespace Foo.Bar.Modules {
/// <summary>
/// Enables support for CustomErrors ResponseRewrite mode in MVC.
/// </summary>
public class ErrorHandler : IHttpModule {
private HttpContext HttpContext { get { return HttpContext.Current; } }
private CustomErrorsSection CustomErrors { get; set; }
public void Init(HttpApplication application) {
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
CustomErrors = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
application.EndRequest += Application_EndRequest;
}
protected void Application_EndRequest(object sender, EventArgs e) {
// only handle rewrite mode, ignore redirect configuration (if it ain't broke don't re-implement it)
if (CustomErrors.RedirectMode == CustomErrorsRedirectMode.ResponseRewrite && HttpContext.IsCustomErrorEnabled) {
int statusCode = HttpContext.Response.StatusCode;
// if this request has thrown an exception then find the real status code
Exception exception = HttpContext.Error;
if (exception != null) {
// set default error status code for application exceptions
statusCode = (int)HttpStatusCode.InternalServerError;
}
HttpException httpException = exception as HttpException;
if (httpException != null) {
statusCode = httpException.GetHttpCode();
}
if ((HttpStatusCode)statusCode != HttpStatusCode.OK) {
Dictionary<int, string> errorPaths = new Dictionary<int, string>();
foreach (CustomError error in CustomErrors.Errors) {
errorPaths.Add(error.StatusCode, error.Redirect);
}
// find a custom error path for this status code
if (errorPaths.Keys.Contains(statusCode)) {
string url = errorPaths[statusCode];
// avoid circular redirects
if (!HttpContext.Request.Url.AbsolutePath.Equals(VirtualPathUtility.ToAbsolute(url))) {
HttpContext.Response.Clear();
HttpContext.Response.TrySkipIisCustomErrors = true;
HttpContext.Server.ClearError();
// do the redirect here
if (HttpRuntime.UsingIntegratedPipeline) {
HttpContext.Server.TransferRequest(url, true);
}
else {
HttpContext.RewritePath(url, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext);
}
// return the original status code to the client
// (this won't work in integrated pipleline mode)
HttpContext.Response.StatusCode = statusCode;
}
}
}
}
}
public void Dispose() {
}
}
}
Usage
Include this as the final HTTP module in your web.config
<system.web>
<httpModules>
<add name="ErrorHandler" type="Foo.Bar.Modules.ErrorHandler" />
</httpModules>
</system.web>
<!-- IIS7+ -->
<system.webServer>
<modules>
<add name="ErrorHandler" type="Foo.Bar.Modules.ErrorHandler" />
</modules>
</system.webServer>
For those of you paying attention you will notice that in Integrated Pipeline mode this will always respond with HTTP 200 due to the way Server.TransferRequest
works. To return the proper error code I use the following error controller.
public class ErrorController : Controller {
public ErrorController() { }
public ActionResult Index(int id) {
// pass real error code to client
HttpContext.Response.StatusCode = id;
HttpContext.Response.TrySkipIisCustomErrors = true;
return View("Errors/" + id.ToString());
}
}
A little bit shorter version. Suppress odd echo.
if (strstr($_SERVER['REQUEST_URI'],'index.php')){
header('HTTP/1.0 404 Not Found');
exit("<h1>404 Not Found</h1>\nThe page that you have requested could not be found.");
}
If you installed new Codeigniter, please check if you added .htaccess file on root directory. If you didn't add it yet, please add it. You can put default content it the .htaccess file like below.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
Problem solved, I've not added the index.html. Which is point out in the web.xml
Note: a project may have more than one web.xml file.
if there are another web.xml in
src/main/webapp/WEB-INF
Then you might need to add another index (this time index.jsp) to
src/main/webapp/WEB-INF/pages/
These answers are no longer recommended since try_files
works faster than if
in this context. Simply add try_files
in your php location block to test if the file exists, otherwise return a 404.
location ~ \.php {
try_files $uri =404;
...
}
Run IIS Server Manager (run command : inetmgr) Open Mime Types and add following
File name extension: .woff
MIME type: application/octet-stream
Is the Config/setup.php
file actually in /test/content/home/
or is in your document root? it is best to make all references relative to your document root.
include $_SERVER['DOCUMENT_ROOT'] . "Config/setup.php";
Your current code assumes that the location of setup.php
is in /text/content/home/Config/setup.php
, is this correct?
An old thread, but since I didn't find it elsewhere, here is one more possibility:
If you're using servlet-api 3.0+, then your web.xml must NOT include metadata-complete="true"
attribute
This tells tomcat to map the servlets using data given in web.xml
instead of using the @WebServlet
annotation.
There is a better guide here for Windows:
https://shellcreeper.com/how-to-create-valid-ssl-in-localhost-for-xampp/
Basic steps:
Create an SSL certificate for your local domain using this: See more details in the link above https://gist.github.com/turtlepod/3b8d8d0eef29de019951aa9d9dcba546 https://gist.github.com/turtlepod/e94928cddbfc46cfbaf8c3e5856577d0
Install this cert in Windows (Trusted Root Certification Authorities) See more details in the link above
Add the site in Windows hosts (C:\Windows\System32\drivers\etc\hosts)
E.g.: 127.0.0.1 site.test
Add the site in XAMPP conf (C:\xampp\apache\conf\extra\httpd-vhosts.conf) E.g.:
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs"
ServerName site.test
ServerAlias *.site.test
</VirtualHost>
<VirtualHost *:443>
DocumentRoot "C:/xampp/htdocs"
ServerName site.test
ServerAlias *.site.test
SSLEngine on
SSLCertificateFile "crt/site.test/server.crt"
SSLCertificateKeyFile "crt/site.test/server.key"
</VirtualHost>
Restart Apache and your browser and it's done!
For me, my Eclipse installation was hosed - I think because I'd installed struts. After trying a dozen remedies for this error, I re-installed Eclipse, made a new workspace and it was OK. Using Kepler-64-Windows, Tomcat 7, Windows 7.
When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,
ErrorDocument 404 /yourfoldernames/errors/404.html
To get your program to run, please put jsp files under web-content and not under WEB-INF
because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:
http://localhost:8080/YourProject/yourfile.jsp
then your problem will be solved.
Use HttpUrlConnection by calling openConnection()
on your URL object.
getResponseCode() will give you the HTTP response once you've read from the connection.
e.g.
URL u = new URL("http://www.example.com/");
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
huc.setRequestMethod("GET");
huc.connect() ;
OutputStream os = huc.getOutputStream();
int code = huc.getResponseCode();
(not tested)
This solution doesn't need web.config file changes or catch-all routes.
First, create a controller like this;
public class ErrorController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Regular Error";
return View();
}
public ActionResult NotFound404()
{
ViewBag.Title = "Error 404 - File not Found";
return View("Index");
}
}
Then create the view under "Views/Error/Index.cshtml" as;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>We're sorry, page you're looking for is, sadly, not here.</p>
Then add the following in the Global asax file as below:
protected void Application_Error(object sender, EventArgs e)
{
// Do whatever you want to do with the error
//Show the custom error page...
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
{
routeData.Values["action"] = "Index";
}
else
{
// Handle 404 error and response code
Response.StatusCode = 404;
routeData.Values["action"] = "NotFound404";
}
Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
IController errorsController = new ErrorController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
errorsController.Execute(rc);
Response.End();
}
If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<httpErrors>
</httpErrors>
</system.webServer>
Fix:
I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".
After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.
C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
Volume in drive C is Windows
Volume Serial Number is 8EE6-5DD0
Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319
03/18/2010 08:23 PM 19,296 aspnet_regbrowsers.exe
03/18/2010 08:23 PM 36,696 aspnet_regiis.exe
03/18/2010 08:23 PM 102,232 aspnet_regsql.exe
3 File(s) 158,224 bytes
0 Dir(s) 34,836,508,672 bytes free
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>
However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.
HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.
is simple for me use base64_encode
$term = base64_encode($term)
$url = $youurl.'?term='.$term
after you decode the term
$term = base64_decode($['GET']['term'])
this way encode the "/" and "\"
In Django 3.x
, the accepted answer won't work because render_to_response
has been removed completely as well as some more changes have been made since the version the accepted answer worked for.
Some other answers are also there but I'm presenting a little cleaner answer:
In your main urls.py
file:
handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'
In yourapp/views.py
file:
def handler404(request, exception):
context = {}
response = render(request, "pages/errors/404.html", context=context)
response.status_code = 404
return response
def handler500(request):
context = {}
response = render(request, "pages/errors/500.html", context=context)
response.status_code = 500
return response
Ensure that you have imported render()
in yourapp/views.py
file:
from django.shortcuts import render
Side note: render_to_response()
was deprecated in Django 2.x
and it has been completely removed in verision 3.x
.
@mani's Original answer is all you want, but if you'd also like to read it in official way, here's
https://router.vuejs.org/guide/essentials/history-mode.html#caveat
You're in luck bud...I had the same issue but had more tech knowledge on the matter and was able to determine that it was a mod_sec issue that hostgator has to fix/whitelist on their own. You cannot do it yourself. Simply ask the hostgator tech to check mod_sec settings on your server.
Enjoy your fixed issue ;D
Right-click on your project's name in Eclipse's Project Explorer, then click Run As followed by Run on Server. Click the Next button. Make sure your project's name is listed in the Configured: column on the right. If it is, then you should be able to access it with this URL:
http://localhost:8085/projectname/
Additionally, whenever you make new additions (such as new JSPs, graphics or other resources) to your project, be sure to refresh the project by clicking on its name and then hitting F5. Otherwise Eclipse does not know that those new resources are available and will not make them available to Tomcat to serve.
Yes the set of instructions above are outdated. For the new GitHub the Settings button must be clicked.
Also the person you try to add as a collaborator must have an existing GitHub account. In other words he should have signed up on GitHub first because it is not possible to send collaboration requests merely by typing in the email address of the collaborator.
Use Platform.runLater(...)
for quick and simple operations and Task
for complex and big operations .
Example: Why Can't we use Platform.runLater(...)
for long calculations (Taken from below reference).
Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.
Code using Platform.runLater(...)
:
final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
@Override public void run() {
for (int i = 1; i <= 1000000; i++) {
final int counter = i;
Platform.runLater(new Runnable() {
@Override public void run() {
bar.setProgress(counter / 1000000.0);
}
});
}
}).start();
This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.
Code using Task :
Task task = new Task<Void>() {
@Override public Void call() {
static final int max = 1000000;
for (int i = 1; i <= max; i++) {
updateProgress(i, max);
}
return null;
}
};
ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
it suffers from none of the flaws exhibited in the previous code
Reference : Worker Threading in JavaFX 2.0
Try this: Same as @Nathan-white answer above with minor tweaks.
/* For removing autocomplete highlight color in chrome (note: use this at bottom of your css file). */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: all 5000s ease-in-out 0s;
transition-property: background-color, color;
}
The definitive answer (covering changes to jQuery api at version 1.6) has been given by Gnarf
I've had good success with the asyncproc module, which deals nicely with the output from the processes. For example:
import os
from asynproc import Process
myProc = Process("myprogram.app")
while True:
# check to see if process has ended
poll = myProc.wait(os.WNOHANG)
if poll is not None:
break
# print any new output
out = myProc.read()
if out != "":
print out
you need to make county_ID
as index for the right frame:
frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
on=[ 'countyid' ], how='left' )
for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.
so you need to verify integrity before joining by , verify_integrity=True
Try this, you will know the difference between change and modify,
ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]
ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
CHANGE
.MODIFY
. You cannot change the name of the column using this statement.Hope, I explained well in detail.
To stick to ==
without consideration of the other type, the following is also possible.
type(a) == type(None)
For somebody like me who's trying to figure this out recently,
https://i.vimeocdn.com/video/[video_id]_[dimension].webp
works for me.
(where dimension
= 200x150 | 640)
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
Assumptions: x
is the horizontal axis, and increases when moving from left to right.
y
is the vertical axis, and increases from bottom to top. (touch_x, touch_y)
is the
point selected by the user. (center_x, center_y)
is the point at the center of the
screen. theta
is measured counter-clockwise from the +x
axis. Then:
delta_x = touch_x - center_x
delta_y = touch_y - center_y
theta_radians = atan2(delta_y, delta_x)
Edit: you mentioned in a comment that y increases from top to bottom. In that case,
delta_y = center_y - touch_y
But it would be more correct to describe this as expressing (touch_x, touch_y)
in polar coordinates relative to (center_x, center_y)
. As ChrisF mentioned,
the idea of taking an "angle between two points" is not well defined.
They have nothing to do with each other.
Java is statically typed, compiles, runs on its own VM.
Javascript is dynamically typed, interpreted, and runs in a browser. It also has first-class functions and anonymous functions, which Java does not. It has direct access to web-page elements, which makes it useful for doing client-side processing.
They are also somewhat similar in syntax, but that's about it.
If you want to use optional arguments, but not named arguments, then this approach worked for me. I think this is much easier code to follow.
REM Get argument values. If not specified, use default values.
IF "%1"=="" ( SET "DatabaseServer=localhost" ) ELSE ( SET "DatabaseServer=%1" )
IF "%2"=="" ( SET "DatabaseName=MyDatabase" ) ELSE ( SET "DatabaseName=%2" )
REM Do work
ECHO Database Server = %DatabaseServer%
ECHO Database Name = %DatabaseName%
FWIW: I got the same error for a different reason. I post the answer here not for the benefit of the OP, but for the benefit of those who may end up on this page due to its title... who might have made the same mistake I did.
I was confused why I was getting "local variable referenced before assignment" because I was calling a FUNCTION that I knew was already defined:
def job_fn(job):
return job + ".job"
def do_something():
a = 1
b = 2
job_fn = job_fn("foo")
do_something()
This was giving:
UnboundLocalError: local variable 'job_fn' referenced before assignment
Took me a while to see my obvious problem: I used a local variable named job_fn
which masked the ability to see the prior function definition for job_fn
.
I do not know of any in-built method, but you could just use linq:
parameterList = parameterList.Where(x => x != null).ToList();
maybe this will help (rotate 90 degree)(this worked for me)
private Bitmap rotateBitmap(Bitmap image){
int width=image.getHeight();
int height=image.getWidth();
Bitmap srcBitmap=Bitmap.createBitmap(width, height, image.getConfig());
for (int y=width-1;y>=0;y--)
for(int x=0;x<height;x++)
srcBitmap.setPixel(width-y-1, x,image.getPixel(x, y));
return srcBitmap;
}
Yes, with set_index you can make Locality
your row index.
data.set_index('Locality', inplace=True)
If inplace=True
is not provided, set_index
returns the modified dataframe as a result.
Example:
> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> df
Locality 2005 2006
0 ABBOTSFORD 427000 448000
1 ABERFELDIE 534000 600000
> df.set_index('Locality', inplace=True)
> df
2005 2006
Locality
ABBOTSFORD 427000 448000
ABERFELDIE 534000 600000
> df.loc['ABBOTSFORD']
2005 427000
2006 448000
Name: ABBOTSFORD, dtype: int64
> df.loc['ABBOTSFORD'][2005]
427000
> df.loc['ABBOTSFORD'].values
array([427000, 448000])
> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]
I had the same issue for a long time and I spent God knows how much on it until I accidentally figured what to do. This solution worked on windows 10. All you need to do is to add C:\WINDOWS\System32 to Path variable under User Variables in Environmental Variables... Note that if you add this to the system variables, it may also work. But, that didn't work for me.
You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function
Following is the working solution to read the entire file in chunks and its efficient solution to read the large files using a scanner class.
try {
FileInputStream fiStream = new FileInputStream(inputFile_name);
Scanner sc = null;
try {
sc = new Scanner(fiStream);
while (sc.hasNextLine()) {
String line = sc.nextLine();
byte[] buf = line.getBytes();
}
} finally {
if (fiStream != null) {
fiStream.close();
}
if (sc != null) {
sc.close();
}
}
}catch (Exception e){
Log.e(TAG, "Exception: " + e.toString());
}
This worked for me in Laravel 5.8
return \Redirect::to('https://bla.com/?yken=KuQxIVTNRctA69VAL6lYMRo0');
Or instead of / you can use
use Redirect;
If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:
var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
I chose cut
here because you could simply extend the code for a few more variables...
If you use tab to indent the code block it will shape the entire block into one line. To avoid this you need to use html ordered list.
Code block
<ol start="3">
<li>item 3</li>
<li>item 4</li>
</ol>
I found this code works for me:
public String Translate(String word)
{
var toLanguage = "en";//English
var fromLanguage = "de";//Deutsch
var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromLanguage}&tl={toLanguage}&dt=t&q={HttpUtility.UrlEncode(word)}";
var webClient = new WebClient
{
Encoding = System.Text.Encoding.UTF8
};
var result = webClient.DownloadString(url);
try
{
result = result.Substring(4, result.IndexOf("\"", 4, StringComparison.Ordinal) - 4);
return result;
}
catch
{
return "Error";
}
}
var contents = document.getElementById('contents');
var contents = $('#contents');
The code snippets are not the same. first one returns a Element
object (source).
The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. (jQuery documentation). Internally jQuery uses document.getElementById()
for efficiency.
In both the cases if more than one element found only the first element will be returned.
When checking the github project for jQuery I found following line snippets which seems to be using document.getElementById codes (https://github.com/jquery/jquery/blob/master/src/core/init.js line 68 onwards)
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
I think a very simple solution could be following:
DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE ','+@Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),tableid)+',%';
You can use pandas.DataFrame.mask
to add virtually as many conditions as you need:
data = {'a': [1,2,3,4,5], 'b': [6,8,9,10,11]}
d = pd.DataFrame.from_dict(data, orient='columns')
c = {'c1': (2, 'Value1'), 'c2': (3, 'Value2'), 'c3': (5, d['b'])}
d['new'] = np.nan
for value in c.values():
d['new'].mask(d['a'] == value[0], value[1], inplace=True)
d['new'] = d['new'].fillna('Else')
d
Output:
a b new
0 1 6 Else
1 2 8 Value1
2 3 9 Value2
3 4 10 Else
4 5 11 11
Just set all the selected time unit's displayFormat
to MMM DD
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MMM DD',
'second': 'MMM DD',
'minute': 'MMM DD',
'hour': 'MMM DD',
'day': 'MMM DD',
'week': 'MMM DD',
'month': 'MMM DD',
'quarter': 'MMM DD',
'year': 'MMM DD',
}
...
Notice that I've set all the unit's display format to MMM DD
. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'MMM DD'
}
...
Fiddle - http://jsfiddle.net/prfd1m8q/
paste -sd+ infile | bc
<cmd> | paste -sd+ | bc
Edit: With some paste implementations you need to be more explicit when reading from stdin:
<cmd> | paste -sd+ - | bc
function calcSize($size,$accuracy=2) {
$units = array('b','Kb','Mb','Gb');
foreach($units as $n=>$u) {
$div = pow(1024,$n);
if($size > $div) $output = number_format($size/$div,$accuracy).$u;
}
return $output;
}
EDIT: I'm torn on whether to delete this post. As a matter of understanding the CSS syntax, it's good that people know all
exists, and it may at times be preferable to a million individual declarations, depending on the structure of your CSS. On the other hand, it may have a performance penalty, although I've yet to see any data supporting that hypothesis. For now, I'll leave it, but I want people to be aware it's a mixed bag.
You can also simply significantly with:
.nav a {
transition: all .2s;
}
FWIW: all
is implied if not specified, so transition: .2s;
will get you to the same place.
When is the global .gitconfig file created?
First off, git doesn't automatically create the global config file (.gitconfig) during its installation. The file is not created until it is written to for the first time. If you have never set a system variable, it will not be on your file system. I'm guessing that might be the source of the problem.
One way to ask Git to create it is to request an edit. Doing so will force the file's creation.
git config --global --edit
If you monitor the user's home folder when you issue this command, you will see the .gitconfig file magically appear.
Where is git configuration stored?
Here's a quick rundown of the the name and location of the configuration files associated with the three Git scopes, namely system, global and local:
Of course, seeing is believing, so here's an image showing each file and each location. I pulled the image from an article I wrote on the topic.
Windows Git configuration file locations (TheServerSide.com)
sed
is the stream editor, in that you can use |
(pipe) to send standard streams (STDIN and STDOUT specifically) through sed
and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition; but can edit files directly, too, using the -i
parameter mentioned below.
Consider the following:
sed -i -e 's/few/asd/g' hello.txt
s/
is used to substitute the found expression few
with asd
:
The few, the brave.
The asd, the brave.
/g
stands for "global", meaning to do this for the whole line. If you leave off the /g
(with s/few/asd/
, there always needs to be three slashes no matter what) and few
appears twice on the same line, only the first few
is changed to asd
:
The few men, the few women, the brave.
The asd men, the few women, the brave.
This is useful in some circumstances, like altering special characters at the beginnings of lines (for instance, replacing the greater-than symbols some people use to quote previous material in email threads with a horizontal tab while leaving a quoted algebraic inequality later in the line untouched), but in your example where you specify that anywhere few
occurs it should be replaced, make sure you have that /g
.
The following two options (flags) are combined into one, -ie
:
-i
option is used to edit in place on the file hello.txt
.
-e
option indicates the expression/command to run, in this case s/
.
Note: It's important that you use -i -e
to search/replace. If you do -ie
, you create a backup of every file with the letter 'e' appended.
I am the developer for Coupious mobile coupons iPhone app and with the amount of time that I spent on that application (v1.0 - v1.5), it was probably a $15,000 - $20,000 investment. However, to be fair, I do admit that I was the only developer working on it and when I started the project, I had never seen or used Objective-C before. Despite that, three months later, it was released so the numbers are probably a little skewed because there was a fair amount of learning going on as well as coding.
However, iPhone competent developers run in the range of $80-$150 depending on their skill and time with the platform. I would say that for a simple application, an app would probably run 2K-5K, a medium complexity app would run 5K-15K and a fairly complex app running 15K-30K. Game applications could be even more.
The reason it is so high is that the skill is fairly specialized and not everyone is able to do it
slicing operator. http://docs.python.org/tutorial/introduction.html#strings and scroll down a bit
DateTime dt = this.dateTimePicker1.Value.Date;
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
$('.sys').children('input[type=text], select').each(function () { ... });
EDIT: Actually this code above is equivalent to the children selector .sys > input[type=text]
if you want the descendant select (.sys input[type=text]
) you need to use the options given by @NiftyDude.
More information:
For Jupyter and Windows users, you can change the Target path in your Jupyter Notebook (anaconda3)
shortcut from C:\Users\<YourUserName>\anaconda3
to C:\Users\<YourUserName>\anaconda3\envs\<YourEnvironmentName>
you could do the same thing for the Anaconda Prompt..etc.
After changing the path you can check your active environment by opening a terminal in Jupyter and run conda info --envs
.
Please keep in mind that the answers here assume that the length of the file is less than or equal to Integer.MAX_VALUE
(2147483647).
If you are reading in from a file, you can do something like this:
File file = new File("myFile");
byte[] fileData = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData);
dis.close();
Java 7 adds some new features in the java.nio.file package that can be used to make this example a few lines shorter. See the readAllBytes() method in the java.nio.file.Files class. Here is a short example:
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
// ...
Path p = FileSystems.getDefault().getPath("", "myFile");
byte [] fileData = Files.readAllBytes(p);
Android has support for this starting in Api level 26 (8.0.0, Oreo).
Fixing the comparison:
At this point it's a little premature to compare EFS and EBS- the performance of EFS isn't known, nor is its reliability known.
Why would you use S3?
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
I tend to use JAX-RS using Jersey (you can write nice resource beans in Scala, Java or Groovy) to write RESTul web applications. Then I use Scalate for the rendering the views using one of the various template languages (JADE, Scaml, Ssp (Scala Server Pages), Mustache, etc.).
I had the same problem and not any of the above mentioned solutions worked.
Until I updated conda packages:
conda update conda
conda update anaconda
and ... Voila! It all works!
Nothing in the example says that the "classes implementing the same interface". MovieCatalog
is a type and CustomerPreferenceDao
is another type. Spring can easily tell them apart.
In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".
What the examples show is various ways that you can use to inject beans into fields, methods and constructors.
The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:
This autowiring will fail:
@Autowired
public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }
Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier
:
@Autowired
public void prepare( @Qualifier("bean1") Interface1 bean1,
@Qualifier("bean2") Interface1 bean2 ) { ... }
Kotlin Native:
memScoped {
val q = alloc<utsname>()
uname(q.ptr)
val identifier = NSString.stringWithCString(q.machine, encoding = NSUTF8StringEncoding)
}
Remove the first /
in the path. Also you don't need type="text/javascript"
anymore in HTML5.
While you do the following, technically speaking:
<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
//reference to the button that triggered the function:
$event.target
};
This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.
You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796
Best way to use sql brackets use callback function in laravel eloquent.
YourModal::where(function ($q) {
$q->where('a', 1)->orWhere('b', 1);
})->where(function ($q) {
$q->where('c', 1)->orWhere('d', 1);
});
You don't have to use
=
symbol, it's come as the default
Lest say if you have a query that contain brackets inside a brackets
WHERE (a = 1 OR (b = 1 and c = 5))
YourModal::where(function ($q) {
$q->where('a', 1)->orWhere(function($q2){
$q2->where('b', 1)->where('c', 5);
});
});
lest say you want to make values dynamics
YourModal::where(function ($q) use($val1, $val2) {
$q->where('a', $val1)->orWhere(function($q2) use($val2){
$q2->where('b', $val2)->where('c', $val2);
});
});
try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b
jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
jQuery('#main').animate('opacity') = '0.6';
Or without the year:
DateTime.Now.ToString("M/dd")
The "-1" part represents the "step" part of the slicing—in this case, it goes through the string 1 character at a time, but backwards (a negative step means start from the end of the string). If you specify the step to be 2, for instance, you would get every other character of the string, starting with the first one. If you specify a step of -2, then you'd get every other character of the string, starting with the last character and working backwards.
So, in a nutshell, if a = '12345'
:
a[::2]
becomes 135
a[::-1]
becomes 54321
a[::-2]
becomes 531
This should give you a start
>>> for col in range(arr.shape[1]):
some_function(arr[:,col])
[1 2 3 4]
[99 14 12 43]
[2 5 7 1]
Another way would be to catch the exeption:
def is_nat(npdatetime):
try:
npdatetime.strftime('%x')
return False
except:
return True
You can use this code:
<select id="menu" name="links" size="1" onchange="window.location.href=this.value;">
<option value="URL">Book</option>
<option value="URL">Pen</option>
<option value="URL">Read</option>
<option value="URL">Apple</option>
</select>
In Firefox you can just add background image to option:
<select>
<option style="background-image:url(male.png);">male</option>
<option style="background-image:url(female.png);">female</option>
<option style="background-image:url(others.png);">others</option>
</select>
Better yet, you can separate HTML and CSS like that
HTML
<select id="gender">
<option>male</option>
<option>female</option>
<option>others</option>
</select>
CSS
select#gender option[value="male"] { background-image:url(male.png); }
select#gender option[value="female"] { background-image:url(female.png); }
select#gender option[value="others"] { background-image:url(others.png); }
In other browsers the only way of doing that would be using some JS widget library, like for example jQuery UI, e.g. using Selectable.
From jQuery UI 1.11, Selectmenu widget is available, which is very close to what you want.
You can use:
if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
//...
}
This works with any .NET version.
The Proxy pattern might help you:
(function() {
// log all calls to setArray
var proxied = jQuery.fn.setArray;
jQuery.fn.setArray = function() {
console.log( this, arguments );
return proxied.apply( this, arguments );
};
})();
The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.
FYI I just tested this and the stack trace reported by 'throw;' is not an entirely correct stack trace. Example:
private void foo()
{
try
{
bar(3);
bar(2);
bar(1);
bar(0);
}
catch(DivideByZeroException)
{
//log message and rethrow...
throw;
}
}
private void bar(int b)
{
int a = 1;
int c = a/b; // Generate divide by zero exception.
}
The stack trace points to the origin of the exception correctly (reported line number) but the line number reported for foo() is the line of the throw; statement, hence you cannot tell which of the calls to bar() caused the exception.
If you want your JSON to have a validated Typescript type, you will need to do that validation work yourself. This is nothing new. In plain Javascript, you would need to do the same.
I like to express my validation logic as a set of "transforms". I define a Descriptor
as a map of transforms:
type Descriptor<T> = {
[P in keyof T]: (v: any) => T[P];
};
Then I can make a function that will apply these transforms to arbitrary input:
function pick<T>(v: any, d: Descriptor<T>): T {
const ret: any = {};
for (let key in d) {
try {
const val = d[key](v[key]);
if (typeof val !== "undefined") {
ret[key] = val;
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(`could not pick ${key}: ${msg}`);
}
}
return ret;
}
Now, not only am I validating my JSON input, but I am building up a Typescript type as I go. The above generic types ensure that the result infers the types from your "transforms".
In case the transform throws an error (which is how you would implement validation), I like to wrap it with another error showing which key caused the error.
In your example, I would use this as follows:
const value = pick(JSON.parse('{"name": "Bob", "error": false}'), {
name: String,
error: Boolean,
});
Now value
will be typed, since String
and Boolean
are both "transformers" in the sense they take input and return a typed output.
Furthermore, the value
will actually be that type. In other words, if name
were actually 123
, it will be transformed to "123"
so that you have a valid string. This is because we used String
at runtime, a built-in function that accepts arbitrary input and returns a string
.
You can see this working here. Try the following things to convince yourself:
const value
definition to see that the pop-over shows the correct type."Bob"
to 123
and re-run the sample. In your console, you will see that the name has been properly converted to the string "123"
.try this within your if statements:
Application.DisplayAlerts = False
Worksheets(“Sheetname”).Delete
Application.DisplayAlerts = True
To customize the colors for the carousel controls, captions, and indicators using Sass you can include these variables
$carousel-control-color:
$carousel-caption-color:
$carousel-indicator-active-bg:
Youre looking for the builtin function zip.
These examples cover the three types of shifts applied to both a positive and a negative number:
// Signed left shift on 626348975
00100101010101010101001110101111 is 626348975
01001010101010101010011101011110 is 1252697950 after << 1
10010101010101010100111010111100 is -1789571396 after << 2
00101010101010101001110101111000 is 715824504 after << 3
// Signed left shift on -552270512
11011111000101010000010101010000 is -552270512
10111110001010100000101010100000 is -1104541024 after << 1
01111100010101000001010101000000 is 2085885248 after << 2
11111000101010000010101010000000 is -123196800 after << 3
// Signed right shift on 626348975
00100101010101010101001110101111 is 626348975
00010010101010101010100111010111 is 313174487 after >> 1
00001001010101010101010011101011 is 156587243 after >> 2
00000100101010101010101001110101 is 78293621 after >> 3
// Signed right shift on -552270512
11011111000101010000010101010000 is -552270512
11101111100010101000001010101000 is -276135256 after >> 1
11110111110001010100000101010100 is -138067628 after >> 2
11111011111000101010000010101010 is -69033814 after >> 3
// Unsigned right shift on 626348975
00100101010101010101001110101111 is 626348975
00010010101010101010100111010111 is 313174487 after >>> 1
00001001010101010101010011101011 is 156587243 after >>> 2
00000100101010101010101001110101 is 78293621 after >>> 3
// Unsigned right shift on -552270512
11011111000101010000010101010000 is -552270512
01101111100010101000001010101000 is 1871348392 after >>> 1
00110111110001010100000101010100 is 935674196 after >>> 2
00011011111000101010000010101010 is 467837098 after >>> 3
Also, you can use shelljs
plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo
I had the same error message while trying to deploy the application. In Spring, the security configuration xml can be a different one from applicationContext.xml, usually applicationContext-security.xml inside WEB-INF folder. The changes to be applied are for web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
And the applicationContext.xml would look like:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config='true'>
<intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page='login.jsp'/>
</http>
</beans:beans>
Even after you make these changes, the namespace error will exist. To get rid of this, add the following jar files to the WEB-INF/lib and then to the library:
For those who want to access a file from an already loaded PowerShell session, either use Unblock-File to mark the file as safe (though you already need to have set a relaxed execution policy like Unrestricted
for this to work), or change the execution policy just for the current PowerShell session:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear:
And trying to move a not-too-long basename to a too-long-pathname is also very clear:
The pathname error is deceptive, though. Quite unhelpful:
This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.
From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.
This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.
I use google newly released Material Design Library. In my case, it works when I use android:focusable="false" and android:cursorVisible="false"
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/to_time_input_layout"
app:endIconMode="custom"
app:endIconDrawable="@drawable/ic_clock"
app:endIconContentDescription="ToTime"
app:endIconTint="@color/colorAccent"
style="@style/OutlinedEditTextStyle"
android:hint="To Time">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/to_time_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:cursorVisible="false" />
</com.google.android.material.textfield.TextInputLayout>
window.onload = codeAddress;
should work - here's a demo, and the full code:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Test</title>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<script type="text/javascript">_x000D_
function codeAddress() {_x000D_
alert('ok');_x000D_
}_x000D_
window.onload = codeAddress;_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Test</title>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<script type="text/javascript">_x000D_
function codeAddress() {_x000D_
alert('ok');_x000D_
}_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
<body onload="codeAddress();">_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Please be careful,
MSSQL: "SELECT * INTO NewTable FROM OldTable"
is not always the same as
MYSQL: "create table temp AS select.."
I think that there are occasions when this (in MSSQL) does not guarantee that all the fields in the new table are of the same type as the old.
For example :
create table oldTable (field1 varchar(10), field2 integer, field3 float)
insert into oldTable (field1,field2,field3) values ('1', 1, 1)
select top 1 * into newTable from oldTable
does not always yield:
create table newTable (field1 varchar(10), field2 integer, field3 float)
but may be:
create table newTable (field1 varchar(10), field2 integer, field3 integer)
Automatic Package Restore will fail for any of the following reasons:
The following article outlines in more detail how to go about points 1-3: https://docs.nuget.org/consume/package-restore/migrating-to-automatic-package-restore
I only have the need to push files during a build, so I just added a Post-build Event Command Line entry like this:
Copy /Y "$(SolutionDir)Third Party\SomeLibrary\*" "$(TargetDir)"
You can set this by right-clicking your Project in the Solution Explorer, then Properties > Build Events
Ok, so you've found a solution already. Just wanted to share what has been useful to me so many times;
I have created setpy2
alias which helps me switch python.
alias setpy2="mkdir -p /tmp/bin; ln -s `which python2.7` /tmp/bin/python; export PATH=/tmp/bin:$PATH"
Execute setpy2
before you run npm install
. The switch stays in effect until you quit the terminal, afterwards python
is set back to system default.
You can make use of this technique for any other command/tool as well.
You can store this in a long
. A long
can store a value from -9223372036854775808
to 9223372036854775807
.
Add this to your main CSS:
table td {
border-top: none !important;
}
Use this for newer versions of bootstrap:
.table th, .table td {
border-top: none !important;
}
@echo off
color 0B
echo =============================================================================
echo.
echo ClockworkMod Recovery for SAMSUNG GALAXY SIII E210L
echo.
echo ClockworkMod Recovery (v6.0.1.2 Touch)
echo.
echo ¡ô¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¡ô
echo ¨U ¨U
echo ¨U SAMSUNG GALAXY SIII E210L ¨U
echo ¡ô¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¡ô
echo.
echo 1) (Settings\Developer options©¥ USB debugging)
echo.
echo 2) CWM SAMSUNG GALAXY SIII E210L
echo.
echo 3) THANK!!!!!!
echo.
echo =============================================================================
echo ARE YOU READY? GO! ¡·¡·¡·
@pause
echo.
echo adb...
adb.exe kill-server
adb.exe wait-for-device
echo wiat¸!
echo.
echo conect...
adb.exe push IMG /data/local/tmp/
adb.exe shell su -c "dd if=/data/local/tmp/GANGSTAR-VEGAS-1.3.0-APK-Andropalace.net.apk of=/mnt/sdcard/Android/GANGSTAR-VEGAS-1.3.0-APK-Andropalace.net.apk
adb.exe shell su -c "rm /data/local/tmp/bootloader.img"
adb.exe shell su -c "rm /data/local/tmp/recovery.img"
echo ===============================================================
echo ClockworkMod Recovery!
echo.
@pause
With ASP.NET Core 2.0, the ideal way to return object from Web API
(which is unified with MVC and uses same base class Controller
) is
public IActionResult Get()
{
return new OkObjectResult(new Item { Id = 123, Name = "Hero" });
}
Notice that
200 OK
status code (it's an Ok
type of ObjectResult
)Accept
header in request. If Accept: application/xml
is sent in request, it'll return as XML
. If nothing is sent, JSON
is default.If it needs to send with specific status code, use ObjectResult
or StatusCode
instead. Both does the same thing, and supports content negotiation.
return new ObjectResult(new Item { Id = 123, Name = "Hero" }) { StatusCode = 200 };
return StatusCode( 200, new Item { Id = 123, Name = "Hero" });
or even more fine grained with ObjectResult:
Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection myContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { System.Net.Mime.MediaTypeNames.Application.Json };
String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
return new ObjectResult(hardCodedJson) { StatusCode = 200, ContentTypes = myContentTypes };
If you specifically want to return as JSON, there are couple of ways
//GET http://example.com/api/test/asjson
[HttpGet("AsJson")]
public JsonResult GetAsJson()
{
return Json(new Item { Id = 123, Name = "Hero" });
}
//GET http://example.com/api/test/withproduces
[HttpGet("WithProduces")]
[Produces("application/json")]
public Item GetWithProduces()
{
return new Item { Id = 123, Name = "Hero" };
}
Notice that
JSON
in two different ways.Json(object)
.Produces()
attribute (which is a ResultFilter
) with contentType = application/json
Read more about them in the official docs. Learn about filters here.
The simple model class that is used in the samples
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
adding following to application.rb
works
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local # Or :utc
if dosen't work after
$ npm install lodash --save
$ npm install --save-dev @types/lodash
you try this and import lodash
typings install lodash --save
Use of folloing command is depreciated
hadoop job -list
hadoop job -kill $jobId
consider using
mapred job -list
mapred job -kill $jobId
The SNIPPETS C Source Code Archive has a CRC32 implementation that is freely usable:
/* Copyright (C) 1986 Gary S. Brown. You may use this program, or
code or tables extracted from it, as desired without restriction.*/
(Unfortunately, c.snippets.org seems to have died. Fortunately, the Wayback Machine has it archived.)
In order to be able to compile the code, you'll need to add typedefs for BYTE
as an unsigned 8-bit integer and DWORD
as an unsigned 32-bit integer, along with the header files crc.h & sniptype.h.
The only critical item in the header is this macro (which could just as easily go in CRC_32.c itself:
#define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8))
Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:
ignore_user_abort(TRUE);
In this way even if wget
terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time
limit (ini directive: 30 seconds by default).
As per wget
anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.
It isn't necessary. It's a quirk of the language.
A good, concise article by Pankaj Malhotra discusses how to do this with NGINX and is available here.
The basic NGINX configuration is reproduced below:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream appserver {
server 192.168.100.10:9222; # appserver_ip:ws_port
}
server {
listen 8888; // client_wss_port
ssl on;
ssl_certificate /path/to/crt;
ssl_certificate_key /path/to/key;
location / {
proxy_pass http://appserver;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
With WinForms you can use the ErrorProvider in conjunction with the Validating
event to handle the validation of user input. The Validating
event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx
Just putting it out there..... docs: https://laravel.com/docs/7.x/requests
Hope, this might help the best : Random Number Generators in Java
import java.util.Random;
public class SecondSplitExample
{
public static void main(String []arguments)
{
int minValue = 20, maxValue=20000;
Random theRandom = new Random();
double theRandomValue = 0.0;
// Checking for a valid range-
if( Double.valueOf(maxValue - minValue).isInfinite() == false )
theRandomValue = minValue + (maxValue - minValue) * theRandom.nextDouble();
System.out.println("Double Random Number between ("+ minValue +","+ maxValue +") = "+ theRandomValue);
}
}
Here is the output of 3 runs:
Code>java SecondSplitExample
Double Random Number between (20,20000) = 2808.2426532469476
Code>java SecondSplitExample
Double Random Number between (20,20000) = 1929.557668284786
Code>java SecondSplitExample
Double Random Number between (20,20000) = 13254.575289900251
Learn More:
Using the accepted answer to create an alias
oops = "!f(){ \
git add -A; \
if [ \"$1\" == '' ]; then \
git commit --amend --no-edit; \
else \
git commit --amend \"$@\"; \
fi;\
}; f"
then you can do
git oops
and it will add everything, and amend using the same message
or
git oops -m "new message"
to amend replacing the message
This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.
So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader
instance. Any time you are creating a Reader
from an InputStream
, you need to specify the character encoding, or java.nio.charset.Charset
instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8
). If you don't specify a Charset
, Java will use your platform default encoding, which on Windows is usually CP-1252.
You can use HTML5 for this:
<video autoplay></video>
<script>
var onFailSoHard = function(e) {
console.log('Reeeejected!', e);
};
// Not showing vendor prefixes.
navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
// Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
// See crbug.com/110938.
video.onloadedmetadata = function(e) {
// Ready to go. Do some stuff.
};
}, onFailSoHard);
</script>
One more possible way — use XOR operation:
console.log(12.3 ^ 0); // 12
console.log("12.3" ^ 0); // 12
console.log(1.2 + 1.3 ^ 0); // 2
console.log(1.2 + 1.3 * 2 ^ 0); // 3
console.log(-1.2 ^ 0); // -1
console.log(-1.2 + 1 ^ 0); // 0
console.log(-1.2 - 1.3 ^ 0); // -2
_x000D_
Priority of bitwise operations is less then priority of math operations, it's useful. Try on https://jsfiddle.net/au51uj3r/
First download json package file from https://github.com/npm/read-package-json and then run npm install from terminal.
In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:
public class Test {
class Control {
public volatile boolean flag = false;
}
final Control control = new Control();
class T1 implements Runnable {
@Override
public void run() {
while ( !control.flag ) {
}
}
}
class T2 implements Runnable {
@Override
public void run() {
while ( !control.flag ) {
}
}
}
private void test() {
T1 main = new T1();
T2 help = new T2();
new Thread(main).start();
new Thread(help).start();
}
public static void main(String[] args) throws InterruptedException {
try {
Test test = new Test();
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I used below to fix issue
yum install -y php-intl php-xsl php-opcache php-xml php-mcrypt php-gd php-devel php-mysql php-mbstring php-bcmath
You will need to alter table abc modify (salary default 0);
Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:
x = int("deadbeef", 16)
With the 0x prefix, Python can distinguish hex and decimal automatically.
>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10
(You must specify 0
as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter int()
will assume base-10.)
As AMissico's answer requires changing the log level, and neither ASMSpy nor ASMSpyPlus are available as a cross-platform solution, here is a short addition for Visual Studio for Mac:
https://docs.microsoft.com/en-us/visualstudio/mac/compiling-and-building
It's in Visual Studio Community ? Preferences... ? Projects ? Build Log ? verbosity
I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:
public event EventHandler Foo;
If you need more complicated subscription/unsubscription logic, you can do that explicitly:
public event EventHandler Foo
{
add
{
// Subscription logic here
}
remove
{
// Unsubscription logic here
}
}
Enter the following code in the opened settings file
{
"editor.formatOnSave": true
}
Save file
With RxJS 5.5+, the catch
operator is now deprecated. You should now use the catchError
operator in conjunction with pipe
.
RxJS v5.5.2 is the default dependency version for Angular 5.
For each RxJS Operator you import, including catchError
you should now import from 'rxjs/operators' and use the pipe operator.
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...
export class ExampleClass {
constructor(private http: HttpClient) {
this.http.request(method, url, options).pipe(
catchError((err: HttpErrorResponse) => {
...
}
)
}
...
}
Notice here that catch
is replaced with catchError
and the pipe
operator is used to compose the operators in similar manner to what you're used to with dot-chaining.
See the rxjs documentation on pipable (previously known as lettable) operators for more info.
If you do not want to use DecimalFormat (e.g. due to its efficiency) and you want a general solution, you could also try this method that uses scaled rounding:
public static double roundToDigits(double value, int digitCount) {
if (digitCount < 0)
throw new IllegalArgumentException("Digit count must be positive for rounding!");
double factor = Math.pow(10, digitCount);
return (double)(Math.round(value * factor)) / factor;
}
fooList = [1,3,348,2]
fooList.append(3)
fooList.append(2734)
print(fooList) # [1,3,348,2,3,2734]
I packaged ideas from several SQL based answers here, mainly the root answer by Alex Aza, into klassify, a console application that generates all the classes for a specified database at once:
For example, given a table Users
that looks like this:
+----+------------------+-----------+---------------------+
| Id | Name | Username | Email |
+----+------------------+-----------+---------------------+
| 1 | Leanne Graham | Bret | [email protected] |
| 2 | Ervin Howell | Antonette | [email protected] |
| 3 | Clementine Bauch | Samantha | [email protected] |
+----+------------------+-----------+---------------------+
klassify
will generate a file called Users.cs
that looks like this:
public class User
{
public int Id {get; set; }
public string Name { get;set; }
public string Username { get; set; }
public string Email { get; set; }
}
It will output one file for every table. Discard what you don't use.
Usage
--out, -o:
output directory << defaults to the current directory >>
--user, -u:
sql server user id << required >>
--password, -p:
sql server password << required >>
--server, -s:
sql server << defaults to localhost >>
--database, -d:
sql database << required >>
--timeout, -t:
connection timeout << defaults to 30 >>
--help, -h:
show help
I simply install all the versions of JDK I need and the latest installed becomes default, so I just reinstall the one I want to be default if necessary.
By using Axios interceptor:
const service = axios.create({
timeout: 20000 // request timeout
});
// request interceptor
service.interceptors.request.use(
config => {
// Do something before request is sent
config.headers["Authorization"] = "bearer " + getToken();
return config;
},
error => {
Promise.reject(error);
}
);
In my case i removed
Restart=always
added
tty: true
And executed the below command to open shell (daemon process, because docker reads the compose file and stops the container once it reaches the last line of the file).
docker-compose up -d
The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
or if you prefer to put the Inner class in another file:
Outer.cs
partial class Outer
{
}
Inner.cs
partial class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
Obligatory jQuery solution. Finds and sets the title
attribute to foo
. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.
$('#element').attr( 'title', 'foo' );
Here's how to make and print a 2D Multi-Dimensional Array using the ArrayList Object.
import java.util.ArrayList;
public class TwoD_ArrayListExample {
static public ArrayList<ArrayList<String>> gameBoard = new ArrayList<ArrayList<String>>();
public static void main(String[] args) {
insertObjects();
printTable(gameBoard);
}
public static void insertObjects() {
for (int rowNum = 0; rowNum != 8; rowNum++) {
ArrayList<String> oneRow = new ArrayList<String>();
gameBoard.add(rowNum, oneRow);
for (int columnNum = 0; columnNum != 8; columnNum++) {
String description= "Description of Objects: row= "+ rowNum + ", column= "+ columnNum;
oneRow.add(columnNum, description);
}
}
}
// The printTable method prints the table to the console
private static void printTable(ArrayList<ArrayList<String>> table) {
for (int row = 0; row != 8; row++) {
for (int col = 0; col != 8; col++) {
System.out.println("Printing: row= "+ row+ ", column= "+ col);
System.out.println(table.get(row).get(col).toString());
}
}
System.out.println("\n");
}
}
You can use Server.Map
path to give relative path and then you can either create image using base64
conversion or you can just add base64
string to image src
.
byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
you can use the function below
SELECT TRUNC(14.568,2);
the result will show :
14.56
you can also cast your variable to the desire type :
SELECT TRUNC(YOUR_VAR::numeric,2)
Alternatively, if you want to get the IP address of whichever interface is used to connect to the network without having to know its name, you can use this:
import socket
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
I know it's a little different than your question, but others may arrive here and find this one more useful. You do not have to have a route to 8.8.8.8 to use this. All it is doing is opening a socket, but not sending any data.
For anyone else looking for answer to the question when dealing with different linebreaks:
string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", ""); // Java 8
This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R"
is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
This passes these tests:
// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));
// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));
// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));
An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/
A step by step guide I found here.
To create a read-only database user account for MySQL
At a UNIX prompt, run the MySQL command-line program, and log in as an administrator by typing the following command:
mysql -u root -p
Type the password for the root account. At the mysql prompt, do one of the following steps:
To give the user access to the database from any host, type the following command:
grant select on database_name.* to 'read-only_user_name'@'%' identified by 'password';
If the collector will be installed on the same host as the database, type the following command:
grant select on database_name.* to 'read-only_user_name' identified by 'password';
This command gives the user read-only access to the database from the local host only. If you know the host name or IP address of the host that the collector is will be installed on, type the following command:
grant select on database_name.* to 'read-only_user_name'@'host_name or IP_address' identified by 'password';
The host name must be resolvable by DNS or by the local hosts file. At the mysql prompt, type the following command:
flush privileges;
Type quit
.
The following is a list of example commands and confirmation messages:
mysql> grant select on dbname.* to 'readonlyuser'@'%' identified
by 'pogo$23';
Query OK, 0 rows affected (0.11 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
You can do that using the descendant selectors:
$("#a #b")
However, id values are supposed to be unique on a page.
The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range
you use.
Please read this explanation and its conclusion, which I guess will give essential information.
The error you are getting is likely due to the sought-for value Sheet2!D2
not being found in the searched range Sheet1!A1:A65536
. This may stem from two cases:
The value is actually not present (pointed out by chris nielsen).
You are searching the wrong Range. If the ActiveSheet
is Sheet1
, then using Range("D2")
without qualifying it will be searching for Sheet1!D2
, and it will throw the same error even if the sought-for value is present in the correct Range.
Code accounting for this (and items below) follows:
Sub srch()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim srchres As Variant
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
On Error Resume Next
srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
On Error GoTo 0
If (IsEmpty(srchres)) Then
ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
Else
ws2.Range("E2").Value = srchres
End If
End Sub
I will point out a few additional notable points:
Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup
(although it will not suitably handle case 2 above).
This catching is actually performed by the function VLOOKUP
as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A
in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...
).
Using =VLOOKUP...
is fundamentally different from Application.WorksheetFunction.VLookup
: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.
Both solutions by L42 qualify Ranges suitably.
You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).
Just to elaborate on the etymology of the command name rev-parse
, Git consistently uses the term rev
in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list
for example prints a list of 40-char commit hashes for a branch or whatever.
In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash
. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.
I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)
Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.
Instead of overwriting the html every time, just toggle the class.
$('#click_advance').click(function() {
$('#display_advance').toggle('1000');
$("i", this).toggleClass("icon-circle-arrow-up icon-circle-arrow-down");
});
With PowerShell 5.1 (PackageManagement module)
Install-Package -Name MyPackage -Source (Get-Location).Path -Destination C:\outputdirectory
You're nearly there, just take out the EXECUTE:
DECLARE
procId NUMBER;
BEGIN
PKG1.INIT(1143824, 0, procId);
DBMS_OUTPUT.PUT_LINE(procId);
END;
The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")
check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print
I did it in one project of mine. I used MDB to store the data about bills and used Excel to render them, giving the user the possibility to adapt it.
In this case the best solution is:
Not to use any ADO/DAO in Excel. I implemented everything as public functions in MDB modules and called them directly from Excel. You can return even complex data objects, like arrays of strings etc by calling MDB functions with necessary arguments. This is similar to client/server architecture of modern web applications: you web application just does the rendering and user interaction, database and middle tier is then on the server side.
Use Excel forms for user interaction and for data visualisation.
I usually have a very last sheet with some names regions for settings: the path to MDB files, some settings (current user, password if needed etc.) -- so you can easily adapt your Excel implementation to different location of you "back-end" data.
You need the actual instance of the WindowSettings
that's open, not a new one.
Currently, you are creating a new instance of WindowSettings
and calling Close
on that. That doesn't do anything because that new instance never has been shown.
Instead, when showing DialogSettingsCancel
set the current instance of WindowSettings
as the parent.
Something like this:
In WindowSettings
:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel();
dialogSettingsCancel.OwningWindowSettings = this;
dialogSettingsCancel.Show();
}
In DialogSettingsCancel
:
public WindowSettings OwningWindowSettings { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Close();
if(OwningWindowSettings != null)
OwningWindowSettings.Close();
}
This approach takes into account, that a DialogSettingsCancel
could potentially be opened without a WindowsSettings
as parent.
If the two are always connected, you should instead use a constructor parameter:
In WindowSettings
:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel(this);
dialogSettingsCancel.Show();
}
In DialogSettingsCancel
:
WindowSettings _owningWindowSettings;
public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
if(owningWindowSettings == null)
throw new ArgumentNullException("owningWindowSettings");
_owningWindowSettings = owningWindowSettings;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
_owningWindowSettings.Close();
}
The answer above didn't work for me, what did eventually was this syntax:
curl https://${URL} &> /dev/stdout | tee -a ${LOG}
tee puts the output on the screen, but also appends it to my log.
Here is screenshot of my Pycharm. Required settings is in following path: File -> Settings -> Editor -> Code Style -> General: Right margin (columns)
If you are in same WORKGROUP you need software to connect and control the target server.shutdown.exe /s /m \\<target-computer-name>
should be enough shutdown /?
for more, otherwise
UPDATE:
Seems shutdown.bat here is for shutting down apache-tomcat.
So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client
As native solution could be wmic
Example:
wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"
In your example should be:
wmic /node:inidsoasrv01 process call create ^
"cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"
wmic /?
and wmic /node /?
for more
It probably just asks the operating system provided function, rather than its own algorithm.
As other comments says, use hashlib or write your own hash function.
Yes... The first parameter of the RAISERROR function needs an NVARCHAR variable. So try the following;
-- Replace PRINT function
DECLARE @strMsg NVARCHAR(100)
SELECT @strMsg = 'Here''s your message...'
RAISERROR (@strMsg, 0, 1) WITH NOWAIT
OR
RAISERROR (n'Here''s your message...', 0, 1) WITH NOWAIT
Solution:
Add the following to your Vagrantfile
:
config.ssh.username = 'root'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'
When you vagrant ssh
henceforth, you will login as root
and should expect the following:
==> mybox: Waiting for machine to boot. This may take a few minutes...
mybox: SSH address: 127.0.0.1:2222
mybox: SSH username: root
mybox: SSH auth method: password
mybox: Warning: Connection timeout. Retrying...
mybox: Warning: Remote connection disconnect. Retrying...
==> mybox: Inserting Vagrant public key within guest...
==> mybox: Key inserted! Disconnecting and reconnecting using new SSH key...
==> mybox: Machine booted and ready!
Update 23-Jun-2015: This works for version 1.7.2 as well. Keying security has improved since 1.7.0; this technique overrides back to the previous method which uses a known private key. This solution is not intended to be used for a box that is accessible publicly without proper security measures done prior to publishing.
Reference:
Above answers are pretty good, just wanted to add short form for this
<input type="text" name="input_text" onKeyUP="this.value = this.value.toUpperCase();">
Ok. I think I found the proper solution:
v = [x[0]-x[1] for x in zip(t[1:],t[:-1])]
We use this instruction to obtain users according to two conditions, type of user classification and user name.
Here we use two conditions for filtering as you type in addition to fetching user information from the profiles table to reduce the number of queries.
$users = $this->user->where([
['name','LIKE','%'.$request->name.'%'],
['trainers_id','=',$request->trainers_id]
])->with('profiles')->paginate(10);
In InnoDB, with a limit on table size of 64 terabytes and a MySQL row-size limit of 65,535 there can be 1,073,741,824 rows. That would be minimum number of records utilizing maximum row-size limit. However, more records can be added if the row size is smaller .
After struggling with this myself, I've come to implement FileReader for browsers that support it (Chrome, Firefox and the as-yet unreleased Safari 6), and a PHP script that echos back POSTed file data as Base64-encoded data for the other browsers.
You can use jquery for this:
$('body').bind('copy paste',function(e) {
e.preventDefault(); return false;
});
Using jQuery bind()
and specififying your desired eventTypes
.
Use this css code for all four sides: box-shadow: 0px 1px 7px 0px rgb(106, 111, 109);
Some cases you might want to kill all the process running in a specific port. For example, if I am running a node app on 3000 port and I want to kill that and start a new one; then I found this command useful.
Find the process IDs running on TCP port 3000 and kill it
kill -9 `lsof -i TCP:3000 | awk '/LISTEN/{print $2}'`
http://requestb.in was similar to the already mentioned tools and also had a very nice UI.
RequestBin gives you a URL that will collect requests made to it and let you inspect them in a human-friendly way. Use RequestBin to see what your HTTP client is sending or to inspect and debug webhook requests.
Though it has been discontinued as of Mar 21, 2018.
We have discontinued the publicly hosted version of RequestBin due to ongoing abuse that made it very difficult to keep the site up reliably. Please see instructions for setting up your own self-hosted instance.
Solved by using "http://jcenter.bintray.com/" instead of "https://jcenter.bintray.com/".
repositories {
jcenter( { url "http://jcenter.bintray.com/" } )
}
It should be that the particular mvn
command exec
s and does not return, thereby not executing the rest of the commands.
Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.
This provides a reasonable graph for me (using Excel 2010).
pg_basebackup
seems to be the better way of doing this now, especially for large databases.
You can copy a database from a server with the same or older major version. Or more precisely:
pg_basebackup
works with servers of the same or an older major version, down to 9.1. However, WAL streaming mode (-X stream
) only works with server version 9.3 and later, and tar format mode (--format=tar
) of the current version only works with server version 9.5 or later.
For that you need on the source server:
listen_addresses = '*'
to be able to connect from the target server. Make sure port 5432 is open for that matter.max_wal_senders = 1
(-X fetch
), 2
for -X stream
(the default in case of PostgreSQL 12), or more.wal_level = replica
or higher to be able to set max_wal_senders > 0
.host replication postgres DST_IP/32 trust
in pg_hba.conf
. This grants access to the pg
cluster to anyone from the DST_IP
machine. You might want to resort to a more secure option.Changes 1, 2, 3 require server restart, change 4 requires reload.
On the target server:
# systemctl stop postgresql@VERSION-NAME
postgres$ pg_basebackup -h SRC_IP -U postgres -D VERSION/NAME --progress
# systemctl start postgresql@VERSION-NAME
in my case, this error is raised due to sequence was not created..
CREATE SEQUENCE J.SOME_SEQ MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE ;
I think the performance will be quite similar. The overhead that is involved when using a List vs an Array is, IMHO when you add items to the list, and when the list has to increase the size of the array that it's using internally, when the capacity of the array is reached.
Suppose you have a List with a Capacity of 10, then the List will increase it's capacity once you want to add the 11th element. You can decrease the performance impact by initializing the Capacity of the list to the number of items it will hold.
But, in order to figure out if iterating over a List is as fast as iterating over an array, why don't you benchmark it ?
int numberOfElements = 6000000;
List<int> theList = new List<int> (numberOfElements);
int[] theArray = new int[numberOfElements];
for( int i = 0; i < numberOfElements; i++ )
{
theList.Add (i);
theArray[i] = i;
}
Stopwatch chrono = new Stopwatch ();
chrono.Start ();
int j;
for( int i = 0; i < numberOfElements; i++ )
{
j = theList[i];
}
chrono.Stop ();
Console.WriteLine (String.Format("iterating the List took {0} msec", chrono.ElapsedMilliseconds));
chrono.Reset();
chrono.Start();
for( int i = 0; i < numberOfElements; i++ )
{
j = theArray[i];
}
chrono.Stop ();
Console.WriteLine (String.Format("iterating the array took {0} msec", chrono.ElapsedMilliseconds));
Console.ReadLine();
On my system; iterating over the array took 33msec; iterating over the list took 66msec.
To be honest, I didn't expect that the variation would be that much. So, I've put my iteration in a loop: now, I execute both iteration 1000 times. The results are:
iterating the List took 67146 msec iterating the array took 40821 msec
Now, the variation is not that large anymore, but still ...
Therefore, I've started up .NET Reflector, and the getter of the indexer of the List class, looks like this:
public T get_Item(int index)
{
if (index >= this._size)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return this._items[index];
}
As you can see, when you use the indexer of the List, the List performs a check whether you're not going out of the bounds of the internal array. This additional check comes with a cost.
You could simple just do the reverse by making the base of log to e.
import math
e = 2.718281
math.log(e, 10) = 2.302585093
ln(10) = 2.30258093
Use this
Let say Application Test.exe is running and function is foo() in form1 [basically it is class form1], then above code will generate below response.
string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
This will return .
s1 = "TEST.form1"
for function name:
string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;
will return
s1 = foo
Note if you want to use this in exception use :
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace );
}
There are three methods:
First shutdown your Tomcat from the its bin
directory (sh shutdown.sh
). Then delete all the content of your Tomcat webapps
folder (rm -fr *
). Then rename your WAR file to ROOT.war
, and finally start your Tomcat from the bin
directory (sh startup.sh
).
Leave your war file in $CATALINA_BASE/webapps
under its original name. Turn off
autoDeploy and deployOnStartup in your Host element in the server.xml
file.
Explicitly define all application Contexts in server.xml
, specifying both the path
and docBase attributes. You must do this because you have disabled all the Tomcat
auto-deploy mechanisms, and Tomcat will not deploy your applications anymore
unless it finds their Context in the server.xml
.
second method: in order to make any change to any application, you will have to stop and restart Tomcat.
Place your WAR file outside of $CATALINA_BASE/webapps
(it must be outside
to prevent double deployment). Place a context file named ROOT.xml
in $CATALINA_BASE/conf/
. The single element in this context file MUST have a
docBase attribute pointing to the location of your WAR file. The path element
should not be set - it is derived from the name of the .xml
file, in this
case ROOT.xml
. See the documentation for the Context container for details.
One more solution: when the files get locked, blocking process is reported (something like "ServiceHub.Host.CLR.x64 (7764)") with it's id in parentheses. To get rid of the process, open PowerShell (x + Win + I) and type: "Stop-Process -Id idNumber".
I wanted to share something that helped me out. Idea credit goes to @Siavash and @Shahab Naseer.
I needed something where I could script disable and re enable of triggers for a particular table. I normally try and stay away from tiggers, but sometimes they could be good to use.
I took the script above and added a join to the sysobjects so I could filter by table name. This script will disable a trigger or triggers for a table.
select 'alter table '+ (select Schema_name(schema_id) from sys.objects o
where o.object_id = parent_id) + '.'+object_name(parent_id) + ' ENABLE TRIGGER '+ t.Name as EnableScript,*
from sys.triggers t
INNER JOIN dbo.sysobjects DS ON DS.id = t.parent_id
where is_disabled = 0 AND DS.name = 'tblSubContact'
Have a look at this jQuery plugin from OvalPixels.
It may do the trick.
To dump database using shell_exec(), below is the method :
shell_exec('mysqldump -h localhost -u username -ppassword databasename | gzip > dbname.sql.gz');
Sometimes it's nice to be explicit (for readability) that the variable doesn't change. Here's a simple example where using final
can save some possible headaches:
public void setTest(String test) {
test = test;
}
If you forget the 'this' keyword on a setter, then the variable you want to set doesn't get set. However, if you used the final
keyword on the parameter, then the bug would be caught at compile time.
iPhone & iPod touch:
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="../iphone.css" type="text/css" />
iPhone 4 & iPod touch 4G:
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="../iphone4.css" />
iPad:
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="../ipad.css" type="text/css" />
As you are using the interface builder, set the constraints for your label (be sure to set the height and width as well). Then in the Size Inspector, check the height for the label. There you will want it to read >= instead of =. Then in the implementation for that view controller, set the number of lines to 0 (can also be done in IB) and set the label [label sizeToFit]; and as your text gains length, the label will grow in height and keep your text in the upper left.
One is a column (aka Series), while the other is a DataFrame:
In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [2]: df
Out[2]:
a b
0 1 2
1 3 4
The column 'b' (aka Series):
In [3]: df['b']
Out[3]:
0 2
1 4
Name: b, dtype: int64
The subdataframe with columns (position) in [1]:
In [4]: df[[1]]
Out[4]:
b
0 2
1 4
Note: it's preferable (and less ambiguous) to specify whether you're talking about the column name e.g. ['b'] or the integer location, since sometimes you can have columns named as integers:
In [5]: df.iloc[:, [1]]
Out[5]:
b
0 2
1 4
In [6]: df.loc[:, ['b']]
Out[6]:
b
0 2
1 4
In [7]: df.loc[:, 'b']
Out[7]:
0 2
1 4
Name: b, dtype: int64
You can simply use it like this:
var regex = /( )/g;
_x000D_
Sample: click here
To install Docker for Mac with homebrew:
brew cask install docker
To install the command line completion:
brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion
This was already in a comment, but deserves its own answer: Without editing the config files: in mysql, as root, do
SET global general_log_file='/tmp/mysql.log';
SET global log_output = 'file';
SET global general_log = on;
Don't forget to turn it off afterwards:
SET global general_log = off;
You can use the accept attribute along with the . It doesn't work in IE and Safari.
Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.
For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes
The command in DougWare's answer did not work, but this did:
reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v FOOBAR /f
The shortcut HKLM
can be used for HKEY_LOCAL_MACHINE
.
The item from iterrows()
is not a Series, but a tuple of (index, Series), so you can unpack the tuple in the for loop like so:
for (idx, row) in df.iterrows():
print(row.loc['A'])
print(row.A)
print(row.index)
#0.890618586836
#0.890618586836
#Index(['A', 'B', 'C', 'D'], dtype='object')
Use FSO to create the file and write to it.
Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test"
oFile.Close
Set fso = Nothing
Set oFile = Nothing
See the documentation here:
No. If you don't have access to the php.ini, you can't guarantee that changes would have any effect.
I doubt you need to extend your sessions time though.
It has pretty sensible timeout at the moment and there are no reasons to extend it.
"A set of persist-able (entity) instances managed by an entity manager instance at a given time" is called persistence context.
JPA @Entity annotation indicates a persist-able entity.
Refer JPA Definition here
I think this is what your looking for, i was looking for it my self, but then i remembered it again befor i found the code.
background-repeat: repeat-x;
background-position: top;
background-size:auto;
background-attachment: fixed;
digital evolution is on its way.
Another option is to pass the single quote as an awk variable:
awk -v q=\' 'BEGIN {FS=" ";} {printf "%s%s%s ", q, $1, q}'
Simpler example with string concatenation:
# Prints 'test me', *including* the single quotes.
$ awk -v q=\' '{print q $0 q }' <<<'test me'
'test me'
Check this out: How to replace all occurrences of a string in JavaScript?
Short answer:
str.replace(/%20/g, " ");
EDIT: In this case you could also do the following:
decodeURI(str)
While that particular idiom is common, even more common is for people to use =
when they mean ==
. The convention when you really mean the =
is to use an extra layer of parentheses:
while ((list = list->next)) { // yes, it's an assignment
This will work for most of the website names :
SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....
One more variation wrapped up nicely where setAttribute isn't needed.
There are 3 lines that wouldn't be needed if Wetfox could dry off.
var saveAs = function (filename, content) {
if(filename === undefined) filename = "Unknown.txt";
if(content === undefined) content = "Empty?!";
let link = document.createElement('a');
link.style.display = "none"; // because Firefox sux
document.body.appendChild(link); // because Firefox sux
link.href = "data:application/octet-stream," + encodeURIComponent(content);
link.download = filename;
link.click();
document.body.removeChild(link); // because Firefox sux
};
Thanks for the help.
One possibility would be to just add the space into you character class, like acheong87 suggested, this depends on how strict you are on your pattern, because this would also allow a string starting with 5 spaces, or strings consisting only of spaces.
The other possibility is to define a pattern:
I will use \w
this is in most regex flavours the same than [a-zA-Z0-9_]
(in some it is Unicode based)
^\w+( \w+)*$
This will allow a series of at least one word and the words are divided by spaces.
^
Match the start of the string
\w+
Match a series of at least one word character
( \w+)*
is a group that is repeated 0 or more times. In the group it expects a space followed by a series of at least one word character
$
matches the end of the string
A compiler, in general, reads higher level language computer code and converts it to either p-code or native machine code. An interpreter runs directly from p-code or an interpreted code such as Basic or Lisp. Typically, compiled code runs much faster, is more compact, and has already found all of the syntax errors and many of the illegal reference errors. Interpreted code only finds such errors after the application attempts to interpret the affected code. Interpreted code is often good for simple applications that will only be used once or at most a couple times, or maybe even for prototyping. Compiled code is better for serious applications. A compiler first takes in the entire program, checks for errors, compiles it and then executes it. Whereas, an interpreter does this line by line, so it takes one line, checks it for errors, and then executes it.
If you need more information, just Google for "difference between compiler and interpreter".
you also should specify def name in the project settings here:
Configuration > Properties/Input/Advanced/Module > Definition File
Both of them have the same function, but people generally prefer while(true)
. It feels easy to read and understand...
It appears you're missing an important point here: JavaScript is a single-threaded execution environment. Let's look again at your code, note I've added alert("Here")
:
var isPaused = false;
function firstFunction(){
isPaused = true;
for(i=0;i<x;i++){
// do something
}
isPaused = false;
};
function secondFunction(){
firstFunction()
alert("Here");
function waitForIt(){
if (isPaused) {
setTimeout(function(){waitForIt()},100);
} else {
// go do that thing
};
}
};
You don't have to wait for isPaused
. When you see the "Here" alert, isPaused
will be false
already, and firstFunction
will have returned. That's because you cannot "yield" from inside the for
loop (// do something
), the loop may not be interrupted and will have to fully complete first (more details: Javascript thread-handling and race-conditions).
That said, you still can make the code flow inside firstFunction
to be asynchronous and use either callback or promise to notify the caller. You'd have to give up upon for
loop and simulate it with if
instead (JSFiddle):
function firstFunction()
{
var deferred = $.Deferred();
var i = 0;
var nextStep = function() {
if (i<10) {
// Do something
printOutput("Step: " + i);
i++;
setTimeout(nextStep, 500);
}
else {
deferred.resolve(i);
}
}
nextStep();
return deferred.promise();
}
function secondFunction()
{
var promise = firstFunction();
promise.then(function(result) {
printOutput("Result: " + result);
});
}
On a side note, JavaScript 1.7 has introduced yield
keyword as a part of generators. That will allow to "punch" asynchronous holes in otherwise synchronous JavaScript code flow (more details and an example). However, the browser support for generators is currently limited to Firefox and Chrome, AFAIK.
This command helped me on linux mint when i had exact same problem
gcc filename.c -L/usr/include -lreadline -o filename
You could use alias if you compile it many times Forexample:
alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'
For me, in Ubuntu 18.04. I needed to chown inside ~/.config/composer/
E.g.
sudo chown -R $USER ~/.config/composer
Then global commands work.
It appears that although colons (:) and periods (.) are valid in the HTML spec, they are invalid as id selectors in CSS so probably best avoided if you intend to use them for that purpose.
You are using DictWriter.writerows()
which expects a list of dicts, not a dict. You want DictWriter.writerow()
to write a single row.
You will also want to use DictWriter.writeheader()
if you want a header for you csv file.
You also might want to check out the with
statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.
Example with these changes made:
import csv
my_dict = {"test": 1, "testing": 2}
with open('mycsvfile.csv', 'w') as f: # You will need 'wb' mode in Python 2.x
w = csv.DictWriter(f, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
Which produces:
test,testing
1,2
In this navbar CSS, set to own color:
/* Navbar */_x000D_
.navbar-default {_x000D_
background-color: #F8F8F8;_x000D_
border-color: #E7E7E7;_x000D_
}_x000D_
/* Title */_x000D_
.navbar-default .navbar-brand {_x000D_
color: #777;_x000D_
}_x000D_
.navbar-default .navbar-brand:hover,_x000D_
.navbar-default .navbar-brand:focus {_x000D_
color: #5E5E5E;_x000D_
}_x000D_
/* Link */_x000D_
.navbar-default .navbar-nav > li > a {_x000D_
color: #777;_x000D_
}_x000D_
.navbar-default .navbar-nav > li > a:hover,_x000D_
.navbar-default .navbar-nav > li > a:focus {_x000D_
color: #333;_x000D_
}_x000D_
.navbar-default .navbar-nav > .active > a, _x000D_
.navbar-default .navbar-nav > .active > a:hover, _x000D_
.navbar-default .navbar-nav > .active > a:focus {_x000D_
color: #555;_x000D_
background-color: #E7E7E7;_x000D_
}_x000D_
.navbar-default .navbar-nav > .open > a, _x000D_
.navbar-default .navbar-nav > .open > a:hover, _x000D_
.navbar-default .navbar-nav > .open > a:focus {_x000D_
color: #555;_x000D_
background-color: #D5D5D5;_x000D_
}_x000D_
/* Caret */_x000D_
.navbar-default .navbar-nav > .dropdown > a .caret {_x000D_
border-top-color: #777;_x000D_
border-bottom-color: #777;_x000D_
}_x000D_
.navbar-default .navbar-nav > .dropdown > a:hover .caret,_x000D_
.navbar-default .navbar-nav > .dropdown > a:focus .caret {_x000D_
border-top-color: #333;_x000D_
border-bottom-color: #333;_x000D_
}_x000D_
.navbar-default .navbar-nav > .open > a .caret, _x000D_
.navbar-default .navbar-nav > .open > a:hover .caret, _x000D_
.navbar-default .navbar-nav > .open > a:focus .caret {_x000D_
border-top-color: #555;_x000D_
border-bottom-color: #555;_x000D_
}
_x000D_
There are 3 different ways you may wish to set this up:
Thrower
inside of Catcher
Catcher
inside of Thrower
Thrower
and Catcher
inside of another class in this example Test
THE WORKING GITHUB EXAMPLE I AM CITING Defaults to Option 3, to try the others simply uncomment the "Optional
" code block of the class you want to be main, and set that class as the ${Main-Class}
variable in the build.xml
file:
4 Things needed on throwing side code:
import java.util.*;//import of java.util.event
//Declaration of the event's interface type, OR import of the interface,
//OR declared somewhere else in the package
interface ThrowListener {
public void Catch();
}
/*_____________________________________________________________*/class Thrower {
//list of catchers & corresponding function to add/remove them in the list
List<ThrowListener> listeners = new ArrayList<ThrowListener>();
public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
//Set of functions that Throw Events.
public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
System.out.println("Something thrown");
}
////Optional: 2 things to send events to a class that is a member of the current class
. . . go to github link to see this code . . .
}
2 Things needed in a class file to receive events from a class
/*_______________________________________________________________*/class Catcher
implements ThrowListener {//implement added to class
//Set of @Override functions that Catch Events
@Override public void Catch() {
System.out.println("I caught something!!");
}
////Optional: 2 things to receive events from a class that is a member of the current class
. . . go to github link to see this code . . .
}
The easiest lib I have used is Paolo Gios's library. It's basically
Create GiosPDFDocument object
Create TextArea object
Add text, images, etc to TextArea object
Add TextArea object to PDFDocument object
Write to stream
This is a great tutorial to get you started.
int rows, cols , i, j;
printf("Enter number of rows and cols for the matrix: \n");
scanf("%d %d",&rows, &cols);
int mat[rows][cols];
printf("enter the matrix:");
for(i = 0; i < rows ; i++)
for(j = 0; j < cols; j++)
scanf("%d", &mat[i][j]);
printf("\nThe Matrix is:\n");
for(i = 0; i < rows ; i++)
{
for(j = 0; j < cols; j++)
{
printf("%d",mat[i][j]);
printf("\t");
}
printf("\n");
}
}
Use this code instead of it:
<frameset rows="100%,*">
<frame src="-------------------------URL-------------------------------">
<noframes>
<body>
Your browser does not support frames. To wiew this page please use supporting browsers.
</body>
</noframes>
</frameset>
Sure, find where -Werror
is set and remove that flag. Then warnings will be only warnings.
And this what I used to see all combination and decide which reads cool:
for (( i = 0; i < 8; i++ )); do
for (( j = 0; j < 8; j++ )); do
printf "$(tput setab $i)$(tput setaf $j)(b=$i, f=$j)$(tput sgr0)\n"
done
done
Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:
kubectl replace --force -f <yml_file_describing_pod>
List of stable versions wkhtmltopdf: http://wkhtmltopdf.org/downloads.html
sudo apt-get install xfonts-75dpi
sudo apt-get install xfonts-base
sudo wget http://download.gna.org/wkhtmltopdf/0.12/0.12.2.1/wkhtmltox-0.12.2.1_linux-jessie-amd64.deb
sudo dpkg -i wkhtmltox-0.12.2.1_linux-jessie-amd64.deb