To continue the Promise.all
loop (even when a Promise rejects) I wrote a utility function which is called executeAllPromises
. This utility function returns an object with results
and errors
.
The idea is that all Promises you pass to executeAllPromises
will be wrapped into a new Promise which will always resolve. The new Promise resolves with an array which has 2 spots. The first spot holds the resolving value (if any) and the second spot keeps the error (if the wrapped Promise rejects).
As a final step the executeAllPromises
accumulates all values of the wrapped promises and returns the final object with an array for results
and an array for errors
.
Here is the code:
function executeAllPromises(promises) {_x000D_
// Wrap all Promises in a Promise that will always "resolve"_x000D_
var resolvingPromises = promises.map(function(promise) {_x000D_
return new Promise(function(resolve) {_x000D_
var payload = new Array(2);_x000D_
promise.then(function(result) {_x000D_
payload[0] = result;_x000D_
})_x000D_
.catch(function(error) {_x000D_
payload[1] = error;_x000D_
})_x000D_
.then(function() {_x000D_
/* _x000D_
* The wrapped Promise returns an array:_x000D_
* The first position in the array holds the result (if any)_x000D_
* The second position in the array holds the error (if any)_x000D_
*/_x000D_
resolve(payload);_x000D_
});_x000D_
});_x000D_
});_x000D_
_x000D_
var errors = [];_x000D_
var results = [];_x000D_
_x000D_
// Execute all wrapped Promises_x000D_
return Promise.all(resolvingPromises)_x000D_
.then(function(items) {_x000D_
items.forEach(function(payload) {_x000D_
if (payload[1]) {_x000D_
errors.push(payload[1]);_x000D_
} else {_x000D_
results.push(payload[0]);_x000D_
}_x000D_
});_x000D_
_x000D_
return {_x000D_
errors: errors,_x000D_
results: results_x000D_
};_x000D_
});_x000D_
}_x000D_
_x000D_
var myPromises = [_x000D_
Promise.resolve(1),_x000D_
Promise.resolve(2),_x000D_
Promise.reject(new Error('3')),_x000D_
Promise.resolve(4),_x000D_
Promise.reject(new Error('5'))_x000D_
];_x000D_
_x000D_
executeAllPromises(myPromises).then(function(items) {_x000D_
// Result_x000D_
var errors = items.errors.map(function(error) {_x000D_
return error.message_x000D_
}).join(',');_x000D_
var results = items.results.join(',');_x000D_
_x000D_
console.log(`Executed all ${myPromises.length} Promises:`);_x000D_
console.log(`— ${items.results.length} Promises were successful: ${results}`);_x000D_
console.log(`— ${items.errors.length} Promises failed: ${errors}`);_x000D_
});
_x000D_
Using execComand:
<input type="button" name="save" value="Save" onclick="javascript:document.execCommand('SaveAs','true','your_file.txt')">
In the next link: execCommand
You can refer in this line - Difference between ASP.NET Core (.NET Core) and ASP.NET Core (.NET Framework)
Xamarin is not a debate at all. When you want to build mobile (iOS, Android, and Windows Mobile) apps using C#, Xamarin is your only choice.
The .NET Framework supports Windows and Web applications. Today, you can use Windows Forms, WPF, and UWP to build Windows applications in .NET Framework. ASP.NET MVC is used to build Web applications in .NET Framework.
.NET Core is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux. .NET Core supports UWP and ASP.NET Core only. UWP is used to build Windows 10 targets Windows and mobile applications. ASP.NET Core is used to build browser based web applications.
you want more details refer this links
https://blogs.msdn.microsoft.com/dotnet/2016/07/15/net-core-roadmap/
https://docs.microsoft.com/en-us/dotnet/articles/standard/choosing-core-framework-server
Insead of calling sed with sed
, I do ./bin/sed
And this is the wrapper script in my ~/project/bin/sed
#!/bin/bash
if [[ "$OSTYPE" == "darwin"* ]]; then
exec "gsed" "$@"
else
exec "sed" "$@"
fi
Don't forget to chmod 755
the wrapper script.
add the onclick attribute
<div onclick="myFunction( event );"><span>shanghai</span><span>male</span></div>
To get the cursor to change use css's cursor rule.
div[onclick] {
cursor: pointer;
}
The selector uses an attribute selector which does not work in some versions of IE. If you want to support those versions, add a class to your div.
I found that doing it in two relatively simple steps seemed to work quite well. The first css definition for ul sets the base indent that you want for the list as a whole. The second definition sets the indent value for each nested list item within it. In my case they are the same, but you can obviously pick whatever you want.
ul {
margin-left: 1.5em;
}
ul > ul {
margin-left: 1.5em;
}
You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:
date.split(/[.,\/ -]/)
Although dashes have special meaning in character classes as a range specifier (ie [a-z]
means the same as [abcdefghijklmnopqrstuvwxyz]
), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.
To explain why your pattern didn't work, /-./
tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".
Mount the certs onto the Docker container using -v
:
docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"
Just change fixed-top
with sticky-top
. this way you won't have to calculate the padding.
And it works!!
I believe that we are overthinking this,
function mouse_position(e)_x000D_
{_x000D_
//do stuff_x000D_
}
_x000D_
<body onmousemove="mouse_position(event)"></body>
_x000D_
Try:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit - had a brain freeze there, position() is more straightforward!
python --version
Python 3.7.5
cd
into /usr/lib/python3/dist-packages
and check the apt_pkg.*
files. You will find that there is none for your default Python version:ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so
# Pygame Example
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('IBM Emulator')
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)
textRectObj = textSurfaceObj.get_rect()
textRectObj = (10, 10)
try:
while True: # main loop
DISPLAYSURF.fill(BLACK)
DISPLAYSURF.blit(textSurfaceObj, textRectObj)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
except SystemExit:
pass
UIButton responds to addTarget:action:forControlEvents: since it inherits from UIControl. But it does not respond to addTarget:action:withObject:forControlEvents:
see reference for the method and for UIButton
You could extend UIButton with a category to implement that method, thought.
<input type='text' minlength=3 /><br />
if browser supports html5,
it will automatical be validate attributes(minlength) in tag
but Safari(iOS) doesn't working
pip3 install --trusted-host pypi.org --trusted-host files.pythonhosted.org <app>
Try the following:
SELECT *
FROM
(SELECT FIELDA,
FIELDB,
FIELDC,
ROW_NUMBER() OVER (ORDER BY FIELDC) R
FROM TABLE_NAME
WHERE FIELDA = 10
)
WHERE R >= 10
AND R <= 15;
via [tecnicume]
Issue: Tomcat (7.0.88) is throwing below exception which leads to 400 – Bad Request.
java.lang.IllegalArgumentException: Invalid character found in the request target.
The valid characters are defined in RFC 7230 and RFC 3986.
This issue is occurring most of the tomcat versions from 7.0.88 onwards.
Solution: (Suggested by Apache team):
Tomcat increased their security and no longer allows raw square brackets in the query string. In the request we have [,] (Square brackets) so the request is not processed by the server.
Add relaxedQueryChars
attribute under tag under server.xml (%TOMCAT_HOME%/conf):
<Connector port="80"
protocol="HTTP/1.1"
maxThreads="150"
connectionTimeout="20000"
redirectPort="443"
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml"
relaxedQueryChars="[,]"
/>
If application needs more special characters that are not supported by tomcat by default, then add those special characters in relaxedQueryChars
attribute, comma-separated as above.
There is no built in function with this capability. The close would be to save the file in a folder named for the current date and use the =INFO("directory") function.
The following will allow you to get at both the key and value at the same time.
foreach ($arr as $key => $value)
{
echo($key);
}
Another way to do this without jQuery would be to use Greensock's TweenLite JS library.
Demo http://codepen.io/anon/pen/yNWwEJ
var display = document.getElementById("display");
var number = {param:0};
var duration = 1;
function count() {
TweenLite.to(number, duration, {param:"+=20", roundProps:"param",
onUpdate:update, onComplete:complete, ease:Linear.easeNone});
}
function update() {
display.innerHTML = number.param;
}
function complete() {
//alert("Complete");
}
count();
As you want to exclude both words, you need a conjuction:
^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$
Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.
Here is another method to get date
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
I made it work with this:
.element {
transition: height 3s ease-out, width 5s ease-in;
}
...\Program Files\Microsoft SQL Server\MSSQL 1.0\MSSQL\Backup
More info
To find a compiler, you'll have 1 per .net version installed, type in a command prompt.
dir c:\Windows\Microsoft.NET\vbc.exe /a/s
Windows Forms
For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).
Compile line in a command prompt.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"
Text for VBS2EXE.vb
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
End With
sc.addcode(Scrpt)
End Sub
End Class
Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.
/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.
/win32manifest: The provided file is embedded in the manifest section of the output PE.
In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.
The command line
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"
The manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0"
processorArchitecture="*" name="VBS2EXE" type="win32" />
<description>Script to Exe</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security> <requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"
uiAccess="false" /> </requestedPrivileges>
</security> </trustInfo> </assembly>
Hopefully it will now ONLY run as admin.
Give Access To a Host's Objects
Here's an example giving the vbscript access to a .NET object.
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state"
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With
sc.addcode(Scrpt)
End Sub
End Class
To Embed version info
Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.
Download ResHacker from http://www.angusj.com/resourcehacker
Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.
Type
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"
if you get this error "Value does not fall within the expected range" in this line:
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
use instead this to fix the error:
SPFolder myLibrary = oWeb.GetList(URL OR NAME).RootFolder;
Use always URl to get Lists or others because they are unique, names are not the best way ;)
Assign something to your strings. This will definitely help.
Most JVMs will kick off a GC (depending on the -XX:DiableExplicitGC and -XX:+ExplicitGCInvokesConcurrent switch). But the specification is just less well defined in order to allow better implementations later on.
The spec needs clarification: Bug #6668279: (spec) System.gc() should indicate that we don't recommend use and don't guarantee behaviour
Internally the gc method is used by RMI and NIO, and they require synchronous execution, which: this is currently in discussion:
Bug #5025281: Allow System.gc() to trigger concurrent (not stop-the-world) full collections
The easiest solution is to simply tell Xcode to compile everything as Objective C++.
Set your project or target settings for Compile Sources As to Objective C++ and recompile.
Then you can use C++ or Objective C everywhere, for example:
void CPPObject::Function( ObjectiveCObject* context, NSView* view )
{
[context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)view.layer]
}
This has the same affect as renaming all your source files from .cpp or .m to .mm.
There are two minor downsides to this: clang cannot analyse C++ source code; some relatively weird C code does not compile under C++.
For Windows Server 2016
Server Manager
formManage
-> Add Roles and Features
Features
pageWCF Services
feature with all subfeaturesNext
and Install
I had a similar issue and was able to resolve it by identifying which JDBC driver I intended to use. In my case, I was connecting to an Oracle database. I placed the following statement, prior to creating the connection variable.
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());
Use
System.getProperty("java.class.path")
see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
You can also split it into it's elements easily
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
Create an array of size 100. If you need the List interface, then call Arrays.asList on it. It'll return a fixed-size list backed by the array.
Collections.singletonList(object)
the list created by this method is immutable.
You might want to check you spaces and tabs. A tab is a default of 4 spaces. However, your "if" and "elif" match, so I am not quite sure why. Go into Options in the top bar, and click "Configure IDLE". Check the Indentation Width on the right in Fonts/Tabs, and make sure your indents have that many spaces.
The reason why you don't see such practice is quite subjective and cannot have a definite answer, because I have seen many of the code which uses your mentioned way rather than iterator
style code.
Following can be reasons of people not considering vector.size()
way of looping:
size()
every time in the loop
condition. However either it's a non-issue or it can be trivially
fixedstd::for_each()
over the for
loop itselfstd::vector
to other one (e.g.
map
, list
) will also demand the change of the looping mechanism,
because not every container support size()
style of loopingC++11 provides a good facility to move through the containers. That is called "range based for loop" (or "enhanced for loop" in Java).
With little code you can traverse through the full (mandatory!) std::vector
:
vector<int> vi;
...
for(int i : vi)
cout << "i = " << i << endl;
Performing a lock: Quite cheap (still more expensive than a null test).
Performing a lock when another thread has it: You get the cost of whatever they've still to do while locking, added to your own time.
Performing a lock when another thread has it, and dozens of other threads are also waiting on it: Crippling.
For performance reasons, you always want to have locks that another thread wants, for the shortest period of time at all possible.
Of course it's easier to reason about "broad" locks than narrow, so it's worth starting with them broad and optimising as needed, but there are some cases that we learn from experience and familiarity where a narrower fits the pattern.
(Incidentally, if you can possibly just use private static volatile Singleton instance = new Singleton()
or if you can possibly just not use singletons but use a static class instead, both are better in regards to these concerns).
Create below class in base class. Class To get all controls:
public static class ControlExtensions
{
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
}
From Database: Get All Actions IDs (like divAction1,divAction2 ....) dynamic in DATASET (DTActions) allow on specific User.
In Aspx: in HTML Put Action(button,anchor etc) in div or span and give them id like
<div id="divAction1" visible="false" runat="server" clientidmode="Static">
<a id="anchorAction" runat="server">Submit
</a>
</div>
IN CS: Use this function on your page:
private void ShowHideActions()
{
var controls = Page.GetAllControlsOfType<HtmlGenericControl>();
foreach (DataRow dr in DTActions.Rows)
{
foreach (Control cont in controls)
{
if (cont.ClientID == "divAction" + dr["ActionID"].ToString())
{
cont.Visible = true;
}
}
}
}
pyspark.sql.Column.contains()
is only available in pyspark version 2.2 and above.
df.where(df.location.contains('google.com'))
There are many places where someone might want to deploy this kind of scenario, but due to the way integrated authentication works, it is not possible.
As gbn mentioned, integrated authentication uses a special token that corresponds to your Windows identity. There are coding practices called "impersonation" (probably used by the Run As... command) that allow you to effectively perform an activity as another Windows user, but there is not really a way to arbitrarily act as a different user (à la Linux) in Windows applications aside from that.
If you really need to administer multiple servers across several domains, you might consider one of the following:
Hopefully this helps!
Log location:
${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log
Get log as a text and save to workspace:
cat ${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log >> log.txt
Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.
In jQuery:
$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })
In plain vanilla javaScript (from w3c):
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
//xmlhttp.data and shtuff
// ...our code here...
}
else
{
alert("Problem retrieving data");
}
}
}
the easiest way I found is
for i in `ls`; do echo "`pwd`/$i"; done
it works well for me
Here:
window.onload = function start() {
slide();
}
function slide() {
var num = 0;
for (num=0;num==10;) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
That makes it keep looping alright! That's why it isn't runnable here.
Here's the beginnings of a parser class to get you started. This ended up being my solution to a similar problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace XML
{
public class Parser
{
private string _FilePath = string.Empty;
private XDocument _XML_Doc = null;
public Parser(string filePath)
{
_FilePath = filePath;
_XML_Doc = XDocument.Load(_FilePath);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
/// </summary>
/// <param name="attributeName"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string attributeName, string newValue)
{
ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
{
ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) and value (oldValue)
/// with the specified new value (newValue) in elements with a given name (elementName).
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
{
ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues),
/// with the specified new value (newValue) in elements with a given name (elementName).
/// If oldValues is empty then oldValues will be ignored.
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="oldValues"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
{
List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();
foreach (XElement element in elements)
{
if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
{
if (element.Attribute(attributeName) != null)
{
if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
{ element.Attribute(attributeName).Value = newValue; }
}
}
}
}
public void SaveChangesToFile()
{
_XML_Doc.Save(_FilePath);
}
}
}
There are different types of shells. The SSH command execution shell is a non-interactive shell, whereas your normal shell is either a login shell or an interactive shell. Description follows, from man bash:
A login shell is one whose first character of argument zero is a -, or one started with the --login option. An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state. The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports an error. Tildes are expanded in file names as described below under Tilde Expansion in the EXPANSION section. When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behav ior. When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists. When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc. When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed: if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi but the value of the PATH variable is not used to search for the file name.
I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9):
Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges:
SET GLOBAL general_log = 'ON';
In a terminal, tail your log file. Mine was here:
>sudo tail -f /usr/local/mysql/data/myMacComputerName.log
You can search for your mysql files with this terminal command:
>ps auxww|grep [m]ysqld
I found that PDO escapes everything, so you can't write
$dynamicField = 'userName';
$sql = "SELECT * FROM `example` WHERE `:field` = :value";
$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field', $dynamicField);
$this->statement->bindValue(':value', 'mick');
$this->statement->execute();
Because it creates:
SELECT * FROM `example` WHERE `'userName'` = 'mick' ;
Which did not create an error, just an empty result. Instead I needed to use
$sql = "SELECT * FROM `example` WHERE `$dynamicField` = :value";
to get
SELECT * FROM `example` WHERE `userName` = 'mick' ;
When you are done execute:
SET GLOBAL general_log = 'OFF';
or else your logs will get huge.
As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.
ALTER TABLE your_table_with_fk
drop FOREIGN KEY name_of_your_fk_from_show_create_table_command_result,
drop KEY the_same_name_as_above
#kinda like the one above but better :P
from __future__ import print_function
from time import sleep
for i in range(101):
str1="Downloading File FooFile.txt [{}%]".format(i)
back="\b"*len(str1)
print(str1, end="")
sleep(0.1)
print(back, end="")
Sounds like you really want a Dictionary<int, string>
or possibly a switch
statement...
You can do it with the conditional operator though:
userType = user.Type == 0 ? "Admin"
: user.Type == 1 ? "User"
: user.Type == 2 ? "Employee"
: "The default you didn't specify";
While you could put that in one line, I'd strongly urge you not to.
I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.
If you are trying to export display using su and it still doesn't work. This is what worked for me. Try X11 forwarding for sudo users.
Connect the remote host using the -X option with ssh.
# ssh -X root@remote-host
Now list the coockie set for the current user.
# xauth list $DISPLAY
node01.thegeekdiary.com/unix:10 MIT-MAGIC-COOKIE-1 dacbc5765ec54a1d7115a172147866aa
# echo $DSIPLAY
localhost:10.0
Switch to another user account using sudo. Add the cookie from the command output above to the sudo user.
# sudo su - [user]
# xauth add node01.thegeekdiary.com/unix:10 MIT-MAGIC-COOKIE-1 dacbc5765ec54a1d7115a172147866aa
Export the display from step 2 again for the sudo user. Try the command xclock to verify if the x client applications are working as expected.
# export DISPLAY=localhost:10.0
The underscore is put there by the compiler and used by the linker. The basic path is:
main.c
test.h ---> [compiler] ---> main.o --+
|
test.c ---> [compiler] ---> test.o --+--> [linker] ---> main.exe
So, your main program should include the header file for the test module which should consist only of declarations, such as the function prototype:
void test(void);
This lets the compiler know that it exists when main.c is being compiled but the actual code is in test.c, then test.o.
It's the linking phase that joins together the two modules.
By including test.c into main.c, you're defining the test() function in main.o. Presumably, you're then linking main.o and test.o, both of which contain the function test().
use Date.prototype.toLocaleTimeString()
as documented here
please note the locale example en-US in the url.
Or use this for an English (or mix it up for custom) format:
StringFormat='{}{0:dd/MM/yyyy}'
Array.prototype.getIndex = function (obj) {
for (var i = 0; i < this.length; i++) {
if (this[i][Id] == obj.Id) {
return i;
}
}
return -1;
}
List.getIndex(obj);
You can use the ternary operator easily:
{{ $usersType ? $usersType : '' }}
Or if you dont know the url, you can use
hadoop fs -rm -r -f /user/the/path/to/your/dir
You need to Enable security and set the security realm on the Configure Global Security page (see: Standard Security Setup) and choose the appropriate Authorization method (Security Realm).
Depending on your selection, create the user using appropriate method. Recommended method is to select Jenkins’ own user database and tick Allow users to sign up, hit Save button, then you should be able to create user from the Jenkins interface. Otherwise if you've chosen external database, you need to create the user there (e.g. if it's Unix database, use credentials of existing Linux/Unix users or create a standard user using shell interface).
See also: Creating user in Jenkins via API
Anyone tried this approach?
Doing a dir /s vs_ultimate.exe
from the root prompt will find it. Mine was in <C:\ProgramData\Package Cache\{[guid]}>
.
Once I navigated there and ran vs_community_ENU.exe /uninstall /force
it uninstalled all the Visual Studio assets I believe.
Got the advice from this post.
Edit your Catlina.bat so that your -Xmx settings are less than your physical memory
x[r,]
where r is the row you're interested in. Try this, for example:
#Add your data
x <- structure(list(A = c(5, 3.5, 3.25, 4.25, 1.5 ),
B = c(4.25, 4, 4, 4.5, 4.5 ),
C = c(4.5, 2.5, 4, 2.25, 3 )
),
.Names = c("A", "B", "C"),
class = "data.frame",
row.names = c(NA, -5L)
)
#The vector your result should match
y<-c(A=5, B=4.25, C=4.5)
#Test that the items in the row match the vector you wanted
x[1,]==y
This page (from this useful site) has good information on indexing like this.
While you declare the model at the top of the view using code like this:
@model MyModel
you need to capitalise your references to it below, for example:
@Html.Encode(Model.MyDisplayValue)
I believe a missing web.config in the Views folder would be the major cause of this, but if that is fixed and the problem still persists, check that you are using Model, not model to refer to it in the source.
if you get the values in int you have to use string for that it is throwing the error
before
holder.villageName.setText(villageModelList.get(position).getVillageName());
holder.villageCount.setText(villageModelList.get(position).getPeopleCount());
holder.peopleCount.setText(villageModelList.get(position).getPeopleCount());
after
holder.villageName.setText(villageModelList.get(position).getVillageName());
holder.villageCount.setText(String.valueOf(villageModelList.get(position).getPeopleCount()));
holder.peopleCount.setText(String.valueOf(villageModelList.get(position).getPeopleCount()));
you can solve the error by adding the String.valueOf
It is same as above answers, but is simple in steps
c:\SRC\folder1
c:\SRC\folder2
c:\SRC\folder3
c:\SRC\folder4
to copy all above folders to c:\DST\ except folder1 and folder2.
Step1: create a file c:\list.txt with below content, one folder name per one line
folder1\
folder2\
Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt
64/32 bit error? I found this as a problem as my dev machine was 32bit and the production server 64bit. If so, you may need to call the 32bit runtime directly from the command line.
This link says it better (No 64bit JET driver): http://social.msdn.microsoft.com/forums/en-US/sqlintegrationservices/thread/da076e51-8149-4948-add1-6192d8966ead/
You should use TryParse
- Parse
throws an exception if the string is not a valid number - e.g. if you want to test for a valid integer:
int v;
if (Int32.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
If you want to test for a valid floating-point number:
double v;
if (Double.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
Note also that Double.TryParse
has an overloaded version with extra parameters specifying various rules and options controlling the parsing process - e.g. localization ('.' or ',') - see http://msdn.microsoft.com/en-us/library/3s27fasw.aspx.
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
You could also use a StringVar
variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
If you are in home page ("/Home/Index") and you would like to call Index action of Admin controller, following would work for you.
<li><a href="/Admin/Index">Admin</a></li>
Try this:
export PATH=/home/your_username/anaconda3/bin:$PATH
in ~/.bashrc
Then source ~/.bashrc
This works for me for the same problem.
The code marked as the solution did not work for me. This was my solution.
/*
* http://www.java2s.com/Code/Java/Security/EncryptingaStringwithDES.htm
* https://stackoverflow.com/questions/23561104/how-to-encrypt-and-decrypt-string-with-my-passphrase-in-java-pc-not-mobile-plat
*/
package encryptiondemo;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
*
* @author zchumager
*/
public class EncryptionDemo {
Cipher ecipher;
Cipher dcipher;
EncryptionDemo(SecretKey key) throws Exception {
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
public String encrypt(String str) throws Exception {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws Exception {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
}
public static void main(String args []) throws Exception
{
String data = "Don't tell anybody!";
String k = "Bar12345Bar12345";
//SecretKey key = KeyGenerator.getInstance("AES").generateKey();
SecretKey key = new SecretKeySpec(k.getBytes(), "AES");
EncryptionDemo encrypter = new EncryptionDemo(key);
System.out.println("Original String: " + data);
String encrypted = encrypter.encrypt(data);
System.out.println("Encrypted String: " + encrypted);
String decrypted = encrypter.decrypt(encrypted);
System.out.println("Decrypted String: " + decrypted);
}
}
Use btoa()
for encode and atob()
for decode
text_val:any="your encoding text";
Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0
Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text
You can delete
one of your layout files
(does not matter which one), after that you need to build project
. Project will build and after that you need to return your layout file by CTRL + Z. In my case, if I tried to build my project before deleting of layout file
, it did not help me. But this way is ok.
I know this post is little bit old but here is a potential solution for anyone who has the same problem:
First, I would change the CSS display for #popup to "none" instead of "hidden".
Second, I would change the HTML as follow:
<div id="overlay-back"></div>
<div id="popup">
<div style="position: relative;">
<img class="close-image" src="images/closebtn.png" />
<span><img src="images/load_sign.png" width="400" height="566" /></span>
</div>
</div>
And for Style as follow:
.close-image
{
display: block;
float: right;
cursor: pointer;
z-index: 3;
position: absolute;
right: 0;
top: 0;
}
I got this idea from this website (kessitek.com). A very good example on how to position elements,:
How to position a div on top of another div
I hope this helps,
Zag,
The author of this post (now deleted post) suggests checking your C:\Windows\System32
folder to make sure that the oci.dll
exists there. Copying in the file from the Oracle home directory solved this problem for me.
I created this class to keep the centered regardless of screen size while maintaining responsive features:
.container {
alignment-adjust: central;
}
You're passing the result of somedict.keys()
to the function. In Python 3, dict.keys
doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.
To fix the problem, use list(somedict.keys())
to collect the keys, and work with that.
For a project structure like
project_name/src/main/java/Main_File.class
in the file build.gradle
, add the following line
mainClassName = 'Main_File'
The Enter key should have the keycode 13. Is it not working?
To find the version of the subversion REPOSITORY you can:
If not displayed, view source of the page
<svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/">
Now for the subversion CLIENT:
svn --version
will suffice
In general, this happens when you insert strings to columns with incompatible encoding/collation.
I got this error when I had TRIGGERs, which inherit server's collation for some reason.
And mysql's default is (at least on Ubuntu) latin-1 with swedish collation.
Even though I had database and all tables set to UTF-8, I had yet to set my.cnf
:
/etc/mysql/my.cnf :
[mysqld]
character-set-server=utf8
default-character-set=utf8
And this must list all triggers with utf8-*:
select TRIGGER_SCHEMA, TRIGGER_NAME, CHARACTER_SET_CLIENT, COLLATION_CONNECTION, DATABASE_COLLATION from information_schema.TRIGGERS
And some of variables listed by this should also have utf-8-* (no latin-1 or other encoding):
show variables like 'char%';
Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/
Use
document.getElementById("select_id").selectedIndex
Or to get the value:
document.getElementById("select_id").value
Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch.
Fork Vs. Clone - two words that both mean copy
Please see this diagram. (Originally from http://www.dataschool.io/content/images/2014/Mar/github1.png).
.-------------------------. 1. Fork .-------------------------.
| Your GitHub repo | <-------------- | Joe's GitHub repo |
| github.com/you/coolgame | | github.com/joe/coolgame |
| ----------------------- | 7. Pull Request | ----------------------- |
| master -> c224ff7 | --------------> | master -> c224ff7 (c) |
| anidea -> 884faa1 (a) | | anidea -> 884faa1 (b) |
'-------------------------' '-------------------------'
| ^
| 2. Clone |
| |
| |
| |
| |
| | 6. Push (anidea => origin/anidea)
v |
.-------------------------.
| Your computer | 3. Create branch 'anidea'
| $HOME/coolgame |
| ----------------------- | 4. Update a file
| master -> c224ff7 |
| anidea -> 884faa1 | 5. Commit (to 'anidea')
'-------------------------'
(a) - after you have pushed it
(b) - after Joe has accepted it
(c) - eventually Joe might merge 'anidea' (make 'master -> 884faa1')
Fork
Clone
Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:
function dispatch(funCode) {
var map = {
'explode': function() {
prepExplosive();
if (flammable()) issueWarning();
doExplode();
},
'hibernate': function() {
if (status() == 'sleeping') return;
// ... I can't keep making this stuff up
},
// ...
};
var thisFun = map[funCode];
if (thisFun) thisFun();
}
Setting up multi-way branching by creating an object has a lot of advantages. You can add and remove functionality dynamically. You can create the dispatch table from data. You can examine it programmatically. You can build the handlers with other functions.
There's the added overhead of a function call to get to the equivalent of a "case", but the advantage (when there are lots of cases) of a hash lookup to find the function for a particular key.
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}
There's no need to check the exit code explicitly. Try
if getent passwd $1 > /dev/null 2>&1; then
echo "yes the user exists"
else
echo "No, the user does not exist"
fi
If that doesn't work, there is something wrong with your getent
, or you have more users defined than you think.
I know this is too old, but, just i case someone gets to this question from Google now, you can install it by typing apt-get install phantomjs
Please try with this
$pattern = "/My name is '\(.*\)' and im fine/";
There are a lot of good answers, but there is another very minor reason to put this
everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this
will make it a whole lot clearer to read.
Imagine this:
public class Hello {
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere() {
// ....
}
// More codes
public class World {
private String bar;
// Another 10k lines of codes
public void doSomething() {
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
}
}
}
This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.
You will struggle to find out where foo
resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere()
for the same reason. Lastly, after you have forgotten what s
is, that bar = s
is going to give you the final blow.
Compare it to this:
public void doSomething() {
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
}
foo
is a variable declared in outer class Hello
.getStringFromSomewhere()
is a method declared in outer class as well.bar
belongs to World
class, and s
is a local variable declared in that method.Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
This is not very difficult to implement yourself:
function reduceObj(obj, callback, initial) {
"use strict";
var key, lastvalue, firstIteration = true;
if (typeof callback !== 'function') {
throw new TypeError(callback + 'is not a function');
}
if (arguments.length > 2) {
// initial value set
firstIteration = false;
lastvalue = initial;
}
for (key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (firstIteration)
firstIteration = false;
lastvalue = obj[key];
continue;
}
lastvalue = callback(lastvalue, obj[key], key, obj);
}
if (firstIteration) {
throw new TypeError('Reduce of empty object with no initial value');
}
return lastvalue;
}
In action:
var o = {a: {value:1}, b: {value:2}, c: {value:3}};
reduceObj(o, function(prev, curr) { prev.value += cur.value; return prev;}, {value:0});
reduceObj(o, function(prev, curr) { return {value: prev.value + curr.value};});
// both == { value: 6 };
reduceObj(o, function(prev, curr) { return prev + curr.value; }, 0);
// == 6
You can also add it to the Object prototype:
if (typeof Object.prototype.reduce !== 'function') {
Object.prototype.reduce = function(callback, initial) {
"use strict";
var args = Array.prototype.slice(arguments);
args.unshift(this);
return reduceObj.apply(null, args);
}
}
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
Themes downloaded from IntelliJ can be installed as a Plugin.
Take these steps:
Preferences -> Plugins -> GearIcon -> Install Plugin from disk -> Reset your IDE -> Preferences -> Appearance -> Theme -> Select your theme.
I spend more than 3 hours reading and testing all the responses. Finally the problem was the library "joda time",
Reading this answer I found the problem, run the gradle console with full stack trace and read the error detail.
Just a note for people who may have found this later (and want java way of achieving this); FirefoxOptions
is also capable of enabling the headless mode:
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);
Your css is here: Project/Web/Support/Styles/file.css
1 time ../
means Project/Web/Support and 2 times ../ i.e. ../../
means Project/Web
Try:
background-image: url('../../images/image.png');
#include <iostream>
#include <string>
#include <random>
std::string generateRandomId(size_t length = 0)
{
static const std::string allowed_chars {"123456789BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz"};
static thread_local std::default_random_engine randomEngine(std::random_device{}());
static thread_local std::uniform_int_distribution<int> randomDistribution(0, allowed_chars.size() - 1);
std::string id(length ? length : 32, '\0');
for (std::string::value_type& c : id) {
c = allowed_chars[randomDistribution(randomEngine)];
}
return id;
}
int main()
{
std::cout << generateRandomId() << std::endl;
}
$session_start();
extract($_POST);
//extract data from submit post
if(isset($submit))
{
if($user=="user" && $pass=="pass")
{
$_SESSION['user']= $user;
//if correct password and name store in session
} else {
echo "Invalid user and password";
header("Locatin:form.php")
}
if(isset($_SESSION['user']))
{
}
CSS does not have an onlclick event handler. You have to use Javascript.
See more info here on CSS Pseudo-classes: http://www.w3schools.com/css/css_pseudo_classes.asp
a:link {color:#FF0000;} /* unvisited link - link is untouched */
a:visited {color:#00FF00;} /* visited link - user has already been to this page */
a:hover {color:#FF00FF;} /* mouse over link - user is hovering over the link with the mouse or has selected it with the keyboard */
a:active {color:#0000FF;} /* selected link - the user has clicked the link and the browser is loading the new page */
Also see...
How can I tell if I have uncommitted work in an Oracle transaction?
It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.
Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.
These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.
You can use the nm tool on an object file to list the symbols defined in a .o file.
You need to enclose multiple conditions in braces due to operator precedence and use the bitwise and (&
) and or (|
) operators:
foo = df[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]
If you use and
or or
, then pandas is likely to moan that the comparison is ambiguous. In that case, it is unclear whether we are comparing every value in a series in the condition, and what does it mean if only 1 or all but 1 match the condition. That is why you should use the bitwise operators or the numpy np.all
or np.any
to specify the matching criteria.
There is also the query method: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.query.html
but there are some limitations mainly to do with issues where there could be ambiguity between column names and index values.
To go the full manual route: This method converts doubles to strings by shifting the number's decimal point around and using floor (to long) and modulus to extract the digits. Also, it uses counting by base division to figure out the place where the decimal point belongs. It can also "delete" higher parts of the number once it reaches the places after the decimal point, to avoid losing precision with ultra-large doubles. See commented code at the end. In my testing, it is never less precise than the Java float representations themselves, when they actually show these imprecise lower decimal places.
/**
* Convert the given double to a full string representation, i.e. no scientific notation
* and always twelve digits after the decimal point.
* @param d The double to be converted
* @return A full string representation
*/
public static String fullDoubleToString(final double d) {
// treat 0 separately, it will cause problems on the below algorithm
if (d == 0) {
return "0.000000000000";
}
// find the number of digits above the decimal point
double testD = Math.abs(d);
int digitsBeforePoint = 0;
while (testD >= 1) {
// doesn't matter that this loses precision on the lower end
testD /= 10d;
++digitsBeforePoint;
}
// create the decimal digits
StringBuilder repr = new StringBuilder();
// 10^ exponent to determine divisor and current decimal place
int digitIndex = digitsBeforePoint;
double dabs = Math.abs(d);
while (digitIndex > 0) {
// Recieves digit at current power of ten (= place in decimal number)
long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
repr.append(digit);
--digitIndex;
}
// insert decimal point
if (digitIndex == 0) {
repr.append(".");
}
// remove any parts above the decimal point, they create accuracy problems
long digit = 0;
dabs -= (long)Math.floor(dabs);
// Because of inaccuracy, move to entirely new system of computing digits after decimal place.
while (digitIndex > -12) {
// Shift decimal point one step to the right
dabs *= 10d;
final var oldDigit = digit;
digit = (long)Math.floor(dabs) % 10;
repr.append(digit);
// This may avoid float inaccuracy at the very last decimal places.
// However, in practice, inaccuracy is still as high as even Java itself reports.
// dabs -= oldDigit * 10l;
--digitIndex;
}
return repr.insert(0, d < 0 ? "-" : "").toString();
}
Note that while StringBuilder is used for speed, this method can easily be rewritten to use arrays and therefore also work in other languages.
If you're looking to find both variations of the square brackets at the same time, you can use the following pattern which defines a range of either the [
sign or the ]
sign: /[\[\]]/
To generalize you can use:
SomeModel.find( $where, function(err,docs){
if (err) return console.log(err);
if (!docs || !Array.isArray(docs) || docs.length === 0)
return console.log('no docs found');
docs.forEach( function (doc) {
doc.remove();
});
});
Another way to achieve this is:
SomeModel.collection.remove( function (err) {
if (err) throw err;
// collection is now empty but not deleted
});
You could use extension methods to make it a little more readable:
public static class DateTimeExtensions
{
public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
{
return dateToCheck >= startDate && dateToCheck < endDate;
}
}
Now you can write:
dateToCheck.InRange(startDate, endDate)
This was marked as a duplicate to this question https://stackoverflow.com/questions/24401064/understanding-and-solving-the-diamond-problems-in-java
You need Java 8 to get a multiple inheritance problem, but it is still not a diamon problem as such.
interface A {
default void hi() { System.out.println("A"); }
}
interface B {
default void hi() { System.out.println("B"); }
}
class AB implements A, B { // won't compile
}
new AB().hi(); // won't compile.
As JB Nizet comments you can fix this my overriding.
class AB implements A, B {
public void hi() { A.super.hi(); }
}
However, you don't have a problem with
interface D extends A { }
interface E extends A { }
interface F extends A {
default void hi() { System.out.println("F"); }
}
class DE implement D, E { }
new DE().hi(); // prints A
class DEF implement D, E, F { }
new DEF().hi(); // prints F as it is closer in the heirarchy than A.
Since 3.5 you can also use the pathlib
for that purpose:
Path.write_text(data, encoding=None, errors=None)
Open the file pointed to in text mode, write data to it, and close the file:
import pathlib
pathlib.Path('textfile.txt').write_text('content')
In your controller:
$scope.num_str = parseInt(num_str, 10); // parseInt with radix
You want to use a FrameLayout or a Merge layout to achieve this. Android dev guide has a great example of this here: Android Layout Tricks #3: Optimize by merging.
You could loop through DataGridView
using Rows
property, like:
foreach (DataGridViewRow row in datagridviews.Rows)
{
currQty += row.Cells["qty"].Value;
//More code here
}
You have a method called getArguments()
that belongs to Fragment
class.
This answer is only for Linux Beginners.
Assuming initially the DB user didn't have file/folder(directory) permission on the client side.
Let's constrain ourselves to the following:
User: postgres
Purpose: You wanted to (write to / read from) a specific folder
Tool: psql
Connected to a specific database: YES
FILE_PATH: /home/user/training/sql/csv_example.csv
Query: \copy (SELECT * FROM table_name TO FILE_PATH, DELIMITER ',' CSV HEADER;
Actual Results: After running the query you got an error : Permission Denied
Expected Results: COPY COUNT_OF_ROWS_COPIED
Inside a terminal to view the permissions for a file/folder you need to long list them by entering the command ls -l
.
The output has a section that shows sth like this -> drwxrwxr-x
Which is interpreted in the following way:
TYPE | OWNER RIGHTS | GROUP RIGHTS | USER RIGHTS
rwx
(r: Read, W: Write, X: Execute)
TYPE (1 Char) = d: directory, -: file
OWNER RIGHTS (3 Chars after TYPE)
GROUP RIGHTS (3 Chars after OWNER)
USER RIGHTS (3 Chars after GROUP)
x
.This means for FILE_PATH, All the directories (home , user, training, sql) should have at least an x
in the USER RIGHTS.
x
. You can use chmod rights_you_want parent_folder
Assuming /training/
didn't have an execute permission.
I'd go the user folder and enter chmod a+x training
w
if you want to write to it. or at least a r
if you want to read from itAssuming /sql
didn't have a write permission.
I would now chmod a+w sql
sudo systemctl restart postgresql
This would most probably help you now get a successful expected result.
Change the submit button to a normal button and handle submitting in its onClick event.
As far as I know, there is no way to tell if the form was submitted by Enter Key or the submit button.
JUnit 5 update (and my opinion)
I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature, why?
By default, unit testing libraries don't try to execute tests in the order that occurs in the source file.
JUnit 5 as JUnit 4 work in that way. Why ? Because if the order matters it means that some tests are coupled between them and that is undesirable for unit tests.
So the @Nested
feature introduced by JUnit 5 follows the same default approach.
But for integration tests, the order of the test method may matter since a test method may change the state of the application in a way expected by another test method.
For example when you write an integration test for a e-shop checkout processing, the first test method to be executed is registering a client, the second is adding items in the basket and the last one is doing the checkout. If the test runner doesn't respect that order, the test scenario is flawed and will fail.
So in JUnit 5 (from the 5.4 version) you have all the same the possibility to set the execution order by annotating the test class with @TestMethodOrder(OrderAnnotation.class)
and by specifying the order with @Order(numericOrderValue)
for the methods which the order matters.
For example :
@TestMethodOrder(OrderAnnotation.class)
class FooTest {
@Order(3)
@Test
void checkoutOrder() {
System.out.println("checkoutOrder");
}
@Order(2)
@Test
void addItemsInBasket() {
System.out.println("addItemsInBasket");
}
@Order(1)
@Test
void createUserAndLogin() {
System.out.println("createUserAndLogin");
}
}
Output :
createUserAndLogin
addItemsInBasket
checkoutOrder
By the way, specifying @TestMethodOrder(OrderAnnotation.class)
looks like not needed (at least in the 5.4.0 version I tested).
Side note
About the question : is JUnit 5 the best choice to write integration tests ? I don't think that it should be the first tool to consider (Cucumber and co may often bring more specific value and features for integration tests) but in some integration test cases, the JUnit framework is enough. So that is a good news that the feature exists.
Just an important note. If you have HTML comment and your uncomment doesn't work
(Maybe it's a PHP file), so don't mark all the comment but just put your cursor at the end or at the beginning of the comment (before ) and try again (Ctrl+/).
Your pkl
file is, in fact, a serialized pickle
file, which means it has been dumped using Python's pickle
module.
To un-pickle the data you can:
import pickle
with open('serialized.pkl', 'rb') as f:
data = pickle.load(f)
Note gzip
is only needed if the file is compressed:
import gzip
import pickle
with gzip.open('mnist.pkl.gz', 'rb') as f:
train_set, valid_set, test_set = pickle.load(f)
Where each set can be further divided (i.e. for the training set):
train_x, train_y = train_set
Those would be the inputs (digits) and outputs (labels) of your sets.
If you want to display the digits:
import matplotlib.cm as cm
import matplotlib.pyplot as plt
plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()
The other alternative would be to look at the original data:
http://yann.lecun.com/exdb/mnist/
But that will be harder, as you'll need to create a program to read the binary data in those files. So I recommend you to use Python, and load the data with pickle
. As you've seen, it's very easy. ;-)
Static members will not be inherited to subclass because inheritance is only for non-static members.. And static members will be loaded inside static pool by class loader. Inheritance is only for those members which are loaded inside the object
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
_x000D_
var keys=Object.keys(a).sort();_x000D_
for(var i=0,key=keys[0];i<keys.length;key=keys[++i]){_x000D_
document.write(key+' : '+a[key]+'<br>');_x000D_
}
_x000D_
If you are developing a child theme you can use:
<img src="<?php echo get_template_directory_uri(); ?>-child/images/example.png" />
get_template_directory_uri() will return url to your currently active theme (parent theme), then you add -child/, then add path to your image (the example above assumes your image is at <child-theme-directory>/images/example.png
)
I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem
You need to configure your environment variables, JAVA_HOME
and PATH
.
JAVA_HOME
must contain the path to java, and you should add %JAVA_HOME%\bin to PATH
Alternatively, you can simply add to your PATH
the whole path to the bin folder, without the JAVA_HOME
variable, however, this makes a little more annoying when you need to have more than one java version on your machine (that way you only need to change JAVA_HOME
and don't even bother with PATH
)
I wrote a method (see below) which extracts a url's domain name and which uses simple String matching. What it actually does is extract the bit between the first "://"
(or index 0
if there's no "://"
contained) and the first subsequent "/"
(or index String.length()
if there's no subsequent "/"
). The remaining, preceding "www(_)*."
bit is chopped off. I'm sure there'll be cases where this won't be good enough but it should be good enough in most cases!
Mike Samuel's post above says that the java.net.URI
class could do this (and was preferred to the java.net.URL
class) but I encountered problems with the URI
class. Notably, URI.getHost()
gives a null value if the url does not include the scheme, i.e. the "http(s)"
bit.
/**
* Extracts the domain name from {@code url}
* by means of String manipulation
* rather than using the {@link URI} or {@link URL} class.
*
* @param url is non-null.
* @return the domain name within {@code url}.
*/
public String getUrlDomainName(String url) {
String domainName = new String(url);
int index = domainName.indexOf("://");
if (index != -1) {
// keep everything after the "://"
domainName = domainName.substring(index + 3);
}
index = domainName.indexOf('/');
if (index != -1) {
// keep everything before the '/'
domainName = domainName.substring(0, index);
}
// check for and remove a preceding 'www'
// followed by any sequence of characters (non-greedy)
// followed by a '.'
// from the beginning of the string
domainName = domainName.replaceFirst("^www.*?\\.", "");
return domainName;
}
>>> import subprocess
>>> subprocess.call('echo $HOME')
Traceback (most recent call last):
...
OSError: [Errno 2] No such file or directory
>>>
>>> subprocess.call('echo $HOME', shell=True)
/user/khong
0
Setting the shell argument to a true value causes subprocess to spawn an intermediate shell process, and tell it to run the command. In other words, using an intermediate shell means that variables, glob patterns, and other special shell features in the command string are processed before the command is run. Here, in the example, $HOME was processed before the echo command. Actually, this is the case of command with shell expansion while the command ls -l considered as a simple command.
source: Subprocess Module
For the sake of completeness of this popular question, since version 1.0.0 of dplyr
, parameter .groups controls the grouping structure of the summarise
function after group_by
summarise help.
With .groups = "drop_last"
, summarise
drops the last level of grouping. This was the only result obtained before version 1.0.0.
library(dplyr)
library(scales)
original <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n()) %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
original
#> # A tibble: 4 x 4
#> # Groups: am [2]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 78.9%
#> 2 0 4 4 21.1%
#> 3 1 4 8 61.5%
#> 4 1 5 5 38.5%
new_drop_last <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "drop_last") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
dplyr::all_equal(original, new_drop_last)
#> [1] TRUE
With .groups = "drop"
, all levels of grouping are dropped. The result is turned into an independent tibble with no trace of the previous group_by
# .groups = "drop"
new_drop <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "drop") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
new_drop
#> # A tibble: 4 x 4
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 46.9%
#> 2 0 4 4 12.5%
#> 3 1 4 8 25.0%
#> 4 1 5 5 15.6%
If .groups = "keep"
, same grouping structure as .data (mtcars, in this case). summarise
does not peel off any variable used in the group_by
.
Finally, with .groups = "rowwise"
, each row is it's own group. It is equivalent to "keep" in this situation
# .groups = "keep"
new_keep <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "keep") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
new_keep
#> # A tibble: 4 x 4
#> # Groups: am, gear [4]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 100.0%
#> 2 0 4 4 100.0%
#> 3 1 4 8 100.0%
#> 4 1 5 5 100.0%
# .groups = "rowwise"
new_rowwise <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "rowwise") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
dplyr::all_equal(new_keep, new_rowwise)
#> [1] TRUE
Another point that can be of interest is that sometimes, after applying group_by
and summarise
, a summary line can help.
# create a subtotal line to help readability
subtotal_am <- mtcars %>%
group_by (am) %>%
summarise (n=n()) %>%
mutate(gear = NA, rel.freq = 1)
#> `summarise()` ungrouping output (override with `.groups` argument)
mtcars %>% group_by (am, gear) %>%
summarise (n=n()) %>%
mutate(rel.freq = n/sum(n)) %>%
bind_rows(subtotal_am) %>%
arrange(am, gear) %>%
mutate(rel.freq = scales::percent(rel.freq, accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
#> # A tibble: 6 x 4
#> # Groups: am [2]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 78.9%
#> 2 0 4 4 21.1%
#> 3 0 NA 19 100.0%
#> 4 1 4 8 61.5%
#> 5 1 5 5 38.5%
#> 6 1 NA 13 100.0%
Created on 2020-11-09 by the reprex package (v0.3.0)
Hope you find this answer useful.
You can't specify units in width
/height
attributes of a table; these are always in pixels, but you should not use them at all since they are deprecated.
I believe it depends on what json interpreter you're using... in plain javascript you could use line terminators
{
"testCases" :
{
"case.1" :
{
"scenario" : "this the case 1.",
"result" : "this is a very long line which is not easily readble. \
so i would like to write it in multiple lines. \
but, i do NOT require any new lines in the output."
}
}
}
Instead of using success
, I change it to then
and it works.
here is the code:
lgrg.controller('login', function($scope, $window, $http) {
$scope.loginUser = {};
$scope.submitForm = function() {
$scope.errorInfo = null
$http({
method : 'POST',
url : '/login',
headers : {'Content-Type': 'application/json'}
data: $scope.loginUser
}).then(function(data) {
if (!data.status) {
$scope.errorInfo = data.info
} else {
//page jump
$window.location.href = '/admin';
}
});
};
});
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
Try something like this:
$link = @new mysqli($this->host, $this->user, $this->pass)
$statement = $link->prepare($sqlStatement);
if(!$statement)
{
$this->debug_mode('query', 'error', '#Query Failed<br/>' . $link->error);
return false;
}
docker rmi $(docker images -f "dangling=true" -q)
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
This method was
deprecatedin API level 24.
You should use FROM_HTML_MODE_LEGACY
Separate block-level elements with blank lines (two newline characters) in between. This is the legacy behavior prior to N.
Code
if (Build.VERSION.SDK_INT >= 24)
{
etOBJ.setText(Html.fromHtml("Intellij \n Amiyo",Html.FROM_HTML_MODE_LEGACY));
}
else
{
etOBJ.setText(Html.fromHtml("Intellij \n Amiyo"));
}
For Kotlin
fun setTextHTML(html: String): Spanned
{
val result: Spanned = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(html)
}
return result
}
Call
txt_OBJ.text = setTextHTML("IIT Amiyo")
I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.
These messages are due to incorrect default value of core.autocrlf
on Windows.
The concept of autocrlf
is to handle line endings conversions transparently. And it does!
Bad news: value needs to be configured manually.
Good news: it should only be done ONE time per git installation (per project setting is also possible).
How autocrlf
works:
core.autocrlf=true: core.autocrlf=input: core.autocrlf=false:
repo repo repo
^ V ^ V ^ V
/ \ / \ / \
crlf->lf lf->crlf crlf->lf \ / \
/ \ / \ / \
Here crlf
= win-style end-of-line marker, lf
= unix-style (and mac osx).
(pre-osx cr
in not affected for any of three options above)
When does this warning show up (under Windows)
– autocrlf
= true
if you have unix-style lf
in one of your files (= RARELY),
– autocrlf
= input
if you have win-style crlf
in one of your files (= almost ALWAYS),
– autocrlf
= false
– NEVER!
What does this warning mean
The warning "LF will be replaced by CRLF" says that you (having autocrlf
=true
) will lose your unix-style LF after commit-checkout cycle (it will be replaced by windows-style CRLF). Git doesn't expect you to use unix-style LF under windows.
The warning "CRLF will be replaced by LF" says that you (having autocrlf
=input
) will lose your windows-style CRLF after a commit-checkout cycle (it will be replaced by unix-style LF). Don't use input
under windows.
Yet another way to show how autocrlf
works
1) true: x -> LF -> CRLF
2) input: x -> LF -> LF
3) false: x -> x -> x
where x is either CRLF (windows-style) or LF (unix-style) and arrows stand for
file to commit -> repository -> checked out file
How to fix
Default value for core.autocrlf
is selected during git installation and stored in system-wide gitconfig (%ProgramFiles(x86)%\git\etc\gitconfig
). Also there're (cascading in the following order):
– "global" (per-user) gitconfig located at ~/.gitconfig
, yet another
– "global" (per-user) gitconfig at $XDG_CONFIG_HOME/git/config
or $HOME/.config/git/config
and
– "local" (per-repo) gitconfig at .git/config
in the working dir.
So, write git config core.autocrlf
in the working dir to check the currently used value and
– add autocrlf=false
to system-wide gitconfig # per-system solution
– git config --global core.autocrlf false
# per-user solution
– git config --local core.autocrlf false
# per-project solution
Warnings
– git config
settings can be overridden by gitattributes
settings.
– crlf -> lf
conversion only happens when adding new files, crlf
files already existing in the repo aren't affected.
Moral (for Windows):
- use core.autocrlf
= true
if you plan to use this project under Unix as well (and unwilling to configure your editor/IDE to use unix line endings),
- use core.autocrlf
= false
if you plan to use this project under Windows only (or you have configured your editor/IDE to use unix line endings),
- never use core.autocrlf
= input
unless you have a good reason to (eg if you're using unix utilities under windows or if you run into makefiles issues),
PS What to choose when installing git for Windows?
If you're not going to use any of your projects under Unix, don't agree with the default first option. Choose the third one (Checkout as-is, commit as-is). You won't see this message. Ever.
PPS My personal preference is configuring the editor/IDE to use Unix-style endings, and setting core.autocrlf
to false
.
Use isset()
$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.
$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
You should add parse_dates=True
, or parse_dates=['column name']
when reading, thats usually enough to magically parse it. But there are always weird formats which need to be defined manually. In such a case you can also add a date parser function, which is the most flexible way possible.
Suppose you have a column 'datetime' with your string, then:
from datetime import datetime
dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)
This way you can even combine multiple columns into a single datetime column, this merges a 'date' and a 'time' column into a single 'datetime' column:
dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv(infile, parse_dates={'datetime': ['date', 'time']}, date_parser=dateparse)
You can find directives (i.e. the letters to be used for different formats) for strptime
and strftime
in this page.
There are two solutions for this issue.
First, is to create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.
Second, if you started to get this error just recently, after MySQL/MariaDB upgrade, like I did, and in case you already have large project with a lot to fix, all you need to do is to edit MySQL/MariaDB configuration file (for example /etc/my.cnf
) and disable strict mode for tables:
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION
This error started to happen quite recently, due to new strict mode enabled by default. Removing STRICT_TRANS_TABLES
from sql_mode
configuration key, makes it work as before.
To get an individual table's creation script just right click on the table name and click Copy to Clipboard > Create Statement.
To enable the File > Forward Engineering SQL_CREATE Script.. option and to get the creation script for your entire database :
The difference is bucketing divides the files by Column Name, and partitioning divides the files under By a particular value inside table
Hopefully I defined it correctly
The following code will compare each item with other list of items using contains() method.Length of for loop must be bigger size() of bigger list then only it will compare all the values of both list.
List<String> str = new ArrayList<String>();
str.add("first");
str.add("second");
str.add("third");
List<String> str1 = new ArrayList<String>();
str1.add("first");
str1.add("second");
str1.add("third1");
for (int i = 0; i<str1.size(); i++)
{
System.out.println(str.contains(str1.get(i)));
}
Output is true true false
[edited]
using your comment about productCode (and assuming product code is a String) as reference...
for(Product p : productList){
s.put(p.getProductCode() , p);
}
simple just run
rm -r node_modules
in fact, you can delete any folder with this.
like rm -r AnyFolderWhichIsNotDeletableFromShiftDeleteOrDelete.
just open the gitbash move to root of the folder and run this command
Hope this will help.
Yes.
However, if you need to use Application.DoEvents
, this is mostly an indication of a bad application design. Perhaps you'd like to do some work in a separate thread instead?
<script type="text/javascript">
$(document).ready(function(e) {
$(".mqimg").mouseover(function()
{
$("#imgprev").animate({height: "250px",width: "70%",left: "15%"},100).html("<img src='"+$(this).attr('src')+"' width='100%' height='100%' />");
})
$(".mqimg").mouseout(function()
{
$("#imgprev").animate({height: "0px",width: "0%",left: "50%"},100);
})
});
</script>
<style>
.mqimg{ cursor:pointer;}
</style>
<div style="position:relative; width:100%; height:1px; text-align:center;">`enter code here`
<div id="imgprev" style="position:absolute; display:block; box-shadow:2px 5px 10px #333; width:70%; height:0px; background:#999; left:15%; bottom:15px; "></div>
<img class='mqimg' src='spppimages/1.jpg' height='100px' />
<img class='mqimg' src='spppimages/2.jpg' height='100px' />
<img class='mqimg' src='spppimages/3.jpg' height='100px' />
<img class='mqimg' src='spppimages/4.jpg' height='100px' />
<img class='mqimg' src='spppimages/5.jpg' height='100px' />
Download and setup Microsoft Build Tools 2013 from http://www.microsoft.com/en-US/download/details.aspx?id=40760
I have reproduced the issue in my system,
postgres=# alter user my-sys with password 'pass11';
ERROR: syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
^
Here is the issue,
psql is asking for input and you have given again the alter query see postgres-#
That's why it's giving error at alter
postgres-# alter user "my-sys" with password 'pass11';
ERROR: syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
^
Solution is as simple as the error,
postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE
There are two separate concepts here:
Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:
void f() {
int i;
i = 1; // OK: in scope
}
void g() {
i = 2; // Error: not in scope
}
Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:
int i;
void f() {
i = 1; // OK: in scope
}
void g() {
i = 2; // OK: still in scope
}
(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)
Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.
for (int i = 0; i < 5; ++i) {
int n = 0;
printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}
Static variables (pedantically, variables with static storage duration) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.
for (int i = 0; i < 5; ++i) {
static int n = 0;
printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}
Note that the static
keyword has various meanings apart from static storage duration. On a global variable or function, it gives it internal linkage so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto
keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.
use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>
PDFBox contains tools for text extraction.
iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.
iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.
Simply, @Id: This annotation specifies the primary key of the entity.
@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used.
GenerationType enum defines four strategies:
1. Generation Type . TABLE,
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY
4. Generation Type. AUTO
GenerationType.SEQUENCE
With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities.
GenerationType.TABLE
With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities.
GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.
GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used.
Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html
If you want to list Store Procedure for Current Selected Database,
SHOW PROCEDURE STATUS WHERE Db = DATABASE();
it will list Routines based on current selected Database
UPDATED to list out functions in your database
select * from information_schema.ROUTINES where ROUTINE_SCHEMA="YOUR DATABASE NAME" and ROUTINE_TYPE="FUNCTION";
to list out routines/store procedures in your database,
select * from information_schema.ROUTINES where ROUTINE_SCHEMA="YOUR DATABASE NAME" and ROUTINE_TYPE="PROCEDURE";
to list tables in your database,
select * from information_schema.TABLES WHERE TABLE_TYPE="BASE TABLE" AND TABLE_SCHEMA="YOUR DATABASE NAME";
to list views in your database,
method 1:
select * from information_schema.TABLES WHERE TABLE_TYPE="VIEW" AND TABLE_SCHEMA="YOUR DATABASE NAME";
method 2:
select * from information_schema.VIEWS WHERE TABLE_SCHEMA="YOUR DATABASE NAME";
Function ExtSql(ByVal sql As String) As Boolean
Dim cnn As SqlConnection
Dim cmd As SqlCommand
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
cmd = New SqlCommand
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cnn.Close()
cmd.Dispose()
Catch ex As Exception
cnn.Close()
Return False
End Try
Return True
End Function
If you want to perform actions like cd
, then use:
String[] command = {command_to_be_executed, arg1, arg2};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("directory_location"));
Example:
String[] command = {"ls", "-al"};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("/ngs/app/abc"));
Process p = builder.start();
It is important that you split the command and all arguments in separate strings of the string array (otherwise they will not be provided correctly by the ProcessBuilder
API).
There are many answers on this question already, but nothing fitted my needs. So i came up with my own solution, I hope it is usefull for someone:
function calledPrivate(){
var stack = new Error().stack.toString().split("\n");
function getClass(line){
var i = line.indexOf(" ");
var i2 = line.indexOf(".");
return line.substring(i,i2);
}
return getClass(stack[2])==getClass(stack[3]);
}
class Obj{
privateMethode(){
if(calledPrivate()){
console.log("your code goes here");
}
}
publicMethode(){
this.privateMethode();
}
}
var obj = new Obj();
obj.publicMethode(); //logs "your code goes here"
obj.privateMethode(); //does nothing
As you can see this system works when using this type of classes in javascript. As far as I figured out none of the methods commented above did.
Since one of your result types is a string (and you're using C, not C++), I recommend passing pointers as output parameters. Use:
void foo(int *a, char *s, int size);
and call it like this:
int a;
char *s = (char *)malloc(100); /* I never know how much to allocate :) */
foo(&a, s, 100);
In general, prefer to do the allocation in the calling function, not inside the function itself, so that you can be as open as possible for different allocation strategies.
sudo groupadd -r kvm
sudo gedit /lib/udev/rules.d/60-qemu-system-common.rules
Add the following line to the opened file and save it
KERNEL=="kvm", GROUP="kvm", MODE="0660"
Finally run:
sudo usermod -a -G kvm <your_username>
Reboot your PC and Done!
As Brannon says, it's OrderByDescending
and ThenByDescending
:
var query = from person in people
orderby person.Name descending, person.Age descending
select person.Name;
is equivalent to:
var query = people.OrderByDescending(person => person.Name)
.ThenByDescending(person => person.Age)
.Select(person => person.Name);
Use outline: transparent;
in order to make the outline appear like it isn't there but still provide accessibility to your forms. outline: none;
will negatively impact accessibility.
Source: http://outlinenone.com/
The official language specification for XPath 2.0 on W3.org details that the language does indeed support if statements. See Section 3.8 Conditional Expressions, in particular. Along with the syntax format and explanation, it gives the following example:
if ($widget1/unit-cost < $widget2/unit-cost)
then $widget1
else $widget2
This would suggest that you shouldn't have brackets surrounding your expressions (otherwise the syntax looks correct). I'm not wholly confident, but it's surely worth a try. So you'll want to change your query to look like this:
if (fn:ends-with(//div [@id='head']/text(),': '))
then fn:substring-before(//div [@id='head']/text(),': ')
else //div [@id='head']/text()
I do strongly suspect this may fix it however, as the fact that your XPath engine seems to be trying to interpret if
as a function, where it is in fact a special construct of the language.
Finally, to point out the obvious, insure that your XPath engine does in fact support XPath 2.0 (as opposed to an earlier version)! I don't believe conditional expressions are part of previous versions of XPath.
You can select the tables from information_schema
SELECT * FROM information_schema.tables
WHERE table_schema = 'public'
an apache server is an http server which can serve any simple http requests, where tomcat server is actually a servlet container which can serve java servlet requests.
Web server [apache] process web client (web browsers) requests and forwards it to servlet container [tomcat] and container process the requests and sends response which gets forwarded by web server to the web client [browser].
Also you can check this link for more clarification:-
https://sites.google.com/site/sureshdevang/servlet-architecture
Also check this answer for further researching :-
General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.
If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.
As per the docs
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Example
public class Dog
{
}
will automatically be modified(by adding default constructor) as follows
public class Dog{
public Dog() {
}
}
and when you create it's object
Dog myDog = new Dog();
this default constructor is invoked.
I was facing the same issue.
Commonly This kind of error occurs due to client has closed its connection and server still trying to write on that client.
So make sure that your client has its connection open until server done with its outputstream.
And one more thing, Don`t forgot to close input and output stream.
Hope this helps.
And if still facing issue than brief your problem here in details.
My requirement is to check if specific software is installed in my system. This solution works as expected. It might help you. I used a windows application in c# with visual studio 2015.
private void Form1_Load(object sender, EventArgs e)
{
object line;
string softwareinstallpath = string.Empty;
string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (var key = baseKey.OpenSubKey(registry_key))
{
foreach (string subkey_name in key.GetSubKeyNames())
{
using (var subKey = key.OpenSubKey(subkey_name))
{
line = subKey.GetValue("DisplayName");
if (line != null && (line.ToString().ToUpper().Contains("SPARK")))
{
softwareinstallpath = subKey.GetValue("InstallLocation").ToString();
listBox1.Items.Add(subKey.GetValue("InstallLocation"));
break;
}
}
}
}
}
if(softwareinstallpath.Equals(string.Empty))
{
MessageBox.Show("The Mirth connect software not installed in this system.")
}
string targetPath = softwareinstallpath + @"\custom-lib\";
string[] files = System.IO.Directory.GetFiles(@"D:\BaseFiles");
// Copy the files and overwrite destination files if they already exist.
foreach (var item in files)
{
string srcfilepath = item;
string fileName = System.IO.Path.GetFileName(item);
System.IO.File.Copy(srcfilepath, targetPath + fileName, true);
}
return;
}
std::string::compare() returns an int
:
s
and t
are equal,s
is less than t
,s
is greater than t
.If you want your first code snippet to be equivalent to the second one, it should actually read:
if (!s.compare(t)) {
// 's' and 't' are equal.
}
The equality operator only tests for equality (hence its name) and returns a bool
.
To elaborate on the use cases, compare()
can be useful if you're interested in how the two strings relate to one another (less or greater) when they happen to be different. PlasmaHH rightfully mentions trees, and it could also be, say, a string insertion algorithm that aims to keep the container sorted, a dichotomic search algorithm for the aforementioned container, and so on.
EDIT: As Steve Jessop points out in the comments, compare()
is most useful for quick sort and binary search algorithms. Natural sorts and dichotomic searches can be implemented with only std::less.
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)XSD files are used to validate that XML files conform to a certain format.
In that respect they are similar to DTDs that existed before them.
The main difference between XSD and DTD is that XSD is written in XML and is considered easier to read and understand.
On CentOS Linux, Python3.6, I edited this file (make a backup copy first)
/usr/lib/python3.6/site-packages/certifi/cacert.pem
to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
This just works on React & React Native
const data = require('./data/photos.json');
console.log('[-- typeof data --]', typeof data); // object
const fotos = data.xs.map(item => {
return { uri: item };
});
Try this:
SELECT
'the sqlserver is ' + substring(@@VERSION, 21, 5) AS [sql version]
Here is the example of the "foreach" construction with simultaneous access to the element indexes in Python:
for idx, val in enumerate([3, 4, 5]):
print (idx, val)
Your understanding is correct. The ApplicationContext
is where your Spring beans live. The purpose of the ContextLoaderListener
is two-fold:
to tie the lifecycle of the ApplicationContext
to the lifecycle of the ServletContext
and
to automate the creation of the ApplicationContext
, so you don't have to write explicit code to do create it - it's a convenience function.
Another convenient thing about the ContextLoaderListener
is that it creates a WebApplicationContext
and WebApplicationContext
provides access to the ServletContext
via ServletContextAware
beans and the getServletContext
method.
For Windows 10 if you want use pip in normal cmd, not only in Anaconda prompt. you need add 3 environment paths. like the followings:
D:\Anaconda3
D:\Anaconda3\Scripts
D:\Anaconda3\Library\bin
most people only add D:\Anaconda3\Scripts
Alternatively, can use for particular table
<table style="width:1000px; height:100px;">
<tr>
<td align="center" valign="top">Text</td> //Remove it
<td class="tableFormatter">Text></td>
</tr>
</table>
Add this css in external file
.tableFormatter
{
width:100%;
vertical-align:top;
text-align:center;
}
I had a git conflict left in my workspace.xml i.e.
<<<<———————HEAD
which caused the unknown tag error. It is a bit annoying that it doesn’t name the file.
Here is a short code snippet for shadowing cin/cout useful for programming contests:
#include <bits/stdc++.h>
using namespace std;
int main() {
ifstream cin("input.txt");
ofstream cout("output.txt");
int a, b;
cin >> a >> b;
cout << a + b << endl;
}
This gives additional benefit that plain fstreams are faster than synced stdio streams. But this works only for the scope of single function.
Global cin/cout redirect can be written as:
#include <bits/stdc++.h>
using namespace std;
void func() {
int a, b;
std::cin >> a >> b;
std::cout << a + b << endl;
}
int main() {
ifstream cin("input.txt");
ofstream cout("output.txt");
// optional performance optimizations
ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cin.rdbuf(cin.rdbuf());
std::cout.rdbuf(cout.rdbuf());
func();
}
Note that ios_base::sync_with_stdio
also resets std::cin.rdbuf
. So the order matters.
See also Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);
Std io streams can also be easily shadowed for the scope of single file, which is useful for competitive programming:
#include <bits/stdc++.h>
using std::endl;
std::ifstream cin("input.txt");
std::ofstream cout("output.txt");
int a, b;
void read() {
cin >> a >> b;
}
void write() {
cout << a + b << endl;
}
int main() {
read();
write();
}
But in this case we have to pick std
declarations one by one and avoid using namespace std;
as it would give ambiguity error:
error: reference to 'cin' is ambiguous
cin >> a >> b;
^
note: candidates are:
std::ifstream cin
ifstream cin("input.txt");
^
In file test.cpp
std::istream std::cin
extern istream cin; /// Linked to standard input
^
See also How do you properly use namespaces in C++?, Why is "using namespace std" considered bad practice? and How to resolve a name collision between a C++ namespace and a global function?
Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)
Just go through these links,
Run Android on Your Windows Mobile Phone
full tutorial on how to put android on windows mobile touch pro 2
How to install Android on most Windows Mobile phones
Update:
For Windows 7 to Android device, this also possible, (You need to do some hack for this)
Just go through these links,
Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]
HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND
Install windows phone 7 on android and iphones | Tips and Tricks
How to install Windows Phone 7 on HTC HD2? (Video)
To Install Android on your iOS Devices (This also possible...)
An option is to use the simple approach of adding a Timestamp with each request no need to clear cache.
let c=new Date().getTime();
$http.get('url?d='+c)
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
gcc
and g++
are compiler-drivers of the GNU Compiler Collection (which was once upon a time just the GNU C Compiler).
Even though they automatically determine which backends (cc1
cc1plus
...) to call depending on the file-type, unless overridden with -x language
, they have some differences.
The probably most important difference in their defaults is which libraries they link against automatically.
According to GCC's online documentation link options and how g++ is invoked, g++
is equivalent to gcc -xc++ -lstdc++ -shared-libgcc
(the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the -v
option (it displays the backend toolchain commands being run).
As second says, most of the "design" decisions made for TeX documents are backed up by well researched usability studies, so changing them should be undertaken with care. It is, however, relatively common to replace Computer Modern with Times (also a serif face).
Try \usepackage{times}
.
Be sure you use the slash (/) on right side of keyboard.
For Line Comment:
Ctrl + /
For Block Comment:
Ctrl + Shift + /
You can see all keymap in Android Studio: Help ? Default Keymap Reference
Do not include bin in your JAVA_HOME env variable
Here is a version that JSLint likes:
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var param = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = param.length,
tmp,
p;
for (p = 0; p < plength; p += 1) {
tmp = param[p].split('=');
GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
Or if you need support for several values for one key like eg. ?key=value1&key=value2 you can use this:
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var params = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = params.length,
tmp,
key,
val,
obj,
p;
for (p = 0; p < plength; p += 1) {
tmp = params[p].split('=');
key = decodeURIComponent(tmp[0]);
val = decodeURIComponent(tmp[1]);
if (GET.hasOwnProperty(key)) {
obj = GET[key];
if (obj.constructor === Array) {
obj.push(val);
} else {
GET[key] = [obj, val];
}
} else {
GET[key] = val;
}
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
"\n" => Newline or Linefeed (semantics)
Unix based systems use just a "\n" to end a line of text.
Browsers aren't always set to print background images by default; if you intend to have people print your page :)
Radio buttons come in groups which have the same name and different ids, one of them will have the checked property set to true, so loop over them until you find it.
function getCheckedRadio(radio_group) {
for (var i = 0; i < radio_group.length; i++) {
var button = radio_group[i];
if (button.checked) {
return button;
}
}
return undefined;
}
var checkedButton = getCheckedRadio(document.forms.frmId.elements.groupName);
if (checkedButton) {
alert("The value is " + checkedButton.value);
}
I did it by adding a point to my initial arrays. In this way I avoid defining self-made functions, and the linear extrapolation (in the example below: right extrapolation) looks ok.
import numpy as np
from scipy import interp as itp
xnew = np.linspace(0,1,51)
x1=xold[-2]
x2=xold[-1]
y1=yold[-2]
y2=yold[-1]
right_val=y1+(xnew[-1]-x1)*(y2-y1)/(x2-x1)
x=np.append(xold,xnew[-1])
y=np.append(yold,right_val)
f = itp(xnew,x,y)
How you detect EOF depends on what you're using to read the stream:
function result on EOF or error
-------- ----------------------
fgets() NULL
fscanf() number of succesful conversions
less than expected
fgetc() EOF
fread() number of elements read
less than expected
Check the result of the input call for the appropriate condition above, then call feof()
to determine if the result was due to hitting EOF or some other error.
Using fgets()
:
char buffer[BUFFER_SIZE];
while (fgets(buffer, sizeof buffer, stream) != NULL)
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fscanf()
:
char buffer[BUFFER_SIZE];
while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fgetc()
:
int c;
while ((c = fgetc(stream)) != EOF)
{
// process c
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted the read
}
Using fread()
:
char buffer[BUFFER_SIZE];
while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1
// element of size
// BUFFER_SIZE
{
// process buffer
}
if (feof(stream))
{
// hit end of file
}
else
{
// some other error interrupted read
}
Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You'll see a lot of examples like:
while(!feof(stream))
{
fscanf(stream, "%s", buffer);
...
}
This form doesn't work the way people think it does, because feof()
won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.