Constant Value Description
----------------------------------------------------------------
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination
vbLf Chr(10) Line feed
vbCr : - return to line beginning
Represents a carriage-return character for print and display functions.
vbCrLf : - similar to pressing Enter
Represents a carriage-return character combined with a linefeed character for print and display
functions.
vbLf : - go to next line
Represents a linefeed character for print and display functions.
Read More from Constants Class
vbCrLf
or vbNewLine
Environment.NewLine
or vbCrLf
or Constants.vbCrLf
Info on VB.NET new line: http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx
The info for Environment.NewLine
came from Cody Gray and J Vermeire
You can do the same in Razor or in the Controller, like so..
@{
//do this on the top most of your View, immediately after `using` statement
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}
Or in the Controller..
public ActionResult Receipt() {
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
return View();
}
I tried this in Chrome and IE9, both is downloading the pdf file.
I probably should add I am using RazorPDF to generate my PDFs. Here is a blog about it: http://nyveldt.com/blog/post/Introducing-RazorPDF
This Works on Framework 4.0 or Higher. Supports "GO". Also show the error message, line, and sql command.
using System.Data.SqlClient;
private bool runSqlScriptFile(string pathStoreProceduresFile, string connectionString)
{
try
{
string script = File.ReadAllText(pathStoreProceduresFile);
// split script on GO command
System.Collections.Generic.IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
using (var command = new SqlCommand(commandString, connection))
{
try
{
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
string spError = commandString.Length > 100 ? commandString.Substring(0, 100) + " ...\n..." : commandString;
MessageBox.Show(string.Format("Please check the SqlServer script.\nFile: {0} \nLine: {1} \nError: {2} \nSQL Command: \n{3}", pathStoreProceduresFile, ex.LineNumber, ex.Message, spError), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
}
}
}
connection.Close();
}
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
}
In the old days, when we could assume that most computers used ASCII, we would just do
int i = c[0] - '0';
But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.
Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.
Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:
select
s.SqmId,
m.c.value('@id', 'varchar(max)') as id,
m.c.value('@type', 'varchar(max)') as type,
m.c.value('@unit', 'varchar(max)') as unit,
m.c.value('@sum', 'varchar(max)') as [sum],
m.c.value('@count', 'varchar(max)') as [count],
m.c.value('@minValue', 'varchar(max)') as minValue,
m.c.value('@maxValue', 'varchar(max)') as maxValue,
m.c.value('.', 'nvarchar(max)') as Value,
m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)
To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:
.DEFAULT_GOAL := mytarget
mytarget will now be the target that is run if "make" is executed and no target is specified.
If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:
.PHONY: default
default: mytarget ;
References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html
A notable 'gotcha' dictates that you should never include more than one input element inside of a <label> element with an explicit "for" attribute, e.g:
<label for="child-input-1">
<input type="radio" id="child-input-1"/>
<span> Associate the following text with the selected radio button: </span>
<input type="text" id="child-input-2"/>
</label>
While this may be tempting for form features in which a custom text value is secondary to a radio button or checkbox, the click-focus functionality of the label element will immediately throw focus to the element whose id is explicitly defined in its 'for' attribute, making it nearly impossible for the user to click into the contained text field to enter a value.
Personally, I try to avoid label elements with input children. It seems semantically improper for a label element to encompass more than the label itself. If you're nesting inputs in labels in order to achieve a certain aesthetic, you should be using CSS instead.
This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.
Obviously, replace new_file_loc with whatever your new file location will be.
@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
call :open "%%i"
exit /B 0
)
:open
start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0
Just wanted to say that this answer is brilliant and I'm using it for a long time without problems. But some time ago I've stumbled upon a problem that DownloadsProvider returns URIs in format content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Fdoc.pdf
and hence app is crashed with NumberFormatException
as it's impossible to parse its uri segments as long. But raw:
segment contains direct uri which can be used to retrieve a referenced file. So I've fixed it by replacing isDownloadsDocument(uri)
if
content with following:
final String id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
Log.e("FileUtils", "Downloads provider returned unexpected uri " + uri.toString(), e);
return null;
}
}
If the user has not generated a ssh public/private key pair set before
This info is working on theChaw but can be applied to all other git repositories which support SSH pubkey authentications. (See gitolite, gitlab or github for example.)
First start by setting up your own public/private key pair set. This can use either DSA or RSA, so basically any key you setup will work. On most systems you can use ssh-keygen.
- First you'll want to cd into your .ssh directory. Open up the terminal and run:
cd ~/.ssh && ssh-keygen
- Next you need to copy this to your clipboard.
- On OS X run:
cat id_rsa.pub | pbcopy
- On Linux run:
cat id_rsa.pub | xclip
- On Windows (via Cygwin/Git Bash) run:
cat id_rsa.pub | clip
- Add your key to your account via the website.
- Finally setup your .gitconfig.
git config --global user.name "bob"
git config --global user.email bob@...
(don't forget to restart your command line to make sure the config is reloaded)That's it you should be good to clone and checkout.
Further information can be found at https://help.github.com/articles/generating-ssh-keys (thanks to @Lee Whitney) -
If the user has generated a ssh public/private key pair set before
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa
The children of a row-flexbox container automatically fill the container's vertical space.
Specify flex: 1;
for a child if you want it to fill the remaining horizontal space:
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space: .wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
In eclipse you can use the old but still usable plugin jarsearch
A file with associated buffering is called a stream and is declared to be a pointer to a defined type FILE. The fopen() function creates certain descriptive data for a stream and returns a pointer to designate the stream in all further transactions. Normally there are three open streams with constant pointers declared in the header and associated with the standard open files. At program startup three streams are predefined and need not be opened explicitly: standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). When opened the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device
Yes it is true.
If you create two instance of your class
Test t1 = new Test();
Test t2 = new Test();
Then t1.foo and t2.foo both synchronize on the same static object and hence block each other.
When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png)
can be problematic if PDF output is required.
The knitr function include_graphics
knitr::include_graphics('/path/to/image.png')
is a more portable alternative
that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.
Most of these answers use sp_executesql as the solution to this problem. I have found that there are some limitations when using sp_executesql, which I will not go into, but I wanted to offer an alternative using EXEC(). I am using SQL Server 2008 and I know that some of the objects I am using in this script are not available in earlier versions of SQL Server so be wary.
DECLARE @CountResults TABLE (CountReturned INT)
DECLARE
@SqlStatement VARCHAR(8000) = 'SELECT COUNT(*) FROM table'
, @Count INT
INSERT @CountResults
EXEC(@SqlStatement)
SET @Count = (SELECT CountReturned FROM @CountResults)
SELECT @Count
For Vb.Net Framework 4.0, U can use:
Alert("your message here", Boolean)
The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.
.jar and .war are both zipped archived files. Both can have the optional META-INF/MANIFEST.MF manifest file which hold informative information like versioning, and instructional attributes like classpath and main-class for the JVM that will execute it.
.war file - Web Application Archive intended to be execute inside a 'Servlet Container' and may include other jar files (at WEB-INF/lib directory) compiled classes (at WEB-INF/classes (servlet goes there too)) .jsp files images, files etc. All WAR content that is there in order to create a self-contained module.
first, in C:\users\your PC
write npm uninstall -g create-react-app
then, create your project folder with npx create-react-app folder-name
.
I use the utility below to cleanup after my integration test run.
It uses the latest AdminZkClient
api. The older api has been deprecated.
import javax.inject.Inject
import kafka.zk.{AdminZkClient, KafkaZkClient}
import org.apache.kafka.common.utils.Time
class ZookeeperUtils @Inject() (config: AppConfig) {
val testTopic = "users_1"
val zkHost = config.KafkaConfig.zkHost
val sessionTimeoutMs = 10 * 1000
val connectionTimeoutMs = 60 * 1000
val isSecure = false
val maxInFlightRequests = 10
val time: Time = Time.SYSTEM
def cleanupTopic(config: AppConfig) = {
val zkClient = KafkaZkClient.apply(zkHost, isSecure, sessionTimeoutMs, connectionTimeoutMs, maxInFlightRequests, time)
val zkUtils = new AdminZkClient(zkClient)
val pp = new Properties()
pp.setProperty("delete.retention.ms", "10")
pp.setProperty("file.delete.delay.ms", "1000")
zkUtils.changeTopicConfig(testTopic , pp)
// zkUtils.deleteTopic(testTopic)
println("Waiting for topic to be purged. Then reset to retain records for the run")
Thread.sleep(60000L)
val resetProps = new Properties()
resetProps.setProperty("delete.retention.ms", "3000000")
resetProps.setProperty("file.delete.delay.ms", "4000000")
zkUtils.changeTopicConfig(testTopic , resetProps)
}
}
There is an option delete topic. But, it marks the topic for deletion. Zookeeper later deletes the topic. Since this can be unpredictably long, I prefer the retention.ms approach
I was getting the same "cannot find symbol" error when I did Build -> Make Project
. I fixed this by deleting my Maven /target
folder, right clicking my project module and doing Maven -> Reimport
, and doing Build -> Rebuild Project
. This was on IntelliJ Idea 13.1.5.
It turns out the Maven -> Reimport
was key, since the problem resurfaced a few times before I finally did that.
For linux systems, you can – starting from major version 20.04
of the docker engine – now also communicate with the host via host.docker.internal
. This won't work automatically, but you need to provide the following run flag:
--add-host=host.docker.internal:host-gateway
See
Try display: inline-block;
. For it to be cross browser compatible please use the below css code.
div {_x000D_
display: inline-block;_x000D_
display:-moz-inline-stack;_x000D_
zoom:1;_x000D_
*display:inline;_x000D_
border-style: solid;_x000D_
border-color: #0000ff;_x000D_
}
_x000D_
<div>_x000D_
<table>_x000D_
<tr>_x000D_
<td>Column1</td>_x000D_
<td>Column2</td>_x000D_
<td>Column3</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
I would suggest using NVM to keep different versions of node and npm and then install the compatible angular-cli
If you have issue with writing into an existing xls file because it is already created you need to put checking part like below:
PATH='filename.xlsx'
if os.path.isfile(PATH):
print "File exists and will be overwrite NOW"
else:
print "The file is missing, new one is created"
... and here part with the data you want to add
There's no readily available syntax to do this in the original Markdown syntax, but Markdown Extra provides a means to at least assign IDs to headers — which you can then link to easily. Note also that you can use regular HTML in both Markdown and Markdown Extra, and that the name
attribute has been superseded by the id
attribute in more recent versions of HTML.
I'd use popen() (++waqas).
But sometimes you need reading and writing...
It seems like nobody does things the hard way any more.
(Assuming a Unix/Linux/Mac environment, or perhaps Windows with a POSIX compatibility layer...)
enum PIPE_FILE_DESCRIPTERS
{
READ_FD = 0,
WRITE_FD = 1
};
enum CONSTANTS
{
BUFFER_SIZE = 100
};
int
main()
{
int parentToChild[2];
int childToParent[2];
pid_t pid;
string dataReadFromChild;
char buffer[BUFFER_SIZE + 1];
ssize_t readResult;
int status;
ASSERT_IS(0, pipe(parentToChild));
ASSERT_IS(0, pipe(childToParent));
switch (pid = fork())
{
case -1:
FAIL("Fork failed");
exit(-1);
case 0: /* Child */
ASSERT_NOT(-1, dup2(parentToChild[READ_FD], STDIN_FILENO));
ASSERT_NOT(-1, dup2(childToParent[WRITE_FD], STDOUT_FILENO));
ASSERT_NOT(-1, dup2(childToParent[WRITE_FD], STDERR_FILENO));
ASSERT_IS(0, close(parentToChild [WRITE_FD]));
ASSERT_IS(0, close(childToParent [READ_FD]));
/* file, arg0, arg1, arg2 */
execlp("ls", "ls", "-al", "--color");
FAIL("This line should never be reached!!!");
exit(-1);
default: /* Parent */
cout << "Child " << pid << " process running..." << endl;
ASSERT_IS(0, close(parentToChild [READ_FD]));
ASSERT_IS(0, close(childToParent [WRITE_FD]));
while (true)
{
switch (readResult = read(childToParent[READ_FD],
buffer, BUFFER_SIZE))
{
case 0: /* End-of-File, or non-blocking read. */
cout << "End of file reached..." << endl
<< "Data received was ("
<< dataReadFromChild.size() << "): " << endl
<< dataReadFromChild << endl;
ASSERT_IS(pid, waitpid(pid, & status, 0));
cout << endl
<< "Child exit staus is: " << WEXITSTATUS(status) << endl
<< endl;
exit(0);
case -1:
if ((errno == EINTR) || (errno == EAGAIN))
{
errno = 0;
break;
}
else
{
FAIL("read() failed");
exit(-1);
}
default:
dataReadFromChild . append(buffer, readResult);
break;
}
} /* while (true) */
} /* switch (pid = fork())*/
}
You also might want to play around with select() and non-blocking reads.
fd_set readfds;
struct timeval timeout;
timeout.tv_sec = 0; /* Seconds */
timeout.tv_usec = 1000; /* Microseconds */
FD_ZERO(&readfds);
FD_SET(childToParent[READ_FD], &readfds);
switch (select (1 + childToParent[READ_FD], &readfds, (fd_set*)NULL, (fd_set*)NULL, & timeout))
{
case 0: /* Timeout expired */
break;
case -1:
if ((errno == EINTR) || (errno == EAGAIN))
{
errno = 0;
break;
}
else
{
FAIL("Select() Failed");
exit(-1);
}
case 1: /* We have input */
readResult = read(childToParent[READ_FD], buffer, BUFFER_SIZE);
// However you want to handle it...
break;
default:
FAIL("How did we see input on more than one file descriptor?");
exit(-1);
}
Use String.Format with alignment values.
For example:
String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);
To create one formatted row.
For your information, the python equivalent is:
imageBuffer = cv.LoadImage( strSrc )
nW = new X size
nH = new Y size
smallerImage = cv.CreateImage( (nH, nW), imageBuffer.depth, imageBuffer.nChannels )
cv.Resize( imageBuffer, smallerImage , interpolation=cv.CV_INTER_CUBIC )
cv.SaveImage( strDst, smallerImage )
Just for posterity, here's the text from several external sources regarding the Excel file formats. Some of these have been mentioned in other answers to this question but without reproducing the essential content.
1. From Doug Mahugh, August 22, 2006:
...the new XLSB binary format. Like Open XML, it’s a full-fidelity file format that can store anything you can create in Excel, but the XLSB format is optimized for performance in ways that aren’t possible with a pure XML format.
The XLSB format (also sometimes referred to as BIFF12, as in “binary file format for Office 12”) uses the same Open Packaging Convention used by the Open XML formats and XPS. So it’s basically a ZIP container, and you can open it with any ZIP tool to see what’s inside. But instead of .XML parts within the package, you’ll find .BIN parts...
This article also refers to documentation about the BIN format, too lengthy to reproduce here.
2. From MSDN Archive, August 29, 2006 which in turn cites an already-missing blog post regarding the XLSB format:
Even though we’ve done a lot of work to make sure that our XML formats open quickly and efficiently, this binary format is still more efficient for Excel to open and save, and can lead to some performance improvements for workbooks that contain a lot of data, or that would require a lot of XML parsing during the Open process. (In fact, we’ve found that the new binary format is faster than the old XLS format in many cases.) Also, there is no macro-free version of this file format – all XLSB files can contain macros (VBA and XLM). In all other respects, it is functionally equivalent to the XML file format above:
File size – file size of both formats is approximately the same, since both formats are saved to disk using zip compression Architecture – both formats use the same packaging structure, and both have the same part-level structures. Feature support – both formats support exactly the same feature set Runtime performance – once loaded into memory, the file format has no effect on application/calculation speed Converters – both formats will have identical converter support
Here's an example:
fun main(args: Array<String>) {
val arr = arrayOf(1, 2, 3);
for (item in arr) {
println(item);
}
}
You can also use a playground to test language features.
Another difference between bool and BOOL is that they do not convert exactly to the same kind of objects, when you do key-value observing, or when you use methods like -[NSObject valueForKey:].
As everybody has said here, BOOL is char. As such, it is converted to an NSNumber holding a char. This object is indistinguishable from an NSNumber created from a regular char like 'A' or '\0'. You have totally lost the information that you originally had a BOOL.
However, bool is converted to an CFBoolean, which behaves the same as NSNumber, but which retains the boolean origin of the object.
I do not think that this is an argument in a BOOL vs. bool debate, but this may bite you one day.
Generally speaking, you should go with BOOL, since this is the type used everywhere in the Cocoa/iOS APIs (designed before C99 and its native bool type).
I like to do it like this:
par(oma=c(0, 0, 0, 5))
plot(1:3, rnorm(3), pch=1, lty=1, type="o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch=2, lty=2, type="o")
legend(par('usr')[2], par('usr')[4], bty='n', xpd=NA,
c("group A", "group B"), pch=c(1, 2), lty=c(1,2))
The only tweaking required is in setting the right margin to be wide enough to accommodate the legend.
However, this can also be automated:
dev.off() # to reset the graphics pars to defaults
par(mar=c(par('mar')[1:3], 0)) # optional, removes extraneous right inner margin space
plot.new()
l <- legend(0, 0, bty='n', c("group A", "group B"),
plot=FALSE, pch=c(1, 2), lty=c(1, 2))
# calculate right margin width in ndc
w <- grconvertX(l$rect$w, to='ndc') - grconvertX(0, to='ndc')
par(omd=c(0, 1-w, 0, 1))
plot(1:3, rnorm(3), pch=1, lty=1, type="o", ylim=c(-2, 2))
lines(1:3, rnorm(3), pch=2, lty=2, type="o")
legend(par('usr')[2], par('usr')[4], bty='n', xpd=NA,
c("group A", "group B"), pch=c(1, 2), lty=c(1, 2))
For me, it was ComponentName.prototype
instead of ComponentName.propTypes
.
auto suggested by Phpstorm
IDE. Hope it will help someone.
Here's what u can also try....
run your application....while it is still running launch your command prompt
while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.
Suggestions to fix it:
If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)
Modify the settings so they read:
MaxUserPort = dword:00004e20 (10,000 decimal) TcpTimedWaitDelay = dword:0000001e (30 decimal)
This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.
Only use suggestion 2 if 1 fails.
Thank you.
In addition to the accepted answer, one other check is to make sure that you have the right reference to your entity package in sessionFactory.setPackagesToScan(...) while setting up your session factory.
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
To list any process listening to the port 8080:
lsof -i:8080
To kill any process listening to the port 8080:
kill $(lsof -t -i:8080)
or more violently:
kill -9 $(lsof -t -i:8080)
(-9
corresponds to the SIGKILL - terminate immediately/hard kill
signal: see List of Kill Signals and What is the purpose of the -9 option in the kill command?. If no signal is specified to kill
, the TERM signal a.k.a. -15
or soft kill
is sent, which sometimes isn't enough to kill a process.).
Try to sort items by creation time. Example below sorts files in a folder and gets first element which is latest.
import glob
import os
files_path = os.path.join(folder, '*')
files = sorted(
glob.iglob(files_path), key=os.path.getctime, reverse=True)
print files[0]
I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.
you could use powershell script like this
$sb = new-object System.Text.StringBuilder
foreach ($file in Get-ChildItem -path 'C:\temp\xx\') {
$content = Get-Content -Path $file.fullname
$sb.Append($content)
}
Out-File -FilePath 'C:\temp\xx\c.txt' -InputObject $sb.toString()
Visual studio command prompt is nothing but the regular command prompt where few environment variables are set by default. This variables are set in the batch script : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat . So basically to get a visual studio command prompt for a particular version, just open regular command prompt and run this batch script : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat (Change the visual studio version based on your installed version). Voila you have got the visual studio command prompt. You can write a script to run the batch file and open cmd.exe.
but classes are so 2018
ScrollToTop.js
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return (null);
}
export default withRouter(ScrollToTop);
Usage:
<Router>
<Fragment>
<ScrollToTop />
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</Fragment>
</Router>
ScrollToTop can also be implemented as a wrapper component:
ScrollToTop.js
import React, { useEffect, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history, children }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return <Fragment>{children}</Fragment>;
}
export default withRouter(ScrollToTop);
Usage:
<Router>
<ScrollToTop>
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</ScrollToTop>
</Router>
var data="your data";//ex data="id="+id;
$.ajax({
method : "POST",
url : "file name", //url: "demo.php"
data : "data",
success : function(result){
//set result to div or target
//ex $("#divid).html(result)
}
});
Change the signature of the CreateFile
method to expect a SupportedPermissions
value instead of plain Enum.
public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
return file.Id;
}
Then when you call your method you pass the SupportedPermissions
value to your method
var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);
To answer my own question: to release the connection (and any other resources associated with the request) you must close the InputStream returned by the HttpEntity:
InputStream is = entity.getContent();
.... process the input stream ....
is.close(); // releases all resources
From the docs
You need to extend FragmentActivity
instead of Activity
You can use npm view [module] version, npm info [module] version, npm show [module] version or npm v [module] version to check the version on an installed npm module.
Let's suppose my grunt module version is the 0.4.5:
npm view grunt version => 0.4.5
npm info grunt version => 0.4.5
npm show grunt version => 0.4.5
npm v grunt version => 0.4.5
These tips on MySQL and UTF-8 may be helpful. Unfortunately, they don't constitute a full solution, just common gotchas.
Well, it actually looks like the warning is telling you what to do.
As part of sklearn.pipeline
stages' uniform interfaces, as a rule of thumb:
when you see X
, it should be an np.array
with two dimensions
when you see y
, it should be an np.array
with a single dimension.
Here, therefore, you should consider the following:
temp = [1,2,3,4,5,5,6,....................,7]
# This makes it into a 2d array
temp = np.array(temp).reshape((len(temp), 1))
temp = scaler.transform(temp)
Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.
Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.
If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.
If you are using jackson you can easily achieve this with configuring a SerializationFeature
in your ObjectMapper
:
com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeValueAsString(<yourObject>);
Thats it.
You have to hide the column at the grid view control rather than at the data source. Hiding it at the data source it will not render to the grid view at all, therefore you won't be able to access the value in the grid view. Doing it the way you're suggesting, you would have to access the column value through the data source as opposed to the grid view.
To hide the column on the grid view control, you can use code like this:
dataGridView1.Columns[0].Visible = false;
To access the column from the data source, you could try something like this:
object colValue = ((DataTable)dataGridView.DataSource).Rows[dataSetIndex]["ColumnName"];
You have to retrieve it from the HOST
header.
var host = req.get('host');
It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.
If this is for supporting cross-origin requests, you would instead use the Origin
header.
var origin = req.get('origin');
Note that some cross-origin requests require validation through a "preflight" request:
req.options('/route', function (req, res) {
var origin = req.get('origin');
// ...
});
If you're looking for the client's IP, you can retrieve that with:
var userIP = req.socket.remoteAddress;
Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.
For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.
Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4
columns_to_overwrite = ["column_1", "column_3"]
First delete the columns that you intend to replace...
original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)
... then re-insert the columns, but using the values that you intended to overwrite
original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]
I optimized the javascript code from cameronjonesweb a little bit. Now you can just add the clips into the array. Everything else is done automatically.
<video autoplay controls id="Player" src="http://www.w3schools.com/html/movie.mp4" onclick="this.paused ? this.play() : this.pause();">Your browser does not support the video tag.</video>
<script>
var nextsrc = ["http://www.w3schools.com/html/movie.mp4","http://www.w3schools.com/html/mov_bbb.mp4"];
var elm = 0; var Player = document.getElementById('Player');
Player.onended = function(){
if(++elm < nextsrc.length){
Player.src = nextsrc[elm]; Player.play();
}
}
</script>
A simple solution is to use Microsoft ASP.NET Web API 2.2 Client
from NuGet.
Then you can simply do this and it'll serialize the object to JSON and set the Content-Type
header to application/json; charset=utf-8
:
var data = new
{
name = "Foo",
category = "article"
};
var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var response = await client.PostAsJsonAsync("", data);
With Windows PowerShell you can use:
Get-Content <file> -Wait
Use this query:
UPDATE `table` SET date_date=now();
Sample code can be:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE `table` SET date_date=now()");
mysql_close($con);
?>
If you're looking to access the current page from within your functions.php file (so, before the loop, before $post
is populated, before $wp_query
is initialized, etc...) you really have no choice but to access the server variables themselves and extract the requested page from the query string.
$page_slug = trim( $_SERVER["REQUEST_URI"] , '/' )
Note that this is a "dumb" solution. It doesn't know, for instance that the page with the slug 'coming-soon' is also p=6
. And it assumes that your permalink settings are set to pagename
(which they should be anyway!).
Still, can be a useful little trick if you have a controlled scenario. I'm using this in a situation where I wish to redirect non-logged in visitors to a "coming soon" page; but I have to make sure that I'm not throwing them into the dreaded "redirect loop", so I need to exclude the "coming soon" page from this rule:
global $pagenow;
if (
! is_admin() &&
'wp-login.php' != $pagenow &&
'coming-soon' != trim( $_SERVER["REQUEST_URI"] , '/' ) &&
! is_user_logged_in()
){
wp_safe_redirect( 'coming-soon' );
}
An empty String is a wrapper on a char[]
with no elements. You can have an empty char[]
. But you cannot have an "empty" char
. Like other primitives, a char
has to have a value.
You say you want to "replace a character without leaving a space".
If you are dealing with a char[]
, then you would create a new char[]
with that element removed.
If you are dealing with a String
, then you would create a new String
(String is immutable) with the character removed.
Here are some samples of how you could remove a char:
public static void main(String[] args) throws Exception {
String s = "abcdefg";
int index = s.indexOf('d');
// delete a char from a char[]
char[] array = s.toCharArray();
char[] tmp = new char[array.length-1];
System.arraycopy(array, 0, tmp, 0, index);
System.arraycopy(array, index+1, tmp, index, tmp.length-index);
System.err.println(new String(tmp));
// delete a char from a String using replace
String s1 = s.replace("d", "");
System.err.println(s1);
// delete a char from a String using StringBuilder
StringBuilder sb = new StringBuilder(s);
sb.deleteCharAt(index);
s1 = sb.toString();
System.err.println(s1);
}
Most probably your server socket is bound to the loopback IP address 127.0.0.1
instead of the "all IP addresses" symbolic IP 0.0.0.0
(note this is NOT a netmask). To confirm this, run sudo netstat -ntlp
(If you are on linux) or netstat -an -f inet -p tcp | grep LISTEN
(OSX) and check which IP your process is bound to (look for the line with ":3000"). If you see "127.0.0.1", that's the problem. Fix it by passing "0.0.0.0" to the listen
call:
var app = connect().use(connect.static('public')).listen(3000, "0.0.0.0");
I have similar scenario where I need to add filters based on the user input and I chain the where clause.
Here is the sample code.
var votes = db.Votes.Where(r => r.SurveyID == surveyId);
if (fromDate != null)
{
votes = votes.Where(r => r.VoteDate.Value >= fromDate);
}
if (toDate != null)
{
votes = votes.Where(r => r.VoteDate.Value <= toDate);
}
votes = votes.Take(LimitRows).OrderByDescending(r => r.VoteDate);
You could easily replace the forward slashes /
with something like an underscore _
such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.
Here is how I did to download quickly with cURL (I'm not sure how many files it can download though) :
setlocal EnableDelayedExpansion
cd where\to\download
set STR=
for /f "skip=2 delims=" %%F in ('P:\curl -l -u user:password ftp://ftp.example.com/directory/anotherone/') do set STR=-O "ftp://ftp.example.com/directory/anotherone/%%F" !STR!
path\to\curl.exe -v -u user:password !STR!
Why skip=2 ?
To get ride of .
and ..
Why delims= ? To support names with spaces
For those who tried gkalpak answer and it did not work,
be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes
ios will always tries to take the best image, but will fall back to other options .. so if you only have normal images in the app and it needs @2x images it will use the normal images.
if you only put @2x in the project and you open the app on a normal device it will scale the images down to display.
if you target ios7 and ios8 devices and want best quality you would need @2x and @3x for phone and normal and @2x for ipad assets, since there is no non retina phone left and no @3x ipad.
maybe it is better to create the assets in the app from vector graphic... check http://mattgemmell.com/using-pdf-images-in-ios-apps/
Possibly a little bit of a necromancing post here, but...
here's a function that follows up to 10 redirects, and detects infinite redirect loops. also parses result into JSON
Note - uses a callback helper (shown at the end of this post)
( TLDR; full working demo in context here or remixed-version here)
function getJSON(url,cb){
var callback=errBack(cb);
//var callback=errBack(cb,undefined,false);//replace previous line with this to turn off logging
if (typeof url!=='string') {
return callback.error("getJSON:expecting url as string");
}
if (typeof cb!=='function') {
return callback.error("getJSON:expecting cb as function");
}
var redirs = [url],
fetch = function(u){
callback.info("hitting:"+u);
https.get(u, function(res){
var body = [];
callback.info({statusCode:res.statusCode});
if ([301,302].indexOf(res.statusCode)>=0) {
if (redirs.length>10) {
return callback.error("excessive 301/302 redirects detected");
} else {
if (redirs.indexOf(res.headers.location)<0) {
redirs.push(res.headers.location);
return fetch(res.headers.location);
} else {
return callback.error("301/302 redirect loop detected");
}
}
} else {
res.on('data', function(chunk){
body.push(chunk);
callback.info({onData:{chunkSize:chunk.length,chunks:body.length}});
});
res.on('end', function(){
try {
// convert to a single buffer
var json = Buffer.concat(body);
console.info({onEnd:{chunks:body.length,bodyLength:body.length}});
// parse the buffer as json
return callback.result(JSON.parse(json),json);
} catch (err) {
console.error("exception in getJSON.fetch:",err.message||err);
if (json.length>32) {
console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
} else {
console.error("json==>|"+json.toString('utf-8')+"|<=== json");
}
return callback.error(err,undefined,json);
}
});
}
});
};
fetch(url);
}
Note - uses a callback helper (shown below)
you can paste this into the node console and it should run as is.
( or for full working demo in context see here )
var
fs = require('fs'),
https = require('https');
function errBack (cb,THIS,logger) {
var
self,
EB=function(fn,r,e){
if (logger===false) {
fn.log=fn.info=fn.warn=fn.errlog=function(){};
} else {
fn.log = logger?logger.log : console.log.bind(console);
fn.info = logger?logger.info : console.info.bind(console);
fn.warn = logger?logger.warn : console.warn.bind(console);
fn.errlog = logger?logger.error : console.error.bind(console);
}
fn.result=r;
fn.error=e;
return (self=fn);
};
if (typeof cb==='function') {
return EB(
logger===false // optimization when not logging - don't log errors
? function(err){
if (err) {
cb (err);
return true;
}
return false;
}
: function(err){
if (err) {
self.errlog(err);
cb (err);
return true;
}
return false;
},
function () {
return cb.apply (THIS,Array.prototype.concat.apply([undefined],arguments));
},
function (err) {
return cb.apply (THIS,Array.prototype.concat.apply([typeof err==='string'?new Error(err):err],arguments));
}
);
} else {
return EB(
function(err){
if (err) {
if (typeof err ==='object' && err instanceof Error) {
throw err;
} else {
throw new Error(err);
}
return true;//redundant due to throw, but anyway.
}
return false;
},
logger===false
? self.log //optimization :resolves to noop when logger==false
: function () {
self.info("ignoring returned arguments:",Array.prototype.concat.apply([],arguments));
},
function (err) {
throw typeof err==='string'?new Error(err):err;
}
);
}
}
function getJSON(url,cb){
var callback=errBack(cb);
if (typeof url!=='string') {
return callback.error("getJSON:expecting url as string");
}
if (typeof cb!=='function') {
return callback.error("getJSON:expecting cb as function");
}
var redirs = [url],
fetch = function(u){
callback.info("hitting:"+u);
https.get(u, function(res){
var body = [];
callback.info({statusCode:res.statusCode});
if ([301,302].indexOf(res.statusCode)>=0) {
if (redirs.length>10) {
return callback.error("excessive 302 redirects detected");
} else {
if (redirs.indexOf(res.headers.location)<0) {
redirs.push(res.headers.location);
return fetch(res.headers.location);
} else {
return callback.error("302 redirect loop detected");
}
}
} else {
res.on('data', function(chunk){
body.push(chunk);
console.info({onData:{chunkSize:chunk.length,chunks:body.length}});
});
res.on('end', function(){
try {
// convert to a single buffer
var json = Buffer.concat(body);
callback.info({onEnd:{chunks:body.length,bodyLength:body.length}});
// parse the buffer as json
return callback.result(JSON.parse(json),json);
} catch (err) {
// read with "bypass refetch" option
console.error("exception in getJSON.fetch:",err.message||err);
if (json.length>32) {
console.error("json==>|"+json.toString('utf-8').substr(0,32)+"|<=== ... (+"+(json.length-32)+" more bytes of json)");
} else {
console.error("json==>|"+json.toString('utf-8')+"|<=== json");
}
return callback.error(err,undefined,json);
}
});
}
});
};
fetch(url);
}
var TLDs,TLDs_fallback = "com.org.tech.net.biz.info.code.ac.ad.ae.af.ag.ai.al.am.ao.aq.ar.as.at.au.aw.ax.az.ba.bb.bd.be.bf.bg.bh.bi.bj.bm.bn.bo.br.bs.bt.bv.bw.by.bz.ca.cc.cd.cf.cg.ch.ci.ck.cl.cm.cn.co.cr.cu.cv.cw.cx.cy.cz.de.dj.dk.dm.do.dz.ec.ee.eg.er.es.et.eu.fi.fj.fk.fm.fo.fr.ga.gb.gd.ge.gf.gg.gh.gi.gl.gm.gn.gp.gq.gr.gs.gt.gu.gw.gy.hk.hm.hn.hr.ht.hu.id.ie.il.im.in.io.iq.ir.is.it.je.jm.jo.jp.ke.kg.kh.ki.km.kn.kp.kr.kw.ky.kz.la.lb.lc.li.lk.lr.ls.lt.lu.lv.ly.ma.mc.md.me.mg.mh.mk.ml.mm.mn.mo.mp.mq.mr.ms.mt.mu.mv.mw.mx.my.mz.na.nc.ne.nf.ng.ni.nl.no.np.nr.nu.nz.om.pa.pe.pf.pg.ph.pk.pl.pm.pn.pr.ps.pt.pw.py.qa.re.ro.rs.ru.rw.sa.sb.sc.sd.se.sg.sh.si.sj.sk.sl.sm.sn.so.sr.st.su.sv.sx.sy.sz.tc.td.tf.tg.th.tj.tk.tl.tm.tn.to.tr.tt.tv.tw.tz.ua.ug.uk.us.uy.uz.va.vc.ve.vg.vi.vn.vu.wf.ws.ye.yt.za.zm.zw".split(".");
var TLD_url = "https://gitcdn.xyz/repo/umpirsky/tld-list/master/data/en/tld.json";
var TLD_cache = "./tld.json";
var TLD_refresh_msec = 15 * 24 * 60 * 60 * 1000;
var TLD_last_msec;
var TLD_default_filter=function(dom){return dom.substr(0,3)!="xn-"};
function getTLDs(cb,filter_func){
if (typeof cb!=='function') return TLDs;
var
read,fetch,
CB_WRAP=function(tlds){
return cb(
filter_func===false
? cb(tlds)
: tlds.filter(
typeof filter_func==='function'
? filter_func
: TLD_default_filter)
);
},
check_mtime = function(mtime) {
if (Date.now()-mtime > TLD_refresh_msec) {
return fetch();
}
if (TLDs) return CB_WRAP (TLDs);
return read();
};
fetch = function(){
getJSON(TLD_url,function(err,data){
if (err) {
console.log("exception in getTLDs.fetch:",err.message||err);
return read(true);
} else {
TLDs=Object.keys(data);
fs.writeFile(TLD_cache,JSON.stringify(TLDs),function(err){
if (err) {
// ignore save error, we have the data
CB_WRAP(TLDs);
} else {
// get mmtime for the file we just made
fs.stat(TLD_cache,function(err,stats){
if (!err && stats) {
TLD_last_msec = stats.mtimeMs;
}
CB_WRAP(TLDs);
});
}
});
}
});
};
read=function(bypassFetch) {
fs.readFile(TLD_cache,'utf-8',function(err,json){
try {
if (err) {
if (bypassFetch) {
// after a http errror, we fallback to hardcoded basic list of tlds
// if the disk file is not readable
console.log("exception in getTLDs.read.bypassFetch:",err.messsage||err);
throw err;
}
// if the disk read failed, get the data from the CDN server instead
return fetch();
}
TLDs=JSON.parse(json);
if (bypassFetch) {
// we need to update stats here as fetch called us directly
// instead of being called by check_mtime
return fs.stat(TLD_cache,function(err,stats){
if (err) return fetch();
TLD_last_msec =stats.mtimeMs;
return CB_WRAP(TLDs);
});
}
} catch (e){
// after JSON error, if we aren't in an http fail situation, refetch from cdn server
if (!bypassFetch) {
return fetch();
}
// after a http,disk,or json parse error, we fallback to hardcoded basic list of tlds
console.log("exception in getTLDs.read:",err.messsage||err);
TLDs=TLDs_fallback;
}
return CB_WRAP(TLDs);
});
};
if (TLD_last_msec) {
return check_mtime(TLD_last_msec);
} else {
fs.stat(TLD_cache,function(err,stats){
if (err) return fetch();
TLD_last_msec =stats.mtimeMs;
return check_mtime(TLD_last_msec);
});
}
}
getTLDs(console.log.bind(console));
Here is a list of python packages that implement Trie:
You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl"
android:state_pressed="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_checked="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />
</selector>
Here you can use 3 different images for radiobutton
and use this file to RadioButton like:
android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content"
I prefer to use "await" command and async functions to get rid of confusions of promises,
In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :
async function SubFunction(output){
// Call to database , returns a promise, like an Ajax call etc :
const response = await axios.get( GetApiHost() + '/api/some_endpoint')
// Return :
return response;
}
and then I would call this function from main function :
async function justTesting() {
const lv_result = await SubFunction(output);
return lv_result + 1;
}
Noting that I returned both main function and sub function to async functions here.
This line add in TableView
cell:
static var nib : UINib{
return UINib(nibName: identifier, bundle: nil)
}
static var identifier : String{
return String(describing: self)
}
And register in viewcontroller like
//This line use in viewdid load
tableview.register(TopDealLikedTableViewCell.nib, forCellReuseIdentifier: TopDealLikedTableViewCell.identifier)
// cell for row at indexpath
if let cell = tableView.dequeueReusableCell(withIdentifier:
TopDealLikedTableViewCell.identifier) as? TopDealLikedTableViewCell{
return cell
}
return UITableViewCell()
you need to make county_ID
as index for the right frame:
frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
on=[ 'countyid' ], how='left' )
for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.
so you need to verify integrity before joining by , verify_integrity=True
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
Like the following. It will make the user database owner.
EXEC sp_addrolemember N'db_owner', N'USerNAme'
Alternatively, if you do not wish to push to a repository:
Export the container to a tarball
docker export <CONTAINER ID> > /home/export.tar
Move your tarball to new machine
Import it back
cat /home/export.tar | docker import - some-name:latest
You can add this in your stylesheet: @page{size:auto; margin:5mm;}
But this discards the page number too
You can redirect the output to /dev/null
. For more info regarding /dev/null read this link.
You can hide the output of a comand in the following ways :
echo -n "Installing nano ......"; yum install nano > /dev/null; echo " done.";
Redirect the standard output to /dev/null
, but not the standard error. This will show the errors occurring during the installation, for example if yum
cannot find a package.
echo -n "Installing nano ......"; yum install nano &> /dev/null; echo " done.";
While this code will not show anything in the terminal since both standard error and standard output are redirected and thus nullified to /dev/null
.
using System;
class Solution
{
static string timeConversion(string s)
{
return DateTime.Parse(s).ToString("HH:mm");
}
static void Main(string[] args)
{
Console.WriteLine(timeConversion("01:00 PM"));
Console.Read();
}
}
Looking under the hood, the two statements will be transformed into different query representations. Depending on the QueryProvider
of Collection
, this might be optimized away or not.
When this is a linq-to-object call, multiple where clauses will lead to a chain of IEnumerables that read from each other. Using the single-clause form will help performance here.
When the underlying provider translates it into a SQL statement, the chances are good that both variants will create the same statement.
For Some reason it is not working so we can do this by another way
just remove the line and add this :-
<a onclick="window.open ('http://www.foracure.org.au', ''); return false" href="javascript:void(0);"></a>
Good luck.
Because @User and @BiXiC asked for help with UTF-8 here a variation of the solution by @Matthew. (I'm not allowed to comment, so I'm answering.)
import unicodecsv as csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(toCSV)
This is the simplest query to retrive all Columns and Tables
SELECT * FROM information_schema.`COLUMNS` C WHERE TABLE_SCHEMA = 'YOUR_DATABASE'
All the tables or those with specific string in name could be searched via Search tab in phpMyAdmin.
Have Nice Query... \^.^/
Swift 3 version (butt_img must be an Image Set into Assets.xcassets or Images.xcassets folder in Xcode):
btnTwo.setBackgroundImage(UIImage(named: "butt_img"), for: .normal)
btnTwo.setTitle("My title", for: .normal)
Anyway, if you want the image to be scaled to fill the button's size, you may add a UIImageView
over it and assign it your image:
let img = UIImageView()
img.frame = btnTwo.frame
img.contentMode = .scaleAspectFill
img.clipsToBounds = true
img.image = UIImage(named: "butt_img")
btnTwo.addSubview(img)
A simple question should be followed by a short, simple and clear answer.
When we are getting a value of the property it fires its get{}
part.
When we are setting a value to the property it fires its set{}
part.
PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{}
part.
Example:
var A:Int = 0
var B:Int = 0
var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
B = newValue
}
}
//When we are getting a value of C it fires get{} part of C property
A = C
A //Now A = 1
//When we are setting a value to C it fires set{} part of C property
C = 2
B //Now B = 2
exit code 139 (people say this means memory fragmentation)
No, it means that your program died with signal 11
(SIGSEGV
on Linux and most other UNIXes), also known as segmentation fault
.
Could anybody tell me why the run fails but debug doesn't?
Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).
Your first step should be running this program under Valgrind, and fixing all errors it reports.
If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out
) and then analyze that core dump with GDB: gdb ./a.out core
; then use where
command.
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
At last i did it Thanks alot friends, and a special thanks to Mr https://stackoverflow.com/users/87015/salman-a because of his code i was able to solve it properly. finally my code is looking like this as i am using groovy grails i hope this will help somebody there.. Thanks alot
html code looks like this in my gsp page
<input id="populate-dropdown" name="nameofClient" type="text">
<input id="wilhaveid" name="idofclient" type="text">
script Function is like this in my gsp page
<script>
$( "#populate-dropdown").on('input', function() {
$.ajax({
url:'autoCOmp',
data: {inputField: $("#populate-dropdown").val()},
success: function(resp){
$('#populate-dropdown').autocomplete({
source:resp,
select: function (event, ui) {
$("#populate-dropdown").val(ui.item.label);
$("#wilhaveid").val(ui.item.value);
return false;
}
})
}
});
});
</script>
And my controller code is like this
def autoCOmp(){
println(params)
def c = Client.createCriteria()
def results = c.list {
like("nameOfClient", params.inputField+"%")
}
def itemList = []
results.each{
itemList << [value:it.id,label:it.nameOfClient]
}
println(itemList)
render itemList as JSON
}
One more thing i have not set id field hidden because at first i was checking that i am getting the exact id , you can keep it hidden just put type=hidden instead of text for second input item in html
Thanks !
An Open Source alternative is Nominatim from Open Street Map. All you have to do is set the variables in an URL and it returns the city/country of that location. Please check the following link for official documentation: Nominatim
To avoid blinking problem use following code
its not mouseover and mouseout instead of that use mouseenter and mouseleave
**app.component.html**
<div (mouseenter)="changeText=true" (mouseleave)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
**app.component.ts**
@Component({
selector: 'app-main',
templateUrl: './app.component.html'
})
export class AppComponent {
changeText: boolean;
constructor() {
this.changeText = false;
}
}
Being relatively new to Python I'm not sure what the most common idiom is, but the simplest thing I can think of is just using a module instead of a class. What would have been instance methods on your class become just functions in the module and any data just becomes variables in the module instead of members of the class. I suspect this is the pythonic approach to solving the type of problem that people use singletons for.
If you really want a singleton class, there's a reasonable implementation described on the first hit on Google for "Python singleton", specifically:
class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise Singleton.__single
Singleton.__single = self
That seems to do the trick.
I am in the same boat as the OP.
Using a Windows command prompt, from directory:
C:\Python34\Scripts>
pip install wheel
seemed to work.
Changing directory to where the whl was located, it just tells me 'pip is not recognized'. Going back to C:\Python34\Scripts>
, then using the full command above to provide the 'where/its/downloaded' location, it says Requirement 'scikit_image-...-win32.whl' looks like a filename, but the filename does not exist
.
So I dropped a copy of the .whl in Python34/Scripts, ran the exact same command over again (with the --find-links=
still going to the other folder), and this time it worked.
After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?
//Check to see if we get rows back, if we do just bind.
if (dtFunding.Rows.Count != 0)
{
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
}
else
{
//Other wise add a emtpy "New Row" to the datatable and then hide it after binding.
dtFunding.Rows.Add(dtFunding.NewRow());
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
grdFunding.Rows[0].Visible = false;
}
Personally I preferred to insert a 1. *
at the very beginning. So the expression become something like this:
1. * (20-10) / (100-10)
As I always do a division for some formula like:
accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)
so it is impossible to simply add a .0
like 20.0
. And in my case, wrapping with a float()
may lose a little bit readability.
In case you need to nest more than one null coalescing operation such as:
model?.data()?.first()
This is not a problem easily solved with or
. It also cannot be solved with .get()
which requires a dictionary type or similar (and cannot be nested anyway) or getattr()
which will throw an exception when NoneType doesn't have the attribute.
The relevant pip considering adding null coalescing to the language is PEP 505 and the discussion relevant to the document is in the python-ideas thread.
Try
namenode -format
start-all.sh
stop-all.sh
jps
see namenode
and datanode
are running and browse
localhost:50070
If localhost:50070
is still not working, then you need to allows ports. So, check
netstat -anp | grep 50070
in
wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:
$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d'
10000000 loops, best of 3: 0.0983 usec per loop
$ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)'
1000000 loops, best of 3: 0.21 usec per loop
While the following observation is not always true, you'll notice that usually, in Python, the faster solution is more elegant and Pythonic; that's why -mtimeit
is SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)
You may want to look into to Simple Logging Facade for Java (SLF4J). It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.
I might be a bit late for the party but I follow below steps to make it fully configurable using IntelliJ's way of in-IDE app test. I believe the best way to go with is to Combine below with @BelusC's answer.
1. run the application using IDE's tomcat run config.
2. ps -ef | grep -i tomcat //this will give you a good idea about what the ide doing actually.
3. Copy the -Dcatalina.base parameter value from the command. this is your application specific catalina base. In this folder you can play with catalina.properties, application root path etc.. basically everything you have been doing is doable here too.
In your app config -
$httpProvider.defaults.transformRequest = function (data) {
if (data === undefined)
return data;
var clonedData = $.extend(true, {}, data);
for (var property in clonedData)
if (property.substr(0, 1) == '$')
delete clonedData[property];
return $.param(clonedData);
};
With your resource request -
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
This is a bit stupid maybe but the error message I got was Permission denied and it sent me spiralling down in a very wrong direction to attempt to solve it. (Here for example)
I haven't even added any bash script myself, I think one is added by nodejs image which I use.
FROM node:14.9.0
I was wrongly running to expose/connect the port on my local:
docker run -p 80:80 [name] . # this is wrong!
which gives
/usr/local/bin/docker-entrypoint.sh: 8: exec: .: Permission denied
But you shouldn't even have a dot in the end, it was added to documentation of another projects docker image by misstake. You should simply run:
docker run -p 80:80 [name]
I like Docker a lot but it's sad it has so many gotchas like this and not always very clear error messages...
C# is a programming language, .NET is the framework that the language is built on.
You can wait until the body is ready:
function onReady(callback) {_x000D_
var intervalId = window.setInterval(function() {_x000D_
if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
window.clearInterval(intervalId);_x000D_
callback.call(this);_x000D_
}_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
setVisible('.page', true);_x000D_
setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 100;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
background-color: rgba(192, 192, 192, 0.5);_x000D_
background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
background-repeat: no-repeat;_x000D_
background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
<h1>The standard Lorem Ipsum passage</h1>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
Here is a JSFiddle that demonstrates this technique.
As this is a very frequently asked question, I wanted to take the time and effort to explain the ViewPager with multiple Fragments and Layouts in detail. Here you go.
The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.
In this case, I have 3 Fragment classes, and a different layout file for each class. In order to keep things simple, the fragment-layouts only differ in their background color. Of course, any layout-file can be used for the Fragments.
FirstFragment.java has a orange background layout, SecondFragment.java has a green background layout and ThirdFragment.java has a red background layout. Furthermore, each Fragment displays a different text, depending on which class it is from and which instance it is.
Also be aware that I am using the support-library's Fragment: android.support.v4.app.Fragment
MainActivity.java (Initializes the Viewpager and has the adapter for it as an inner class). Again have a look at the imports. I am using the android.support.v4
package.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
case 3: return ThirdFragment.newInstance("ThirdFragment, Instance 2");
case 4: return ThirdFragment.newInstance("ThirdFragment, Instance 3");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
@Override
public int getCount() {
return 5;
}
}
}
activity_main.xml (The MainActivitys .xml file) - a simple layout file, only containing the ViewPager that fills the whole screen.
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
The Fragment classes, FirstFragment.java import android.support.v4.app.Fragment;
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
first_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_orange_dark" >
<TextView
android:id="@+id/tvFragFirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26dp"
android:text="TextView" />
</RelativeLayout>
SecondFragment.java
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
tv.setText(getArguments().getString("msg"));
return v;
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
second_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_green_dark" >
<TextView
android:id="@+id/tvFragSecond"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26dp"
android:text="TextView" />
</RelativeLayout>
ThirdFragment.java
public class ThirdFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.third_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragThird);
tv.setText(getArguments().getString("msg"));
return v;
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
third_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_light" >
<TextView
android:id="@+id/tvFragThird"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26dp"
android:text="TextView" />
</RelativeLayout>
The end result is the following:
The Viewpager holds 5 Fragments, Fragments 1 is of type FirstFragment, and displays the first_frag.xml layout, Fragment 2 is of type SecondFragment and displays the second_frag.xml, and Fragment 3-5 are of type ThirdFragment and all display the third_frag.xml.
Above you can see the 5 Fragments between which can be switched via swipe to the left or right. Only one Fragment can be displayed at the same time of course.
Last but not least:
I would recommend that you use an empty constructor in each of your Fragment classes.
Instead of handing over potential parameters via constructor, use the newInstance(...)
method and the Bundle
for handing over parameters.
This way if detached and re-attached the object state can be stored through the arguments. Much like Bundles
attached to Intents
.
If error comes for ".settings/language.settings.xml" or any such file you don't need to git.
Now if Staged file list empty, and Unstaged file list all files are marked as Ignored. You can pull. Otherwise, follow other answers.
add below line in styles.xml
<style name="AppTheme.Gray" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorButtonNormal">@color/colorGray</item>
</style>
in button, add android:theme="@style/AppTheme.Gray"
, example:
<Button
android:theme="@style/AppTheme.Gray"
android:textColor="@color/colorWhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@android:string/cancel"/>
Add the following in the base.mk file. The following 3rd line is important
-include $(TOP)/defs.mk
CFLAGS=$(DEBUG) -Wall -W -Wwrite-strings
CFLAGS_C=-Wmissing-prototypes
CFLAGS_CXX=-std=c++0x
LDFLAGS=
LIBS=
to avoid the #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options
You could also just use jQuery to remove the contents of the div that contains your svg.
$("#container_div_id").html("");
str.replace()
does fixed replacements. Use re.sub()
instead.
You can try running a simple web server based on Twisted
update table_name set field1 = field1 + 1;
Apparently, there are two most obvious ways to clear std::queue
: swapping with empty object and assignment to empty object.
I would suggest using assignment because it simply faster, more readable, and unambiguous.
I measured performance using following simple code and I found that swapping in C++03 version works 70-80% slower than assignment to an empty object. In C++11 there is no difference in performance, however. Anyway, I would go with assignment.
#include <algorithm>
#include <ctime>
#include <iostream>
#include <queue>
#include <vector>
int main()
{
std::cout << "Started" << std::endl;
std::queue<int> q;
for (int i = 0; i < 10000; ++i)
{
q.push(i);
}
std::vector<std::queue<int> > queues(10000, q);
const std::clock_t begin = std::clock();
for (std::vector<int>::size_type i = 0; i < queues.size(); ++i)
{
// OK in all versions
queues[i] = std::queue<int>();
// OK since C++11
// std::queue<int>().swap(queues[i]);
// OK before C++11 but slow
// std::queue<int> empty;
// std::swap(empty, queues[i]);
}
const double elapsed = double(clock() - begin) / CLOCKS_PER_SEC;
std::cout << elapsed << std::endl;
return 0;
}
I am using following code to decode base64 string in node API nodejs version 10.7.0
let data = 'c3RhY2thYnVzZS5jb20='; // Base64 string
let buff = new Buffer(data, 'base64'); //Buffer
let text = buff.toString('ascii'); //this is the data type that you want your Base64 data to convert to
console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"');
Please don't try to run above code in console of the browser, won't work. Put the code in server side files of nodejs. I am using above line code in API development.
Many programming language optimize the switch statement so that it is much faster than a standard if-else if structure provided the cases are compiler constants. Many languages use a jump table or indexed branch table to optimize switch statements. Wikipedia has a good discussion of the switch statement. Also, here is a discussion of switch optimization in C.
One thing to note is that switch statements can be abused and, depending on the case, it may be preferable to use polymorphism instead of switch statements. See here for an example.
I also found that in some cases the reason for 502/400 in case of many headers could be because of a large number of headers without regard to size. from the docs
tune.http.maxhdr Sets the maximum number of headers in a request. When a request comes with a number of headers greater than this value (including the first line), it is rejected with a "400 Bad Request" status code. Similarly, too large responses are blocked with "502 Bad Gateway". The default value is 101, which is enough for all usages, considering that the widely deployed Apache server uses the same limit. It can be useful to push this limit further to temporarily allow a buggy application to work by the time it gets fixed. Keep in mind that each new header consumes 32bits of memory for each session, so don't push this limit too high.
https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#3.2-tune.http.maxhdr
This LINQ solution works, not sure how it compares in performance to SequenceEquals. But it handles different array lengths and the .All will exit on the first item that is not equal without iterating through the whole array.
private static bool arraysEqual<T>(IList<T> arr1, IList<T> arr2)
=>
ReferenceEquals(arr1, arr2) || (
arr1 != null && arr2 != null &&
arr1.Count == arr2.Count &&
arr1.Select((a, i) => arr2[i].Equals(a)).All(i => i)
);
I faced this issue once, and I solved this by wrapping the LayoutManager
and disabling predictive animations.
Here an example:
public class LinearLayoutManagerWrapper extends LinearLayoutManager {
public LinearLayoutManagerWrapper(Context context) {
super(context);
}
public LinearLayoutManagerWrapper(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public LinearLayoutManagerWrapper(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
}
And set it to RecyclerView
:
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManagerWrapper(context, LinearLayoutManager.VERTICAL, false);
You can use the parse()
function to convert the characters into an expression. You need to specify that the input is text, because parse expects a file by default:
eval(parse(text="5+5"))
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
I tried your code and got a top rounded corner button. I gave the colors as @ffffff
and stroke I gave #C0C0C0
.
try
If your find
handles this syntax, you can use it:
find -maxdepth 1 -name "file.txt" -size -90k
This will output file.txt
to stdout if and only if the size of file.txt
is less than 90k. To execute a script script
if file.txt
has a size less than 90k:
find -maxdepth 1 -name "file.txt" -size -90k -exec script \;
Here is a procedure and code using generated ProjectInstaller
in Visual Studio:
ProjectInstaller
in design editor (it should open automatically when installer is created) and set properties of generated serviceProcessInstaller1
(e.g. Account: LocalSystem) and serviceInstaller1
(e.g. StartType: Automatic)ProjectInstaller
in code editor (press F7
in design editor) and add event handler to ServiceInstaller.AfterInstall
- see the following code. It will start the service after its installation.ProjectInstaller class:
using System.ServiceProcess;
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent(); //generated code including property settings from previous steps
this.serviceInstaller1.AfterInstall += Autorun_AfterServiceInstall; //use your ServiceInstaller name if changed from serviceInstaller1
}
void Autorun_AfterServiceInstall(object sender, InstallEventArgs e)
{
ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
sc.Start();
}
}
}
The method is implicitly defined (i.e. generated by the compiler).
From the JLS:
In addition, if
E
is the name of anenum
type, then that type has the following implicitly declaredstatic
methods:/** * Returns an array containing the constants of this enum * type, in the order they're declared. This method may be * used to iterate over the constants as follows: * * for(E c : E.values()) * System.out.println(c); * * @return an array containing the constants of this enum * type, in the order they're declared */ public static E[] values(); /** * Returns the enum constant of this type with the specified * name. * The string must match exactly an identifier used to declare * an enum constant in this type. (Extraneous whitespace * characters are not permitted.) * * @return the enum constant with the specified name * @throws IllegalArgumentException if this enum type has no * constant with the specified name */ public static E valueOf(String name);
Stealing from @Lila (couldn't make a comment because of no formatting), this shows the module's /path/, as well:
#!/usr/bin/env python
import sys
from modulefinder import ModuleFinder
finder = ModuleFinder()
# Pass the name of the python file of interest
finder.run_script(sys.argv[1])
# This is what's different from @Lila's script
finder.report()
which produces:
Name File
---- ----
...
m token /opt/rh/rh-python35/root/usr/lib64/python3.5/token.py
m tokenize /opt/rh/rh-python35/root/usr/lib64/python3.5/tokenize.py
m traceback /opt/rh/rh-python35/root/usr/lib64/python3.5/traceback.py
...
.. suitable for grepping or what have you. Be warned, it's long!
Date
, SimpleDateFormat
and whatever classes are required on the I/O side of things (there are many possibilities).
Just do one thing, We need to set the name property for the same types. for eg.
Try below:
<form>
<div id="group1">
<input type="radio" value="val1" name="group1">
<input type="radio" value="val2" name="group1">
</div>
</form>
And also we can do it in angular1,angular 2 or in jquery also.
<div *ngFor="let option of question.options; index as j">
<input type="radio" name="option{{j}}" value="option{{j}}" (click)="checkAnswer(j+1)">{{option}}
</div>
The answer below is apparently obsolete now, but works with older drivers. See comments.
If you have the connection string you could also use MongoDatabase directly:
var db = MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");
Apparently there is now a library for this - https://pypi.python.org/pypi/attrdict - which implements this exact functionality plus recursive merging and json loading. Might be worth a look.
Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.
I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up
My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:
in resources/lang/en/validaton.php:
'uploaded' => 'The :attribute failed to upload.',
And this is the message displayed when the file is larger than the limit set by PHP.
I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.
However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.
So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.
Here is what works if the file to smaller than the PHP file size limit:
In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:
This is how I set a custom error message and maximum file size:
I have an input field <input type="file" name="upload">
. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
...
...
public function rules() {
return [
'upload' => 'required|file|max:8192',
];
}
public function messages()
{
return [
'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
];
}
}
Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.
Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.
If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:
USING CTE (Row, Name, PicID)
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
U.NAME, P.PIC_ID
FROM USERS U
INNER JOIN POSTINGS P1
ON U.EMAIL_ID = P1.EMAIL_ID
INNER JOIN PICTURES P
ON P1.PIC_ID = P.PIC_ID
WHERE P.CAPTION LIKE '%car%'
ORDER BY U.NAME, P.PIC_ID
)
SELECT
CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
ON current.Row = previous.Row + 1
ORDER BY current.Row
The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.
You can also use the summary for linear models:
summary(lm(obs ~ mod, data=df))$r.squared
Does IE11 displays any message relative to the blocked execution of your ActiveX ?
You should read this and this.
Use the following JS function to detect support of ActiveX :
function IsActiveXSupported() {
var isSupported = false;
if(window.ActiveXObject) {
return true;
}
if("ActiveXObject" in window) {
return true;
}
try {
var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
isSupported = true;
} catch (e) {
if (e.name === "TypeError" || e.name === "Error") {
isSupported = true;
}
}
return isSupported;
}
Each column has like()
method, which can be used in query.filter()
. Given a search string, add a %
character on either side to search as a substring in both directions.
tag = request.form["tag"]
search = "%{}%".format(tag)
posts = Post.query.filter(Post.tags.like(search)).all()
URL Encoding the data works as well for me
For example
var data = '<b>Hello</b>'
In Browser call encodeURIComponent(data) before posting
On Server call HttpUtility.UrlDecode(received_data) to decode
That way you can control exactly which fields area allowed to have html
This is called modular exponentiation(https://en.wikipedia.org/wiki/Modular_exponentiation).
Let's assume you have the following expression:
19 ^ 3 mod 7
Instead of powering 19 directly you can do the following:
(((19 mod 7) * 19) mod 7) * 19) mod 7
But this can take also a long time due to a lot of sequential multipliations and so you can multiply on squared values:
x mod N -> x ^ 2 mod N -> x ^ 4 mod -> ... x ^ 2 |log y| mod N
Modular exponentiation algorithm makes assumptions that:
x ^ y == (x ^ |y/2|) ^ 2 if y is even
x ^ y == x * ((x ^ |y/2|) ^ 2) if y is odd
And so recursive modular exponentiation algorithm will look like this in java:
/**
* Modular exponentiation algorithm
* @param x Assumption: x >= 0
* @param y Assumption: y >= 0
* @param N Assumption: N > 0
* @return x ^ y mod N
*/
public static long modExp(long x, long y, long N) {
if(y == 0)
return 1 % N;
long z = modExp(x, Math.abs(y/2), N);
if(y % 2 == 0)
return (long) ((Math.pow(z, 2)) % N);
return (long) ((x * Math.pow(z, 2)) % N);
}
Special thanks to @chux for found mistake with incorrect return value in case of y and 0 comparison.
You can use the RelativeLayout
.
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
def listToStringWithoutBrackets(list1):
return str(list1).replace('[','').replace(']','')
Hope this helps somebody. :)
// This html:
// <form id="someCoolForm">
// <input type="text" class="form-control" name="username" value="...." />
//
// <input type="text" class="form-control" name="profile.first_name" value="...." />
// <input type="text" class="form-control" name="profile.last_name" value="...." />
//
// <input type="text" class="form-control" name="emails[]" value="..." />
// <input type="text" class="form-control" name="emails[]" value=".." />
// <input type="text" class="form-control" name="emails[]" value="." />
// </form>
//
// With this js:
//
// var form1 = parseForm($('#someCoolForm'));
// console.log(form1);
//
// Will output something like:
// {
// username: "test2"
// emails:
// 0: "[email protected]"
// 1: "[email protected]"
// profile: Object
// first_name: "..."
// last_name: "..."
// }
//
// So, function below:
var parseForm = function (form) {
var formdata = form.serializeArray();
var data = {};
_.each(formdata, function (element) {
var value = _.values(element);
// Parsing field arrays.
if (value[0].indexOf('[]') > 0) {
var key = value[0].replace('[]', '');
if (!data[key])
data[key] = [];
data[value[0].replace('[]', '')].push(value[1]);
} else
// Parsing nested objects.
if (value[0].indexOf('.') > 0) {
var parent = value[0].substring(0, value[0].indexOf("."));
var child = value[0].substring(value[0].lastIndexOf(".") + 1);
if (!data[parent])
data[parent] = {};
data[parent][child] = value[1];
} else {
data[value[0]] = value[1];
}
});
return data;
};
I found meliae to be much more functional than Heapy or PySizer. If you happen to be running a wsgi webapp, then Dozer is a nice middleware wrapper of Dowser
It means that the field is (part of) a non-unique index. You can issue
show create table <table>;
To see more information about the table structure.
Add
actionBar.setHomeButtonEnabled(true);
and then add the following
@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
As suggested by naXa I've added a check on the itemId
, to have it work correctly in case there are multiple buttons on the action bar.
What about something like this:
SELECT
name,
count(*) AS num
FROM
your_table
GROUP BY
name
ORDER BY
count(*)
DESC
You are selecting the name and the number of times it appears, but grouping by name so each name is selected only once.
Finally, you order by the number of times in DESCending order, to have the most frequently appearing users come first.
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
To complement @gertvdijk's answer - I'm adding few screenshots in case it helps someone quick.
On my git bash shell
git branch
command without any parameters shows all my local branches. The current branch which is currently checked out is shown in different color (green) along with an asterisk (*) prefix which is really intuitive.
When you try to see all branches including the remote branches using
git branch -a
command then remote branches which aren't checked out yet are shown in red color:
Please see this wiki page for definition of closure.
And this page for closure in Java 8: http://mail.openjdk.java.net/pipermail/lambda-dev/2011-September/003936.html
Also look at this Q&A: Closures in Java 7
In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.
You could calculate the required height of the TreeView, by figuring out the height of a node, multiplying it by the number of nodes, then setting the form's MinimumSize property accordingly.
// assuming the treeview is populated!
nodeHeight = treeview1.Nodes[0].Bounds.Height;
this.MaximumSize = new Size(someMaximumWidth, someMaximumHeight);
int requiredFormHeight = (treeView1.GetNodeCount(true) * nodeHeight);
this.MinimumSize = new Size(this.Width, requiredFormHeight);
NB. This assumes though that the treeview1 is the only control on the form. When setting the requiredFormHeight variable you'll need to allow for other controls and height requirements surrounding the treeview, such as the tabcontrol you mentioned.
(I would however agree with @jgauffin and assess the rationale behind the requirement to resize a form everytime it loads without the user's consent - maybe let the user position and size the form and remember that instead??)
one easy way i know using JsonObject:
try {
JSONObject json = new JSONObject();
json.put("string", myString);
String converted = json.getString("string");
} catch (JSONException e) {
e.printStackTrace();
}
This is taken from Romain Guy's presentation at Devoxx, pdf found here.
Paint mShadow = new Paint();
// radius=10, y-offset=2, color=black
mShadow.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
// in onDraw(Canvas)
canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
Hope this helps.
NOTES
My solution is not efficient but helped me in situation where the values (bank cheque numbers and wire transfer ref no.) were stored as varchar where some entries had alpha numeric values with them and I had to pad if length is smaller than 6 chars.
Thought to share if someone comes across same situation
declare @minlen int = 6
declare @str varchar(20)
set @str = '123'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 000123
set @str = '1234'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 001234
set @str = '123456'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456
set @str = '123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456789
set @str = '123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456789
set @str = 'NEFT 123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: NEFT 123456789
If you are using JPA to hibernate make sure the Entity has the correct data type for a field defined against a date column like use java.util.Date instead of String.
You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array()
for this.
// Process all rows
while($row = mysql_fetch_array($result)) {
echo $row['column_name']; // Print a single column data
echo print_r($row); // Print the entire row data
}
Change your code to this :
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open)
ORDER BY idM1O LIMIT 1"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['fieldname'];
}
The React docs now have a section for this. https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute
render: function() {
return (
<TextInput
ref={function(input) {
if (input != null) {
input.focus();
}
}} />
);
},
Even though this answer does elaborate on returning a recordset from a stored procedure, I am posting here, because it took me ages to figure it out and this thread helped me.
My application was using Eclipselink-2.3.1, but I will force an upgrade to Eclipselink-2.5.0, as JPA 2.1 has much better support for stored procedures.
This method requires imports of EclipseLink classes from "org.eclipse.persistence", so it is specific to Eclipselink implementation.
I found it at "http://www.yenlo.nl/en/calling-oracle-stored-procedures-from-eclipselink-with-multiple-out-parameters".
StoredProcedureCall storedProcedureCall = new StoredProcedureCall();
storedProcedureCall.setProcedureName("mypackage.myprocedure");
storedProcedureCall.addNamedArgument("i_input_1"); // Add input argument name.
storedProcedureCall.addNamedOutputArgument("o_output_1"); // Add output parameter name.
DataReadQuery query = new DataReadQuery();
query.setCall(storedProcedureCall);
query.addArgument("i_input_1"); // Add input argument names (again);
List<Object> argumentValues = new ArrayList<Object>();
argumentValues.add("valueOf_i_input_1"); // Add input argument values.
JpaEntityManager jpaEntityManager = (JpaEntityManager) getEntityManager();
Session session = jpaEntityManager.getActiveSession();
List<?> results = (List<?>) session.executeQuery(query, argumentValues);
DatabaseRecord record = (DatabaseRecord) results.get(0);
String result = String.valueOf(record.get("o_output_1")); // Get output parameter
This method is implementation independent (don't need Eclipslink imports).
StoredProcedureQuery query = getEntityManager().createStoredProcedureQuery("mypackage.myprocedure");
query.registerStoredProcedureParameter("i_input_1", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("o_output_1", String.class, ParameterMode.OUT);
query.setParameter("i_input_1", "valueOf_i_input_1");
boolean queryResult = query.execute();
String result = String.valueOf(query.getOutputParameterValue("o_output_1"));
Now you can use the aggregate. Example:
db.users.aggregate(
[ { $sample: { size: 3 } } ]
)
Note first that a double
is a binary fraction and does not really have decimal places.
If you need decimal places, use a BigDecimal
, which has a setScale()
method for truncation, or use DecimalFormat
to get a String
.
tag is a block-level element but tag is inline element.Normally we use span tag to style inside block elements.but you don't need to use span tag to inline style.you have to do is; convert block element to inline element using "display: inline"
Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:
If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:
Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:
Install the 2 components from 1 above
You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project
NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!
I solved this. double click this error leads to behavior.
for my case. a miss match of debug and release mod kills my afternoon.
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">copy %(Filename)%(Extension) ..\..\cvd\
</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
</CustomBuild>
Stop abusing private fields!!!
The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.
Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.
There are two cases you want to extend a class:
There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.
Consider a simple library that models cars:
class Car {
private screw;
public assembleCar() {
screw.install();
};
private putScrewsTogether() {
...
};
}
The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar()
right? Let's mark screw as private.
Well, the author is wrong. If you want to modify only the assembleCar()
method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw
field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.
Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.
The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected
so everyone would be happier later. At least don't abuse private field.
I very much support Nick's answer.
In rails 5, as per the instructions in Rails Guides, you can use:
redirect_back(fallback_location: root_path)
The 'back' location is pulled from the HTTP_REFERER header which is not guaranteed to be set by the browser. Thats why you should provide a 'fallback_location'.
This is a pretty straight forward way of having HTML5 perform validation for any form, while still having modern JS control over the form. The only caveat is the submit button must be inside the <form>
.
html
<form id="newUserForm" name="create">
Email<input type="email" name="username" id="username" size="25" required>
Phone<input type="tel" id="phone" name="phone" pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" size="12" maxlength="12" required>
<input id="submit" type="submit" value="Create Account" >
</form>
js
// bind in ready() function
jQuery( "#submit" ).click( newAcctSubmit );
function newAcctSubmit()
{
var myForm = jQuery( "#newUserForm" );
// html 5 is doing the form validation for us,
// so no need here (but backend will need to still for security)
if ( ! myForm[0].checkValidity() )
{
// bonk! failed to validate, so return true which lets the
// browser show native validation messages to the user
return true;
}
// post form with jQuery or whatever you want to do with a valid form!
var formVars = myForm.serialize();
etc...
}
Single source file solution for straightforward parsing needs, useful. Deals with all the nasty edge cases. Such as new line normalization and handling new lines in quoted string literals. Your welcome!
If you CSV file has a header you just read out the column names (and compute column indexes) from the first row. Simple as that.
Note that Dump
is a LINQPad method, you might want to remove that if you are not using LINQPad.
void Main()
{
var file1 = "a,b,c\r\nx,y,z";
CSV.ParseText(file1).Dump();
var file2 = "a,\"b\",c\r\nx,\"y,z\"";
CSV.ParseText(file2).Dump();
var file3 = "a,\"b\",c\r\nx,\"y\r\nz\"";
CSV.ParseText(file3).Dump();
var file4 = "\"\"\"\"";
CSV.ParseText(file4).Dump();
}
static class CSV
{
public struct Record
{
public readonly string[] Row;
public string this[int index] => Row[index];
public Record(string[] row)
{
Row = row;
}
}
public static List<Record> ParseText(string text)
{
return Parse(new StringReader(text));
}
public static List<Record> ParseFile(string fn)
{
using (var reader = File.OpenText(fn))
{
return Parse(reader);
}
}
public static List<Record> Parse(TextReader reader)
{
var data = new List<Record>();
var col = new StringBuilder();
var row = new List<string>();
for (; ; )
{
var ln = reader.ReadLine();
if (ln == null) break;
if (Tokenize(ln, col, row))
{
data.Add(new Record(row.ToArray()));
row.Clear();
}
}
return data;
}
public static bool Tokenize(string s, StringBuilder col, List<string> row)
{
int i = 0;
if (col.Length > 0)
{
col.AppendLine(); // continuation
if (!TokenizeQuote(s, ref i, col, row))
{
return false;
}
}
while (i < s.Length)
{
var ch = s[i];
if (ch == ',')
{
row.Add(col.ToString().Trim());
col.Length = 0;
i++;
}
else if (ch == '"')
{
i++;
if (!TokenizeQuote(s, ref i, col, row))
{
return false;
}
}
else
{
col.Append(ch);
i++;
}
}
if (col.Length > 0)
{
row.Add(col.ToString().Trim());
col.Length = 0;
}
return true;
}
public static bool TokenizeQuote(string s, ref int i, StringBuilder col, List<string> row)
{
while (i < s.Length)
{
var ch = s[i];
if (ch == '"')
{
// escape sequence
if (i + 1 < s.Length && s[i + 1] == '"')
{
col.Append('"');
i++;
i++;
continue;
}
i++;
return true;
}
else
{
col.Append(ch);
i++;
}
}
return false;
}
}
in html/js context, on modern browsers, with other iterable objects than Arrays we could also use [Iterable].entries():
for(let [index, element] of document.querySelectorAll('div').entries()) {
element.innerHTML = '#' + index
}
You can create a batch by PreparedStatement#addBatch()
and execute it by PreparedStatement#executeBatch()
.
Here's a kickoff example:
public void save(List<Entity> entities) throws SQLException {
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (Entity entity : entities) {
statement.setString(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.
See also:
How about this :
// Checks to see if the value passed is valid.
if (!TypeDescriptor.GetConverter(typeof(T)).IsValid(value))
{
throw new ArgumentException();
}
In Bash, you can also redirect to a subshell using process substitution:
command > >(stdlog pipe) 2> >(stderr pipe)
For the case at hand:
command 2> >(grep 'something') >/dev/null
Use this code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"
android:radius="0.1dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp" />
<solid android:color="#Efffff" />
<stroke
android:width="2dp"
android:color="#25aaff" />
</shape>
declare @OrderByCmd nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd
With support for C++11 initializer lists it is very easy:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using Strings = vector<string>;
void foo( Strings const& strings )
{
for( string const& s : strings ) { cout << s << endl; }
}
auto main() -> int
{
foo( Strings{ "hi", "there" } );
}
Lacking that (e.g. for Visual C++ 10.0) you can do things like this:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> Strings;
void foo( Strings const& strings )
{
for( auto it = begin( strings ); it != end( strings ); ++it )
{
cout << *it << endl;
}
}
template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }
template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
v.push_back( a );
return v;
}
int main()
{
foo( r( Strings() ) << "hi" << "there" );
}
If they're meant to be separate values, try this:
var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])
If they're meant to be a single value (like in French, where one-half is written 0,5)
var value = parseFloat("554,20".replace(",", "."));
I have a Class Library WPF Project, and I Use:
'Read Settings
Dim value as string = My.Settings.my_key
value = "new value"
'Write Settings
My.Settings.my_key = value
My.Settings.Save()
Instead of using --no-optional
every single time, we can just add it to npm or yarn config.
For Yarn, there is a default no-optional config, so we can just edit that:
yarn config set ignore-optional true
For npm, there is no default config set, so we can create one:
npm config set ignore-optional true
(untested) something like this may do the job
WITH
base AS
(
select * -- get the table
from sometable
order by name -- in the desired order
),
twenty AS
(
select * -- get the first 30 rows
from base
where rownum < 30
order by name -- in the desired order
)
select * -- then get rows 21 .. 30
from twenty
where rownum > 20
order by name -- in the desired order
There is also the analytic function rank, that you can use to order by.
Arrays themselves do not have that method. A List, however, does: indexOf
For me the solution was easy, there was no room left on drive C, once deleted some old files i was able to perform IISReset and all the services started successfully.
You can try like this:
yourArray.shift()
That will be possible only if the HTML file is also loaded with the file
protocol from the local user's harddisk.
If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src
attribute with the file://
protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.
As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.
pmac72 is using GO to break down the query into batches and using an ALTER.
You appear to be running the same batch but running it twice after changing it: DROP... CREATE... edit... DROP... CREATE..
Perhaps post your exact code so we can see what is going on.
There's no easy way (in terms of performance) to do what you want to do.
Reflection works with assemblys and types mainly so you'll have to get all the types of the assembly and query them for the right interface. Here's an example:
Assembly asm = Assembly.Load("MyAssembly");
Type[] types = asm.GetTypes();
Type[] result = types.where(x => x.GetInterface("IMyInterface") != null);
That will get you all the types that implement the IMyInterface in the Assembly MyAssembly
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css()
and it will return an object, which you can then plug back into jQuery's $().css()
, ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
The problem is that the body of the page isn't actually visible. The DIVs under have width of 100% and have background colors themselves that override the body CSS.
To Fix the no-man's land, this might work. It's not elegant, but works.
#doc3 {
margin: auto 10px;
width: auto;
height: 2000px;
background-color: yellow;
}
Is there a way to ignore existing errors in project. Something similar what eclipse allows in case of java projects.
In my case the errors exist in jni directory. The errors are shown even though ndk-buid succeeds. So all i want to do is to ignore the errors reported by eclipse.
If the errors are indeed errors then i should get unresolved symbols during ndk-build.
I have ensured standard android includes are there in include path.
Also my project is of type android/c/c++.
I have two builders associated with the project 1. statndard android builder 2. custom ndk builder that ive explicitly created.
Just wishing to avoid the console error, I solved this using a similar approach to Artur's earlier answer, following these steps:
This is not the greatest solution (patched local script to maintain, losing control of where messages are sent) but it solved my issue.
Please see the security warning about removing the targetOrigin URI stated here before using this solution - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
The plus operator converts operands to int first and then does the addition. So the result is the int. You need to cast it back to short explicitly because conversions from a "longer" type to "shorter" type a made explicit, so that you don't loose data accidentally with an implicit cast.
As to why int16 is cast to int, the answer is, because this is what is defined in C# spec. And C# is this way is because it was designed to closely match to the way how CLR works, and CLR has only 32/64 bit arithmetic and not 16 bit. Other languages on top of CLR may choose to expose this differently.
"MMMM" is definitely NOT the right solution (even if it works for many languages), use "LLLL" pattern with SimpleDateFormat
The support for 'L' as ICU-compatible extension for stand-alone month names was added to Android platform on Jun. 2010.
Even if in English there is no difference between the encoding by 'MMMM' and 'LLLL', your should think about other languages, too.
E.g. this is what you get, if you use Calendar.getDisplayName
or the "MMMM" pattern for January with the Russian Locale
:
?????? (which is correct for a complete date string: "10 ??????, 2014")
but in case of a stand-alone month name you would expect:
??????
The right solution is:
SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );
If you are interested in where all the translations come from - here is the reference to gregorian calendar translations (other calendars linked on top of the page).
I am using 11.2 and received timeouts.
I resolved by using the version of jsoup below.
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.7.2</version>
<scope>compile</scope>
</dependency>
Change the adapter type in VirtualBox to bridged, and set the guest to use DHCP or set a static IP address outside of the bounds of DHCP. This will cause the Virtual Machine to act like a normal guest on your home network. You can then port forward.
Q1) Here are couple things to read or google more :
Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.
Q2) Here are couple of good tutorials for soap (I had them bookmarked) :
http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/
http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html
Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.
SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.
Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).
Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.
If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development
.
It's fantastic, not hard to read and not too big either (win win).
To move a file this api can be used but you need atleat 26 as api level -
But if you want to move directory no support is there so this native code can be used
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import java.io.File;
public class FileModule {
public void moveDirectory(String src, String des) {
File srcDir = new File(src);
File destDir = new File(des);
try {
FileUtils.moveDirectory(srcDir,destDir);
} catch (Exception e) {
Log.e("Exception" , e.toString());
}
}
public void deleteDirectory(String dir) {
File delDir = new File(dir);
try {
FileUtils.deleteDirectory(delDir);
} catch (IOException e) {
Log.e("Exception" , e.toString());
}
}
}
Alternate solution to doing shallow clone (git clone --depth=1 <URL>
) would be, if remote side supports it, to use --remote
option of git archive:
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -
Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.
You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window
and document
both fit the bill (with just a few differences).
From mozilla dev network:
addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.
So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.
Instead of creating runner functions or using set -e
, use a trap
:
trap 'echo "error"; do_cleanup failed; exit' ERR
trap 'echo "received signal to stop"; do_cleanup interrupted; exit' SIGQUIT SIGTERM SIGINT
do_cleanup () { rm tempfile; echo "$1 $(date)" >> script_log; }
command1
command2
command3
The trap even has access to the line number and the command line of the command that triggered it. The variables are $BASH_LINENO
and $BASH_COMMAND
.
What you could try to do is create an object to hold the property value. That way you could pass the object and still have access to the property inside.
In my case, I'm using j-hipster and I had to do ./mvnw clean
to overcome this warning.
The postgresql port is defined in your postgresql.conf
file.
For me in Ubuntu 14.04 it is: /etc/postgresql/9.3/main/postgresql.conf
Inside there is a line:
port = 5432
Changing the number there requires restart of postgresql for it to take effect.
I know this isn't JavaScript, but you can also physically use the mouse-click to click a dynamic Javascript anchor:
public static void mouseClickByLocator( String cssLocator ) {
String locator = cssLocator;
WebElement el = driver.findElement( By.cssSelector( locator ) );
Actions builder = new Actions(driver);
builder.moveToElement( el ).click( el );
builder.perform();
}