There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.
The following was tested for IIS 8.5 and Windows 8.1.
As of IIS 7, Windows recommends restarting IIS via net stop/start
. Via the command prompt (as Administrator):
> net stop WAS
> net start W3SVC
net stop WAS
will stop W3SVC
as well. Then when starting, net start W3SVC
will start WAS
as a dependency.
Make sure your account uses IIS 7. For more information, see Customizing IIS Settings on Your Windows Hosting Account. Follow the instructions in Changing Pipeline Mode on Your Windows IIS 7 Hosting Account. Select Integrated Pipeline Mode. In your Project References section, set Copy Local to True for the following assemblies:
System.Web.Abstractions
System.Web.Helpers
System.Web.Routing
System.Web.Mvc
System.Web.WebPages
Add the following assemblies to your project, and then set Copy Local to True:
Microsoft.Web.Infrastructure
System.Web.Razor
System.Web.WebPages.Deployment
System.Web.WebPages.Razor
Publish your application.
I stumbled upon this question when I ran into the same issue. The root cause of my issue was an incorrectly-configured app pool. It was set for 2.0 inadvertently, when it needed to be set to 4.0. The answer at the following link helped me uncover this issue: http://forums.iis.net/t/1160143.aspx
Editing the web.config
file or updating a DLL in the bin
folder just recycles the worker process for that application, not the whole pool.
If you have loads of re-directs to create, having loads of virtual directories over the places is a nightmare to maintain. You could try using ISAPI redirect an IIS extension. Then all you re-directs are managed in one place.
http://www.isapirewrite.com/docs/
It allows also you to match patterns based on reg ex expressions etc. I've used where I've had to re-direct 100's of pages and its saved a lot of time.
This one disables all bogus verbs and only allows GET and POST
<system.webServer>
<security>
<requestFiltering>
<verbs allowUnlisted="false">
<clear/>
<add verb="GET" allowed="true"/>
<add verb="POST" allowed="true"/>
</verbs>
</requestFiltering>
</security>
</system.webServer>
Add this to your Web Config
<system.web>
<httpRuntime executionTimeout="180" />
</system.web>
https://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx
Optional TimeSpan attribute.
Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
This time-out applies only if the debug attribute in the compilation element is False. To help to prevent shutting down the application while you are debugging, do not set this time-out to a large value.
The default is "00:01:50" (110 seconds).
I got the same error when I added the applicationinitialization module with lots of initializationpages and deployed it on Azure app. The issue turned out to be duplicate entries in my applicationinitialization module. I din't see any errors in the logs so it was hard to troubleshoot. Below is an example of the error code:
<configuration>
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
<add initializationPage="/init1.aspx?call=2"/>
<add initializationPage="/init1.aspx?call=2" />
</applicationInitialization>
</system.webServer>
Make sure there are no duplicate entries because those will be treated as duplicate keys which are not allowed and will result in "Cannot add duplicate collection entry" error for web.config.
Try the Windows event log, there can be some useful information
Super easy answer for those that only have this on one webpage. Edit your actionlink and a + "/" on the end of it.
@Html.ActionLink("Edit", "Edit", new { id = item.name + "/" }) |
Dont know is it related to your problem or not BUT Windows 2008 Server R2 or SP2 has changed its IIS settings, which leads to issue in session persistence. By default, it manages separate session variable for HTTP and HTTPS. When variables are set in HTTPS, these will be available only on HTTPS pages whenever switched.
To solve the issue, there is IIS setting. In IIS Manager, open up the ASP properties, expand Session Properties, and change New ID On Secure Connection to False.
In most of the cases, if you are unable to export the certificate as a PFX (including the private key) is because MMC/IIS cannot find/don't have access to the private key (used to generate the CSR). These are the steps I followed to fix this issue:
Hope this helps!
Sometimes, you create new application pool and cann't solve it via DCOMCNFG. Then there is another method to do:
Set the Identity (Model Name) of application pool to LocalSystem.
I don't know the root cause, but it solve my problem one time.
There are two reasons you might get this message:
%FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i
. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.IIS now has
Idle Time-out Action : Suspend
setting
Suspending is just freezes the process and it is much more efficient than the destroying the process.
I had the same problem and setting the uploadReadAheadSize
solved it:
http://www.iis.net/configreference/system.webserver/serverruntime
"The value must be between 0 and 2147483647."
It is easily set it in the applicationHost.config-fle if you don't want to do a cmd-thing.
Its located in WindowsFOLDER\System32\inetsrv\config
(2008 server).
You must open it with notepad. Do a Backup of the file first.
According to the comments in config the recommended way to unlock sections is by using a location tag:
<location path="Default Web Site" overrideMode="Allow">
<system.webServer>
<asp />
</system.webServer>
</location>"
So you can write in the bottom (since it doesn't exist before). I write maxvalue
here - write your own value if you want.
<location path="THENAMEOFTHESITEYOUHAVE" overrideMode="Allow">
<system.webServer>
<asp />
<serverRuntime uploadReadAheadSize="2147483647" />
</system.webServer>
</location>
If you put it last before </configuration>
for example, you know where you have it.
Hope that solves your problems. It was an SSL overhead issue for me, where too much post freezed the application, raising a (413) Request Entity Too Large error.
This worked for me:
Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.
GitHub solution solved the problem for me by adding
This error is coming from the staticfile handler -- which by default doesn't filter any verbs, but probably can only deal with HEAD and GET.
And this is because no other handler stepped up to the plate and said they could handle DELETE.
Since you are using the WEBAPI, which because of routing doesn't have files and therefore extensions, the following additions need to be added to your web.config file:
<system.webserver>
<httpProtocol>
<handlers>
...
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Obviously what is needed depends on classicmode vs integratedmode, and classicmode depends on bitness. In addition, the OPTIONS header has been added for CORS processing, but if you don't do CORS you don't need that.
FYI, your web.config is the local to the application (or application directory) version whose top level is applicationHost.config.
If you installed IIS after the .Net framework you can solve the porblem by re-installing the .Net framework. Part of its install detects whether IIS is present and updates IIS accordingly.
Remove ~
character in location
so
path="~/Admin/SomePage.aspx"
becomes
path="Admin/SomePage.aspx"
Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.
With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.
If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.
The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.
There simply is no console listening by default. Running in debug mode there is a console attached, but in a production environment it is as you suspected, the message just doesn't go anywhere because nothing is listening.
To turn on the IIS is not recommended as other comments suggests if you are not using your system as a live server. For development purpose only IIS Express is adequate.
Open a windows command line. Switch directories to C:\Windows\Microsoft.Net\Framework\v4.0.xxxx
where the x's are the build number. Type aspnet_regiis -ir
and hit enter. This should register .Net v4.0 and create the application pools by default. If it doesn't, you will need to create them manually by right-clicking the Application Pools
folder in IIS and choosing Add Application Pool
.
Edit: As a reference, please refer to the section of the linked document referring to the -i argument.
This worked for me:
Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.
I have got same issue on my server. Follow below steps -
It works and solved my problem.
Often this error is caused by the WebDAV module that try to handle this kind of requests. An easy solution is to remove it from modules and from handlers of the system.webServer
section just inside your web.config file.
Here a configuration example:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>
What Identity is your Application Pool for the Web application running as, to troubleshoot, try creating a new App Pool with say Network Service as its identity and make your web application use that new App Pool you created and see if the error persists.
There is one way that I have used my self. Go to Control Panel\Programs\Turn Windows features on or off
then uninstall IIS and all of its components completely. I restart windows but I'm not sure if it's required or not. Then install it again from the same path.
Try this as it worked for me...
courtesy of Last paragraph mentioned in here
Create a custom Windows Service.
I had some mission-critical tasks set up as scheduled console apps and found them difficult to maintain. I created a Windows Service with a 'heartbeat' that would check a schedule in my DB every couple of minutes. It's worked out really well.
Having said that, I still use scheduled console apps for most of my non-critical maintenance tasks. If it ain't broke, don't fix it.
I tried the update, but it did not work for me. Helped:
An additional possible cause.
My HTML page had these starting tags:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
This was on a page that using the slick jquery slideshow.
I removed the tags and replaced with:
<html>
And everything is working again.
Although this post is post is tagged for Windows, it is relevant question on OS X that I have not seen answers for elsewhere. Here are steps to create a self-signed cert for localhost on OS X:
# Use 'localhost' for the 'Common name'
openssl req -x509 -sha256 -nodes -newkey rsa:2048 -days 365 -keyout localhost.key -out localhost.crt
# Add the cert to your keychain
open localhost.crt
In Keychain Access
, double-click on this new localhost cert. Expand the arrow next to "Trust" and choose to "Always trust". Chrome and Safari should now trust this cert. For example, if you want to use this cert with node.js:
var options = {
key: fs.readFileSync('/path/to/localhost.key').toString(),
cert: fs.readFileSync('/path/to/localhost.crt').toString(),
ciphers: 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
honorCipherOrder: true,
secureProtocol: 'TLSv1_2_method'
};
var server = require('https').createServer(options, app);
This is an authentication issue. In my case, it solved by below steps: 1- Go to IIS manager, in the left pane, expand the server root and select your web application from Sites node. 2- In the Home screen, go to IIS section and select Authentication. 3- Enable Anonymous Authentication. 4- Then, select Edit and set Edit Anonymous Authentication Credentials to Application pool identity.
Code Climber and this blog entry provide detailed ways of increasing application's performance.
Compiled query will increase performance of your application, but it has nothing in common with ASP.NET MVC. It will speed up every db application, so it is not really about MVC.
Try opening Visual Studio with Administrator privileges. In my case, it gave access to the IIS site and made this error go away. I was then able to switch the project to use IIS Express which doesn't seem to need administrator privileges.
I found this page because I needed to migrate a site with many many bindings to a new server. I used some of the code here to generate the powershell script below to add the bindings to the new server. Sharing in case it is useful to someone else:
Import-Module WebAdministration
$Websites = Get-ChildItem IIS:\Sites
$site = $Websites | Where-object { $_.Name -eq 'site-name-in-iis-here' }
$Binding = $Site.bindings
[string]$BindingInfo = $Binding.Collection
[string[]]$Bindings = $BindingInfo.Split(" ")
$i = 0
$header = ""
Do{
[string[]]$Bindings2 = $Bindings[($i+1)].Split(":")
Write-Output ("New-WebBinding -Name `"site-name-in-iis-here`" -IPAddress " + $Bindings2[0] + " -Port " + $Bindings2[1] + " -HostHeader `"" + $Bindings2[2] + "`"")
$i=$i+2
} while ($i -lt ($bindings.count))
It generates records that look like this:
New-WebBinding -Name "site-name-in-iis-here" -IPAddress "*" -Port 80 -HostHeader www.aaa.com
For Windows Server 2016
Server Manager
formManage
-> Add Roles and Features
Features
pageWCF Services
feature with all subfeaturesNext
and Install
I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line
; On windows: extension_dir = "ext"
I changed it to:
; On windows: extension_dir = "C:\php\ext"
And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.
The excellent NWebsec library can upgrade your requests from HTTP to HTTPS using its upgrade-insecure-requests
tag within the Web.config
:
<nwebsec>
<httpHeaderSecurityModule>
<securityHttpHeaders>
<content-Security-Policy enabled="true">
<upgrade-insecure-requests enabled="true" />
</content-Security-Policy>
</securityHttpHeaders>
</httpHeaderSecurityModule>
</nwebsec>
Please do the following two steps on IIS 8.0
Add new MIME type & HttpHandler
Extension: .svc, MIME type: application/octet-stream
Request path: *.svc, Type: System.ServiceModel.Activation.HttpHandler, Name: svc-Integrated
I have also encountered this same error, despite all the provided solutions for the following reasons:
Try to add the following settings to web.config
file.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
I got this error by putting the <customErrors>
tag inside of <system.webServer>
instead of <system.web>
where it belongs. There was a little squiggle under the <customErrors>
tag but I didn't notice it right away.
If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.
MembershipUser u = Membership.GetUser(LoginUser.UserName);
You need to unlock handlers. This can be done using following cmd command:
%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/handlers
Maybe another info for people that are getting this error on IIS 8, in my case was on Microsoft Server 2012 platform. I had spend couple of hours battling with other errors that bubbled up after executing appcmd. In the end I was able to fix it by removing Web Server Role and installing it again.
Check this in the web.config and change overrideModeDefault
from Deny
to Allow
.
<configSections>
<sectionGroup name="system.webServer">
<section name="handlers" overrideModeDefault="Deny" />
<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" />
You can also manage sections on web server level in your IIS management console from "Feature Delegation".
Try granting permission to the NETWORK SERVICE user.
After disabling the firewall I was able to run it without any issues.
Clearly HttpContext.Current
is not null
only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".
It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.
Overall, don't use Application["Setting"]
to store global stuffs, as they are not global as you discovered.
If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext
or Application["Settings"]
, as that violates the principles of isolation and decoupling.
Update:
Due to the introduction of async/await
it is more often that such issues happen, so you might consider the following tip,
In general, you should only call HttpContext.Current
in only a few scenarios (within an HTTP module for example). In all other cases, you should use
Page.Context
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.context?view=netframework-4.7.2 Controller.HttpContext
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.httpcontext?view=aspnet-mvc-5.2instead of HttpContext.Current
.
I only needed to add the feature in windows features as Charlie mentioned.For people who cannot find it on window 10 or server 2012+ find it as below. I struggled a bit
As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:
Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}
From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.
This along with @BlackHawkDesign comment should help you find what you need.
I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00
That's not quite true. E.g. for HTTP Windows supports URL based port sharing, allowing multiple processes to use the same IP address and Port.
For me the database was not created and EF code first should have created it but always endet in this error. The same connection string was working in aspnet core default web project. The solution was to add
_dbContext.Database.EnsureCreated()
before the first database contact (before DB seeding).
I had the same issue in a Xamarin.Forms project. The fix was manually converting the PCL from .NET 4.6 to .NET Standard 2.0.
For Visual Studio Mac: make sure you do it for each project
I suppose you want to publish and access your applications/websites from LAN; probably as virtual directories under the default website.The steps could vary depending on your IIS version, but basically it comes down to these steps:
Restore your "Default Website" Website :
create a new website
set "Default Website" as its name
In the Binding section (bottom panel), enter your local IP address in the "IP Address" edit.
that's it: now whenever you type your local ip address in your browser, you will get the website you just added. Now if you want to access any of your other webapplications/websites from LAN, just add a virtual application under your default website pointing to the directory containing your published application/website. Now you can type : http://yourLocalIPAddress/theNameOfYourApplication to access it from your LAN.
I had a permissions issue to a website and just couldn't get Windows authentication to work. It was a folder permissions rather than ASP.NET configuration issue in the end and once the Everyone
user was granted permissions it started working.
None of these worked for me. I had to go to a SuperUser question.
If it is a System Process—PID 4—you need to disable the HTTP.sys driver which is started on demand by another service, such as Windows Remote Management or Print Spooler on Windows 7 or 2008.
There is two ways to disable it but the first one is safer:
Go to device manager, select “show hidden devices” from menu/view, go to “Non-Plug and Play Driver”/HTTP, double click it to disable it (or set it to manual, some services depended on it).
Reboot and use
netstat -nao | find ":80"
to check if 80 is still used.
This is the one that worked for me!
As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.
So:
Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default
Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com
You may need to wait 5-10 mins for the DNS records to update but that's all you need.
I had also the same problem and finally I could overcame it.
Solution Explorer
? Right click on project
? Properties
? Web tab
? Project Url
I have chosen another port number, and every things became fine!
What worked for me... It seems if you install (or a dependent package installs) Microsoft.CodeDom.Providers.DotNetCompilerPlatform
NuGet package it makes some web.config
transforms that allow you to use C#7.x features in ASP.NET Razor pages. Whilst I found these worked fine on my local machine they didn't work on our server (even when the compiler was in the /bin/ folder).
The solution was to locate the element below and remove completely from web.config
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
The invalid hostname indicates that the actual site you configured in the IIS Express configuration file is (most likely) not running. IIS Express doesn't have a process model like IIS does.
For your site to run it would need to be started explicitly (either by opening and accessing from webmatrix, or from command line calling iisexpress.exe (from it's installation directory) with the /site parameter.
In general, the steps to allow fully qualified DNS names to be used for local access are Let's use your example of the DNS name dev.example.com
Configure IIS Express binding for your site (eg:Site1) to include dev.example.com. Administrative privilege will be needed to use the binding. Alternatively, a one-time URL reservation can be made with http.sys using
netsh http add urlacl url=http://dev.example.com:<port>/ user=<user_name>
start iisexpress /site:Site1
or open Site1 in WebMatrix
I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.
In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.
Right-click the domain when it appears under the Sites list, and choose Edit Permissions
Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS
is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.
Click the Edit button, then Add...
In the text box, type IIS AppPool\MyApplicationPoolName
, substituting MyApplicationPoolName
with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com
Press the Check Names button. The text you typed will transform (notice the underline):
Press OK to add the user
With the new user (your domain) selected, now you can safely provide any Modify or Write permissions
Complementing Elmer's answer, as my edit was rolled back.
To cache static content for 365 days with public cache-control header, IIS can be configured with the following
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
</staticContent>
This will translate into a header like this:
Cache-Control: public,max-age=31536000
Note that max-age is a delta in seconds, being expressed by a positive 32bit integer as stated in RFC 2616 Sections 14.9.3 and 14.9.4. This represents a maximum value of 2^31 or 2,147,483,648 seconds (over 68 years). However, to better ensure compatibility between clients and servers, we adopt a recommended maximum of 365 days (one year).
As mentioned on other answers, you can use these directives also on the web.config of your site for all static content. As an alternative, you can use it only for contents in a specific location too (on the sample, 30 days public cache for contents in "cdn" folder):
<location path="cdn">
<system.webServer>
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00"/>
</staticContent>
</system.webServer>
</location>
You may need to enable 32-bit applications in your AppPool. Go to > 'Application Pool' in IIS => right click your app pool => advance setting => 'enable 32 bit application' to true.
Please don't forget to restart your app pool and your corresponding application pointing to that app pool.
select site where you are facing the problem
Select Below
- Right click on Anonymous Authentication and click on edit and follow below
As the error idnicates - "This happens when the section is locked at a parent level". To unlock the section you can use appcmd.exe and execute the following command:
%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/handlers -commitpath:apphost
For more information on about section locking and what a parent configuration context is refer to IIS documentation.
To summarize all the answers in a single place:
<system.web>
<httpRuntime targetFramework="4.5.2" maxRequestLength="1048576"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
Rules:
Notes:
more info MSDN
Enable CORS (nice and neat)
1.Add CORS nuget package
Install-Package microsoft.aspnet.webapi.cors
2.in the WebApiConfig.cs file to Register method add bellow code :
config.EnableCors();
ex:
using System.Web.Http;
namespace test
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors(); //add this**************************
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
3.Add bellow code into namespace of the controller include get,post,delete,put or any http method
[EnableCors(origins: "The address from which the request comes", headers: "*", methods: "*")]
ex:
using System.Web.Http.Cors;//add this******************************
namespace Test.Controllers
{
[EnableCors(origins: "http://localhost:53681/HTML/Restaurant.html", headers: "*", methods: "*")]
public class RestaurantController : ApiController
{
protected TestBusinessLayer DevTestBLL = new TestBusinessLayer();
public List<Restaurant> GET()
{
return DevTestBLL.GetRestaurant();
}
public List<Restaurant> DELETE(int id)
{
return DevTestBLL.DeleteRestaurant(id);
}
}
}
reference :http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
I faced with this error today, reason was; IIS user doesn't have permission to reach to the application folder. I gave the read permissions to the app root folder.
An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool.
Every application within an application pool shares the same worker process.
Also remember, when running on alternate ports, you need to specify the port on the URL:
There may be firewalls or proxy servers to consider depending on your environment.
Other than the options mentioned above, there are a couple of other Solutions which works well with automated deployments or require fewer configuration changes.
1. Modifying the project file (.CsProj) file
MSBuild supports the EnvironmentName
Property which can help to set the right environment variable as per the Environment you wish to Deploy. The environment name would be added in the web.config during the Publish phase.
Simply open the project file (*.csProj) and add the following XML.
<!-- Custom Property Group added to add the Environment name during publish
The EnvironmentName property is used during the publish for the Environment variable in web.config
-->
<PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>
Above code would add the environment name as Development
for Debug configuration or if no configuration is specified. For any other Configuration the Environment name would be Production
in the generated web.config file. More details here
2. Adding the EnvironmentName Property in the publish profiles.
We can add the <EnvironmentName>
property in the publish profile as well. Open the publish profile file which is located at the Properties/PublishProfiles/{profilename.pubxml}
This will set the Environment name in web.config when the project is published. More Details here
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
3. Command line options using dotnet publish
Additionaly, we can pass the property EnvironmentName
as a command line option to the dotnet publish
command. Following command would include the environment variable as Development
in the web.config file.
dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development
If you are using the updated Microsoft.Web.RedisSessionStateProvider
(starting from 3.0.2
) you can add this to your web.config
to allow concurrent sessions.
<appSettings>
<add key="aspnet:AllowConcurrentRequestsPerSession" value="true"/>
</appSettings>
There is a Refactor --> Rename Bug in Visual Studio 2012 that wrongly renamed the "id" inside the literal string value of the url parameter in my RouteConfig.cs. This caused a 403.14 on a fresh and otherwise correct setup in both Windows Server 2012 and Windows Server 2008 R2.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
was changed to
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{renamed_text}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
XAMPP is more powerful and resource taking than WAMP.
WAMP provides support for MySQL and PHP.
XAMPP provides support for MYSQL, PHP and PERL
XAMPP also has SSL feature while WAMP doesnt.
If your applications need to deal with native web apps only, Go for WAMP.
If you need advanced features as stated above, go for XAMPP.
As of priority, you cant run both together with default installation as XAMPP gets a higher priority and it takes up ports. So WAMP cant be run in parallel with XAMPP.
If the server doesn't have enough memory also will cause this problem. This is my personal experience with Godaddy VPS.
One solution that I've found is that you should have to change the .Net Framework back to v2.0 by Right Clicking on the site that you have manager under the Application Pools from the Advance Settings.
Making this its own post because this had me going for hours.
I saw maybe a dozen of similar posts here and elsewhere about this problema and the aspnet_regiis fix. They weren't working for me, and aspnet_regiis was acting odd, just listing options etc.
As user ryan-anderson above indicated, you cannot enter .exe
For those less comfy with things outside IIS on the server, here's what you do in simple steps.
Find aspnet_regiis in a folder similar to this path. c:\Windows\Microsoft.NET\Framework\v4.0.30319\
Right-click command prompt in the start menu or wherever and tell it to run as administrator. Using the windows "Run" feature just won't work, or didn't for me.
Go back to the aspnet_regiis executable. Click-drag it right into the command prompt or copy-paste the address into the command prompt.
Remove, if it's there, the .exe at the end. This is key. Add the -i (space minus eye) at the end. Enter.
If you did this correctly, you will see that it starts to install asp.net, and then tells you it succeeded.
This is my current method of checking if Mod_rewrite enabled for both Apache and IIS
/**
* --------------------------------------------------------------
* MOD REWRITE CHECK
* --------------------------------------------------------------
* - By A H Abid
* Define Constant for MOD REWRITE
*
* Check if server allows MOD REWRITE. Checks for both
* Apache and IIS.
*
*/
if( function_exists('apache_get_modules') && in_array('mod_rewrite',apache_get_modules()) )
$mod_rewrite = TRUE;
elseif( isset($_SERVER['IIS_UrlRewriteModule']) )
$mod_rewrite = TRUE;
else
$mod_rewrite = FALSE;
define('MOD_REWRITE', $mod_rewrite);
It works in my local machine and also worked in my IIS based webhost. However, on a particular apache server, it didn't worked for Apache as the apache_get_modules() was disabled but the mod_rewrite was enable in that server.
Unfortunatelly, for IIS installed on Windows 7/8 machines, there is no option to create users only for IIS authentification. For Windows Server there is that option where you can add users from IIS Manager UI. These users have roles only on IIS, but not for the rest of the system. In this article it shows how you add users, but it is incorrect stating that is also appliable to standard OS, it only applies to server versions.
Integrated application pool mode
When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.
There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.
Classic application pool mode
When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.
This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.
Be sure to test your existing applications for compatibility in Integrated mode before upgrading a production environment to IIS 7.0 and assigning applications to application pools in Integrated mode. You should only add an application to an application pool in Classic mode if the application fails to work in Integrated mode. For example, your application might rely on an authentication token passed from IIS to the managed runtime, and, due to the new architecture in IIS 7.0, the process breaks your application.
Taken from: What is the difference between DefaultAppPool and Classic .NET AppPool in IIS7?
Original source: Introduction to IIS Architecture
IUSR permissions
use on a folder if not under inetpub/wwwroot will be solution for some.
It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.
I did it and my problem solved.
I had the same problem and couldn't figure it out for almost a day. I added IUSR and NetworkService to the folder permissions, I made sure it was running as NetworkService. I tried impersonation and even running as administrator (DO NOT DO THIS). Then someone recommended that I try running the page from inside the Windows 2008 R2 server and it pointed me to the Handler Mappings, which were all disabled.
I got it to work with this:
Now try refreshing your website.
I encountered the same problem and I was able to resolve it with two solutions: First, I used the MMC snap-in "Certificates" for the "Computer account" and dragged the self-signed certificate into the "Trusted Root Certification Authorities" folder. This means the local computer (the one that generated the certificate) will now trust that certificate. Secondly I noticed that the certificate was generated for some internal computer name, but the web service was being accessed using another name. This caused a mismatch when validating the certificate. We generated the certificate for computer.operations.local, but accessed the web service using https://computer.internaldomain.companydomain.com. When we switched the URL to the one used to generate the certificate we got no more errors.
Maybe just switching URLs would have worked, but by making the certificate trusted you also avoid the red screen in Internet Explorer where it tells you it doesn't trust the certificate.
If using Visual Studio 2010 you can right-click on the project for the service, and select properties
. Then select the Web
tab. Under the Servers
section you can configure the URL. There is also a button to create the virtual directory.
Control Panel >> Windows Firewall
Advanced settings >> Inbound Rules >> World Wide Web Services - Enable it All or (Domain, Private, Public) as needed.
This issue occurs because the Applicationhost.config
file for Windows Process Activation Service (WAS) has some tags that are not compatible with the .NET Framework 4.0.
Based on your environment, you have 4 workarounds to solve this issue:
Check the detailed steps for each woraround at Solving Could not load type system.servicemodel.activation.httpmodule from assembly System.ServiceModel
I was trying to access my web pages on specific port number and tried much things, but I've found the port was filtered by firewall. Just added a bypass rule and everything was done.
Maybe help someone!
In addition to "answered Mar 28 '11 at 12:27Bryan Bedard"
In case that the solution doesn't work, you have to enable Windows Authentication in iss manager. How to do that:
1.To start IIS Manager from the Run dialog box: On the Start menu, click All Programs, click Accessories, and then click Run. In the Open box, type inetmgr and then click OK.
2.In the Connections pane, expand the server name, expand Sites, and go to the level in the hierarchy pane that you want to configure, and then click the Web site or Web application. 3. Scroll to the IIS section in the Home pane, and then double-click Authentication.
4.In the Authentication pane, select Anonymous Authentication, and then click Disable.
The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits>
<headerLimits>
<add header="Content-type" sizeLimit="100" />
</headerLimits>
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits
had the same problem.
You need to ensure you are installing on the same server as the one you created the "CSR" file from. Otherwise, it won't have the private keys.
If you got your cert, just ask to re-key, it will ask for a new CSR file. I.e. Go Daddy allows you to re-key, just find the cert, and hit "manage"
I am not expert at this stuff, but this managed to work.
You would need an HTTP module that looked at the requested resource and if it was a css or js, it would tack on the Access-Control-Allow-Origin header with the requestors URL, unless you want it wide open with '*'.
see below snap.
Just to add to these Anniversary Update
issues (thanks Microsoft) if the file you are missing is cgi.dll
, ie your Event Viewer
has
The Module DLL C:\WINDOWS\System32\inetsrv\cgi.dll failed to load. The data is the error.
Then to fix this:
IIS Manager
Connections
panel (typically your PC name)Management
, you should have Web Platform Installer
Products
cgi
then hit <Enter>
IIS: CGI
then click Add
on the right and finally Install
on the bottomSince you're dealing with static content...
On the folder that acts as the root of your website- if you right click > properties > security, does "Users" show up in the list? if not click "Add..." and type it in, be sure to click "Apply" when you're done.
You can also use this first command to kill a process that owns a particular port:
sudo netstat -ap | grep :<port_number>
For example, say this process holds port 8000 TCP, then running the command:
sudo netstat -ap | grep :8000
will output the line corresponding to the process holding port 8000, for example:
tcp 0 0 *:8000 *:* LISTEN 4683/procHoldingPort
In this case, procHoldingPort is the name of the process that opened the port, 4683 is its pid, and 8000 (note that it is TCP) is the port number it holds (which you wish to close).
Then kill the process, following the above example:
kill 4683
As others mentioned here out, if that doesn't work (you can try using kill with -9 as an argument):
kill -9 4683
Again, in general, it's better to avoid sending SIGKILL
(-9) if you can.
As for me, it's a bad and quick solution for your problem :
android {
lintOptions {
abortOnError false
}
}
Better solution is solving problem in your code, because lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.
This problem most frequently occurring when:
Find your bugs by Inspect Code
in Android Studio: Improve Your Code with Lint
theta_rad = Math.Atan2(y,x);
if(theta_rad < 0)
theta_rad = theta_rad + 2 * Math.PI; //if neg., add 2 PI to it
theta_deg = (theta_rad/M_PI*180) ; //convert from radian to degree
//or
theta_rad = Math.Atan2(y,x);
theta_rad = (theta_rad < 0) ? theta_rad + 2 * Math.PI : theta_rad;
theta_deg = (theta_rad/M_PI*180) ;
-1 deg becomes (-1 + 360) = 359 deg
-179 deg becomes (-179 + 360) = 181 deg
When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools
Run either of these a few second apart. You'll detect the high CPU connection. Or: stored CPU in a local variable, WAITFOR DELAY, compare stored and current CPU values
select * from master..sysprocesses
where status = 'runnable' --comment this out
order by CPU
desc
select * from master..sysprocesses
order by CPU
desc
May not be the most elegant but it'd effective and quick.
This works perfectly for me. Just put the button first since you're starting on the right. If FlowDirection becomes a problem just add a StackPanel around it and specify FlowDirection="LeftToRight" for that portion. Or simply specify FlowDirection="LeftToRight" for the relevant control.
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" FlowDirection="RightToLeft">
<Button Width="40" HorizontalAlignment="Right" Margin="3">Right</Button>
<TextBlock Margin="5">Left</TextBlock>
<StackPanel FlowDirection="LeftToRight">
<my:DatePicker Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />
</StackPanel>
<my:DatePicker FlowDirection="LeftToRight" Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />
</StackPanel>
here's an answer that does follow the syntax of
$(element).hasAnyOfClasses("class1","class2","class3")
(function($){
$.fn.hasAnyOfClasses = function(){
for(var i= 0, il=arguments.length; i<il; i++){
if($self.hasClass(arguments[i])) return true;
}
return false;
}
})(jQuery);
it's not the fastest, but its unambiguous and the solution i prefer. bench: http://jsperf.com/hasclasstest/10
Building up on Shavy Levy answer:
[bool]($var -as [int])
Because $null is evaluated to false (in bool), this statement Will give you true or false depending if the casting succeeds or not.
To get the format you want:
SELECT (substring(CONVERT(VARCHAR,GETDATE(),22),10,8) + ' ' +
SUBSTRING(CONVERT(VARCHAR,getdate(),22), 19,2))
Why are you pulling this from sql?
<a href="1.html"><input type="text" class="button_active" value="1"></a>
<a href="2.html"><input type="text" class="button" value="2"></a>
<a href="3.html"><input type="text" class="button" value="3"></a>
Try that. Unless you truly need to stick with the type as submit, then what I provided should work. If you are going to stick with submit, then everything mentioned above is correct, it makes no sense.
I'm working with Nob Hill's Marketing team, I wanted to tell you I'll be happy to hear your questions, suggestion or anything else, please feel free to contact me.
We originally decided to create our tool from scratch because while there are other such products on the market, none of them do the job right. It’s quite easy to show you the differences between databases. It’s quite another to actually make one database like the other. Smooth migration, both of schema and data, has always been a challenge. Well, we have achieved it here.
We are so confident that it could provide you a smooth migration, than if it doesn’t – if the migration scripts it generates are not readable enough or won’t work for you, and we can’t fix it in five business days – you will get your own free copy!
In case you want to sort dates with descending order the minus sign doesn't work with Dates.
out <- DF[rev(order(as.Date(DF$end))),]
However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:
#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/09 12:00', '6/1/10 14:20', '1/1/11 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]
Hope it helped.
Template literals
may solve your issue as it will allow writing multi-line strings and string interpolation features. You can use variables or expression inside string (as given below). It's easy to insert bulk html in a reader friendly way.
I have modified the example given in question and please see it below. I am not sure how much browser compatible Template literals
are. Please read about Template literals here.
var a = 1, b = 2;_x000D_
var div = document.createElement('div');_x000D_
div.setAttribute('class', 'post block bc2');_x000D_
div.innerHTML = `_x000D_
<div class="parent">_x000D_
<div class="child">${a}</div>_x000D_
<div class="child">+</div>_x000D_
<div class="child">${b}</div>_x000D_
<div class="child">=</div>_x000D_
<div class="child">${a + b}</div>_x000D_
</div>_x000D_
`;_x000D_
document.getElementById('posts').appendChild(div);
_x000D_
.parent {_x000D_
background-color: blue;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}_x000D_
.post div {_x000D_
color: white;_x000D_
font-size: 2.5em;_x000D_
padding: 20px;_x000D_
}
_x000D_
<div id="posts"></div>
_x000D_
What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.
From fragment to activty:
((YourActivityClassName)getActivity()).yourPublicMethod();
From activity to fragment:
FragmentManager fm = getSupportFragmentManager();
//if you added fragment via layout xml
YourFragmentClass fragment =
(YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();
If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
The other scenario you mush verify is that the file you're trying to unpack is not empty and is valid.
In my case I wasn't downloading the file correctly, after double check and I made sure I had the right file I could unpack it without any issues.
NOTE: For glassfish Server login via admin console -> Configurations -> server-config -> JVM-settings. * Remember to check Enable checkbox for Debug. Now Note the address, this address will be used in port of eclipse Remote Java Application Debug.Check the snap shot in glassfish server here
For list comprehension lovers, this will write all the key : value
pairs in new lines in dog.txt
my_dict = {'foo': [1,2], 'bar':[3,4]}
# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]
# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
[ my_file.write(f'{st}\n') for st in list_of_strings ]
Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.
Look here for permanently changing the heap size.
I'm an Eclipse/Android beginner as well, but hopefully my simple debugging process can help...
You set breakpoints in Eclipse by right-clicking next to the line you want to break at and selecting "Toggle Breakpoint". From there you'll want to select "Debug" rather than the standard "Run", which will allow you to step through and so on. Use the filters provided by LogCat (referenced in your tutorial) so you can target the messages you want rather than wading through all the output. That will (hopefully) go a long way in helping you make sense of your errors.
As for other good tutorials, I was searching around for a few myself, but didn't manage to find any gems yet.
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
A set of four generalized sizes: small, normal, large, and xlarge Note: Beginning with Android 3.2 (API level 13), these size groups are deprecated in favor of a new technique for managing screen sizes based on the available screen width. If you're developing for Android 3.2 and greater, see Declaring Tablet Layouts for Android 3.2 for more information.
A set of six generalized densities:
ldpi (low) ~120dpi
mdpi (medium) ~160dpi
hdpi (high) ~240dpi
xhdpi (extra-high) ~320dpi
xxhdpi (extra-extra-high) ~480dpi
xxxhdpi (extra-extra-extra-high) ~640dpi
From developer.android.com : http://developer.android.com/guide/practices/screens_support.html
Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?
mongodb.com -> new project -> new cluster -> new collection -> connect -> IP address: 0.0.0.0/0 & db cred -> connect your application -> copy connection string and paste in .env file of your node app and make sure to replace "" with the actual password for the user and also replace "/test" with your db name
create new file .env
CONNECTIONSTRING=x --> const client = new MongoClient(CONNECTIONSTRING)
PORT=8080
JWTSECRET=mysuper456secret123phrase
netstat -ano|grep 443|grep LISTEN
will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).
$filename = basename($path);
Have you tried logging in as the jenkins user?
Try this:
sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git
Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.
If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?
As this isn't mentioned in the accepted answer.
You can make use of Simple Requests.
In order to perform a 'Simple Requests' the request needs to meet several conditions. E.g. only allowing POST
, GET
and HEAD
method, as well as only allowing some given Headers (you can find all conditions here).
If your client code does not explicit set affected Headers (e.g. "Accept") with a fix value in the request it might occur that some clients do set these Headers automatically with some "non-standard" values causing the server to not accept it as Simple Request - which will give you a CORS error.
Usually this means that your schema and mapping files are not in synch and there is a renamed or missing column someplace.
try this tool https://github.com/kamranahmedse/git-standup
```bash
$ git standup [-a <author name>]
[-w <weekstart-weekend>]
[-m <max-dir-depth>]
[-f]
[-L]
[-d <days-ago>]
[-D <date-format>]
[-g]
[-h]
```
Below is the description for each of the flags
- `-a` - Specify author to restrict search to (name or email)
- `-w` - Specify weekday range to limit search to (e.g. `git standup -w SUN-THU`)
- `-m` - Specify the depth of recursive directory search
- `-L` - Toggle inclusion of symbolic links in recursive directory search
- `-d` - Specify the number of days back to include
- `-D` - Specify the date format for "git log" (default: relative)
- `-h` - Display the help screen
- `-g` - Show if commit is GPG signed or not
- `-f` - Fetch the latest commits beforehand
I had a similar issue while using Sublime Text-3. After making new changes in the code and saving it, when I tried the git add ./status commands the response was "branch already-up to date". I figured out, regardless saving the updates in the text editor, the file was actually unchanged. Opening file in other editor and saving the changes worked for me.
webbot
even works web pages which have dynamically changing id and classnames and has more methods and features than selenium or mechanize.
Here's a snippet :)
from webbot import Browser
web = Browser()
web.go_to('google.com')
web.click('Sign in')
web.type('[email protected]' , into='Email')
web.click('NEXT' , tag='span')
web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
web.click('NEXT' , tag='span') # you are logged in ^_^
The docs are also pretty straight forward and simple to use : https://webbot.readthedocs.io
if you are running your matlab on linux, you can terminate the matlab by command in linux consule. first you should find the PID number of matlab by this code:
top
then you can use this code to kill matlab: kill
example: kill 58056
Yes, it's possible, the syntax is curl [protocol://]<host>[:port]
, for example:
curl example.com:1234
If you're using Bash, you can also use pseudo-device /dev
files to open a TCP connection, e.g.:
exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.
See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).
One need to update Newtonsoft.Json -Version GO to Tools => NuGet Package Manager => Package Manager Console and Type Install-Package Newtonsoft.Json -Version 12.0.2 in Package Manager Console Window.
Apart from grabbing the special __name__
attribute, you might find yourself in need of the qualified name for a given class/function. This is done by grabbing the types __qualname__
.
In most cases, these will be exactly the same, but, when dealing with nested classes/methods these differ in the output you get. For example:
class Spam:
def meth(self):
pass
class Bar:
pass
>>> s = Spam()
>>> type(s).__name__
'Spam'
>>> type(s).__qualname__
'Spam'
>>> type(s).Bar.__name__ # type not needed here
'Bar'
>>> type(s).Bar.__qualname__ # type not needed here
'Spam.Bar'
>>> type(s).meth.__name__
'meth'
>>> type(s).meth.__qualname__
'Spam.meth'
Since introspection is what you're after, this is always you might want to consider.
The biggest problem with a batch script is handling rollback when the user clicks cancel (or something goes wrong during your install). The correct way to handle this scenario is to create a CustomAction that adds temporary rows to the RemoveFiles table. That way the Windows Installer handles the rollback cases for you. It is insanely simpler when you see the solution.
Anyway, to have an action only execute during uninstall add a Condition element with:
REMOVE ~= "ALL"
the ~= says compare case insensitive (even though I think ALL is always uppercaesd). See the MSI SDK documentation about Conditions Syntax for more information.
PS: There has never been a case where I sat down and thought, "Oh, batch file would be a good solution in an installation package." Actually, finding an installation package that has a batch file in it would only encourage me to return the product for a refund.
What worked for me on Windows was (I had cloned code from a repo 1st):
eval $(ssh-agent)
ssh-add
git pull
at which time it asked me one last time for my passphrase
Credits: the solution was taken from https://unix.stackexchange.com/questions/12195/how-to-avoid-being-asked-passphrase-each-time-i-push-to-bitbucket
.loc
and .iloc
are used for indexing, i.e., to pull out portions of data. In essence, the difference is that .loc
allows label-based indexing, while .iloc
allows position-based indexing.
If you get confused by .loc
and .iloc
, keep in mind that .iloc
is based on the index (starting with i) position, while .loc
is based on the label (starting with l).
.loc
.loc
is supposed to be based on the index labels and not the positions, so it is analogous to Python dictionary-based indexing. However, it can accept boolean arrays, slices, and a list of labels (none of which work with a Python dictionary).
iloc
.iloc
does the lookup based on index position, i.e., pandas
behaves similarly to a Python list. pandas
will raise an IndexError
if there is no index at that location.
The following examples are presented to illustrate the differences between .iloc
and .loc
. Let's consider the following series:
>>> s = pd.Series([11, 9], index=["1990", "1993"], name="Magic Numbers")
>>> s
1990 11
1993 9
Name: Magic Numbers , dtype: int64
.iloc
Examples
>>> s.iloc[0]
11
>>> s.iloc[-1]
9
>>> s.iloc[4]
Traceback (most recent call last):
...
IndexError: single positional indexer is out-of-bounds
>>> s.iloc[0:3] # slice
1990 11
1993 9
Name: Magic Numbers , dtype: int64
>>> s.iloc[[0,1]] # list
1990 11
1993 9
Name: Magic Numbers , dtype: int64
.loc
Examples
>>> s.loc['1990']
11
>>> s.loc['1970']
Traceback (most recent call last):
...
KeyError: ’the label [1970] is not in the [index]’
>>> mask = s > 9
>>> s.loc[mask]
1990 11
Name: Magic Numbers , dtype: int64
>>> s.loc['1990':] # slice
1990 11
1993 9
Name: Magic Numbers, dtype: int64
Because s
has string index values, .loc
will fail when
indexing with an integer:
>>> s.loc[0]
Traceback (most recent call last):
...
KeyError: 0
Use the download
attribute:
<a download='FileName' href='your_url'>
The download
attribute works on Chrome, Firefox, Edge, Opera, desktop Safari 10+, iOS Safari 13+, and not IE11.
Use rgba!
.alpha60 {
/* Fallback for web browsers that don't support RGBa */
background-color: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background-color: rgba(0, 0, 0, 0.6);
/* For IE 5.5 - 7*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}
In addition to this, you have to declare
background: transparent
for IE web browsers, preferably served via conditional comments or similar!
I like to use np.vectorize
for such tasks. Consider the following:
>>> # function which returns True when constraints are satisfied.
>>> func = lambda d: d >= r and d<= (r+dr)
>>>
>>> # Apply constraints element-wise to the dists array.
>>> result = np.vectorize(func)(dists)
>>>
>>> result = np.where(result) # Get output.
You can also use np.argwhere
instead of np.where
for clear output. But that is your call :)
Hope it helps.
If you don't need to handle special shell characters in the array elements:
array=(a c b f 3 5)
sorted=($(printf '%s\n' "${array[@]}"|sort))
With bash you'll need an external sorting program anyway.
With zsh no external programs are needed and special shell characters are easily handled:
% array=('a a' c b f 3 5); printf '%s\n' "${(o)array[@]}"
3
5
a a
b
c
f
ksh has set -s
to sort ASCIIbetically.
As the error code says, "no alternative certificate subject name matches target host name" - so there is an issue with the SSL certificate.
The certificate should include SAN, and only SAN will be used. Some browsers ignore the deprecated Common Name.
RFC 2818 clearly states "If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead."
For me, I just right click on project -> Build path -> configure build path -> Libraries -> remove dependency
after it works.
Why does it work in Chrome and not Firefox?
The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS
requests returning a status of 401 still send the subsequent request.
Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS
request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.
How can I get the OPTIONS
request to send and respond consistently?
Simply have the server (API in this example) respond to OPTIONS
requests without requiring authentication.
Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.
*X*YZ* = string contains X and contains YZ
@".*X.*YZ"
X*YZ*P = string starts with X, contains YZ and ends with P.
@"^X.*YZ.*P$"
This code works for me:
$rootScope.$$listeners.nameOfYourEvent=[];
NSString * varyingString = ...;
NSString * cat = [NSString stringWithFormat:@"%s%@%@",
"first part of string",
varyingString,
@"third part of string"];
or simply -[NSString stringByAppendingString:]
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
I'll sometimes do this:
def draw_menu(options, selected_index):
for i in range(len(options)):
if i == selected_index:
print " [*] %s" % options[i]
else:
print " [ ] %s" % options[i]
Though I tend to avoid this if it means I'll be saying options[i]
more than a couple of times.
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
This did NOT work in IE8 (yet did in FF):
$("#selectList").append(new Option("option text", "value"));
This DID work:
var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);
Methods on SynchronizedMap
hold the lock on the object, whereas in ConcurrentHashMap
there's a concept of "lock striping" where locks are held on buckets of the contents instead. Thus improved scalability and performance.
If you are using lodash, its even simpler with takeRight.
_.takeRight(arr, 5);
Try it:
String command = "killall <your_proccess>";
Process p = Runtime.getRuntime().exec(command);
p.destroy();
if the process is still alive, add:
p.destroyForcibly();
Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.
If you already have a dictionary, a counter can easily be formed by:
c = Counter(d['123'])
as an example from your data.
The most_common
function allows easy access to descending order of the items in the counter
The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html
If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding ID}"/>
</StackPanel>
That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.
On the anaconda prompt, do a
conda -V
or conda --version
to get the conda version.python -V
or python --version
to get the python version.conda list anaconda$
to get the Anaconda version.conda list
to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).conda info
to get all the current environment details.conda info --envs
To see a list of all your environmentsProgram prints ab
, goes back one character and prints si
overwriting the b
resulting asi
.
Carriage return returns the caret to the first column of the current line. That means the ha
will be printed over as
and the result is hai
As opposed to passing the text as a variable, you can use the DOM to retrieve the data in your function:
var text = document.getElementsByName("textbox1").value;
With Java 1.8 there is a new StringJoiner class - so no need for Guava or Apache Commons:
String str = new StringJoiner(",").add("a").add("b").add("c").toString();
Or using a collection directly with the new stream api:
String str = Arrays.asList("a", "b", "c").stream().collect(Collectors.joining(","));
you need to add it to Foo's prototype:
function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()
You open the file in text mode.
More specifically:
ifile = open('sample.csv', "rt", encoding=<theencodingofthefile>)
Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.
Try below one:
svn copy http://svn.example.com/repos/calc/trunk@rev-no
http://svn.example.com/repos/calc/branches/my-calc-branch
-m "Creating a private branch of /calc/trunk." --parents
No slash "\" between the svn URLs.
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding
Alternatively you can just look inside
C:\Program Files\dotnet\sdk
1-> Using File Default Config- Angular-cli comes from the ember-cli project. To run the application on specific port, create an .ember-cli file in the project root. Add your JSON config in there:
{ "port": 1337 }
2->Using Command Line Tool Run this command in Angular-Cli
ng serve --port 1234
To change the port number permanently:
Goto
node_modules/angular-cli/commands/server.js
Search for var defaultPort = process.env.PORT || 4200;
(change 4200 to anything else you want).
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
If you have a parameter where you may need to indicate the absence of a value, it's common practice to make the parameter a pointer value and pass in NULL.
A better solution in most cases (from a safety perspective) is to use boost::optional. This allows you to pass in optional values by reference and also as a return value.
// Sample method using optional as input parameter
void PrintOptional(const boost::optional<std::string>& optional_str)
{
if (optional_str)
{
cout << *optional_str << std::endl;
}
else
{
cout << "(no string)" << std::endl;
}
}
// Sample method using optional as return value
boost::optional<int> ReturnOptional(bool return_nothing)
{
if (return_nothing)
{
return boost::optional<int>();
}
return boost::optional<int>(42);
}
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
Ahum, three years later...
Why nobody uses the methods provided by the standard javascript Date class (except Callum Linington)?
Getting the day name from a date:
function getDayName(dateStr, locale)
{
var date = new Date(dateStr);
return date.toLocaleDateString(locale, { weekday: 'long' });
}
var dateStr = '05/23/2014';
var day = getDayName(dateStr, "nl-NL"); // Gives back 'Vrijdag' which is Dutch for Friday.
Getting all weekdays in an array:
function getWeekDays(locale)
{
var baseDate = new Date(Date.UTC(2017, 0, 2)); // just a Monday
var weekDays = [];
for(i = 0; i < 7; i++)
{
weekDays.push(baseDate.toLocaleDateString(locale, { weekday: 'long' }));
baseDate.setDate(baseDate.getDate() + 1);
}
return weekDays;
}
var weekDays = getWeekDays('nl-NL'); // Gives back { 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag', 'zondag'} which are the days of the week in Dutch.
For American dates use 'en-US' as locale.
if you are using matplotlib version 3.1.1 or above, you can try:
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'B', 'C']
values = [0, 0, 1, 2, 2, 2]
colours = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y,c=values, cmap=colours)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)
You can also check run time. Put one breakpoint in code and inside (lldb) console write
(lldb) po [yourObject class]
Like this..
Initialize the current cursor. Use it to get the position of X and Y
this.Cursor = new Cursor(Cursor.Current.Handle);
int posX = Cursor.Position.X;
int posY = Cursor.Position.Y;
You could "reset" your repository to any commit you want (e.g. 1 month ago).
Use git-reset for that:
git clone [remote_address_here] my_repo
cd my_repo
git reset --hard [ENTER HERE THE COMMIT HASH YOU WANT]
declare @sql1 nvarchar(max)
SELECT @sql1 =
STUFF(
(
select ' drop table dbo.[' + name + ']'
FROM sys.sysobjects AS sobjects
WHERE (xtype = 'U') AND (name LIKE 'GROUP_BASE_NEW_WORK_%')
for xml path('')
),
1, 1, '')
execute sp_executesql @sql1
The causes of this error are many so first locate your log file and check it for clues. It might be at /usr/local/var/log/postgres.log
or /usr/local/var/postgres/server.log
or possibly elsewhere. If you installed with Homebrew you can find the location in ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
.
As @Hesham Eraqi suggested, it worked for me in this way (transfering from Ubuntu to Windows (I tried to add a comment in that answer but because of reputation, I couldn't)):
pscp -v -r -P 53670 [email protected]:/data/genetic_map/sample/P2_283/* \\Desktop-mojbd3n\d\cc_01-1940_data\
where:
-v
: show verbose messages.
-r
: copy directories recursively.
-P
: connect to specified port.
53670
: the port number to connect the Ubuntu server.
\\Desktop-mojbd3n\d\genetic_map_data\
: I needed to transfer to an external HDD, thus I had to give permissions of sharing to this device.
If you are here because your pytorch always gives False
for torch.cuda.is_available()
that's probably because you installed your pytorch version without GPU support. (Eg: you coded up in laptop then testing on server).
The solution is to uninstall and install pytorch again with the right command from pytorch downloads page. Also refer this pytorch issue.
Just put {'\n'}
within the Text tag
<Text>
Hello {'\n'}
World!
</Text>
In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.
On Ubuntu 14.04 none of these suggestions worked. Postfix would override with the logged in system user as the sender. What worked was the following solution listed at this link --> Change outgoing mail address from root@servername - rackspace sendgrid postfix
STEPS:
1) Make sure this is set in /etc/postfix/main.cf:
smtp_generic_maps = hash:/etc/postfix/generic
2) echo 'www-data [email protected]' >> /etc/postfix/generic
3) sudo postmap /etc/postfix/generic
4) sudo service postfix restart
Use these settings and it will work fine.
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.pm.motivator"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
}
}
If you want to compare with empty string without worrying about null values you can do the following.
if ("".equals(text))
Ultimately you should do what what you believe is clearest. Most programmers assume "" means empty string, not a string someone forgot to put anything into.
If you think there is a performance advantage, you should test it. If you don't think its worth testing for yourself, its a good indication it really isn't worth it.
It sounds like to you try to solve a problem which was solved when the language was designed more than 15 years ago.
You can get the index of the current iteration by adding another parameter to your iterator function
, e.g.
_.each(['foo', 'bar', 'baz'], function (val, i) {
console.log(i + ": " + val); // 0: foo, 1: bar, 2: baz
});
"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"
You can check out my small free utility for service create\edit\delete operations. Here is create example:
Go to Service -> Modify -> Create
Executable file (google drive): [Download]
Source code: [Download]
Blog post: [BlogLink]
Service editor class: WinServiceUtils.cs
I would do something like:
$(documento).on('click', '#answer', function() {
feedback('hey there');
});
You can use the concept of selector. onFocus removes the hint.
android:hint="Email"
So when TextView
has focus, or has user input (i.e. not empty) the hint will not display.
Asymptotic notation is something you can understand as: how do functions compare when zooming out? (A good way to test this is simply to use a tool like Desmos and play with your mouse wheel). In particular:
f(n) ? o(n)
means: at some point, the more you zoom out, the more f(n)
will be dominated by n
(it will progressively diverge from it).g(n) ? T(n)
means: at some point, zooming out will not change how g(n)
compare to n
(if we remove ticks from the axis you couldn't tell the zoom level).Finally h(n) ? O(n)
means that function h
can be in either of these two categories. It can either look a lot like n
or it could be smaller and smaller than n
when n
increases. Basically, both f(n)
and g(n)
are also in O(n)
.
In computer science, people will usually prove that a given algorithm admits both an upper O
and a lower bound . When both bounds meet that means that we found an asymptotically optimal algorithm to solve that particular problem.
For example, if we prove that the complexity of an algorithm is both in O(n)
and (n)
it implies that its complexity is in T(n)
. That's the definition of T
and it more or less translates to "asymptotically equal". Which also means that no algorithm can solve the given problem in o(n)
. Again, roughly saying "this problem can't be solved in less than n
steps".
An upper bound of O(n)
simply means that even in the worse case, the algorithm will terminate in at most n
steps (ignoring all constant factors, both multiplicative and additive). A lower bound of (n)
means on the opposite that we built some examples where the problem solved by this algorithm couldn't be solved in less than n
steps (again ignoring multiplicative and additive constants). The number of steps is at most n
and at least n
so this problem complexity is "exactly n
". Instead of saying "ignoring constant multiplicative/additive factor" every time we just write T(n)
for short.
Is sku
just a property of the Product
model? If so:
$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
foreach ($products as $product ) {
// Access $product->sku here...
}
Or is sku
a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
}
catch (Exception e)
{
//handle exception
}
and yes path must be in a format of like this
file:///mnt/sdcard/filename.jpg
Normally, mutt sets the From:
header based on the from
configuration variable you set in ~/.muttrc
:
set from="Fubar <foo@bar>"
If this is not set, mutt
uses the EMAIL
environment variable by default. In which case, you can get away with calling mutt like this on the command line (as opposed to how you showed it in your comment):
EMAIL="foo@bar" mutt -s '$MailSubject' -c "abc@def"
However, if you want to be able to edit the From:
header while composing, you need to configure mutt
to allow you to edit headers first. This involves adding the following line in your ~/.muttrc
:
set edit_headers=yes
After that, next time you open up mutt and are composing an E-mail, your chosen text editor will pop up containing the headers as well, so you can edit them. This includes the From:
header.
cross apply
sometimes enables you to do things that you cannot do with inner join
.
Example (a syntax error):
select F.* from sys.objects O
inner join dbo.myTableFun(O.name) F
on F.schema_id= O.schema_id
This is a syntax error, because, when used with inner join
, table functions can only take variables or constants as parameters. (I.e., the table function parameter cannot depend on another table's column.)
However:
select F.* from sys.objects O
cross apply ( select * from dbo.myTableFun(O.name) ) F
where F.schema_id= O.schema_id
This is legal.
Edit: Or alternatively, shorter syntax: (by ErikE)
select F.* from sys.objects O
cross apply dbo.myTableFun(O.name) F
where F.schema_id= O.schema_id
Edit:
Note: Informix 12.10 xC2+ has Lateral Derived Tables and Postgresql (9.3+) has Lateral Subqueries which can be used to a similar effect.
trap 'kill $(jobs -p)' EXIT
I would make only minor changes to Johannes' answer and use jobs -pr to limit the kill to running processes and add a few more signals to the list:
trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT
Using an ungreedy match is a good start, but I'd also suggest that you reconsider any use of .*
-- what about this?
groups = re.search(r"\([^)]*\)", x)
You can use the bind function to set the context of this
within a function.
function myFunc() {
console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"
I would suggest you to try
https://spark.apache.org/docs/latest/sql-programming-guide.html#rdds
JavaRDD<Person> people = sc.textFile("examples/src/main/resources/people.txt").map(
new Function<String, Person>() {
public Person call(String line) throws Exception {
String[] parts = line.split(",");
Person person = new Person();
person.setName(parts[0]);
person.setAge(Integer.parseInt(parts[1].trim()));
return person;
}
});
You have to have a class in this example person with the spec of your file header and associate your data to the schema and apply criteria like in mysql.. to get desired result
As far as I know, renaming a file will not append its contents to that of an existing file with the target name.
About renaming a file in Java, see the documentation for the renameTo()
method in class File
.
Something like this:
// When your program starts up
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// then, when you want to schedule a task
Runnable task = ....
executor.schedule(task, 5, TimeUnit.SECONDS);
// and finally, when your program wants to exit
executor.shutdown();
There are various other factory methods on Executor
which you can use instead, if you want more threads in the pool.
And remember, it's important to shutdown the executor when you've finished. The shutdown()
method will cleanly shut down the thread pool when the last task has completed, and will block until this happens. shutdownNow()
will terminate the thread pool immediately.
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
My solution...
HTML :
<input type="file" id="uploadImages" style="display:none;" multiple>
<input type="button" id="callUploadImages" value="Select">
<input type="button" id="uploadImagesInfo" value="0 file(s)." disabled>
<input type="button" id="uploadProductImages" value="Upload">
Jquery:
$('#callUploadImages').click(function(){
$('#uploadImages').click();
});
$('#uploadImages').change(function(){
var uploadImages = $(this);
$('#uploadImagesInfo').val(uploadImages[0].files.length+" file(s).");
});
This is just evil :D
There is no difference between the %i
and %d
format specifiers for printf
. We can see this by going to the draft C99 standard section 7.19.6.1
The fprintf function which also covers printf
with respect to format specifiers and it says in paragraph 8:
The conversion specifiers and their meanings are:
and includes the following bullet:
d,i The int argument is converted to signed decimal in the style [-]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters.
On the other hand for scanf
there is a difference, %d
assume base 10 while %i
auto detects the base. We can see this by going to section 7.19.6.2
The fscanf function which covers scanf
with respect to format specifier, in paragraph 12 it says:
The conversion specifiers and their meanings are:
and includes the following:
d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer. i Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.
You can have a debug.cmd that calls yourscript.cmd
yourscript.cmd > logall.txt
you schedule debug.cmd instead of yourscript.cmd
This code is tested and working.
public void dumpMe(Map m) { dumpMe(m, ""); }
private void dumpMe(Map m, String padding) {
Set s = m.keySet();
java.util.Iterator ir = s.iterator();
while (ir.hasNext()) {
String key = (String) ir.next();
Object value = m.get(key);
if (value == null) continue;
if (value instanceof Map) {
System.out.println (padding + key + " = {");
dumpMe((Map)value, padding + " ");
System.out.println(padding + "}");
}
else if (value instanceof String ||
value instanceof Integer ||
value instanceof Double ||
value instanceof Float ||
value instanceof Long ) {
System.out.println(padding + key + " = " + value.toString());
}
else {
System.out.println(padding + key + " = UNKNOWN OBJECT: " + value.toString());
// You could also throw an exception here
}
} // while
} // dumpme
Charles.
You don't need regex to split a string on whitespace:
In [1]: text = '''WYATT - Ranked # 855 with 0.006 %
...: XAVIER - Ranked # 587 with 0.013 %
...: YONG - Ranked # 921 with 0.006 %
...: YOUNG - Ranked # 807 with 0.007 %'''
In [2]: print '\n'.join(line.split()[0] for line in text.split('\n'))
WYATT
XAVIER
YONG
YOUNG
I agree httpclient is something of a standard - but I guess you are looking for options so...
Restlet provides a http client specially designed for interactong with Restful web services.
Example code:
Client client = new Client(Protocol.HTTP);
Request r = new Request();
r.setResourceRef("http://127.0.0.1:8182/sample");
r.setMethod(Method.GET);
r.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_XML));
client.handle(r).getEntity().write(System.out);
See http://www.restlet.org/ for more details
As described in Documentation Environment.getExternalStorageDirectory() :
Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.
This is an example of how to use it reading an image :
String fileName = "stored_image.jpg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";
File f = new File(pathDir + File.separator + fileName);
if(f.exists()){
Log.d("Application", "The file " + file.getName() + " exists!";
}else{
Log.d("Application", "The file no longer exists!";
}
Constants can be declare outside of classes and use within your class. Otherwise the get
property is a nice workaround
const MY_CONSTANT: string = "wazzup";
export class MyClass {
public myFunction() {
alert(MY_CONSTANT);
}
}
You could also do it with PowerShell:
Get-WmiObject win32_service -filter "Name='My Service'" `
| Invoke-WmiMethod -Name Change `
-ArgumentList @($null,$null,$null,$null,$null, `
"C:\Program Files (x86)\My Service\NewName.EXE")
Or:
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\My Service" `
-Name ImagePath -Value "C:\Program Files (x86)\My Service\NewName.EXE"
Delete parent:
$(document).on("click", ".remove", function() {
$(this).parent().remove();
});
Delete all parents:
$(document).on("click", ".remove", function() {
$(this).parents().remove();
});
Here:
important!: this only works if an extra space or newline at the start is no problem for your use case of the file
(e.g. if it is an SQL file, Java file or human readable text file)
one could use a combination of creating an empty (non-UTF8 or ASCII (UTF8-compatible)) file and appending to it (replace $str
with gc $src
if the source is a file):
" " | out-file -encoding ASCII -noNewline $dest
$str | out-file -encoding UTF8 -append $dest
replace $dest
and $str
according to your use case:
$_ofdst = $dest ; " " | out-file -encoding ASCII -noNewline $_ofdst ; $src | out-file -encoding UTF8 -append $_ofdst
function Out-File-UTF8-noBOM { param( $str, $dest )
" " | out-file -encoding ASCII -noNewline $dest
$str | out-file -encoding UTF8 -append $dest
}
using it with a source file:
Out-File-UTF8-noBOM (gc $src), $dest
using it with a string:
Out-File-UTF8-noBOM $str, $dest
optionally: continue appending with Out-File
:
"more foo bar" | Out-File -encoding UTF8 -append $dest
You've forgot to define an onclick attribute to do something when the button is clicked, so nothing happening is the correct execution, see below;
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
----------------------
Here is the working solution for ie, firefox and chrome:
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
var confirmationMessage = 'Are you sure to leave the page?'; // a space
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
<script>
function subadd(){
subadd= parseFloat(document.forms[0][0].value) + parseFloat(document.forms[0][1].value)
window.alert(subadd)
}
</script>
<body>
<form>
<input type="text" >+
<input type="text" >
<input type="button" value="add" onclick="subadd()">
</form>
</body>
substring(field, 1,3) will work on your examples.
select substring(field, 1,3) from table
Also, if the alphabetic part is of variable length, you can do this to extract the alphabetic part:
select substring(field, 1, PATINDEX('%[1234567890]%', field) -1)
from table
where PATINDEX('%[1234567890]%', field) > 0
I had a similar problem - authenticate device and user at device. I used a Cookie
header alongside an Authorization: Bearer...
header. One header authenticated the device, the other authenticated the user. I used a Cookie
header because these are commonly used for authentication.
Pointed out solution works well. Clean and smooth.
However, if you want strongly typed enumerations, you can use this:
class TestEnum extends Enum
{
public static $TEST1;
public static $TEST2;
}
TestEnum::init(); // Automatically initializes enum values
With an Enum class looking like:
class Enum
{
public static function parse($enum)
{
$class = get_called_class();
$vars = get_class_vars($class);
if (array_key_exists($enum, $vars)) {
return $vars[$enum];
}
return null;
}
public static function init()
{
$className = get_called_class();
$consts = get_class_vars($className);
foreach ($consts as $constant => $value) {
if (is_null($className::$$constant)) {
$constantValue = $constant;
$constantValueName = $className . '::' . $constant . '_VALUE';
if (defined($constantValueName)) {
$constantValue = constant($constantValueName);
}
$className::$$constant = new $className($constantValue);
}
}
}
public function __construct($value)
{
$this->value = $value;
}
}
This way, enum values are strongly typed and
TestEnum::$TEST1 === TestEnum::parse('TEST1') // true statement
There is another extended Stored Procedure which can be used to see the Version info:
exec [master].sys.[xp_msver]
A unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for your keys would be:
create table [misc_info]
(
[id] INTEGER PRIMARY KEY IDENTITY NOT NULL,
[key] nvarchar(450) UNIQUE NOT NULL,
[value] nvarchar(max) NOT NULL
)
i.e. the key can't be over 450 characters. If you can switch to varchar
instead of nvarchar
(e.g. if you don't need to store characters from more than one codepage) then that could increase to 900 characters.
I had the same problem.
'Periodic workspace save.' has encountered a problem. Could not write metadata for '/External Files'. D:\java\fuentes\.metadata\.plugins\org.eclipse.core.resources\.projects\External Files\.markers.snap (El sistema no puede hallar la ruta especificada)
I created the folder "External Files" and it worked fine. In a few minutes the files ".markers.snap" and ".syncinfo.snap" appeared in this folder and the message didn´t appear any more.
It was talked about it a lot already, u can find even on Wiki the reasons...
And I hear more and more Java programmers that try to convince people that Java is not slow, it is not slow for drawing a widget on the screen and drawing some ASCII characters on the widget, to receive and send data through network(And it is recommended to use it in this cases(network data manipulation) instead of C/C++)... But it is damn slow when it comes to serious stuff like math calculations, memory allocation/manipulation and a lot of this good stuff.
I remember an article on MIT site where they show what C/C++ can do if u use the language and compiler features: A matrix multiplier(2 matrices), 1 implementation in Java and 1 implementation in C/C++, with C/C++ features and appropriate compiler optimisations activated, the C/C++ implementation was ~296 260 times faster than the Java implementation.
I hope you understand now why people use C/C++ instead of Java in games, imagine Crysis in Java, there would not be any computer in this world which could handle that... + Garbage collection works ok for Widgets which just destroyed an image but it's still cached in there and needs to be cleaned but not for games, for sure, u will have even more lags on every garbage collection activation.
Edit: Because somebody asked for the article, here, I searched in the web archive to get that, I hope you are satisfied...MIT Case Study
And to add, no, Java for gaming is still an awful idea. Just a few days ago a big company that I will not name started rewriting their game client from Java to C++ because a very simple game(In terms of Graphics) was lagging and heating i7 Laptops with powerful nVidia GT 5xx and 6xx generation video cards(not only nVidia, the point here is that this powerful cards that can handle on Max settings most of the new games and can't handle this game) and the memory consumption was ~2.5 - 2.6 GB Ram. For such simple graphics it needs a beast of a machine.
This is simple to do with Seaborn (pip install seaborn
) as a oneliner
sns.scatterplot(x_vars="one", y_vars="two", data=df, hue="key1")
:
import seaborn as sns
import pandas as pd
import numpy as np
np.random.seed(1974)
df = pd.DataFrame(
np.random.normal(10, 1, 30).reshape(10, 3),
index=pd.date_range('2010-01-01', freq='M', periods=10),
columns=('one', 'two', 'three'))
df['key1'] = (4, 4, 4, 6, 6, 6, 8, 8, 8, 8)
sns.scatterplot(x="one", y="two", data=df, hue="key1")
Here is the dataframe for reference:
Since you have three variable columns in your data, you may want to plot all pairwise dimensions with:
sns.pairplot(vars=["one","two","three"], data=df, hue="key1")
https://rasbt.github.io/mlxtend/user_guide/plotting/category_scatter/ is another option.
I was handling a bigint datatype to be shown in a DataGridView and made it like this
something = (int)(Int64)data_reader[0];
// copy /tmp/abc.txt to /tmp/abc.txt (target path)
// username and password of 10.1.1.2 is "username" and "password"
sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt
// install sshpass (ubuntu)
sudo apt-get install sshpass
You can't according to the PHP manual:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.
But you can work around it by also setting $_COOKIE
when you call setcookie()
:
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()"
instead.
You may want to considering replacing this method with onsubmit="return checkform()"
in the form tag instead, though both will work for clicking the button.
If the text is a simple markup and has existing anchors, stage the existing anchor tags first, swap out the urls, then replace the staged markers.
$text = '
Lorem Ipsum is simply dummy text found by searching http://google.com/?q=lorem in your <a href=https://www.mozilla.org/en-US/firefox/>Firefox</a>,
<a href="https://www.apple.com/safari/">Safari</a>, or https://www.google.com/chrome/ browser.
Link replacements will first stage existing anchor tags, replace each with a marker, then swap out the remaining links.
Links should be properly encoded. If links are not separated from surrounding content like a trailing "." period then they it will be included in the link.
Links that are not encoded properly may create a problem, so best to use this when you know the text you are processing is not mixed HTML.
Example: http://google.com/i,m,complicate--d/index.html
Example: https://www.google.com/chrome/?123&t=123
Example: http://google.com/?q='. urlencode('<a href="http://google.com">http://google.com</a>') .'
';
// Replace existing links with a marker
$linkStore = array();
$text = preg_replace_callback('/(<a.*?a>)/', function($match) use (&$linkStore){ $key = '__linkStore'.count($linkStore).'__'; $linkStore[$key] = $match[0]; return $key; }, $text);
// Replace remaining URLs with an anchor tag
$text = preg_replace_callback("/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/", function($match) use (&$linkStore){ return '<a href="'. $match[0] .'">'. $match[0] .'</a>'; }, $text);
// Replace link markers with original
$text = str_replace(array_keys($linkStore), array_values($linkStore), $text);
echo '<pre>'.$text;
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
As other answers suggest... Some guy (for whatever reason) decided that your old code should not work when you upgrade your PHP, because he knows better than you and don't care about what your code does or how simple it is for you to upgrade.
Well, if you can't upgrade your project overnight you can
downgrade your version of PHP to whatever version that worked
or...
use a shim (kind of polyfill) such as https://github.com/dshafik/php7-mysql-shim or https://github.com/dotpointer/mysql-shim, and then find a place for
include_once("choice_shim.php");
somewhere in your code
That will keep your old PHP code up and running until you are in a mood to update...
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum
You just have to use class="row-eq-height"
with your class="row"
to get equal height columns for previous bootstrap versions.
but with bootstrap 4 this comes natively.
check this link --http://getbootstrap.com.vn/examples/equal-height-columns/
If your intention is to call other Activities from the current Activity, you should use Intents. Your focus could be less on persisting data than on sharing it on an as-needed basis.
However, if you really need to persist these values then you could persist them in some kind of structured text file or database on local storage. A properties file, XML file, or JSON file could store your data and be easily parsed during activity creation. Don't forget also that you have SQLite on all Android devices, so you could store them in a database table. You could also use a Map to store key-value pairs and serialize the map to local storage, but this might be too cumbersome to be useful for simple data structures.
@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error
Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid']
instead of $objData->token
Have you considered fetching the HTML separately, and then loading it into a webview?
String fetchContent(WebView view, String url) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = httpClient.execute(get);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
HttpEntity entity = response.getEntity();
String html = EntityUtils.toString(entity); // assume html for simplicity
view.loadDataWithBaseURL(url, html, "text/html", "utf-8", url); // todo: get mime, charset from entity
if (statusCode != 200) {
// handle fail
}
return html;
}
I had this same error and I didn't understand but I realized that my modem was using the same port as mysql. Well, I stop apache2.service by sudo systemctl stop apache2.service
and restarted the xammp, sudo /opt/lampp/lampp start
Just maybe, if you were not using a password for mysql yet you had, 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
, then you have to pass an empty string as the password
My Django Setup : 1.11 Bootstrap: 3.3.7
Since none of the answers are completely clear, I am sharing my template code which presents no errors at all.
Top Half of template:
{% extends 'base.html' %}
{% load static %}
{% load i18n %}
{% block head %}
<title>Add Interview</title>
{% endblock %}
{% block content %}
<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<script type="text/javascript" src="{% static 'js/jquery.js' %}"></script>
Bottom Half:
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.min.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/actions.min.js' %}"></script>
{% endblock %}
df.loc will do the job :
>>> df = pd.DataFrame(np.random.randn(3, 2), columns=['A','B'])
>>> df
A B
0 -0.269036 0.534991
1 0.069915 -1.173594
2 -1.177792 0.018381
>>> df.loc[13] = df.loc[1]
>>> df
A B
0 -0.269036 0.534991
1 0.069915 -1.173594
2 -1.177792 0.018381
13 0.069915 -1.173594
The ideal answer found in the forum mentioned above is this:
sed -i 's/facebook-android-sdk:4.+/facebook-android-sdk:4.22.1/g' ./node_modules/react-native-fbsdk/android/build.gradle
This works
In .plist file set property:
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
It hides the statusBar.
If you are invoking share Intent in Cordova plugin, setting the Flag will not help. Instead use this -
cordova.getActivity().startActivity(Intent.createChooser(shareIntent, "title"));
My solution applies Array.prototype.some() and Array.prototype.includes() array helpers which do their job pretty efficient as well
ES6
const originalFruits = ["apple","banana","orange"];_x000D_
_x000D_
const fruits1 = ["apple","banana","pineapple"];_x000D_
_x000D_
const fruits2 = ["grape", "pineapple"];_x000D_
_x000D_
const commonFruits = (myFruitsArr, otherFruitsArr) => {_x000D_
return myFruitsArr.some(fruit => otherFruitsArr.includes(fruit))_x000D_
}_x000D_
console.log(commonFruits(originalFruits, fruits1)) //returns true;_x000D_
console.log(commonFruits(originalFruits, fruits2)) //returns false;
_x000D_
It worked for me this way, it's the best I've found. It is for a max length of 200 characters
editObservations.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (editObservations.getText().length() >= 201){
String str = editObservations.getText().toString().substring(0, 200);
editObservations.setText(str);
editObservations.setSelection(str.length());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
When you import a module,
import file_name
Python stores the compiled bytecode in __pycache__
directory so that future imports can use it directly, rather than having to parse and compile the source again.
It does not do that for merely running a script, only when a file is imported.
(Previous versions used to store the cached bytecode as .pyc files that littered up the same directory as the .py files, but starting in Python 3 they were moved to a subdirectory to make things tidier.)
PYTHONDONTWRITEBYTECODE ---> If this is set to a non-empty string, Python won’t try to write .pyc files on the import of source modules. This is equivalent to specifying the -B option.
I had the same symptoms as described here. I could connect once to a bluetooth printer but subsequent connects failed with "socket closed" no matter what I did.
I found it a bit strange that the workarounds described here would be necessary. After going through my code I found that I had forgot to close the socket's InputStream and OutputSteram and not terminated the ConnectedThreads properly.
The ConnectedThread I use is the same as in the example here:
http://developer.android.com/guide/topics/connectivity/bluetooth.html
Note that ConnectThread and ConnectedThread are two different classes.
Whatever class that starts the ConnectedThread must call interrupt() and cancel() on the thread. I added mmInStream.close() and mmOutStream.close() in the ConnectedTread.cancel() method.
After closing the threads/streams/sockets properly I could create new sockets without any problem.
Here are the steps you need. Step5 is important if you want the data. Step 2 is where you can select individual tables.
EDIT stack's version isn't quite readable... here's a full-size image http://i.imgur.com/y6ZCL.jpg
Assuming that you have access to Prototype, this could work. I wrote this code for myself just a few minutes ago; I only needed a single key at a time, so this isn't time efficient for big lists of key:value pairs or for spitting out multiple key names.
function key(int) {
var j = -1;
for(var i in this) {
j++;
if(j==int) {
return i;
} else {
continue;
}
}
}
Object.prototype.key = key;
This is numbered to work the same way that arrays do, to save headaches. In the case of your code:
buttons.key(0) // Should result in "button1"
Sometimes it is just a matter of closing Visual Studio 2015 and then open again.
Update: Visual Studio 2017 apparently as well.
I have had this happen on a few machines.
This does happen.
"Have you tried to delete the "Your_Solution_FileName.suo" file?"
Also computer crashing like e.g. power outage etc...
Applies to Update 2 and Update 3 as well as fresh base without any updates...
import numpy as np
hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5))
Below, hist
indicates that there are 0 items in bin #0, 2 in bin #1, 4 in bin #3, 1 in bin #4.
print(hist)
# array([0, 2, 4, 1])
bin_edges
indicates that bin #0 is the interval [0,1), bin #1 is [1,2), ...,
bin #3 is [3,4).
print (bin_edges)
# array([0, 1, 2, 3, 4]))
Play with the above code, change the input to np.histogram
and see how it works.
But a picture is worth a thousand words:
import matplotlib.pyplot as plt
plt.bar(bin_edges[:-1], hist, width = 1)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()
If showing data to the user, do a redirect:
<script language="JavaScript">
var tester = "foobar";
document.location="http://www.host.org/myphp.php?test=" + tester;
</script>
or an iframe:
<script language="JavaScript">
var tester = "foobar";
document.write("<iframe src=\"http://www.host.org/myphp.php?test=" + tester + "\"></iframe>");
</script>
If you don't need user output, create an iframe with width=0 and height=0.
I think this may be what you are looking for: ON CONFLICT clause.
If you define your table like this:
CREATE TABLE table1(
id INTEGER PRIMARY KEY ON CONFLICT REPLACE,
field1 TEXT
);
Now, if you do an INSERT with an id that already exists, SQLite automagically does UPDATE instead of INSERT.
Hth...
You can use JQuery, select the item by id:
$("input#Password").attr("autocomplete","off");
Or select the item by type:
$("input[type='password']").attr("autocomplete","off");
Or also:
You can use pure Javascript:
document.getElementById('Password').autocomplete = 'off';
What is the difference between encrypting some data vs signing some data (using RSA)?
Encryption preserves confidentiality of the message ("some data"), while signing provides non-repudiation: i.e. only the entity that signed it could have signed it. There are functional differences as well; read on.
Does it simply reverse the role of the public-private keys?
Absolutely not. The use of the same private keys for signing and decryption (or, likewise, the same public keys for verification and encryption) is frowned upon, as you should not mix purposes. This is not so much a mathematical issue (RSA should still be secure), but a problem with key management, where e.g. the signing key should have a shorter live and contain more protection before it is used.
For the same message, you should use the senders private key for signing and the receivers trusted public key for encryption. Commonly sign-then-encrypt is used otherwise an adversary could replace the signature with his own. Likewise you should use the private key of the receiver for decryption and the trusted public key of the sender for verification.
Furthermore, you should understand that signature generation doesn't use "encryption with the private key". Although all RSA operations are based upon modular exponentiation, the padding scheme is entirely different for signature generation. Furthermore, the public key has entirely different properties than the RSA private key in all practical uses of RSA.
For example, I want to use my private key to generate messages so only I can possibly be the sender.
That's non-repudiation property, which can be achieved by signing.
I want my public key to be used to read the messages and I do not care who reads them.
The public key should be considered known by all. If you want everybody to read the messages, then you simply do not encrypt them.
Signing will generally not influence the content of the message. The message is is considered separate from signatures. Officially such signatures are known as "signatures with appendix" where the appendix is the message. It's a bit weird name as the message is considered more important than the signature over it, but yeah. Only few signatures offer (partial) message recovery; they are not used much anymore and are generally considered deprecated.
Note that signature protocols such as CMS may deploy a container format that includes both the message and the signature. In that case you'd need first get the - still unencrypted - message out of the container, much like unzipping a file from a plain .zip archive. So the message may be hidden from view and cannot be directly used in that case.
I want to be able to encrypt certain information and use it as a product-key for my software. I only care that I am the only one who can generate these.
Encryption is used to achieve confidentiality. In the past RSA signature generation was often thought of as "encryption with the private key". However, the operations are quite different as explained above, and the later standards desperately try and separate encryption and signature generation.
I would like to include my public key in my software to decrypt/read the signature of the key. I do not care who can read the data in the key, I only care that I am the only verifiable one who can generate them.
Yes, this is called establishing trust in the public key. However, protecting your program code is very different from protecting messages. You can perform code signing but then you'd need something to check the signature outside of your code. There are operating systems that offer this.
There is Microsoft Authenticode for instance. Application stores like the iStore and Android app store may or may not use code signing, but they offer some reassurance that your application isn't cloned or at least not cloned within the store. Cryptography is not always the solution after all.
Keeping your code from being cloned / altered at all is much harder, and you'd be solidly in DRM territory if you go that way.
Is signing useful in this scenario?
Yes, absolutely. It can certainly help making sure that the messages were only signed by you, if there is trust in the public key. If it can be helpful for authenticating your application code / integrated public key depends entirely on the environment that you expect to run the code in.
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, @"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Correct me if i'm wrong, but json is just text seperated by ":", so just use
String line = ""; //stores the text to parse.
StringTokenizer st = new StringTokenizer(line, ":");
String input1 = st.nextToken();
keep using st.nextToken() until you're out of data. Make sure to use "st.hasNextToken()" so you don't get a null exception.
You can also change the port when starting up:
$ pg_ctl -o "-F -p 5433" start
Or
$ postgres -p 5433
More about this in the manual.
# I like using the codecs opening in a with
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
logger = csv.DictWriter(logfile, fieldnames=field_names)
logger.writeheader()
# some more code stuff
for video in aList:
video_result = {}
video_result['date'] = video['snippet']['publishedAt']
video_result['user'] = video['id']
video_result['text'] = video['snippet']['description'].encode('utf8')
logger.writerow(video_result)
Avoid on the same box using transform:--- and position:fixed. Element will stay in position:static if there is any transform.
Check out the "nohup" program.
When I'd like to view incoming connections from our application servers to the database I use the following command:
SELECT username FROM v$session
WHERE username IS NOT NULL
ORDER BY username ASC;
Simple, but effective.
There's no need to check for EOF in python, simply do:
with open('t.ini') as f:
for line in f:
# For Python3, use print(line)
print line
if 'str' in line:
break
It is good practice to use the
with
keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
TYPE variable = jsonbody["key"]?.Value<TYPE>() ?? DEFAULT_VALUE;
e.g.
bool attachMap = jsonbody["map"]?.Value<bool>() ?? false;
by @Brian Gardner:
Gradle is an extensive build tool and dependency manager for programming projects. It has a domain specific language based on Groovy. Gradle also provides build-by-convention support for many types of projects including Java, Android and Scala.
Feature of Gradle:
Ant is already installed on some older versions of Mac OS X, so you should run ant -version
to test if it is installed before attempting to install it.
If it is not already installed, then your best bet is to install Homebrew (brew install ant
) or MacPorts (sudo port install apache-ant
), and use those tools to install Apache Ant.
Alternatively, though I would highly advise using Homebrew or MacPorts instead, you can install Apache Ant manually. To do so, you would need to:
The commands that you would need, assuming apache-ant-1.8.1-bin.tar.gz
(replace 1.8.1 with the actual version) were still in your Downloads directory, would be the following (explanatory comments included):
cd ~/Downloads # Let's get into your downloads folder.
tar -xvzf apache-ant-1.8.1-bin.tar.gz # Extract the folder
sudo mkdir -p /usr/local # Ensure that /usr/local exists
sudo cp -rf apache-ant-1.8.1-bin /usr/local/apache-ant # Copy it into /usr/local
# Add the new version of Ant to current terminal session
export PATH=/usr/local/apache-ant/bin:"$PATH"
# Add the new version of Ant to future terminal sessions
echo 'export PATH=/usr/local/apache-ant/bin:"$PATH"' >> ~/.profile
# Verify new version of ant
ant -version
Also, we can assign the Value to the Control in Designer Class (i.e. FormName.Designer.cs).
DateTimePicker1.Value = DateTime.Now;
This way you always get Current Date...
To configure IIS to run 32-bit applications you must follow these steps:
Open IIS Go to current server – > Application Pools Select the application pool your 32-bit application will run under Click Advanced setting or Application Pool Default Set Enable 32-bit Applications to True
This solution worked for me, thanks.
With the dplyr
-package loaded use
bob=bob%>%mutate_at("phenotype", as.character)
if you only want to change the phenotype
-column specifically.
As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.
You should never need to modify the path directly, either through environment variables or sys.path
. Whether you use the os (ex. apt-get
), or pip
in a virtualenv, packages will be installed to a location already on the path.
In your example, GNU Radio is installed to the system Python 2's standard site-packages
location, which is already in the path. Pointing PyCharm at the correct interpreter is enough; if it isn't there is something else wrong that isn't apparent. It may be that /usr/bin/python
does not point to the same interpreter that GNU Radio was installed in; try pointing specifically at the python2.7
binary. Or, PyCharm used to be somewhat bad at detecting packages; File > Invalidate Caches > Invalidate and Restart
would tell it to rescan.
This answer will cover how you should set up a project environment, install packages in different scenarios, and configure PyCharm. I refer multiple times to the Python Packaging User Guide, written by the same group that maintains the official Python packaging tools.
The correct way to develop a Python application is with a virtualenv. Packages and version are installed without affecting the system or other projects. PyCharm has a built-in interface to create a virtualenv and install packages. Or you can create it from the command line and then point PyCharm at it.
$ cd MyProject
$ python2 -m virtualenv env
$ . env/bin/activate
$ pip install -U pip setuptools # get the latest versions
$ pip install flask # install other packages
In your PyCharm project, go to File > Settings > Project > Project Interpreter
. If you used virtualenvwrapper
or PyCharm to create the env, then it should show up in the menu. If not, click the gear, choose Add Local
, and locate the Python binary in the env. PyCharm will display all the packages in the selected env.
In some cases, such as with GNU Radio, there is no package to install with pip
, the package was installed system-wide when you install the rest of GNU Radio (ex. apt-get install gnuradio
). In this case, you should still use a virtualenv, but you'll need to make it aware of this system package.
$ python2 -m virtualenv --system-site-packages env
Unfortunately it looks a little messy, because all system packages will now appear in your env, but they are just links, you can still safely install or upgrade packages without affecting the system.
In some cases, you will have multiple local packages you're developing, and will want one project to use the other package. In this case you might think you have to add the local package to the other project's path, but this is not the case. You should install your package in development mode. All this requires is adding a setup.py
file to your package, which will be required anyway to properly distribute and deploy the package later.
Minimal setup.py
for your first project:
from setuptools import setup, find_packages
setup(
name='mypackage',
version='0.1',
packages=find_packages(),
)
Then install it in your second project's env:
$ pip install -e /path/to/first/project
Raj_89 solution is the closest to being valid option altough as mentioned by Kevin Swarts in comment it is going to break IE, which for large number of corporate client is an issue (and telling your client that you won't code for IE "because reasons" is unlikely to make your boss happy ;) ).
So I played around with it and here is the problem: the 'onmousedown' event is throwing a fit in IE, so what we want to do, is to prevent default when user clicks the dropdown for the first time. It is important this is only time we do this: if we prevent defult on the next click, when user makes his pick, the onchange event won't fire.
This way we get nice dropdown, no flicker, no breaking down IE - just works... well at least in IE10 and up, and latest relases of all the other major browsers.
<p>Which is the most annoing browser of them all:</p>
<select id="sel" size = "1">
<option></option>
<option>IE 9</option>
<option>IE 10</option>
<option>Edge</option>
<option>Firefox</option>
<option>Chrome</option>
<option>Opera</option>
</select>
Here is the fiddle: https://jsfiddle.net/88cxzhom/27/
Few more things to notice: 1) The absolute positioning and setting z-index is helpful to avoid moving other elements when the options are displayed. 2) Use 'currentTarget' property - this will be the select element across all browsers. While 'target' will be select in IE, the rest will actually allow you to work with option.
Hope this helps someone.
See this answer on SO.
There is another solution that you can use to suppress the formatting of specific block comments. Use /*-
(note the hyphen) at the beginning of the block comment, and the formatting won't be affected if you format the rest of the file.
/*-
* Here is a block comment with some very special
* formatting that I want indent(1) to ignore.
*
* one
* two
* three
*/
Source: Documentation at Oracle.
As a workaround, go to sdk installation directory and perform the following steps:
system-images/android-19/default
system-images/android-19/
The directory structure should look like this:
And it should work!
This worked for me:
curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/
I could see the value in backend using
print request.cookies
gitweb will allow you to browse through the code (and changes) via a browser.
http://git.or.cz/gitwiki/Gitweb
(Don't know if someone has already setup a public gitweb for Android, but it's probably not too hard.)
click on the notification present on bottom of the task bar if you receiving the error like port in use then select the iiss icon right click then click on exit ,it work like charm for me
Copy paste this for bright pastel rainbow colors
int R = (int)(Math.random()*256);
int G = (int)(Math.random()*256);
int B= (int)(Math.random()*256);
Color color = new Color(R, G, B); //random color, but can be bright or dull
//to get rainbow, pastel colors
Random random = new Random();
final float hue = random.nextFloat();
final float saturation = 0.9f;//1.0 for brilliant, 0.0 for dull
final float luminance = 1.0f; //1.0 for brighter, 0.0 for black
color = Color.getHSBColor(hue, saturation, luminance);
From the javascript I tried from several ways and I could not.
You need an server side solution, for example on c# I did create an controller that call to the http, en deserialize the object, and the result is that when I call from javascript, I'm doing an request from my https://domain to my htpps://domain. Please see my c# code:
[Authorize]
public class CurrencyServicesController : Controller
{
HttpClient client;
//GET: CurrencyServices/Consultar?url=valores?moedas=USD&alt=json
public async Task<dynamic> Consultar(string url)
{
client = new HttpClient();
client.BaseAddress = new Uri("http://api.promasters.net.br/cotacao/v1/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
System.Net.Http.HttpResponseMessage response = client.GetAsync(url).Result;
var FromURL = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject(FromURL);
}
And let me show to you my client side (Javascript)
<script async>
$(document).ready(function (data) {
var TheUrl = '@Url.Action("Consultar", "CurrencyServices")?url=valores';
$.getJSON(TheUrl)
.done(function (data) {
$('#DolarQuotation').html(
'$ ' + data.valores.USD.valor.toFixed(2) + ','
);
$('#EuroQuotation').html(
'€ ' + data.valores.EUR.valor.toFixed(2) + ','
);
$('#ARGPesoQuotation').html(
'Ar$ ' + data.valores.ARS.valor.toFixed(2) + ''
);
});
});
I wish that this help you! Greetings
You need to distinguish between a language and an implementation. Python is a language,
According to Wikipedia, "A programming language is a notation for writing programs, which are specifications of a computation or algorithm". This means that it's simply the rules and syntax for writing code. Separately we have a programming language implementation which in most cases, is the actual interpreter or compiler.
Python is a language. CPython is the implementation of Python in C. Jython is the implementation in Java, and so on.
To sum up: You are already using CPython (if you downloaded from here).
The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.
In Ruby, the condition and the then
part of an if
expression must be separated by either an expression separator (i.e. ;
or a newline) or the then
keyword.
So, all of these would work:
if @item.rigged then 'Yes' else 'No' end
if @item.rigged; 'Yes' else 'No' end
if @item.rigged
'Yes' else 'No' end
There is also a conditional operator in Ruby, but that is completely unnecessary. The conditional operator is needed in C, because it is an operator: in C, if
is a statement and thus cannot return a value, so if you want to return a value, you need to use something which can return a value. And the only things in C that can return a value are functions and operators, and since it is impossible to make if
a function in C, you need an operator.
In Ruby, however, if
is an expression. In fact, everything is an expression in Ruby, so it already can return a value. There is no need for the conditional operator to even exist, let alone use it.
BTW: it is customary to name methods which are used to ask a question with a question mark at the end, like this:
@item.rigged?
This shows another problem with using the conditional operator in Ruby:
@item.rigged? ? 'Yes' : 'No'
It's simply hard to read with the multiple question marks that close to each other.
Delete
/.idea/libraries
Then sync gradle to build project.
Use white-space:nowrap
and overflow:hidden
You can try this way
javac --release 8 yourClass.java
Three related packages for covering this issue with many advanced options are:
It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.
You should actually just return false
in the onclick
event, like so:
<a href="#" onclick="return false;">hello</a>
Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false
.
To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.
<a href="backup_page_displaying_image.aspx"
onclick="return coolImageDisplayFunction();">hello</a>
Here's a quick sample using the DecimalFormat
class mentioned by Nick.
float f = 12.345f;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));
The output of the print statement will be 12.35. Notice that it will round it for you.
If you're using eclipse you can open default.properties
file in your workspace and change the project target to the new sdk (target=android-8
for 2.2). I accidentally selected the 1.5 sdk for my version and didn't catch it until much later, but updating that and restarting eclipse seemed to have done the trick.
You need to download their source from the github. Find the main file and then include it in your main file.
An example of this can be found here > How to manually install a node.js module?
Usually you need to find the source and go through the package.json file. There you can find which is the main file. So that you can include that in your application.
To include example.js in your app. Copy it in your application folder and append this on the top of your main js file.
var moduleName = require("path/to/example.js")
It's also useful for splitting ranges; range(a,b)
can be split into range(a, x)
and range(x, b)
, whereas with inclusive range you would write either x-1
or x+1
. While you rarely need to split ranges, you do tend to split lists quite often, which is one of the reasons slicing a list l[a:b]
includes the a-th element but not the b-th. Then range
having the same property makes it nicely consistent.
body{
height: 100%;
overflow: hidden !important;
width: 100%;
position: fixed;
works on iOS9
You will need to link to the file relative to the file that includes eventManager.php
(Page A)
Change your code from
require_once('../includes/dbconn.inc');
To
require_once('../mysite/php/includes/dbconn.inc');
In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of
. Take this examples:
'use strict';_x000D_
_x000D_
var arr = ['one', 'two', undefined, 3, 4],_x000D_
output;_x000D_
_x000D_
arr[6] = 'five';_x000D_
_x000D_
output = '';_x000D_
arr.forEach(function (val) {_x000D_
output += val + ' ';_x000D_
});_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
output += arr[i] + ' ';_x000D_
}_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var val of arr) {_x000D_
output += val + ' ';_x000D_
};_x000D_
console.log(output);
_x000D_
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->_x000D_
<script src="//gh-canon.github.io/stack-snippet-console/console.min.js"></script>
_x000D_
All array methods which you can use to iterate safely over dense arrays use the length
property of an object created by calling ToObject
internaly. See for instance the algorithm used in the forEach
method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18
However in es6, you can use for...of
safely for iterating over sparse arrays.
See also Are Javascript arrays sparse?.
Why don't you use cURL
?
$yourkey="your api key";
$url="https://prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=$yourkey";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$auth = curl_exec($curl);
if($auth)
{
$json = json_decode($auth);
print_r($json);
}
}
There are already many good answers, but if your entire file is on a single line and you still want to process "rows" (as opposed to fixed-size blocks), these answers will not help you.
99% of the time, it is possible to process files line by line. Then, as suggested in this answer, you can to use the file object itself as lazy generator:
with open('big.csv') as f:
for line in f:
process(line)
However, I once ran into a very very big (almost) single line file, where the row separator was in fact not '\n'
but '|'
.
'|'
to '\n'
before processing was also out of the question, because some of the fields of this csv contained '\n'
(free text user input).For these kind of situations, I created the following snippet:
def rows(f, chunksize=1024, sep='|'):
"""
Read a file where the row separator is '|' lazily.
Usage:
>>> with open('big.csv') as f:
>>> for r in rows(f):
>>> process(row)
"""
curr_row = ''
while True:
chunk = f.read(chunksize)
if chunk == '': # End of file
yield curr_row
break
while True:
i = chunk.find(sep)
if i == -1:
break
yield curr_row + chunk[:i]
curr_row = ''
chunk = chunk[i+1:]
curr_row += chunk
I was able to use it successfully to solve my problem. It has been extensively tested, with various chunk sizes.
Test suite, for those who want to convince themselves.
test_file = 'test_file'
def cleanup(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
os.unlink(test_file)
return wrapper
@cleanup
def test_empty(chunksize=1024):
with open(test_file, 'w') as f:
f.write('')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 1
@cleanup
def test_1_char_2_rows(chunksize=1024):
with open(test_file, 'w') as f:
f.write('|')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 2
@cleanup
def test_1_char(chunksize=1024):
with open(test_file, 'w') as f:
f.write('a')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 1
@cleanup
def test_1025_chars_1_row(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1025):
f.write('a')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 1
@cleanup
def test_1024_chars_2_rows(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1023):
f.write('a')
f.write('|')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 2
@cleanup
def test_1025_chars_1026_rows(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1025):
f.write('|')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 1026
@cleanup
def test_2048_chars_2_rows(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1022):
f.write('a')
f.write('|')
f.write('a')
# -- end of 1st chunk --
for i in range(1024):
f.write('a')
# -- end of 2nd chunk
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 2
@cleanup
def test_2049_chars_2_rows(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1022):
f.write('a')
f.write('|')
f.write('a')
# -- end of 1st chunk --
for i in range(1024):
f.write('a')
# -- end of 2nd chunk
f.write('a')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 2
if __name__ == '__main__':
for chunksize in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]:
test_empty(chunksize)
test_1_char_2_rows(chunksize)
test_1_char(chunksize)
test_1025_chars_1_row(chunksize)
test_1024_chars_2_rows(chunksize)
test_1025_chars_1026_rows(chunksize)
test_2048_chars_2_rows(chunksize)
test_2049_chars_2_rows(chunksize)