I installed System.Configuration.ConfigurationManager
from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
You have your storyboard set up to expect an outlet called tableView
but the actual outlet name is myTableView
.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
LocalDate dateBefore = LocalDate.of(2020, 05, 20);
LocalDate dateAfter = LocalDate.now();
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
long monthsBetween= ChronoUnit.MONTHS.between(dateBefore, dateAfter);
long yearsBetween= ChronoUnit.YEARS.between(dateBefore, dateAfter);
System.out.println(daysBetween);
If some one came here after expo eject
then below steps will help.
expo start
in your terminalpod install
Here's some code that'll substitute for the blink tag
<p id="blink">This text will blink!</p>
<script>
var blacktime = 1000;
var whitetime = 1000;
//These can be as long as you desire in milliseconds
setTimeout(whiteFunc,blacktime);
function whiteFunc(){
document.getElementById("blink").style.color = "white";
setTimeout(blackFunc,whitetime);
}
function blackFunc(){
document.getElementById("blink").style.color = "black";
setTimeout(whiteFunc,blacktime);
}
</script>
I recommend @Jens Gustedt hexadecimal solution: use %a.
OP wants “print with maximum precision (or at least to the most significant decimal)”.
A simple example would be to print one seventh as in:
#include <float.h>
int Digs = DECIMAL_DIG;
double OneSeventh = 1.0/7.0;
printf("%.*e\n", Digs, OneSeventh);
// 1.428571428571428492127e-01
But let's dig deeper ...
Mathematically, the answer is "0.142857 142857 142857 ...", but we are using finite precision floating point numbers.
Let's assume IEEE 754 double-precision binary.
So the OneSeventh = 1.0/7.0
results in the value below. Also shown are the preceding and following representable double
floating point numbers.
OneSeventh before = 0.1428571428571428 214571170656199683435261249542236328125
OneSeventh = 0.1428571428571428 49212692681248881854116916656494140625
OneSeventh after = 0.1428571428571428 769682682968777953647077083587646484375
Printing the exact decimal representation of a double
has limited uses.
C has 2 families of macros in <float.h>
to help us.
The first set is the number of significant digits to print in a string in decimal so when scanning the string back,
we get the original floating point. There are shown with the C spec's minimum value and a sample C11 compiler.
FLT_DECIMAL_DIG 6, 9 (float) (C11)
DBL_DECIMAL_DIG 10, 17 (double) (C11)
LDBL_DECIMAL_DIG 10, 21 (long double) (C11)
DECIMAL_DIG 10, 21 (widest supported floating type) (C99)
The second set is the number of significant digits a string may be scanned into a floating point and then the FP printed, still retaining the same string presentation. There are shown with the C spec's minimum value and a sample C11 compiler. I believe available pre-C99.
FLT_DIG 6, 6 (float)
DBL_DIG 10, 15 (double)
LDBL_DIG 10, 18 (long double)
The first set of macros seems to meet OP's goal of significant digits. But that macro is not always available.
#ifdef DBL_DECIMAL_DIG
#define OP_DBL_Digs (DBL_DECIMAL_DIG)
#else
#ifdef DECIMAL_DIG
#define OP_DBL_Digs (DECIMAL_DIG)
#else
#define OP_DBL_Digs (DBL_DIG + 3)
#endif
#endif
The "+ 3" was the crux of my previous answer. Its centered on if knowing the round-trip conversion string-FP-string (set #2 macros available C89), how would one determine the digits for FP-string-FP (set #1 macros available post C89)? In general, add 3 was the result.
Now how many significant digits to print is known and driven via <float.h>
.
To print N significant decimal digits one may use various formats.
With "%e"
, the precision field is the number of digits after the lead digit and decimal point.
So - 1
is in order. Note: This -1
is not in the initial int Digs = DECIMAL_DIG;
printf("%.*e\n", OP_DBL_Digs - 1, OneSeventh);
// 1.4285714285714285e-01
With "%f"
, the precision field is the number of digits after the decimal point.
For a number like OneSeventh/1000000.0
, one would need OP_DBL_Digs + 6
to see all the significant digits.
printf("%.*f\n", OP_DBL_Digs , OneSeventh);
// 0.14285714285714285
printf("%.*f\n", OP_DBL_Digs + 6, OneSeventh/1000000.0);
// 0.00000014285714285714285
Note: Many are use to "%f"
. That displays 6 digits after the decimal point; 6 is the display default, not the precision of the number.
You could consider using PDFObject by Philip Hutchison.
Alternatively, if you're looking for a non-Javascript solution, you could use markup like this:
<object data="myfile.pdf" type="application/pdf" width="100%" height="100%">
<p>Alternative text - include a link <a href="myfile.pdf">to the PDF!</a></p>
</object>
I had this and looked over everything and didn't see any problems, but eventually remembered to try Clean and clear Derived Data and that solved it!
I had the same problem and after spending 2 days researching I found this solution from Ksesocss that fits for me and maybe is good for you too. It allows fixed header and dynamic width and only uses CSS. The only problem is that the source is in spanish but you can find the html and css code there.
This is the link:
http://ksesocss.blogspot.com/2014/10/responsive-table-encabezado-fijo-scroll.html
I hope this helps
Your method (placing script before the closing body tag)
<script>
myFunction()
</script>
</body>
</html>
is a reliable way to support old and new browsers.
You are correct in that static files are copied to the application at link-time, and that shared files are just verified at link time and loaded at runtime.
The dlopen call is not only for shared objects, if the application wishes to do so at runtime on its behalf, otherwise the shared objects are loaded automatically when the application starts. DLLS and .so are the same thing. the dlopen exists to add even more fine-grained dynamic loading abilities for processes. You dont have to use dlopen yourself to open/use the DLLs, that happens too at application startup.
You will find below some code for reading unencrypted RSA keys encoded in the following formats:
-----BEGIN RSA PRIVATE KEY-----
)-----BEGIN PRIVATE KEY-----
) It works with Java 7+ (and after 9) and doesn't use third-party libraries (like BouncyCastle) or internal Java APIs (like DerInputStream
or DerValue
).
private static final String PKCS_1_PEM_HEADER = "-----BEGIN RSA PRIVATE KEY-----";
private static final String PKCS_1_PEM_FOOTER = "-----END RSA PRIVATE KEY-----";
private static final String PKCS_8_PEM_HEADER = "-----BEGIN PRIVATE KEY-----";
private static final String PKCS_8_PEM_FOOTER = "-----END PRIVATE KEY-----";
public static PrivateKey loadKey(String keyFilePath) throws GeneralSecurityException, IOException {
byte[] keyDataBytes = Files.readAllBytes(Paths.get(keyFilePath));
String keyDataString = new String(keyDataBytes, StandardCharsets.UTF_8);
if (keyDataString.contains(PKCS_1_PEM_HEADER)) {
// OpenSSL / PKCS#1 Base64 PEM encoded file
keyDataString = keyDataString.replace(PKCS_1_PEM_HEADER, "");
keyDataString = keyDataString.replace(PKCS_1_PEM_FOOTER, "");
return readPkcs1PrivateKey(Base64.decodeBase64(keyDataString));
}
if (keyDataString.contains(PKCS_8_PEM_HEADER)) {
// PKCS#8 Base64 PEM encoded file
keyDataString = keyDataString.replace(PKCS_8_PEM_HEADER, "");
keyDataString = keyDataString.replace(PKCS_8_PEM_FOOTER, "");
return readPkcs8PrivateKey(Base64.decodeBase64(keyDataString));
}
// We assume it's a PKCS#8 DER encoded binary file
return readPkcs8PrivateKey(Files.readAllBytes(Paths.get(keyFilePath)));
}
private static PrivateKey readPkcs8PrivateKey(byte[] pkcs8Bytes) throws GeneralSecurityException {
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
try {
return keyFactory.generatePrivate(keySpec);
} catch (InvalidKeySpecException e) {
throw new IllegalArgumentException("Unexpected key format!", e);
}
}
private static PrivateKey readPkcs1PrivateKey(byte[] pkcs1Bytes) throws GeneralSecurityException {
// We can't use Java internal APIs to parse ASN.1 structures, so we build a PKCS#8 key Java can understand
int pkcs1Length = pkcs1Bytes.length;
int totalLength = pkcs1Length + 22;
byte[] pkcs8Header = new byte[] {
0x30, (byte) 0x82, (byte) ((totalLength >> 8) & 0xff), (byte) (totalLength & 0xff), // Sequence + total length
0x2, 0x1, 0x0, // Integer (0)
0x30, 0xD, 0x6, 0x9, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL
0x4, (byte) 0x82, (byte) ((pkcs1Length >> 8) & 0xff), (byte) (pkcs1Length & 0xff) // Octet string + length
};
byte[] pkcs8bytes = join(pkcs8Header, pkcs1Bytes);
return readPkcs8PrivateKey(pkcs8bytes);
}
private static byte[] join(byte[] byteArray1, byte[] byteArray2){
byte[] bytes = new byte[byteArray1.length + byteArray2.length];
System.arraycopy(byteArray1, 0, bytes, 0, byteArray1.length);
System.arraycopy(byteArray2, 0, bytes, byteArray1.length, byteArray2.length);
return bytes;
}
You need some form of iteration here, as val
(except when called with a function) only works on the first element:
$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));
should be:
$("input[placeholder]").each( function () {
$(this).val( $(this).attr("placeholder") );
});
or
$("input[placeholder]").val(function() {
return $(this).attr("placeholder");
});
The second. The first is invalid.
A browser will handle it like so:
<p>tetxtextextete
<!-- Start of paragraph -->
<ol>
<!-- Start of ordered list. Paragraphs cannot contain lists. Insert </p> -->
<li>first element</li></ol>
<!-- A list item element. End of list -->
</p>
<!-- End of paragraph, but not inside paragraph, discard this tag to recover from the error -->
<p>other textetxet</p>
<!-- Another paragraph -->
The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).
The way I would actually do it is to use jQuery's .text()
.
Since the frameborder
attribute is only necessary for IE, there is another way to get around the validator. This is a lightweight way that doesn't require Javascript or any DOM manipulation.
<!--[if IE]>
<iframe src="source" frameborder="0">?</iframe>
<![endif]-->
<!--[if !IE]>-->
<iframe src="source" style="border:none">?</iframe>
<!-- <![endif]-->
You may have outlets to UI Element but not IBOutlet property in .h File
For all UI element in Connection Attribute check outlets and it corresponding property in .h header file.
May be missing one or more property entry in .h file.
GCC compilers always try to compile your program if this is at all possible. However, in some
cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers
such as gcc or g++ must issue a diagnostic when these extensions are encountered. For example,
the gcc compiler’s -pedantic option causes gcc to issue warnings in such cases. Using the stricter
-pedantic-errors
option converts such diagnostic warnings into errors that will cause compilation
to fail at such points. Only those non-ISO constructs that are required to be flagged by a conforming
compiler will generate warnings or errors.
For me this is the correct way, This just worked:
$linker = rawurldecode("$link");
<a href="<?php echo $link;?>" target="_blank"><?php echo $linker ;?></a>
This worked, and now links are displayed properly:
http://newspaper.annahar.com/article/121638-????--????-???-??-??????-?????-????-??????-??????-????-??????-?????-????????
Link found on:
I prefer This One
document.forms['idOfTheForm'].nameOfTheInputFiled.value;
The Jackson-databind library also has ISO8601DateFormat class that does that (actual implementation in ISO8601Utils.
ISO8601DateFormat df = new ISO8601DateFormat();
Date d = df.parse("2010-07-28T22:25:51Z");
In C++ 17 you can use inline variables:
class A {
private:
static inline const std::string my_string = "some useful string constant";
};
Note that this is different from abyss.7's answer: This one defines an actual std::string
object, not a const char*
You almost got it. It should be this:
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
The value in for
should be the id of the element you are labeling.
I think it depends on the operations you'll be needing to do most frequently.
If you need the full value as a decimal number, then use decimal with appropriate precision and scale. Float is way beyond your needs, I believe.
If you'll be converting to/from degºmin'sec"fraction notation often, I'd consider storing each value as an integer type (smallint, tinyint, tinyint, smallint?).
you really don't need quotes if let say use are using the image from your css file it can be
{background-image: url(your image.png/jpg etc);}
Try to insert these rows into the CSS and call the "disHighlight" at class property:
.disHighlight {
user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
-webkit-touch-callout: none;
-o-user-select: none;
-moz-user-select: none;
}
Well you don't really have to worry about IE7 code not working in IE8 because IE8 has compatibility mode (it can render pages the same as IE7). But if you still want to target different versions of IE, a way that's been done for a while now is to either use conditional comments or begin your css rule with a * to target IE7 and below. Or you could pay attention to user agent on the servers and dish up a different CSS file based on that information.
pdf validation with OPEN validator:
DROID (Digital Record Object Identification) http://sourceforge.net/projects/droid/
JHOVE - JSTOR/Harvard Object Validation Environment http://hul.harvard.edu/jhove/
No REAL easy way to do this. Lots of ideas out there, though.
SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names
FROM information_schema.columns AS extern
CROSS APPLY
(
SELECT column_name + ','
FROM information_schema.columns AS intern
WHERE extern.table_name = intern.table_name
FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY table_name, column_names;
Or a version that works correctly if the data might contain characters such as <
WITH extern
AS (SELECT DISTINCT table_name
FROM INFORMATION_SCHEMA.COLUMNS)
SELECT table_name,
LEFT(y.column_names, LEN(y.column_names) - 1) AS column_names
FROM extern
CROSS APPLY (SELECT column_name + ','
FROM INFORMATION_SCHEMA.COLUMNS AS intern
WHERE extern.table_name = intern.table_name
FOR XML PATH(''), TYPE) x (column_names)
CROSS APPLY (SELECT x.column_names.value('.', 'NVARCHAR(MAX)')) y(column_names)
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
You might also be interested in the unit testing framework that is part of qooxdoo, an open source RIA framework similar to Dojo, ExtJS, etc. but with quite a comprehensive tool chain.
Try the online version of the testrunner. Hint: hit the gray arrow at the top left (should be made more obvious). It's a "play" button that runs the selected tests.
To find out more about the JS classes that let you define your unit tests, see the online API viewer.
For automated UI testing (based on Selenium RC), check out the Simulator project.
We have been using jqGrid on a project and have had some good luck with it. Lots of options for inline editing, etc. If that stuff isn't necessary, then we've just used a plain foreach loop like @Hrvoje.
DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture)
should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.
EDIT: To get the additional Z
at the end as the OP requires, use "o"
instead of "s"
.
Generally speaking, people refer to an application's presentation layer as its front end, its persistence layer (database, usually) as the back end, and anything between as middle tier. This set of ideas is often referred to as 3-tier architecture. They let you separate your application into more easily comprehensible (and testable!) chunks; you can also reuse lower-tier code more easily in higher tiers.
Which code is part of which tier is somewhat subjective; graphic designers tend to think of everything that isn't presentation as the back end, database people think of everything in front of the database as the front end, and so on.
Not all applications need to be separated out this way, though. It's certainly more work to have 3 separate sub-projects than it is to just open index.php and get cracking; depending on (1) how long you expect to have to maintain the app (2) how complex you expect the app to get, you may want to forgo the complexity.
Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat
is a bit confusing. I was trying to use r'?.*'
as a pattern, and thought it was complaining for some strange reason about the *
, but the problem is actually that ?
is a way of saying "repeat zero or one times". So I needed to say r'\?.*'
to match a literal ?
One-to-Many and Many-to-One are similar in Multiplicity but not Aspect (i.e. Directionality).
The mapping of Associations between entity classes and the Relationships between tables. There are two categories of Relationships:
The question is about a non rooted device but if it is rooted the simplest way would be to:
From the terminal on your phone, do this:
su
setprop service.adb.tcp.port 5555
stop adbd
start adbd
See this answer for full details.
As mentioned here (in French), this can happen when you have two versions of R installed on your computer. Uninstall the oldest one, then try your package installation again! It worked fine for me.
Using Python will be one easy way to achieve what you want.
I found one using Google.
"convert from json to csv using python" is an example.
To accept both @PathVariable
and @RequestParam
in the same /user
endpoint:
@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
@RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Testing with curl:
run
runs an imagestart
starts a container.The docker run
doc does mention:
The
docker run
command first creates a writeable container layer over the specified image, and then starts it using the specified command.That is, docker run is equivalent to the API
/containers/create
then/containers/(id)/start
.
You do not run an existing container, you docker exec to it (since docker 1.3).
You can restart an exited container.
Make sure you have the contentSize property of the scroll view set to the correct size (ie, one large enough to encompass all your content.)
I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010.
I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching.
/**
* Performs an in-place complex FFT.
*
* Released under the MIT License
*
* Copyright (c) 2010 Gerald T. Beauregard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
public class FFT2
{
// Element for linked list in which we store the
// input/output data. We use a linked list because
// for sequential access it's faster than array index.
class FFTElement
{
public double re = 0.0; // Real component
public double im = 0.0; // Imaginary component
public FFTElement next; // Next element in linked list
public uint revTgt; // Target position post bit-reversal
}
private uint m_logN = 0; // log2 of FFT size
private uint m_N = 0; // FFT size
private FFTElement[] m_X; // Vector of linked list elements
/**
*
*/
public FFT2()
{
}
/**
* Initialize class to perform FFT of specified size.
*
* @param logN Log2 of FFT length. e.g. for 512 pt FFT, logN = 9.
*/
public void init(
uint logN )
{
m_logN = logN;
m_N = (uint)(1 << (int)m_logN);
// Allocate elements for linked list of complex numbers.
m_X = new FFTElement[m_N];
for (uint k = 0; k < m_N; k++)
m_X[k] = new FFTElement();
// Set up "next" pointers.
for (uint k = 0; k < m_N-1; k++)
m_X[k].next = m_X[k+1];
// Specify target for bit reversal re-ordering.
for (uint k = 0; k < m_N; k++ )
m_X[k].revTgt = BitReverse(k,logN);
}
/**
* Performs in-place complex FFT.
*
* @param xRe Real part of input/output
* @param xIm Imaginary part of input/output
* @param inverse If true, do an inverse FFT
*/
public void run(
double[] xRe,
double[] xIm,
bool inverse = false )
{
uint numFlies = m_N >> 1; // Number of butterflies per sub-FFT
uint span = m_N >> 1; // Width of the butterfly
uint spacing = m_N; // Distance between start of sub-FFTs
uint wIndexStep = 1; // Increment for twiddle table index
// Copy data into linked complex number objects
// If it's an IFFT, we divide by N while we're at it
FFTElement x = m_X[0];
uint k = 0;
double scale = inverse ? 1.0/m_N : 1.0;
while (x != null)
{
x.re = scale*xRe[k];
x.im = scale*xIm[k];
x = x.next;
k++;
}
// For each stage of the FFT
for (uint stage = 0; stage < m_logN; stage++)
{
// Compute a multiplier factor for the "twiddle factors".
// The twiddle factors are complex unit vectors spaced at
// regular angular intervals. The angle by which the twiddle
// factor advances depends on the FFT stage. In many FFT
// implementations the twiddle factors are cached, but because
// array lookup is relatively slow in C#, it's just
// as fast to compute them on the fly.
double wAngleInc = wIndexStep * 2.0*Math.PI/m_N;
if (inverse == false)
wAngleInc *= -1;
double wMulRe = Math.Cos(wAngleInc);
double wMulIm = Math.Sin(wAngleInc);
for (uint start = 0; start < m_N; start += spacing)
{
FFTElement xTop = m_X[start];
FFTElement xBot = m_X[start+span];
double wRe = 1.0;
double wIm = 0.0;
// For each butterfly in this stage
for (uint flyCount = 0; flyCount < numFlies; ++flyCount)
{
// Get the top & bottom values
double xTopRe = xTop.re;
double xTopIm = xTop.im;
double xBotRe = xBot.re;
double xBotIm = xBot.im;
// Top branch of butterfly has addition
xTop.re = xTopRe + xBotRe;
xTop.im = xTopIm + xBotIm;
// Bottom branch of butterly has subtraction,
// followed by multiplication by twiddle factor
xBotRe = xTopRe - xBotRe;
xBotIm = xTopIm - xBotIm;
xBot.re = xBotRe*wRe - xBotIm*wIm;
xBot.im = xBotRe*wIm + xBotIm*wRe;
// Advance butterfly to next top & bottom positions
xTop = xTop.next;
xBot = xBot.next;
// Update the twiddle factor, via complex multiply
// by unit vector with the appropriate angle
// (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm)
double tRe = wRe;
wRe = wRe*wMulRe - wIm*wMulIm;
wIm = tRe*wMulIm + wIm*wMulRe;
}
}
numFlies >>= 1; // Divide by 2 by right shift
span >>= 1;
spacing >>= 1;
wIndexStep <<= 1; // Multiply by 2 by left shift
}
// The algorithm leaves the result in a scrambled order.
// Unscramble while copying values from the complex
// linked list elements back to the input/output vectors.
x = m_X[0];
while (x != null)
{
uint target = x.revTgt;
xRe[target] = x.re;
xIm[target] = x.im;
x = x.next;
}
}
/**
* Do bit reversal of specified number of places of an int
* For example, 1101 bit-reversed is 1011
*
* @param x Number to be bit-reverse.
* @param numBits Number of bits in the number.
*/
private uint BitReverse(
uint x,
uint numBits)
{
uint y = 0;
for (uint i = 0; i < numBits; i++)
{
y <<= 1;
y |= x & 0x0001;
x >>= 1;
}
return y;
}
}
I found the way for checking office bitness .
We can check office 365 and 2016 bitness using this registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\ClickToRun\Configuration
Platform x86 for 32 bit.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\ClickToRun\Configuration
Platform x64 for 64 bit.
Please check...
.a
files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.
Nobody have mention the new type of "Pull to refresh" which shows on top of the action bar like in the Google Now or Gmail application.
There is a library ActionBar-PullToRefresh which works exactly the same.
It is not necessary to declare the interface abstract.
Just like declaring all those methods public (which they already are if the interface is public) or abstract (which they already are in an interface) is redundant.
No one is stopping you, though.
Other things you can explicitly state, but don't need to:
extends Object
Is there other rules that applies with an abstract interface?
An interface is already "abstract". Applying that keyword again makes absolutely no difference.
An exemple of the only solution that works for me in the simple usecase where I am on a fork and I want to checkout a new branch from a tag that is on the main project repository ( here upstream )
git fetch upstream --tags
Give me
From https://github.com/keycloak/keycloak
90b29b0e31..0ba9055d28 stage -> upstream/stage
* [new tag] 11.0.0 -> 11.0.0
Then I can create a new branch from this tag and checkout on it
git checkout -b tags/<name> <newbranch>
git checkout tags/11.0.0 -b v11.0.0
you can use case/esac instead of if/else
case "$choose" in
[yY]) echo "Yes" && exit;;
[nN]) echo "No" && exit;;
* ) echo "wrong input" && exit;;
esac
For context, this information comes from out-of-the-box, no plugins, no .vimrc Vim 7.4 behavior in Linux Mint with the default options.
You can always select text with the mouse (or using V or v and placing the selection in the "* register), and paste it into the command line with Shift + Ctrl + v.
Typing Ctrl + r in the command line will cause a prompt for a register name. so typing :CTRL-r* will place the content register * into the command line. It will paste any register, not just "*. See :help c_CTRL-R
.
Furthermore, the middle mouse button will paste into the command line.
See :help->quote-plus
for a description of the how X Window deals with selection. Even in a plain, out-of-the-box Vim (again, in Vim 7.4 in Linux Mint, anyway), any selection made with the left mouse button can be pasted in the command line with the middle mouse button.
In addition, the middle mouse button will also paste text selected in Vim into many other X Window applications, even GUI ones (for example, Firefox and Thunderbird) and pasting text into the command line is also possible where the text was selected from other apps.
See :help->x11-selection for addl information.
tl;dr
Try the :CTRL-r approach first, and then use Shift + Ctrl + v or the middle mouse button if you need something else.
It is conceded that it can be confusing.
Here is my variant to have 'one statement to truncate 'em all'.
First, I am using a separate database named 'util' for my helper stored procedures. The code of my stored procedure to truncate all tables is:
DROP PROCEDURE IF EXISTS trunctables;
DELIMITER ;;
CREATE PROCEDURE trunctables(theDb varchar(64))
BEGIN
declare tname varchar(64);
declare tcursor CURSOR FOR
SELECT table_name FROM information_schema.tables WHERE table_type <> 'VIEW' AND table_schema = theDb;
SET FOREIGN_KEY_CHECKS = 0;
OPEN tcursor;
l1: LOOP
FETCH tcursor INTO tname;
if tname = NULL then leave l1; end if;
set @sql = CONCAT('truncate `', theDB, '`.`', tname, '`');
PREPARE stmt from @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP l1;
CLOSE tcursor;
SET FOREIGN_KEY_CHECKS = 1;
END ;;
DELIMITER ;
Once you have this stored procedure in your util database, you can call it like
call util.trunctables('nameofdatabase');
which is now exactly one statement :-)
Firstly, run the command below:
apt-get update && apt-get install procps
and then run:
ps -ef
In neither case is the "syntax malformed". It's the semantics that are wrong. Hence, IMHO a 400 is inappropriate. Instead, it would be appropriate to return a 200 along with some kind of error object such as { "error": { "message": "Unknown request keyword" } }
or whatever.
Consider the client processing path(s). An error in syntax (e.g. invalid JSON) is an error in the logic of the program, in other words a bug of some sort, and should be handled accordingly, in a way similar to a 403, say; in other words, something bad has gone wrong.
An error in a parameter value, on the other hand, is an error of semantics, perhaps due to say poorly validated user input. It is not an HTTP error (although I suppose it could be a 422). The processing path would be different.
For instance, in jQuery, I would prefer not to have to write a single error handler that deals with both things like 500 and some app-specific semantic error. Other frameworks, Ember for one, also treat HTTP errors like 400s and 500s identically as big fat failures, requiring the programmer to detect what's going on and branch depending on whether it's a "real" error or not.
Appears you are having 'y' default to 1: An arrow function would be useful in 2020:
let x = (y = 1) => //insert operation with y here
Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.
I learned that you also can get this error by storing the source file in a folder named Java
You could put it as a startup item... Startup items don't show off a prompt to run as an administrator at all.
Check this article Elevated Program Shortcut Without UAC rompt
Make sure that your WebAPI service is expecting a strongly typed object with a structure that matches the JSON that you are passing. And make sure that you stringify the JSON that you are POSTing.
Here is my JavaScript (using AngluarJS):
$scope.updateUserActivity = function (_objuserActivity) {
$http
({
method: 'post',
url: 'your url here',
headers: { 'Content-Type': 'application/json'},
data: JSON.stringify(_objuserActivity)
})
.then(function (response)
{
alert("success");
})
.catch(function (response)
{
alert("failure");
})
.finally(function ()
{
});
And here is my WebAPI Controller:
[HttpPost]
[AcceptVerbs("POST")]
public string POSTMe([FromBody]Models.UserActivity _activity)
{
return "hello";
}
require section This section contains the packages/dependencies which are better candidates to be installed/required in the production environment.
require-dev section: This section contains the packages/dependencies which can be used by the developer to test her code (or to experiment on her local machine and she doesn't want these packages to be installed on the production environment).
You can use OnClientClick event to call a JavaScript function:
<asp:Button ID="Button1" runat="server" Text="Button" onclientclick='redirect()' />
JavaScript code:
function redirect() {
location.href = 'page.aspx';
}
But i think the best would be to style a hyperlink with css.
Example :
.button {
display: block;
height: 25px;
background: #f1f1f1;
padding: 10px;
text-align: center;
border-radius: 5px;
border: 1px solid #e1e1e2;
color: #000;
font-weight: bold;
}
The simplest answer is a simple question - do you need your results to be repeatable? If yes then NOLOCKS is not appropriate under any circumstances
If you don't need repeatability then nolocks may be useful, especially if you don't have control over all processes connecting to the target database.
Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:
xx <- reshape(df, idvar=c("skew","version","color"),
v.names="price", timevar="product", direction="wide")
xx will have columns price.p1, ... price.p4, so:
ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
geom_point(shape=19, size=5)
ggp + facet_grid(color~version)
gives the result from your image.
Bit late to the party here but surprised I didn't see the following in this list:
:tab sball
- this opens a new tab for each open buffer.
:help switchbuf
- this controls buffer switching behaviour, try :set switchbuf=usetab,newtab
. This should mean switching to the existing tab if the buffer is open, or creating a new one if not.
It looks to me like the UIWebView has a UIScrollView. You can use documented APIs for this, but bouncing is set for both directions, not individually. This is in the API docs. UIScrollView has a bounce property, so something like this works (don't know if there's more than one scrollview):
NSArray *subviews = myWebView.subviews;
NSObject *obj = nil;
int i = 0;
for (; i < subviews.count ; i++)
{
obj = [subviews objectAtIndex:i];
if([[obj class] isSubclassOfClass:[UIScrollView class]] == YES)
{
((UIScrollView*)obj).bounces = NO;
}
}
To remove button in java code:
Button btn=(Button)findViewById(R.id.btn);
btn.setVisibility(View.GONE);
To transparent Button in java code:
Button btn=(Button)findViewById(R.id.btn);
btn.setVisibility(View.INVISIBLE);
To remove button in Xml file:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
To transparent button in Xml file:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>
You can't compare arrays directly like this
array1==array2
You should compare them char-by-char; for this you can use a function and return a boolean (True:1, False:0) value. Then you can use it in the test condition of the while loop.
Try this:
#include <stdio.h>
int checker(char input[],char check[]);
int main()
{
char input[40];
char check[40];
int i=0;
printf("Hello!\nPlease enter a word or character:\n");
scanf("%s",input);
printf("I will now repeat this until you type it back to me.\n");
scanf("%s",check);
while (!checker(input,check))
{
printf("%s\n", input);
scanf("%s",check);
}
printf("Good bye!");
return 0;
}
int checker(char input[],char check[])
{
int i,result=1;
for(i=0; input[i]!='\0' || check[i]!='\0'; i++) {
if(input[i] != check[i]) {
result=0;
break;
}
}
return result;
}
The only solution worked for me is putting the .jar file under WEB-INF/lib . Hope this will help.
The component solution and deep-clone solution have their advantages, but also have issues:
Sometimes you want to track changes in abstract data - it doesn't always make sense to build components around that data.
Deep-cloning your entire data structure every time you make a change can be very expensive.
I think there's a better way. If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so:
var vm = new Vue({
data: {
list: [
{name: 'obj1 to watch'},
{name: 'obj2 to watch'},
],
},
methods: {
handleChange (newVal) {
// Handle changes here!
console.log(newVal);
},
},
created () {
this.list.forEach((val) => {
this.$watch(() => val, this.handleChange, {deep: true});
});
},
});
With this structure, handleChange()
will receive the specific list item that changed - from there you can do any handling you like.
I have also documented a more complex scenario here, in case you are adding/removing items to your list (rather than only manipulating the items already there).
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
In a nutshell, if you turn on the OAuth 2.0
for Canvas advanced option, Facebook will send a $_REQUEST['signed_request']
along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
If you are using MySQL you can do it like this:
SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;
For a pure PHP solution use strtotime
strtotime('+ 30 minute',$yourdate);
Try that:
bool IsValidURL(string URL)
{
string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return Rgx.IsMatch(URL);
}
It will accept URL like that:
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
Try this function
function mb_html_entity_decode($string) {
if (extension_loaded('mbstring') === true)
{
mb_language('Neutral');
mb_internal_encoding('UTF-8');
mb_detect_order(array('UTF-8', 'ISO-8859-15', 'ISO-8859-1', 'ASCII'));
return mb_convert_encoding($string, 'UTF-8', 'HTML-ENTITIES');
}
return html_entity_decode($string, ENT_COMPAT, 'UTF-8');
}
Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.
Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.
The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
template: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
return htmlText;
}
compile: function(element, attrs)
{
//do whatever else is necessary
}
}
})
Set the DIV's z-index to one larger than the other DIVs. You'll also need to make sure the DIV has a position
other than static
set on it, too.
CSS:
#someDiv {
z-index:9;
}
Read more here: http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/
With your example:
<input type="checkbox" id="c2" name="c2" value="DE039230952"/>
Replace $$ with document.querySelectorAll in the examples:
$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
Use the examples directly with:
const $$ = document.querySelectorAll.bind(document);
Some additions:
$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
on osx log into your terminal and execute
sudo nano /opt/lampp/etc/extra/httpd-xampp.conf
and replace
<Directory "/opt/lampp/phpmyadmin">
AllowOverride AuthConfig Limit
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
with this
<Directory "/opt/lampp/phpmyadmin">
AllowOverride AuthConfig Limit
Order allow,deny
Allow from all
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
and then restart apache and mysql
or use this command
/opt/lampp/xampp restart
random.randrange(0,2) this works!
This syntax isn't valid in any version of PostgreSQL:
ALTER SEQUENCE payments_id_seq LASTVALUE 22
This would work:
ALTER SEQUENCE payments_id_seq RESTART WITH 22;
And is equivalent to:
SELECT setval('payments_id_seq', 22, FALSE);
More in the current manual for ALTER SEQUENCE
and sequence functions.
Note that setval()
expects either (regclass, bigint)
or (regclass, bigint, boolean)
. In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:
SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);
For repeated operations you might be interested in:
ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
ALTER SEQUENCE payments_id_seq RESTART; -- without value
START [WITH]
stores a default RESTART
number, which is used for subsequent RESTART
calls without value. You need Postgres 8.4 or later for the last part.
If Sybase is SQL-92 compliant then this information is stored within the INFORMATION_SCHEMA tables.
So the following will give you a list of tables and views in any SQL-92 compliant database
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
CREATE TABLE Admission (
Rno INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(25) NOT NULL,
Gender ENUM('M','F'),
Boolean_Valu boolean,
Dob Date,
Fees numeric(7,2) NOT NULL
);
insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Raj','M',true,'1990-07-12',50000);
insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Rani','F',false,'1994-05-10',15000);
select * from admission;
Yes, you can. Go to Tools > Designers > Table and Designers and uncheck "Prevent Saving Changes That Prevent Table Recreation".
It's a little trickier to do what you're trying to do than I'd prefer, but that's because you don't really directly bind a DataGrid
to a DataTable
.
When you bind DataGrid.ItemsSource
to a DataTable
, you're really binding it to the default DataView
, not to the table itself. This is why, for instance, you don't have to do anything to make a DataGrid
sort rows when you click on a column header - that functionality's baked into DataView
, and DataGrid
knows how to access it (through the IBindingList
interface).
The DataView
implements IEnumerable<DataRowView>
(more or less), and the DataGrid
fills its items by iterating over this. This means that when you've bound DataGrid.ItemsSource
to a DataTable
, its SelectedItem
property will be a DataRowView
, not a DataRow
.
If you know all this, it's pretty straightforward to build a wrapper class that lets you expose properties that you can bind to. There are three key properties:
Table
, the DataTable
,Row
, a two-way bindable property of type DataRowView
, and SearchText
, a string property that, when it's set, will find the first matching DataRowView
in the table's default view, set the Row
property, and raise PropertyChanged
.It looks like this:
public class DataTableWrapper : INotifyPropertyChanged
{
private DataRowView _Row;
private string _SearchText;
public DataTableWrapper()
{
// using a parameterless constructor lets you create it directly in XAML
DataTable t = new DataTable();
t.Columns.Add("id", typeof (int));
t.Columns.Add("text", typeof (string));
// let's acquire some sample data
t.Rows.Add(new object[] { 1, "Tower"});
t.Rows.Add(new object[] { 2, "Luxor" });
t.Rows.Add(new object[] { 3, "American" });
t.Rows.Add(new object[] { 4, "Festival" });
t.Rows.Add(new object[] { 5, "Worldwide" });
t.Rows.Add(new object[] { 6, "Continental" });
t.Rows.Add(new object[] { 7, "Imperial" });
Table = t;
}
// you should have this defined as a code snippet if you work with WPF
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
// SelectedItem gets bound to this two-way
public DataRowView Row
{
get { return _Row; }
set
{
if (_Row != value)
{
_Row = value;
OnPropertyChanged("Row");
}
}
}
// the search TextBox is bound two-way to this
public string SearchText
{
get { return _SearchText; }
set
{
if (_SearchText != value)
{
_SearchText = value;
Row = Table.DefaultView.OfType<DataRowView>()
.Where(x => x.Row.Field<string>("text").Contains(_SearchText))
.FirstOrDefault();
}
}
}
public DataTable Table { get; private set; }
}
And here's XAML that uses it:
<Window x:Class="DataGridSelectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:DataGridSelectionDemo="clr-namespace:DataGridSelectionDemo"
Title="DataGrid selection demo"
Height="350"
Width="525">
<Window.DataContext>
<DataGridSelectionDemo:DataTableWrapper />
</Window.DataContext>
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label>Text</Label>
<TextBox Grid.Column="1"
Text="{Binding SearchText, Mode=TwoWay}" />
</Grid>
<dg:DataGrid DockPanel.Dock="Top"
ItemsSource="{Binding Table}"
SelectedItem="{Binding Row, Mode=TwoWay}" />
</DockPanel>
</Window>
When you create any activity in android file you have to specify it in AndroidManifest.xml like
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MyCreativityActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OrderScreen"></activity>
</application>
I just replaced the swt.jar in my package with the 64bit version and it worked straight away. No need to recompile the whole package, just replace the swt.jar file and make sure your application manifest includes it.
It's legit and very handy!
Try this:
<script id="hello" type="text/template">
Hello world
</script>
<script>
alert($('#hello').html());
</script>
Several Javascript templating libraries use this technique. Handlebars.js is a good example.
There is a Superuser Roles: root, which is a Built-In Roles, may meet your need.
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError
popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
MVC is just a general design pattern that, in the context of lean web app development, makes it easy for the developer to keep the HTML markup in an app’s presentation layer (the view) separate from the methods that receive and handle client requests (the controllers) and the data representations that are returned within the view (the models). It’s all about separation of concerns, that is, keeping code that serves one functional purpose (e.g. handling client requests) sequestered from code that serves an entirely different functional purpose (e.g. representing data).
It’s the same principle for why anybody who’s spent more than 5 min trying to build a website can appreciate the need to keep your HTML markup, JavaScript, and CSS in separate files: If you just dump all of your code into a single file, you end up with spaghetti that’s virtually un-editable later on.
Since you asked for possible "cons": I’m no authority on software architecture design, but based on my experience developing in MVC, I think it’s also important to point out that following a strict, no-frills MVC design pattern is most useful for 1) lightweight web apps, or 2) as the UI layer of a larger enterprise app. I’m surprised this specification isn’t talked about more, because MVC contains no explicit definitions for your business logic, domain models, or really anything in the data access layer of your app. When I started developing in ASP.NET MVC (i.e. before I knew other software architectures even existed), I would end up with very bloated controllers or even view models chock full of business logic that, had I been working on enterprise applications, would have made it difficult for other devs who were unfamiliar with my code to modify (i.e. more spaghetti).
Follow the directions here, under "Setting up your project file."
Setting up your project file
You need to add libxml2.dylib to your project (don't put it in the Frameworks section). On the Mac, you'll find it at
/usr/lib/libxml2.dylib
and for the iPhone, you'll want the/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.0.sdk/usr/lib/libxml2.dylib
version.Since libxml2 is a .dylib (not a nice friendly .framework) we still have one more thing to do. Go to the Project build settings (Project->Edit Project Settings->Build) and find the "Search Paths". In "Header Search Paths" add the following path:
$(SDKROOT)/usr/include/libxml2
Also see the OP's answer.
There are a couple of different ways to approach the problem:
Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.
NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.
I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.
If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+.
EDIT NOTE: I've updated the following helper scripts and created a class that easier/simpler to use; check it out here ::: https://github.com/tjmehta/fbExec.js
window.fbAsyncInit = function() {
FB.init({
//...
});
window.fbApiInit = true; //init flag
if(window.thisFunctionIsCalledAfterFbInit)
window.thisFunctionIsCalledAfterFbInit();
};
fbEnsureInit will call it's callback after FB.init
function fbEnsureInit(callback){
if(!window.fbApiInit) {
window.thisFunctionIsCalledAfterFbInit = callback; //find this in index.html
}
else{
callback();
}
}
fbEnsureInitAndLoginStatus will call it's callback after FB.init and after FB.getLoginStatus
function fbEnsureInitAndLoginStatus(callback){
runAfterFbInit(function(){
FB.getLoginStatus(function(response){
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
callback();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
});
}
(FB.login needs to be run after FB has been initialized)
fbEnsureInit(function(){
FB.login(
//..enter code here
);
});
(FB.api needs to be run after FB.init and FB user must be logged in.)
fbEnsureInitAndLoginStatus(function(){
FB.api(
//..enter code here
);
});
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
For Swift 2.1 use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "Cyan.jpg")?.drawInRect(self.view.bounds)
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
The only real difference between a vertical RecyclerView
and a horizontal one is how you set up the LinearLayoutManager
. Here is the code snippet. The full example is below.
LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManagaer);
This fuller example is modeled after my vertical RecyclerView
answer.
Make sure the following dependencies are in your app gradle.build
file:
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
You can update the version numbers to whatever is the most current.
Add the RecyclerView
to your xml layout.
activity_main.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.support.v7.widget.RecyclerView
android:id="@+id/rvAnimals"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Each item in our RecyclerView
is going to have a single a colored View
over a TextView
. Create a new layout resource file.
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<View
android:id="@+id/colorView"
android:layout_width="100dp"
android:layout_height="100dp"/>
<TextView
android:id="@+id/tvAnimalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
The RecyclerView
needs an adapter to populate the views in each row (horizontal item) with your data. Create a new java file.
MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<Integer> mViewColors;
private List<String> mAnimals;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, List<Integer> colors, List<String> animals) {
this.mInflater = LayoutInflater.from(context);
this.mViewColors = colors;
this.mAnimals = animals;
}
// inflates the row layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the view and textview in each row
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
int color = mViewColors.get(position);
String animal = mAnimals.get(position);
holder.myView.setBackgroundColor(color);
holder.myTextView.setText(animal);
}
// total number of rows
@Override
public int getItemCount() {
return mAnimals.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View myView;
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myView = itemView.findViewById(R.id.colorView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mAnimals.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Notes
ListViews
and is a common need. You can remove this code if you don't need it.Add the following code to your main activity.
MainActivity.java
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
private MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
ArrayList<Integer> viewColors = new ArrayList<>();
viewColors.add(Color.BLUE);
viewColors.add(Color.YELLOW);
viewColors.add(Color.MAGENTA);
viewColors.add(Color.RED);
viewColors.add(Color.BLACK);
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
LinearLayoutManager horizontalLayoutManager
= new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManager);
adapter = new MyRecyclerViewAdapter(this, viewColors, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on item position " + position, Toast.LENGTH_SHORT).show();
}
}
Notes
ItemClickListener
that we defined in our adapter. This allows us to handle item click events in onItemClick
.That's it. You should be able to run your project now and get something similar to the image at the top.
Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the @Override
is invoked, the state of the object may be inconsistent and/or incomplete.
A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:
There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
Here's an example to illustrate:
public class ConstructorCallsOverride {
public static void main(String[] args) {
abstract class Base {
Base() {
overrideMe();
}
abstract void overrideMe();
}
class Child extends Base {
final int x;
Child(int x) {
this.x = x;
}
@Override
void overrideMe() {
System.out.println(x);
}
}
new Child(42); // prints "0"
}
}
Here, when Base
constructor calls overrideMe
, Child
has not finished initializing the final int x
, and the method gets the wrong value. This will almost certainly lead to bugs and errors.
Constructors with many parameters can lead to poor readability, and better alternatives exist.
Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:
Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...
The telescoping constructor pattern is essentially something like this:
public class Telescope {
final String name;
final int levels;
final boolean isAdjustable;
public Telescope(String name) {
this(name, 5);
}
public Telescope(String name, int levels) {
this(name, levels, false);
}
public Telescope(String name, int levels, boolean isAdjustable) {
this.name = name;
this.levels = levels;
this.isAdjustable = isAdjustable;
}
}
And now you can do any of the following:
new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);
You can't, however, currently set only the name
and isAdjustable
, and leaving levels
at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean
and int
arguments, which would really make a mess out of things.
As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).
Bloch recommends using a builder pattern, which would allow you to write something like this instead:
Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();
Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.
The GMaps Utility Library has a plugin called MapIconMaker that makes it easy to generate different marker styles on the fly. It uses Google Charts to draw the markers.
There's a good demo here that shows what kind of markers you can make with it.
I'm not with computer,so I write a draft. You might be clear of what I say.
func main(){
const dir = "/etc/"
filesInfo, e := ioutil.ReadDir(dir)
var fileNames = make([]string, 0, 10)
for i,v:=range filesInfo{
if !v.IsDir() {
fileNames = append(fileNames, v.Name())
}
}
var fileNumber = len(fileNames)
var contents = make([]string, fileNumber, 10)
wg := sync.WaitGroup{}
wg.Add(fileNumber)
for i,_:=range content {
go func(i int){
defer wg.Done()
buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
defer file.Close()
content[i] = string(buf)
}(i)
}
wg.Wait()
}
What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.
A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}
-block can throw (or a super class of that).
try {
//do something that throws ExceptionA, e.g.
throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
//do something to handle the exception, e.g.
System.out.println("Message: " + e.getMessage());
}
What you are trying to do is this:
try {
throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
System.out.println("Message: " + e.getMessage());
}
This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement
.
I have a single form and display where I "add / delete / edit / insert / move" data records using one form and one submit button. What I do first is to check to see if the $_post is set, if not, set it to nothing. then I run through the rest of the code,
then on the actual $_post's I use switches and if / else's based on the data entered and with error checking for each data part required for which function is being used.
After it does whatever to the data, I run a function to clear all the $_post data for each section. you can hit refresh till your blue in the face it won't do anything but refresh the page and display.
So you just need to think logically and make it idiot proof for your users...
You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)
$sum = 0;
foreach($group as $key=>$value)
{
$sum+= $value;
}
echo $sum;
I faced the same problem but on Ubuntu Server. So all I did is changed to superuser before I activate virtual environment for django and then I ran the django server. It worked fine for me.
First copy paste
sudo su
Then activate the virtual environment if you have one.
source myvenv/bin/activate
At last run your django server.
python3 manage.py runserver
Hope, this will help you.
In my case, I just had to make sure I have my urls both with and without www for Application Domain and Redirect URLs:
In my case, I had to use: signin-facebook
after my site url, for redirect url.
I had a same issue. It was working fine on the local machine but it had issues on the server. I have changed the SMTP setting. It works fine for me.
If you're using GoDaddy Plesk Hosting, use the following SMTP details.
Host = relay-hosting.secureserver.net
Port = 25
You can't do this with CSS alone. Using jQuery you can do
HTML
<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />
CSS
.highlight{
background:yellow;
}
jQuery
$('#check').click(function(){
$('#lab').toggleClass('highlight')
})
This will work in all browsers
Just try this out:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<style>
body {
margin: 0px;
padding: 0px;
}
#wrapper {
position: relative;
border: 1px solid #9C9898;
width: 578px;
height: 200px;
}
#buttonWrapper {
position: absolute;
width: 30px;
top: 2px;
right: 2px;
}
input[type =
"button"] {
padding: 5px;
width: 30px;
margin: 0px 0px 2px 0px;
}
</style>
<script>
function draw(scale, translatePos){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(translatePos.x, translatePos.y);
context.scale(scale, scale);
context.beginPath(); // begin custom shape
context.moveTo(-119, -20);
context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
context.bezierCurveTo(131, 50, 131, 20, 101, 0);
context.bezierCurveTo(141, -60, 81, -70, 51, -50);
context.bezierCurveTo(31, -95, -39, -80, -39, -50);
context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
context.closePath(); // complete custom shape
var grd = context.createLinearGradient(-59, -100, 81, 100);
grd.addColorStop(0, "#8ED6FF"); // light blue
grd.addColorStop(1, "#004CB3"); // dark blue
context.fillStyle = grd;
context.fill();
context.lineWidth = 5;
context.strokeStyle = "#0000ff";
context.stroke();
context.restore();
}
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var translatePos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var scale = 1.0;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function(){
scale /= scaleMultiplier;
draw(scale, translatePos);
}, false);
document.getElementById("minus").addEventListener("click", function(){
scale *= scaleMultiplier;
draw(scale, translatePos);
}, false);
// add event listeners to handle screen drag
canvas.addEventListener("mousedown", function(evt){
mouseDown = true;
startDragOffset.x = evt.clientX - translatePos.x;
startDragOffset.y = evt.clientY - translatePos.y;
});
canvas.addEventListener("mouseup", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseover", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseout", function(evt){
mouseDown = false;
});
canvas.addEventListener("mousemove", function(evt){
if (mouseDown) {
translatePos.x = evt.clientX - startDragOffset.x;
translatePos.y = evt.clientY - startDragOffset.y;
draw(scale, translatePos);
}
});
draw(scale, translatePos);
};
jQuery(document).ready(function(){
$("#wrapper").mouseover(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
</script>
</head>
<body onmousedown="return false;">
<div id="wrapper">
<canvas id="myCanvas" width="578" height="200">
</canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
</div>
</div>
<h2 id="status">
0, 0
</h2>
</body>
</html>
Works perfect for me with zooming and mouse movement.. you can customize it to mouse wheel up & down Njoy!!!
Here is fiddle for this Fiddle
Here is a plunker showing how you can use it with the ngClass
directive.
I'm demonstrating with div
s instead of img
s though.
Template:
<ul>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 1}" (click)="setSelected(1)"> </div></li>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 2}" (click)="setSelected(2)"> </div></li>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 3}" (click)="setSelected(3)"> </div></li>
</ul>
TS:
export class App {
selectedIndex = -1;
setSelected(id: number) {
this.selectedIndex = id;
}
}
If you simply need to answer "y" to all the overwrite prompts, try this:
y | mv srcdir/* targetdir/
Best solution with react hooks, no need of external libraries for that
import React, { useState } from 'react';_x000D_
_x000D_
const MyComponent = () => {_x000D_
const [copySuccess, setCopySuccess] = useState('');_x000D_
_x000D_
// your function to copy here_x000D_
_x000D_
const copyToClipBoard = async copyMe => {_x000D_
try {_x000D_
await navigator.clipboard.writeText(copyMe);_x000D_
setCopySuccess('Copied!');_x000D_
} catch (err) {_x000D_
setCopySuccess('Failed to copy!');_x000D_
}_x000D_
};_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<Button onClick={() => copyToClipBoard('some text to copy')}>_x000D_
Click here to copy_x000D_
</Button>_x000D_
// after copying see the message here_x000D_
{copySuccess}_x000D_
</div>_x000D_
)_x000D_
}
_x000D_
check here for further documentation about navigator.clip board , navigator.clipboard documentation navigotor.clipboard is supported by a huge number of browser look here supported browser
this is to topup to what was selected as the correct answer. It has one missing step that when not done, the user will still be able to access the rest of the database. First, do as @DineshDB suggested
1. Connect to your SQL server instance using management studio
2. Goto Security -> Logins -> (RIGHT CLICK) New Login
3. fill in user details
4. Under User Mapping, select the databases you want the user to be able to access and configure
the missing step is below:
5. Under user mapping, ensure that "sysadmin" is NOT CHECKED and select "db_owner" as the role for the new user.
And thats it.
This will work for the non-US date format (dd/MM/yyyy
):
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
7z a QuickBackup%backupFilename%.zip *.backup
I've been looking for something like this myself - I came up with the following, although it does use a timer, it uses it only once for the initial delay, and doesn't require any Sleep
calls ...
public void foo()
{
System.Threading.Timer timer = null;
timer = new System.Threading.Timer((obj) =>
{
bar();
timer.Dispose();
},
null, 1000, System.Threading.Timeout.Infinite);
}
public void bar()
{
// do stuff
}
(thanks to Fred Deschenes for the idea of disposing the timer within the callback)
I just got the same error but due to a different mistake: I used double braces like:
{{count}}
to insert the value of count
instead of the correct:
{count}
which the compiler presumably turned into {{count: count}}
, i.e. trying to insert an Object as a React child.
As per the new Deprecation warning of Moment JS
You need to pass Format of Start and end date Format along with values for example :
let trackStartTime = "2020-12-29 09:59:19.07 +05:30";
let trackEndTime = "2020-12-29 11:04:19.07 +05:30" || moment().format("YYYY-MM-DD HH:mm:ss.SS Z");
let overallActivity = moment.duration(moment(trackEndTime, 'YYYY-MM-DD HH:mm:ss.SS Z').diff(moment(trackStartTime, 'YYYY-MM-DD HH:mm:ss.SS Z'))).asHours();
This seems close to what you want:
#foo {_x000D_
background: red;_x000D_
max-height: 100px;_x000D_
overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
background: blue;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
float: left;_x000D_
margin: 1em;_x000D_
}
_x000D_
<div id="foo">_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>_x000D_
<div class="bar"></div>_x000D_
</div>
_x000D_
If you are working with numpy you can use
import numpy as np
np.abs(-1.23)
>> 1.23
It will provide absolute values.
You probably need to some plugin like Jquery multiselect dropdown. Here is a demo.
Also you need to close your option tags like this:
<select name="test" multiple>
<option>123</option>
<option>456</option>
<option>789</option>
</select>
A simple solution of error is that you first need to change the folder directory in command prompt. By default in command prompt or in terminal(Inside Android studio in the bottom)tab the path is set to C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app> Change accordingly:- C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app>cd\
As this question attained a lot of attention and there are several ways to fulfill your task, let me present several options.
Those are all one-liners by the way ;)
Starting with:
df
cluster load_date budget actual fixed_price
0 A 1/1/2014 1000 4000 Y
1 A 2/1/2014 12000 10000 Y
2 A 3/1/2014 36000 2000 Y
3 B 4/1/2014 15000 10000 N
4 B 4/1/2014 12000 11500 N
5 B 4/1/2014 90000 11000 N
6 C 7/1/2014 22000 18000 N
7 C 8/1/2014 30000 28960 N
8 C 9/1/2014 53000 51200 N
Overview of potential operations:
ser_aggCol (collapse each column to a list)
cluster [A, A, A, B, B, B, C, C, C]
load_date [1/1/2014, 2/1/2014, 3/1/2...
budget [1000, 12000, 36000, 15000...
actual [4000, 10000, 2000, 10000,...
fixed_price [Y, Y, Y, N, N, N, N, N, N]
dtype: object
ser_aggRows (collapse each row to a list)
0 [A, 1/1/2014, 1000, 4000, Y]
1 [A, 2/1/2014, 12000, 10000...
2 [A, 3/1/2014, 36000, 2000, Y]
3 [B, 4/1/2014, 15000, 10000...
4 [B, 4/1/2014, 12000, 11500...
5 [B, 4/1/2014, 90000, 11000...
6 [C, 7/1/2014, 22000, 18000...
7 [C, 8/1/2014, 30000, 28960...
8 [C, 9/1/2014, 53000, 51200...
dtype: object
df_gr (here you get lists for each cluster)
load_date budget actual fixed_price
cluster
A [1/1/2014, 2/1/2014, 3/1/2... [1000, 12000, 36000] [4000, 10000, 2000] [Y, Y, Y]
B [4/1/2014, 4/1/2014, 4/1/2... [15000, 12000, 90000] [10000, 11500, 11000] [N, N, N]
C [7/1/2014, 8/1/2014, 9/1/2... [22000, 30000, 53000] [18000, 28960, 51200] [N, N, N]
a list of separate dataframes for each cluster
df for cluster A
cluster load_date budget actual fixed_price
0 A 1/1/2014 1000 4000 Y
1 A 2/1/2014 12000 10000 Y
2 A 3/1/2014 36000 2000 Y
df for cluster B
cluster load_date budget actual fixed_price
3 B 4/1/2014 15000 10000 N
4 B 4/1/2014 12000 11500 N
5 B 4/1/2014 90000 11000 N
df for cluster C
cluster load_date budget actual fixed_price
6 C 7/1/2014 22000 18000 N
7 C 8/1/2014 30000 28960 N
8 C 9/1/2014 53000 51200 N
just the values of column load_date
0 1/1/2014
1 2/1/2014
2 3/1/2014
3 4/1/2014
4 4/1/2014
5 4/1/2014
6 7/1/2014
7 8/1/2014
8 9/1/2014
Name: load_date, dtype: object
just the values of column number 2
0 1000
1 12000
2 36000
3 15000
4 12000
5 90000
6 22000
7 30000
8 53000
Name: budget, dtype: object
just the values of row number 7
cluster C
load_date 8/1/2014
budget 30000
actual 28960
fixed_price N
Name: 7, dtype: object
============================== JUST FOR COMPLETENESS ==============================
you can convert a series to a list
['C', '8/1/2014', '30000', '28960', 'N']
<class 'list'>
you can convert a dataframe to a nested list
[['A', '1/1/2014', '1000', '4000', 'Y'], ['A', '2/1/2014', '12000', '10000', 'Y'], ['A', '3/1/2014', '36000', '2000', 'Y'], ['B', '4/1/2014', '15000', '10000', 'N'], ['B', '4/1/2014', '12000', '11500', 'N'], ['B', '4/1/2014', '90000', '11000', 'N'], ['C', '7/1/2014', '22000', '18000', 'N'], ['C', '8/1/2014', '30000', '28960', 'N'], ['C', '9/1/2014', '53000', '51200', 'N']]
<class 'list'>
the content of a dataframe can be accessed as a numpy.ndarray
[['A' '1/1/2014' '1000' '4000' 'Y']
['A' '2/1/2014' '12000' '10000' 'Y']
['A' '3/1/2014' '36000' '2000' 'Y']
['B' '4/1/2014' '15000' '10000' 'N']
['B' '4/1/2014' '12000' '11500' 'N']
['B' '4/1/2014' '90000' '11000' 'N']
['C' '7/1/2014' '22000' '18000' 'N']
['C' '8/1/2014' '30000' '28960' 'N']
['C' '9/1/2014' '53000' '51200' 'N']]
<class 'numpy.ndarray'>
code:
# prefix ser refers to pd.Series object
# prefix df refers to pd.DataFrame object
# prefix lst refers to list object
import pandas as pd
import numpy as np
df=pd.DataFrame([
['A', '1/1/2014', '1000', '4000', 'Y'],
['A', '2/1/2014', '12000', '10000', 'Y'],
['A', '3/1/2014', '36000', '2000', 'Y'],
['B', '4/1/2014', '15000', '10000', 'N'],
['B', '4/1/2014', '12000', '11500', 'N'],
['B', '4/1/2014', '90000', '11000', 'N'],
['C', '7/1/2014', '22000', '18000', 'N'],
['C', '8/1/2014', '30000', '28960', 'N'],
['C', '9/1/2014', '53000', '51200', 'N']
], columns=['cluster', 'load_date', 'budget', 'actual', 'fixed_price'])
print('df',df, sep='\n', end='\n\n')
ser_aggCol=df.aggregate(lambda x: [x.tolist()], axis=0).map(lambda x:x[0])
print('ser_aggCol (collapse each column to a list)',ser_aggCol, sep='\n', end='\n\n\n')
ser_aggRows=pd.Series(df.values.tolist())
print('ser_aggRows (collapse each row to a list)',ser_aggRows, sep='\n', end='\n\n\n')
df_gr=df.groupby('cluster').agg(lambda x: list(x))
print('df_gr (here you get lists for each cluster)',df_gr, sep='\n', end='\n\n\n')
lst_dfFiltGr=[ df.loc[df['cluster']==val,:] for val in df['cluster'].unique() ]
print('a list of separate dataframes for each cluster', sep='\n', end='\n\n')
for dfTmp in lst_dfFiltGr:
print('df for cluster '+str(dfTmp.loc[dfTmp.index[0],'cluster']),dfTmp, sep='\n', end='\n\n')
ser_singleColLD=df.loc[:,'load_date']
print('just the values of column load_date',ser_singleColLD, sep='\n', end='\n\n\n')
ser_singleCol2=df.iloc[:,2]
print('just the values of column number 2',ser_singleCol2, sep='\n', end='\n\n\n')
ser_singleRow7=df.iloc[7,:]
print('just the values of row number 7',ser_singleRow7, sep='\n', end='\n\n\n')
print('='*30+' JUST FOR COMPLETENESS '+'='*30, end='\n\n\n')
lst_fromSer=ser_singleRow7.tolist()
print('you can convert a series to a list',lst_fromSer, type(lst_fromSer), sep='\n', end='\n\n\n')
lst_fromDf=df.values.tolist()
print('you can convert a dataframe to a nested list',lst_fromDf, type(lst_fromDf), sep='\n', end='\n\n')
arr_fromDf=df.values
print('the content of a dataframe can be accessed as a numpy.ndarray',arr_fromDf, type(arr_fromDf), sep='\n', end='\n\n')
as pointed out by cs95 other methods should be preferred over pandas .values
attribute from pandas version 0.24 on see here. I use it here, because most people will (by 2019) still have an older version, which does not support the new recommendations. You can check your version with print(pd.__version__)
do {
stuff()
} while (condition())
->
while True:
stuff()
if not condition():
break
You can do a function:
def do_while(stuff, condition):
while condition(stuff()):
pass
But 1) It's ugly. 2) Condition should be a function with one parameter, supposed to be filled by stuff (it's the only reason not to use the classic while loop.)
Would this CSS fix it?
iframe {
display:block;
width:100%;
}
From this example: http://jsfiddle.net/HNyJS/2/show/
something.innerHTML += 'add whatever you want';
it worked for me. I added a button to an input text using this solution
The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):
body{
$colorStart: rgba(0,0,0,0);
$colorEnd: rgba(0,0,0,0.8);
@include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}
I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.
Try this...
var str = 'f 34 545 323 12345 54321 123456',
matches = str.match(/\b\d{5}\b/g);
console.log(matches); // ["12345", "54321"]
The word boundary \b
is your friend here.
My regex will get a number like this 12345
, but not like a12345
. The other answers provide great regexes if you require the latter.
The best solution for me is the custom pipe from @Kamalakar but with a slight modification to allow passing the format:
import { Pipe, PipeTransform} from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, format: any): any {
return super.transform(value, format);
}
}
And then called as:
console.log('Formatted date:', this._dateFormatPipe.transform(new Date(), 'MMM/dd/yyyy'));
Can place code anywhere
<input class="my_<? print 'test' ?>" />
if error is react is not define,please add ==>import React from 'react';
if error is reactDOM is not define,please add ==>import ReactDOM from 'react-dom';
Have you considered applying ON DELETE CASCADE
where relevant?
I had the same problem and found a very elegant solution for a Pager Class from
http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/
In your controller the call looks like:
return View(partnerList.ToPagedList(currentPageIndex, pageSize));
and in your view:
<div class="pager">
Seite: <%= Html.Pager(ViewData.Model.PageSize,
ViewData.Model.PageNumber,
ViewData.Model.TotalItemCount)%>
</div>
The column of the first matrix and the row of the second matrix should be equal and the order should be like this only
column of first matrix = row of second matrix
and do not follow the below step
row of first matrix = column of second matrix
it will throw an error
This is in fact the best example ever for Image Zoom and Pan in android,
http://blog.sephiroth.it/2011/04/04/imageview-zoom-and-scroll/
public EditText editField;
public Button clear = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_layout);
this. editField = (EditText)findViewById(R.id.userName);
this.clear = (Button) findViewById(R.id.clear_button);
this.editField.setOnClickListener(this);
this.clear.setOnClickListener(this);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.clear_button){
//setText will remove all text that is written by someone
editField.setText("");
}
}
I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below
{DefaultNamespace}.Properties.Resources.{ResourceName}
It's just the required syntax:
void Func(int (&myArray)[100])
^ Pass array of 100 int
by reference the parameters name is myArray
;
void Func(int* myArray)
^ Pass an array. Array decays to a pointer. Thus you lose size information.
void Func(int (*myFunc)(double))
^ Pass a function pointer. The function returns an int
and takes a double
. The parameter name is myFunc
.
Combining all answers above, you can write reusable code with BaseEntity:
@Data
@NoArgsConstructor
@MappedSuperclass
public abstract class BaseEntity {
@Transient
public static final Sort SORT_BY_CREATED_AT_DESC =
Sort.by(Sort.Direction.DESC, "createdAt");
@Id
private Long id;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@PrePersist
void prePersist() {
this.createdAt = LocalDateTime.now();
}
@PreUpdate
void preUpdate() {
this.updatedAt = LocalDateTime.now();
}
}
DAO object overloads findAll method - basically, still uses findAll()
public interface StudentDAO extends CrudRepository<StudentEntity, Long> {
Iterable<StudentEntity> findAll(Sort sort);
}
StudentEntity
extends BaseEntity
which contains repeatable fields (maybe you want to sort by ID, as well)
@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@Entity
class StudentEntity extends BaseEntity {
String firstName;
String surname;
}
Finally, the service and usage of SORT_BY_CREATED_AT_DESC
which probably will be used not only in the StudentService
.
@Service
class StudentService {
@Autowired
StudentDAO studentDao;
Iterable<StudentEntity> findStudents() {
return this.studentDao.findAll(SORT_BY_CREATED_AT_DESC);
}
}
This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:
import pylab
datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]
for data, label in datalist:
pylab.plot( data[:,0], data[:,1], label=label )
pylab.legend()
pylab.title("Title of Plot")
pylab.xlabel("X Axis Label")
pylab.ylabel("Y Axis Label")
You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.
ngModel
The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.
This directive executes at priority level 1.
Example Plunker
JAVASCRIPT
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = '1';
}]);
CSS
.my-input {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-input.ng-invalid {
color:white;
background: red;
}
HTML
<p id="inputDescription">
Update input to see transitions when valid/invalid.
Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
aria-describedby="inputDescription" />
</form>
ngModel is responsible for:
ngBind
The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
This directive executes at priority level 0.
Example Plunker
JAVASCRIPT
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.name = 'Whirled';
}]);
HTML
<div ng-controller="ExampleController">
<label>Enter name: <input type="text" ng-model="name"></label><br>
Hello <span ng-bind="name"></span>!
</div>
ngBind is responsible for:
string[] lines = File.ReadLines("c:\\file.txt").ToArray();
Although one wonders why you'll want to do that when ReadAllLines
works just fine.
Or perhaps you just want to enumerate with the return value of File.ReadLines
:
var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
Console.WriteLine("\t" + line);
}
It seems Nuget still uses the proxy script address (for our VPN) even though the proxy settings are disabled. I removed the script address and it works.
You can define a table dynamically just as you are inserting into it dynamically, but the problem is with the scope of temp tables. For example, this code:
DECLARE @sql varchar(max)
SET @sql = 'CREATE TABLE #T1 (Col1 varchar(20))'
EXEC(@sql)
INSERT INTO #T1 (Col1) VALUES ('This will not work.')
SELECT * FROM #T1
will return with the error "Invalid object name '#T1'." This is because the temp table #T1 is created at a "lower level" than the block of executing code. In order to fix, use a global temp table:
DECLARE @sql varchar(max)
SET @sql = 'CREATE TABLE ##T1 (Col1 varchar(20))'
EXEC(@sql)
INSERT INTO ##T1 (Col1) VALUES ('This will work.')
SELECT * FROM ##T1
Hope this helps, Jesse
I believe you could try something like this:
var postData =
{
"bid":bid,
"location1":"1","quantity1":qty1,"price1":price1,
"location2":"2","quantity2":qty2,"price2":price2,
"location3":"3","quantity3":qty3,"price3":price3
}
$.ajax({
type: "POST",
dataType: "json",
url: "add_cart.php",
data: postData,
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
the json encode should happen automatically, and a dump of your post should give you something like:
array(
"bid"=>bid,
"location1"=>"1",
"quantity1"=>qty1,
"price1"=>price1,
"location2"=>"2",
"quantity2"=>qty2,
"price2"=>price2,
"location3"=>"3",
"quantity3"=>qty3,
"price3"=>price3
)
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
Could it work declaring the filter the following way?
app.filter('dateUTC', function ($filter) {
return function (input, format) {
if (!angular.isDefined(format)) {
format = 'dd/MM/yyyy';
}
var date = new Date(input);
return $filter('date')(date.toISOString().slice(0, 23), format);
};
});
If you need the digit to be at the end of any word, this worked for me:
/\b([a-zA-Z]+[0-9]+)\b/g
Here's a way to do it:
>>> mylist = ['a', 'b', 'c', 'd']
>>> [item for item in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Alternatively, you can do:
>>> [(i, j) for i, j in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
The reason you got an error was that you were missing the () around i
and j
to make it a tuple.
In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
You should have a look at the HttpClient
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/yourwebapi");
Make sure your requests ask for the response in JSON using the Accept header like this:
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API
, if not, then you have to map the objects to your own objects. ASP.NET
will convert the JSON
you receive to the object you want it to be.
HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;
foreach (var x in yourcustomobjects)
{
//Call your store method and pass in your own object
SaveCustomObjectToDB(x);
}
}
else
{
//Something has gone wrong, handle it here
}
please note that I use .Result
for the case of the example. You should consider using the async
await
pattern here.
Change:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
To:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))
You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON
In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.
I came across this question while Googling for "git remove folder from tracking". The OP's question lead me to the answer. I am summarizing it here for future generations.
Question
How do I remove a folder from my git repository without deleting it from my local machine (i.e., development environment)?
Answer
Step 1. Add the folder path to your repo's root .gitignore
file.
path_to_your_folder/
Step 2. Remove the folder from your local git tracking, but keep it on your disk.
git rm -r --cached path_to_your_folder/
Step 3. Push your changes to your git repo.
The folder will be considered "deleted" from Git's point of view (i.e. they are in past history, but not in the latest commit, and people pulling from this repo will get the files removed from their trees), but stay on your working directory because you've used --cached
.
I like to use the following to get a nicely sorted listing of the current dir:
> dir . /s /b sortorder:N
.NET Core is a free and open-source, managed computer software framework for Windows, Linux, and macOS operating systems. It is an open source, cross platform successor to .NET Framework.
.NET Core applications are supported on Windows, Linux, and macOS. In a nutshell .NET Core is similar to .NET framework, but it is cross-platform, i.e., it allows the .NET applications to run on Windows, Linux and MacOS. .NET framework applications can only run on the Windows system. So the basic difference between .NET framework and .NET core is that .NET Core is cross platform and .NET framework only runs on Windows.
Furthermore, .NET Core has built-in dependency injection by Microsoft and you do not have to use third-party software/DLL files for dependency injection.
You can also use this first command to kill a process that owns a particular port:
sudo netstat -ap | grep :<port_number>
For example, say this process holds port 8000 TCP, then running the command:
sudo netstat -ap | grep :8000
will output the line corresponding to the process holding port 8000, for example:
tcp 0 0 *:8000 *:* LISTEN 4683/procHoldingPort
In this case, procHoldingPort is the name of the process that opened the port, 4683 is its pid, and 8000 (note that it is TCP) is the port number it holds (which you wish to close).
Then kill the process, following the above example:
kill 4683
As others mentioned here out, if that doesn't work (you can try using kill with -9 as an argument):
kill -9 4683
Again, in general, it's better to avoid sending SIGKILL
(-9) if you can.
Sometimes it's just better to use an iterator.
(Allegedly, "85%" of the requests for an index in the posh for loop is for implementing a String
join method (which you can easily do without).)
You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)
>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
Incidentally, there's another string form which might be a bit clearer:
>>> print(r'baz "\"')
baz "\"
Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".
Go to the "Network & Security" -> Security Group settings in the left hand navigation
Find the Security Group that your instance is apart of Click on Inbound Rules Use the drop down and add HTTP (port 80) Click Apply and enjoy
In php.ini
, I had to change
extension_dir = "ext"
to
extension_dir = "C:/PHP/ext"
as my PHP was installed in C:\PHP
. I had to use /
instead of \
, and then it worked.
Also uncomment mbstrings
, mysqli
and mysql
extensions.
That's one solution. If you add it to your .bashrc, it'll display the current branch in the console.
# git branch
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1) /'
}
$PS1="\$(parse_git_branch)$PS1"
However it's pretty limited. But there is a great project called git sh, which is doing exactly that (and much more).
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
removeChild
should be invoked on the parent, i.e.:
parent.removeChild(child);
In your example, you should be doing something like:
if (frameid) {
frameid.parentNode.removeChild(frameid);
}
If you landed here just wondering how to limit to 2 decimal places I have a native javascript solution:
Javascript:
function limitDecimalPlaces(e, count) {
if (e.target.value.indexOf('.') == -1) { return; }
if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
e.target.value = parseFloat(e.target.value).toFixed(count);
}
}
HTML:
<input type="number" oninput="limitDecimalPlaces(event, 2)" />
Note that this cannot AFAIK, defend against this chrome bug with the number input.
Whenever I do rake run:android,
my Androidmenifest.xml file is built-up again so my changes done
for NoTitlebar no more persist.
Rather than user adroid_title: 0
This helped me.
edit your build.yml
android: android_title: 0 #rest of things #you needed
One big thing not mentioned is the fact that with WinSCP you can also use key file authentication which I am unable to do successfully with Ubuntu FTP clients. KFTPGrabber is the closest thing I can find that supports key file authentication... but it still doesn't work for me, where WinSCP does.
Another variation
.blink {_x000D_
-webkit-animation: blink 1s step-end infinite;_x000D_
animation: blink 1s step-end infinite;_x000D_
}_x000D_
@-webkit-keyframes blink { 50% { visibility: hidden; }}_x000D_
@keyframes blink { 50% { visibility: hidden; }}
_x000D_
This is <span class="blink">blink</span>
_x000D_
You could do the following, without needing CSS...
<a href="ENTER_DESTINATION_URL"><img src="URL_OF_FIRST_IMAGE_SOURCE" onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" /></a>
Example: https://jsfiddle.net/jord8on/k1zsfqyk/
This solution was PERFECT for my needs! I found this solution here.
Disclaimer: Having a solution that is possible without CSS is important to me because I design content on the Jive-x cloud community platform which does not give us access to global CSS.
<?php
$args = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args );
?>
This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products
>>> s = 'my string with \\"double quotes\\" blablabla'
>>> s
'my string with \\"double quotes\\" blablabla'
>>> print s
my string with \"double quotes\" blablabla
>>>
When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...
>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>>
queryForMap
is appropriate if you want to get a single row. You are selecting without a where
clause, so you probably want to queryForList
. The error is probably indicative of the fact that queryForMap
wants one row, but you query is retrieving many rows.
Check out the docs. There is a queryForList
that takes just sql; the return type is a
List<Map<String,Object>>
.
So once you have the results, you can do what you are doing. I would do something like
List results = template.queryForList(sql);
for (Map m : results){
m.get('userid');
m.get('username');
}
I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.
If you have a User
object, and you actually want to load User instances, you can use the queryForList
that takes sql and a class type
queryForList(String sql, Class<T> elementType)
(wow Spring has changed a lot since I left Javaland.)
There are 3 ways:
First way
You need specify the directory to store mysql data on your host machine. You can then remove the data container. Your mysql data will be saved on you local filesystem.
Mysql container definition must look like this:
mysql:
container_name: flask_mysql
restart: always
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this
MYSQL_USER: 'test'
MYSQL_PASS: 'pass'
volumes:
- /opt/mysql_data:/var/lib/mysql
ports:
- "3306:3306"
Second way
Would be to commit the data container before typing docker-compose down
:
docker commit my_data_container
docker-compose down
Third way
Also you can use docker-compose stop
instead of docker-compose down
(then you don't need to commit the container)
just add container element befor your img element just to be sure that your intersted element not the first one, tested in ie,ff
I encounter a problem in quasar
which is a mobile framework based vue
, the tidle syntax ~assets/cover.jpg
works in normal component, but not in my dynamic defined component, that is defined by
let c=Vue.component('compName',{...})
finally this work:
computed: {
coverUri() {
return require('../assets/cover.jpg');
}
}
<q-img class="coverImg" :src="coverUri" :height="uiBook.coverHeight" spinner-color="white"/>
according to the explain at https://quasar.dev/quasar-cli/handling-assets
In *.vue components, all your templates and CSS are parsed by vue-html-loader and css-loader to look for asset URLs. For example, in <img src="./logo.png"> and background: url(./logo.png), "./logo.png" is a relative asset path and will be resolved by Webpack as a module dependency.
The compiler is pointing the error to you, you're comparing a structure instance and nil. They're not of the same type so it considers it as an invalid comparison and yells at you.
What you want to do here is to compare a pointer to your config instance to nil, which is a valid comparison. To do that you can either use the golang new builtin, or initialize a pointer to it:
config := new(Config) // not nil
or
config := &Config{
host: "myhost.com",
port: 22,
} // not nil
or
var config *Config // nil
Then you'll be able to check if
if config == nil {
// then
}
I presume you are trying to compile the application and run it without using an IDE. I also presume you have maven installed and correctly added maven to your environment variable.
To install and add maven to environment variable visit Install maven if you are under a proxy check out add proxy to maven
Navigate to the root of the project via command line and execute the command
mvn spring-boot:run
The CLI will run your application on the configured port and you can access it just like you would if you start the app in an IDE.
Note: This will work only if you have maven added to your pom.xml
I was facing the same issue. After many tries below solution worked for me.
Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.
After that you can follow the below steps.
@ABHI KUMAR
Download the Visual C++ Redistributable 2015
Visual C++ Redistributable for Visual Studio 2015 (64-bit)
Visual C++ Redistributable for Visual Studio 2015 (32-bit)
(Reinstal if already installed) then restart your computer or use windows updates for download auto.
For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.
The accepted solution by @JacobRelkin didn't work for me in iOS 7.0 using Auto Layout.
I have a custom subclass of UIViewController
and added an instance variable _tableView
as a subview of its view
. I positioned _tableView
using Auto Layout. I tried calling this method at the end of viewDidLoad
and even in viewWillAppear:
. Neither worked.
So, I added the following method to my custom subclass of UIViewController
.
- (void)tableViewScrollToBottomAnimated:(BOOL)animated {
NSInteger numberOfRows = [_tableView numberOfRowsInSection:0];
if (numberOfRows) {
[_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:numberOfRows-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
}
}
Calling [self tableViewScrollToBottomAnimated:NO]
at the end of viewDidLoad
works. Unfortunately, it also causes tableView:heightForRowAtIndexPath:
to get called three times for every cell.
Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.
If you don't need to support IE7, the following is a great, concise hack:
JSON.parse(JSON.stringify(new Date()))
It's python source parser failure on sum.up=False
named argument as sum.up is not valid argument name (you can't use dots -- only alphanumerics and underscores in argument names).
You can't wait()
on an object unless the current thread owns that object's monitor. To do that, you must synchronize
on it:
class Runner implements Runnable
{
public void run()
{
try
{
synchronized(Main.main) {
Main.main.wait();
}
} catch (InterruptedException e) {}
System.out.println("Runner away!");
}
}
The same rule applies to notify()
/notifyAll()
as well.
The Javadocs for wait()
mention this:
This method should only be called by a thread that is the owner of this object's monitor. See the
Throws:notify
method for a description of the ways in which a thread can become the owner of a monitor.
IllegalMonitorStateException
– if the current thread is not the owner of this object's monitor.
And from notify()
:
A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a
synchronized
statement that synchronizes on the object.- For objects of type
Class
, by executing a synchronized static method of that class.
I set all element's border-radius to "0" like this:
* {
border-radius: 0 !important;
}
As I'm sure I don't want to overwrite this later I just use !important.
If you are not compiling your less files just do:
* {
-webkit-border-radius: 0 !important;
-moz-border-radius: 0 !important;
border-radius: 0 !important;
}
In bootstrap 3 if you are compiling it you can now set radius in the variables.less file:
@border-radius-base: 0px;
@border-radius-large: 0px;
@border-radius-small: 0px;
In bootstrap 4 if you are compiling it you can disable radius alltogether in the _custom.scss
file:
$enable-rounded: false;
You should use setAlignmentX(..)
on components you want to align, not on the container that has them..
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);
c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);
You should have a default server for catch-all, you can return 404
or better to not respond at all (will save some bandwidth) by returning 444
which is nginx specific HTTP response that simply close the connection and return nothing
server {
listen 80 default_server;
server_name _; # some invalid name that won't match anything
return 444;
}
This is what you want:
>>> string1 = "go"
>>> string2 = "now"
>>> string3 = "great"
>>> mystring = """
... I will {string1} there
... I will go {string2}
... {string3}
... """
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
>>> print(mystring.format(**locals()))
I will go there
I will go now
great
TempData
is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.
To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.
Hope this helps.
I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too
var countries = ['Canada','Us','France','Italy'];
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});
Add white-space: nowrap;
:
.garage-title {
clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;
}
The best site to test website and see them realtime on MAC Safari is by using
They have like 25 free minutes of first time testing and then 10 free mins each day..You can even test your pages from your local PC by using their WEB TUNNEL Feature
I tested 7 to 8 pages in browserstack...And I think they have some java debugging tool in the upper right corner that is great help
I would do this:
std::string a("Hello ");
std::string b("World");
std::string c = a + b;
Which compiles in VS2008.
It's caused by n % x
where x = 0
in the first loop iteration. You can't calculate a modulus with respect to 0.
fopen()
will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.
This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.
Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:
$fp = fopen("myText.txt","wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}
So I had the same problem because I wasn't in the right directory where my file was located. So when I ran javac Example.java
(for me) it said it couldn't find it. But I needed to go to where my Example.java
file was located. So I used the command cd
and right after that the location of the file. That worked for me. Tell me if it helps! Thanks!
2019-05-26
This worked for me !
Example docker-compose:
version: "3"
services:
jenkins:
image: jenkinsci/blueocean
privileged: true
ports:
- "8080:8080"
volumes:
- $HOME/learning/jenkins/jenkins_home:/var/jenkins_home
environment:
- DOCKER_HOST=tcp://socat:2375
links:
- socat
socat:
image: bpack/socat
command: TCP4-LISTEN:2375,fork,reuseaddr UNIX-CONNECT:/var/run/docker.sock
volumes:
- /var/run/docker.sock:/var/run/docker.sock
expose:
- "2375"
This is a terrible idea, but it does work.
public enum myEnum
{
ThisNameWorks,
ThisNameDoesntWork149141331,// This Name doesn't work
NeitherDoesThis1849204824// Neither.does.this;
}
class Program
{
private static unsafe void ChangeString(string original, string replacement)
{
if (original.Length < replacement.Length)
throw new ArgumentException();
fixed (char* pDst = original)
fixed (char* pSrc = replacement)
{
// Update the length of the original string
int* lenPtr = (int*)pDst;
lenPtr[-1] = replacement.Length;
// Copy the characters
for (int i = 0; i < replacement.Length; i++)
pDst[i] = pSrc[i];
}
}
public static unsafe void Initialize()
{
ChangeString(myEnum.ThisNameDoesntWork149141331.ToString(), "This Name doesn't work");
ChangeString(myEnum.NeitherDoesThis1849204824.ToString(), "Neither.does.this");
}
static void Main(string[] args)
{
Console.WriteLine(myEnum.ThisNameWorks);
Console.WriteLine(myEnum.ThisNameDoesntWork149141331);
Console.WriteLine(myEnum.NeitherDoesThis1849204824);
Initialize();
Console.WriteLine(myEnum.ThisNameWorks);
Console.WriteLine(myEnum.ThisNameDoesntWork149141331);
Console.WriteLine(myEnum.NeitherDoesThis1849204824);
}
Requirements
Your enum names must have the same number of characters or more than the string that you want to it to be.
Your enum names shouldn't be repeated anywhere, just in case string interning messes things up
Why this is a bad idea (a few reasons)
Your enum names become ugly beause of the requirements
It relies on you calling the initialization method early enough
Unsafe pointers
If the internal format of string changes, e.g. if the length field is moved, you're screwed
If Enum.ToString() is ever changed so that it returns only a copy, you're screwed
Raymond Chen will complain about your use of undocumented features, and how it's your fault that the CLR team couldn't make an optimization to cut run time by 50%, during his next .NET week.
Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming
Update March 2013
Git 1.8.2 added the possibility to track branches.
"
git submodule
" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".
Also see Vogella's tutorial on submodules for general information on submodules.
Note:
git submodule add -b . [URL to Git repo];
^^^
A special value of
.
is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.
See commit b928922727d6691a3bdc28160f93f25712c565f6:
submodule add
: If --branch
is given, record it in .gitmodules
This allows you to easily record a
submodule.<name>.branch
option in.gitmodules
when you add a new submodule. With this patch,
$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>
reduces to
$ git submodule add -b <branch> <repository> [<path>]
This means that future calls to
$ git submodule update --remote ...
will get updates from the same branch that you used to initialize the submodule, which is usually what you want.
Signed-off-by: W. Trevor King [email protected]
Original answer (February 2012):
A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log
within that submodule.
So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:
gitslave (that you already looked at) seems to be the best fit, including for the commit operation.
It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).
Other alternatives are detailed here.
In my case, the same error had a much easier fix. Basically my function was in a .js file that was not included in the current aspx that was showing. All I needed was the include line.
Since you are providing a relative pathway to the image, the image location is looked for from the location in which you have the css file. So if you have the image in a different location to the css file you could either try giving the absolute URL(pathway starting from the root folder) or give the relative file location path. In your case since img and css are in the folder assets to move from location of css file to the img file, you can use '..' operator to refer that the browser has to move 1 folder back and then follow the pathway you have after the '..' operator. This is basically how relative pathway works and you can use it to access resoures in different folders. Hope it helps.
Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.
max-width:something px;
max-height:something px;
The other option would be to use the devlopr tools and see if you can remove the natural padding.
padding: 0;
You can do this:
function void PrintType(Type t) {
var t = true;
new Dictionary<Type, Action>{
{typeof(bool), () => Console.WriteLine("bool")},
{typeof(int), () => Console.WriteLine("int")}
}[t.GetType()]();
}
It's clear and its easy. It a bit slower than caching the dictionary somewhere.. but for lots of code this won't matter anyway..
Using JODA:
PeriodFormatter periodFormat = new PeriodFormatterBuilder()
.minimumParsedDigits(2)
.appendHour() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendMinute() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendSecond()
.appendSeparator(".")
.appendMillis3Digit()
.toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();
You can use parseInt(jQuery.offset().top)
to always use the Integer (primitive - int
) value across all browsers.
Updated: 2018
String to Date
var dateString = "02-03-2017"
var dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "dd-MM-yyyy"
//`date(from:)` returns an optional so make sure you unwrap when using.
var dateFromString: Date? = dateFormatter.date(from: dateString)
Date to String
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
guard let unwrappedDate = dateFromString else { return }
//Using the dateFromString variable from before.
let stringDate: String = formatter.string(from: dateFromString)
Updated: 20th July 2017
String to NSDate
var dateString = "02-03-2017"
var dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "dd-MM-yyyy"
var dateFromString = dateFormatter.date(from: dateString)
NSDate to String
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.string(from: dateFromString)
Updated: 22nd October 2015
String to NSDate
var dateString = "01-02-2010"
var dateFormatter = NSDateFormatter()
// this is imporant - we set our input date format to match our input string
dateFormatter.dateFormat = "dd-MM-yyyy"
// voila!
var dateFromString = dateFormatter.dateFromString(dateString)
NSDate to String
var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.stringFromDate(NSDate())
println(stringDate)
NSString to NSDate
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSDate convert to NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
Nobody provided the "classic Reflection" solution, so here is a complete code example:
using System;
using System.Collections;
using System.Collections.Generic;
namespace DictionaryRuntime
{
public class DynamicDictionaryFactory
{
/// <summary>
/// Factory to create dynamically a generic Dictionary.
/// </summary>
public IDictionary CreateDynamicGenericInstance(Type keyType, Type valueType)
{
//Creating the Dictionary.
Type typeDict = typeof(Dictionary<,>);
//Creating KeyValue Type for Dictionary.
Type[] typeArgs = { keyType, valueType };
//Passing the Type and create Dictionary Type.
Type genericType = typeDict.MakeGenericType(typeArgs);
//Creating Instance for Dictionary<K,T>.
IDictionary d = Activator.CreateInstance(genericType) as IDictionary;
return d;
}
}
}
The above DynamicDictionaryFactory
class has a method
CreateDynamicGenericInstance(Type keyType, Type valueType)
and it creates and returns an IDictionary instance, the types of whose keys and values are exactly the specified on the call keyType
and valueType
.
Here is a complete example how to call this method to instantiate and use a Dictionary<String, int>
:
using System;
using System.Collections.Generic;
namespace DynamicDictionary
{
class Test
{
static void Main(string[] args)
{
var factory = new DictionaryRuntime.DynamicDictionaryFactory();
var dict = factory.CreateDynamicGenericInstance(typeof(String), typeof(int));
var typedDict = dict as Dictionary<String, int>;
if (typedDict != null)
{
Console.WriteLine("Dictionary<String, int>");
typedDict.Add("One", 1);
typedDict.Add("Two", 2);
typedDict.Add("Three", 3);
foreach(var kvp in typedDict)
{
Console.WriteLine("\"" + kvp.Key + "\": " + kvp.Value);
}
}
else
Console.WriteLine("null");
}
}
}
When the above console application is executed, we get the correct, expected result:
Dictionary<String, int>
"One": 1
"Two": 2
"Three": 3
datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.
Suppose we have a datetime
object and date is represented as:
"2017-05-04"
>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59
A simple, although awk-less solution in bash:
while IFS=, read -r a a a b; do echo "$a"; done <inputfile
It works faster for small files (<100 lines) then awk as it uses less resources (avoids calling the expensive fork
and execve
system calls).
EDIT from Ed Morton (sorry for hi-jacking the answer, I don't know if there's a better way to address this):
To put to rest the myth that shell will run faster than awk for small files:
$ wc -l file
99 file
$ time while IFS=, read -r a a a b; do echo "$a"; done <file >/dev/null
real 0m0.016s
user 0m0.000s
sys 0m0.015s
$ time awk -F, '{print $3}' file >/dev/null
real 0m0.016s
user 0m0.000s
sys 0m0.015s
I expect if you get a REALY small enough file then you will see the shell script run in a fraction of a blink of an eye faster than the awk script but who cares?
And if you don't believe that it's harder to write robust shell scripts than awk scripts, look at this bug in the shell script you posted:
$ cat file
a,b,-e,d
$ cut -d, -f3 file
-e
$ awk -F, '{print $3}' file
-e
$ while IFS=, read -r a a a b; do echo "$a"; done <file
$
You can also download swagger ui from: https://github.com/swagger-api/swagger-ui, take the dist folder, modify index.html: change the constructor
const ui = SwaggerUIBundle({
url: ...,
into
const ui = SwaggerUIBundle({
spec: YOUR_JSON,
now the dist folder contains all what you need and can be distributed as is
If you want to create arrays using reflections then you can do like this:
int size = 3;
int[] intArray = (int[]) Array.newInstance(int.class, size );
Dockerfile
is good if you only have one docker file (per-directory). You can use whatever standard you want if you need multiple docker files in the same directory -
if you have a good reason. In a recent project there were AWS docker files and local dev environment files because the environments differed enough:
Dockerfile
Dockerfile.aws
I had same problem. it happen because javascript
expect json
data type in returning data. but if you use echo or print in your php this situation occur. if you use echo
function in php
to return data, Simply remove dataType : "json"
working pretty well.
char *a = "stack overflow";
char *b = "new string, it's real";
int d = strlen(a);
b = malloc(d * sizeof(char));
b = strcpy(b,a);
printf("%s %s\n", a, b);
You can use GET variables in the action
parameter of your form
element. Example:
<form method="post" action="script.php?foo=bar">
<input name="quu" ... />
...
</form>
This will give you foo
as a GET variable and quu
as a POST variable.
A few things to consider:
SQLite3 DB files grow roughly in multiples of the DB page size and do not shrink unless you use VACUUM
. If you delete some rows, the freed space is marked internally and reused in later inserts. Therefore an insert will often not cause a change in the size of the backing DB file.
You should not use traditional backup tools for SQLite (or any other database, for that matter), since they do not take into account the DB state information that is critical to ensure an uncorrupted database. Especially, copying the DB files in the middle of an insert transaction is a recipe for disaster...
SQLite3 has an API specifically for backing-up or copying databases that are in use.
And yes, it does seem that your DB files are corrupted. It could be a hardware/filesystem error. Or perhaps you copied them while they were in use? Or maybe restored a backup that was not properly taken?
Use BigDecimal
:
new BigDecimal(theInputString);
It retains all decimal digits. And you are sure of the exact representation since it uses decimal base, not binary base, to store the precision/scale/etc.
And it is not subject to precision loss like float
or double
are, unless you explicitly ask it to.
Once a dom element is created, the tag is immutable, I believe. You'd have to do something like this:
$(this).replaceWith($('<h5>' + this.innerHTML + '</h5>'));
The most efficient, but not the C++ way would be:
FILE* f = fopen(filename, "r");
// Determine file size
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
char* where = new char[size];
rewind(f);
fread(where, sizeof(char), size, f);
delete[] where;
#
EDIT - 2Just tested the std::filebuf
variant also. Looks like it can be called the best C++ approach, even though it's not quite a C++ approach, but more a wrapper. Anyway, here is the chunk of code that works almost as fast as plain C does.
std::ifstream file(filename, std::ios::binary);
std::streambuf* raw_buffer = file.rdbuf();
char* block = new char[size];
raw_buffer->sgetn(block, size);
delete[] block;
I've done a quick benchmark here and the results are following. Test was done on reading a 65536K binary file with appropriate (std::ios:binary
and rb
) modes.
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN ] IO.C_Kotti
[ OK ] IO.C_Kotti (78 ms)
[ RUN ] IO.CPP_Nikko
[ OK ] IO.CPP_Nikko (106 ms)
[ RUN ] IO.CPP_Beckmann
[ OK ] IO.CPP_Beckmann (1891 ms)
[ RUN ] IO.CPP_Neil
[ OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)
[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[ PASSED ] 4 tests.
window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.
$("#btn_screenshot").click(function(){_x000D_
element_to_png("container", "testhtmltocanvasimg");_x000D_
});_x000D_
_x000D_
_x000D_
function element_to_png(srcElementID, targetIMGid){_x000D_
console.log("element_to_png called for element id " + srcElementID);_x000D_
html2canvas($("#"+srcElementID)[0]).then( function (canvas) {_x000D_
var myImage = canvas.toDataURL("image/png");_x000D_
$("#"+targetIMGid).attr("src", myImage);_x000D_
console.log("html2canvas completed. png rendered to " + targetIMGid);_x000D_
});_x000D_
}
_x000D_
<div id="testhtmltocanvasdiv" class="mt-3">_x000D_
<img src="" id="testhtmltocanvasimg">_x000D_
</div>
_x000D_
I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!
Use an interval instead of an integer:
SELECT *
FROM table
WHERE auth_user.lastactivity > CURRENT_TIMESTAMP - INTERVAL '100 days'
Ahh, found the answer myself:
if (/[a-zA-Z]/.test(num)) {
alert('Letter Found')
}
I prefer to do the following one-liner, in POSIX shell compatible format:
$ [ -f "/$DIR/$FILE" ] || echo "$FILE NOT FOUND"
$ [ -f "/$DIR/$FILE" ] && echo "$FILE FOUND"
For a couple of commands, like I would do in a script:
$ [ -f "/$DIR/$FILE" ] || { echo "$FILE NOT FOUND" ; exit 1 ;}
Once I started doing this, I rarely use the fully typed syntax anymore!!
Because java.net.URL is not adequate for handling all kinds of low level resources, Spring introduced org.springframework.core.io.Resource. To access resources, we can use @Value annotation or ResourceLoader class. @Autowired private ResourceLoader resourceLoader;
@Override public void run(String... args) throws Exception {
Resource res = resourceLoader.getResource("classpath:thermopylae.txt");
Map<String, Integer> words = countWords.getWordsCount(res);
for (String key : words.keySet()) {
System.out.println(key + ": " + words.get(key));
}
}
<?php
function mysqli_insert_array($table, $data, $exclude = array()) {
$con= mysqli_connect("localhost", "root","","test");
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( mysqli_query($con,"INSERT INTO `$table` ($fields) VALUES ($values)") ) {
return array( "mysql_error" => false,
"mysql_insert_id" => mysqli_insert_id($con),
"mysql_affected_rows" => mysqli_affected_rows($con),
"mysql_info" => mysqli_info($con)
);
} else {
return array( "mysql_error" => mysqli_error($con) );
}
}
$a['firstname']="abc";
$a['last name']="xyz";
$a['birthdate']="1993-09-12";
$a['profilepic']="img.jpg";
$a['gender']="male";
$a['email']="[email protected]";
$a['likechoclate']="Dm";
$a['status']="1";
$result=mysqli_insert_array('registration',$a,'abc');
if( $result['mysql_error'] ) {
echo "Query Failed: " . $result['mysql_error'];
} else {
echo "Query Succeeded! <br />";
echo "<pre>";
print_r($result);
echo "</pre>";
}
?>
The Concat
method will return an object which implements IEnumerable<T>
by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList()
on Cat
and use the resulting List<T>
(which will represent a snapshot of the contents of A and B).
Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.
np.append needs the array as the first argument and the list you want to append as the second:
mean_data = np.append(mean_data, [ur, ua, np.mean(data[samepoints,-1])])
This solution is somewhat similar to the answer by Erwin Brandstetter, but uses only the sql language.
Not all PostgreSQL installations has the plpqsql language by default, this means you may have to call CREATE LANGUAGE plpgsql
before creating the function, and afterwards have to remove the language again, to leave the database in the same state as it was before (but only if the database did not have the plpgsql language to begin with). See how the complexity grows?
Adding the plpgsql may not be issue if you are running your script locally, however, if the script is used to set up schema at a customer it may not be desirable to leave changes like this in the customers database.
This solution is inspired by a post by Andreas Scherbaum.
-- Function which creates table
CREATE OR REPLACE FUNCTION create_table () RETURNS TEXT AS $$
CREATE TABLE table_name (
i int
);
SELECT 'extended_recycle_bin created'::TEXT;
$$
LANGUAGE 'sql';
-- Test if table exists, and if not create it
SELECT CASE WHEN (SELECT true::BOOLEAN
FROM pg_catalog.pg_tables
WHERE schemaname = 'public'
AND tablename = 'table_name'
) THEN (SELECT 'success'::TEXT)
ELSE (SELECT create_table())
END;
-- Drop function
DROP FUNCTION create_table();
TL:DR version:
//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)
Either you didn't set your picker to select the row (which you say you seem to have done but anyhow):
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
OR you didn't use the the following method to get the selected item from your picker
- (NSInteger)selectedRowInComponent:(NSInteger)component
This will get the selected row as Integer from your picker and do as you please with it. This should do the trick for yah. Good luck.
Anyhow read the ref: https://developer.apple.com/documentation/uikit/uipickerview
EDIT:
An example of manually setting and getting of a selected row in a UIPickerView:
the .h file:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
UIPickerView *picker;
NSMutableArray *source;
}
@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;
-(void)pressed;
@end
the .m file:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize picker;
@synthesize source;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.view.backgroundColor = [UIColor yellowColor];
self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];
UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
[pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
pressme.backgroundColor = [UIColor lightGrayColor];
[pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pressme];
self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
self.picker.delegate = self;
self.picker.dataSource = self;
[self.view addSubview:self.picker];
//This is how you manually SET(!!) a selection!
[self.picker selectRow:2 inComponent:0 animated:YES];
}
//logs the current selection of the picker manually
-(void)pressed
{
//This is how you manually GET(!!) a selection
int row = [self.picker selectedRowInComponent:0];
NSLog(@"%@", [source objectAtIndex:row]);
}
- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return [source count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return [source objectAtIndex:row];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
// NSLog(@"%@", [source objectAtIndex:row]);
}
@end
EDIT for Swift solution (Source: Dan Beaulieu's answer)
Define an Outlet:
@IBOutlet weak var pickerView: UIPickerView! // for example
Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:
pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)
If you inspect the Swift 2.0 framework you'll see .selectRow defined as:
func selectRow(row: Int, inComponent component: Int, animated: Bool)
option clicking .selectRow in Xcode displays the following:
CSS Styles are key-value pairs, not just "tags". By default, each element has a full set of CSS styles assigned to it, most of them is implicitly using the browser defaults and some of them is explicitly redefined in CSS stylesheets.
To get the value assigned to a particular CSS entry of an element and compare it:
if ($('#yourElement').css('position') == 'absolute')
{
// true
}
If you didn't redefine the style, you will get the browser default for that particular element.
I have had this problem several times and it can be usually resolved with a clean and rebuild as answered by many before me. But this time this would not fix it.
I use my cordova app to build 2 seperate apps that share majority of the same codebase and it drives off the config.xml. I could not build in end up because i had a space in my id.
com.company AppName
instead of:
com.company.AppName
If anyone is in there config as regular as me. This could be your problem, I also have 3 versions of each app. Live / Demo / Test - These all have different ids.
com.company.AppName.Test
Easy mistake to make, but even easier to overlook. Spent loads of time rebuilding, checking plugins, versioning etc. Where I should have checked my config. First Stop Next Time!
Installing angular cli globally solved my problem.
npm install -g @angular/cli
document.activeElement
is now part of the HTML5 working draft specification, but it might not yet be supported in some non-major/mobile/older browsers. You can fall back to querySelector
(if that is supported). It's also worth mentioning that document.activeElement
will return document.body
if no element is focused — even if the browser window doesn't have focus.
The following code will work around this issue and fall back to querySelector
giving a little better support.
var focused = document.activeElement;
if (!focused || focused == document.body)
focused = null;
else if (document.querySelector)
focused = document.querySelector(":focus");
An addition thing to note is the performance difference between these two methods. Querying the document with selectors will always be much slower than accessing the activeElement
property. See this jsperf.com test.
Simple use this to strip the text :
echo strlen($string) >= 500 ?
substr($string, 0, 490) . ' <a href="link/to/the/entire/text.htm">[Read more]</a>' :
$string;
Edit and finally :
function split_words($string, $nb_caracs, $separator){
$string = strip_tags(html_entity_decode($string));
if( strlen($string) <= $nb_caracs ){
$final_string = $string;
} else {
$final_string = "";
$words = explode(" ", $string);
foreach( $words as $value ){
if( strlen($final_string . " " . $value) < $nb_caracs ){
if( !empty($final_string) ) $final_string .= " ";
$final_string .= $value;
} else {
break;
}
}
$final_string .= $separator;
}
return $final_string;
}
Here separator is the href link to read more ;)