You need to set the content-type
in postman as JSON (application/json).
Go to the body inside your POST request, there you will find the raw option.
Right next to it, there will be a drop down, select JSON (application.json).
My functions:
$('.input_integer_only').on('input', function(e) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
$('.input_float_only').on('input', function(e) {
var $var = $(this).val().replace(/[^0-9\.]/g, '');
var $aVar = $var.split('.');
if($aVar.length > 2) {
$var = $aVar[0] + '.' + $aVar[1];
}
$(this).val($var);
});
READ AT LEAST THE FIRST PARA HERE!
I know this is 3 years too late, but Matt's (accepted) answer is incomplete and will eventually get you into trouble. The key here is that, if you choose to use multipart/form-data
, the boundary must not appear in the file data that the server eventually receives.
This is not a problem for application/x-www-form-urlencoded
, because there is no boundary. x-www-form-urlencoded
can also always handle binary data, by the simple expedient of turning one arbitrary byte into three 7BIT
bytes. Inefficient, but it works (and note that the comment about not being able to send filenames as well as binary data is incorrect; you just send it as another key/value pair).
The problem with multipart/form-data
is that the boundary separator must not be present in the file data (see RFC 2388; section 5.2 also includes a rather lame excuse for not having a proper aggregate MIME type that avoids this problem).
So, at first sight, multipart/form-data
is of no value whatsoever in any file upload, binary or otherwise. If you don't choose your boundary correctly, then you will eventually have a problem, whether you're sending plain text or raw binary - the server will find a boundary in the wrong place, and your file will be truncated, or the POST will fail.
The key is to choose an encoding and a boundary such that your selected boundary characters cannot appear in the encoded output. One simple solution is to use base64
(do not use raw binary). In base64 3 arbitrary bytes are encoded into four 7-bit characters, where the output character set is [A-Za-z0-9+/=]
(i.e. alphanumerics, '+', '/' or '='). =
is a special case, and may only appear at the end of the encoded output, as a single =
or a double ==
. Now, choose your boundary as a 7-bit ASCII string which cannot appear in base64
output. Many choices you see on the net fail this test - the MDN forms docs, for example, use "blob" as a boundary when sending binary data - not good. However, something like "!blob!" will never appear in base64
output.
Just searched for the docs, and found this:
Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:
{# returns true #}
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}
IMHO the safer way would be to create a new collection, to iterate over your given collection, adding each element in the new collection, and adding extra elements as needed in the new collection as well, finally returning the new collection.
$query_string = "";
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
$kv[] = stripslashes($key) . "=" . stripslashes($value);
}
$query_string = join("&", $kv);
}
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$url = 'https://www.abcd.com/servlet/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
curl_close($ch);
' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")
' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close
' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
Line = File.ReadLine
WScript.Echo(Line)
Loop
File.Close
' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close
I got the same thing. Running "make" and it fails with just this message.
% make
make: *** [all] Error 1
This was caused by a command in a rule terminates with non-zero exit status. E.g. imagine the following (stupid) Makefile
:
all:
@false
echo "hello"
This would fail (without printing "hello") with the above message since false
terminates with exit status 1.
In my case, I was trying to be clever and make a backup of a file before processing it (so that I could compare the newly generated file with my previous one). I did this by having a in my Make
rule that looked like this:
@[ -e $@ ] && mv $@ [email protected]
...not realizing that if the target file does not exist, then the above construction will exit (without running the mv
command) with exit status 1, and thus any subsequent commands in that rule failed to run. Rewriting my faulty line to:
@if [ -e $@ ]; then mv $@ [email protected]; fi
Solved my problem.
I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.
Here is code example as my words may not describe it best.
<p:tabView id="tabs">
<p:tab id="search" title="Search">
<h:form id="insTable">
<p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
<p:column>
<p:commandLink id="select"
Remove the failing update within this component
oncomplete="dlg.show()">
<f:setPropertyActionListener value="#{lndInstrument}"
target="#{instrumentBean.selectedInstrument}" />
<h:outputText value="#{lndInstrument.name}" />
</p:commandLink>
</p:column>
</p:dataTable>
<p:dialog id="dlg" modal="true" widgetVar="dlg">
<h:panelGrid id="display">
Add a component within the component of the id you are trying to update using an update that will fail
<p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>
<h:outputText value="Name:" />
<h:outputText value="#{instrumentBean.selectedInstrument.name}" />
</h:panelGrid>
</p:dialog>
</h:form>
</p:tab>
</p:tabView>
Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton
So the correct clientId to use would then be the bold plus the id of the target container (display in this case)
tabs:insTable:display
public void setHoursWorked(){
hoursWorked = hours;
}
You haven't defined hours
inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.
You can use extension methods to do the same thing with less code.
public enum AccountType
{
Retailer = 1,
Customer = 2,
Manager = 3,
Employee = 4
}
static class AccountTypeMethods
{
public static bool IsRetailer(this AccountType ac)
{
return ac == AccountType.Retailer;
}
}
And to use:
if (userProfile.AccountType.isRetailer())
{
//your code
}
I would recommend to rename the AccountType
to Account
. It's not a name convention.
System.IO.Path.GetTempPath()
The path specified by the TMP
environment variable.
The path specified by the TEMP
environment variable.
The path specified by the USERPROFILE
environment variable.
The Windows directory.
Look here:
It recommends using pscp.exe
from PuTTY, which can be found here: https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html
A direct transfer like FTP is not possible, because all commands during your session are send to the server.
This should work properly just try it.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
mysqldump
has options for CSV formatting:
--fields-terminated-by=name
Fields in the output file are terminated by the given
--lines-terminated-by=name
Lines in the output file are terminated by the given
The name
should contain one of the following:
`--fields-terminated-by`
\t
or "\""
`--fields-enclosed-by=name`
Fields in the output file are enclosed by the given
and
--lines-terminated-by
\r
\n
\r\n
Naturally you should mysqldump each table individually.
I suggest you gather all table names in a text file. Then, iterate through all tables running mysqldump. Here is a script that will dump and gzip 10 tables at a time:
MYSQL_USER=root
MYSQL_PASS=rootpassword
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
SQLSTMT="SELECT CONCAT(table_schema,'.',table_name)"
SQLSTMT="${SQLSTMT} FROM information_schema.tables WHERE table_schema NOT IN "
SQLSTMT="${SQLSTMT} ('information_schema','performance_schema','mysql')"
mysql ${MYSQL_CONN} -ANe"${SQLSTMT}" > /tmp/DBTB.txt
COMMIT_COUNT=0
COMMIT_LIMIT=10
TARGET_FOLDER=/path/to/csv/files
for DBTB in `cat /tmp/DBTB.txt`
do
DB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $1}'`
TB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $2}'`
DUMPFILE=${DB}-${TB}.csv.gz
mysqldump ${MYSQL_CONN} -T ${TARGET_FOLDER} --fields-terminated-by="," --fields-enclosed-by="\"" --lines-terminated-by="\r\n" ${DB} ${TB} | gzip > ${DUMPFILE}
(( COMMIT_COUNT++ ))
if [ ${COMMIT_COUNT} -eq ${COMMIT_LIMIT} ]
then
COMMIT_COUNT=0
wait
fi
done
if [ ${COMMIT_COUNT} -gt 0 ]
then
wait
fi
Apple changed the canOpenURL method on iOS 9. Apps which are checking for URL Schemes on iOS 9 and iOS 10 have to declare these Schemes as it is submitted to Apple.
// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";
// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
yield mb_substr($str, $i, 1);
}
})($str);
var_dump(
true === $gen instanceof Traversable,
// PHP 7.1
true === is_iterable($gen)
);
foreach ($gen as $char) {
echo $char, PHP_EOL;
}
I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.
The WITH syntax appears to be valid in an inline view, e.g.
UPDATE (WITH comp AS ...
SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
SET SomeColumn=ComputedValue;
But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view
, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.
You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:
MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;
But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING
clause arbitrarily complex, incorporating multiple WITH
clauses.
I understand your problem boils down to how to call a SOAP (JAX-WS) web service from Java and get its returning object. In that case, you have two possible approaches:
wsimport
and use them; or
About the first approach (using wsimport
):
I see you already have the services' (entities or other) business classes, and it's a fact that the wsimport
generates a whole new set of classes (that are somehow duplicates of the classes you already have).
I'm afraid, though, in this scenario, you can only either:
wsimport
generated code to make it use your business classes (this is difficult and somehow not worth it - bear in mind everytime the WSDL changes, you'll have to regenerate and readapt the code); orwsimport
generated classes. (In this solution, you business code could "use" the generated classes as a service from another architectural layer.)About the second approach (create your custom SOAP client):
In order to implement the second approach, you'll have to:
java.net.HttpUrlconnection
(and some java.io
handling).Creating a SOAP client using classic java.net.HttpUrlConnection
is not that hard (but not that simple either), and you can find in this link a very good starting code.
I recommend you use the SAAJ framework:
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "https://www.w3schools.com/xml/tempconvert.asmx";
String soapAction = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "https://www.w3schools.com/xml/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="https://www.w3schools.com/xml/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:CelsiusToFahrenheit>
<myNamespace:Celsius>100</myNamespace:Celsius>
</myNamespace:CelsiusToFahrenheit>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);
soapBodyElem1.addTextNode("100");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
About using JAXB for serializing/deserializing, it is very easy to find information about it. You can start here: http://www.mkyong.com/java/jaxb-hello-world-example/.
First check if your wlan card support hosted network and if no update the card driver. Follow this steps
1) open cmd with administrative rights
2) on the black screen type: netsh wlan show driver | findstr Hosted
3) See Hosted network supported, if No then update drivers
After installing php5-gd
apache restart is needed.
I tested it by requesting my website (apache) with all available chars on my german keyboard as URL parameter:
http://example.com/?^1234567890ß´qwertzuiopü+asdfghjklöä#<yxcvbnm,.-°!"§$%&/()=? `QWERTZUIOPÜ*ASDFGHJKLÖÄ\'>YXCVBNM;:_²³{[]}\|µ@€~
These were not encoded:
^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-!/()=?`*;:_{}[]\|~
Not encoded after urlencode()
:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_
Not encoded after rawurlencode()
:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~
Note: Before PHP 5.3.0 rawurlencode()
encoded ~
because of RFC 1738. But this was replaced by RFC 3986 so its safe to use, now. But I do not understand why for example {}
are encoded through rawurlencode()
because they are not mentioned in RFC 3986.
An additional test I made was regarding auto-linking in mail texts. I tested Mozilla Thunderbird, aol.com, outlook.com, gmail.com, gmx.de and yahoo.de and they fully linked URLs containing these chars:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~+#,%&=*;:@
Of course the ?
was linked, too, but only if it was used once.
Some people would now suggest to use only the rawurlencode()
chars, but did you ever hear that someone had problems to open these websites?
Asterisk
http://wayback.archive.org/web/*/http://google.com
Colon
https://en.wikipedia.org/wiki/Wikipedia:About
Plus
https://plus.google.com/+google
At sign, Colon, Comma and Exclamation mark
https://www.google.com/maps/place/USA/@36.2218457,...
Because of that these chars should be usable unencoded without problems. Of course you should not use &;
because of encoding sequences like &
. The same reason is valid for %
as it used to encode chars in general. And =
as it assigns a value to a parameter name.
Finally I would say its ok to use these unencoded:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~!+,*:@
But if you expect randomly generated URLs you should not use .!
, because those mark the end of a sentence and some mail apps will not auto-link the last char of the url. Example:
Visit http://example.com/foo=bar! !
I also found that System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke()
is not always dispatcher of target control, just as dotNet wrote in his answer. I didn't had access to control's own dispatcher, so I used Application.Current.Dispatcher
and it solved the problem.
You can append a queryString to your src and change it only when you will release an updated version:
<script src="test.js?v=1"></script>
In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)
$("video").prop('muted', true); //mute
AND
$("video").prop('muted', false); //unmute
See all events here
(side note: use attr
if in jQuery < 1.6)
You can specify multiple method signatures on the interface then have multiple method overloads on the class method:
interface INotificationService {
error(message: string, title?: string, autoHideAfter?: number);
error(message: string, autoHideAfter: number);
}
class MyNotificationService implements INotificationService {
error(message: string, title?: string, autoHideAfter?: number);
error(message: string, autoHideAfter?: number);
error(message: string, param1?: (string|number), param2?: number) {
var autoHideAfter: number,
title: string;
// example of mapping the parameters
if (param2 != null) {
autoHideAfter = param2;
title = <string> param1;
}
else if (param1 != null) {
if (typeof param1 === "string") {
title = param1;
}
else {
autoHideAfter = param1;
}
}
// use message, autoHideAfter, and title here
}
}
Now all these will work:
var service: INotificationService = new MyNotificationService();
service.error("My message");
service.error("My message", 1000);
service.error("My message", "My title");
service.error("My message", "My title", 1000);
...and the error
method of INotificationService
will have the following options:
I had the same issue. Fixed by adding a pom.xml in parent folder with <modules>
listed.
My understanding is that this is actually very simple:
So, to work through some of your examples:
function f(a,b,c) {
// Argument a is re-assigned to a new value.
// The object or primitive referenced by the original a is unchanged.
a = 3;
// Calling b.push changes its properties - it adds
// a new property b[b.length] with the value "foo".
// So the object referenced by b has been changed.
b.push("foo");
// The "first" property of argument c has been changed.
// So the object referenced by c has been changed (unless c is a primitive)
c.first = false;
}
var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false
Example 2:
var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4"; // a is now ["1", "4", {foo:"bar"}]; b still has the value
// it had at the time of assignment
a[2] = "5"; // a is now ["1", "4", "5"]; c still has the value
// it had at the time of assignment, i.e. a reference to
// the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"
The CPPFLAGS
macro is the one to use to specify #include
directories.
Both CPPFLAGS
and CFLAGS
work in your case because the make
(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).
You don't need to specify .
as an include-directory if you use the form #include "..."
. You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.
You just need to iterate the anchors in the two links.
<a href="#hide2" class="hide" id="hide2">+</a>
<a href="#show2" class="show" id="show2">-</a>
See this jsfiddle http://jsfiddle.net/eJX8z/
I also added some margin to the FAQ call to improve the format.
When you say:
#include <cstring>
the g++ compiler should put the <string.h>
declarations it itself includes into the std::
AND the global namespaces. It looks for some reason as if it is not doing that. Try replacing one instance of strcpy
with std::strcpy
and see if that fixes the problem.
The webpage is incorrect and I have pointed this out to MS and they will get it changed.
As already stated above .NET 4.5 is an in-place upgrade of 4.0 so you will only have Microsoft.NET\Framework\v4.0.30319.
The ToolVersion for MSBuild remains at "4.0".
Goto your app info.plist
1) Set View controller-based status bar appearance
to NO
2) Set Status bar style
to UIStatusBarStyleLightContent
Then Goto your app delegate and paste the following code where you set your Windows's RootViewController.
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
view.backgroundColor=[UIColor blackColor];
[self.window.rootViewController.view addSubview:view];
}
Hope it helps.
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
You have to use babel-preset-env and nodemon for hot-reload.
Then create .babelrc file with below content:
{
"presets": ["env"]
}
Finally, create script in package.json:
"scripts": {
"babel-node": "babel-node --presets=env",
"start": "nodemon --exec npm run babel-node -- ./index.js",
"build": "babel src -d dist"
}
Or just use this boilerplate:
Here's an improved/combined version of Lee's, Oliver's and Stephan's answers.
public delegate void InvokeIfRequiredDelegate<T>(T obj)
where T : ISynchronizeInvoke;
public static void InvokeIfRequired<T>(this T obj, InvokeIfRequiredDelegate<T> action)
where T : ISynchronizeInvoke
{
if (obj.InvokeRequired)
{
obj.Invoke(action, new object[] { obj });
}
else
{
action(obj);
}
}
The template allows for flexible and cast-less code which is much more readable while the dedicated delegate provides efficiency.
progressBar1.InvokeIfRequired(o =>
{
o.Style = ProgressBarStyle.Marquee;
o.MarqueeAnimationSpeed = 40;
});
This often occurs when you build software in RHEL 7 and try to run on RHEL 6.
To update GLIBC to any version, simply download the package from
For example glibc-2.14.tar.gz in your case.
1. tar xvfz glibc-2.14.tar.gz
2. cd glibc-2.14
3. mkdir build
4. cd build
5. ../configure --prefix=/opt/glibc-2.14
6. make
7. sudo make install
8. export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH
Then try to run your software, glibc-2.14 should be linked.
I just got my GUC232A cable with a molded-in PL2302 converter chip.
In addition to adding myself and br to group dialout
, I found this helpful tip in the README.Debian file in /usr/share/doc/bottlerocket
:
This package uses debconf to configure the /dev/firecracker symlink, should you need to change the symlink in the future run this command:
dpkg-reconfigure -pmedium bottlerocket
That will then prompt you for your new serial port and modify the symlink. This is required for proper use of bottlerocket.
I did that and voila! bottlerocket is able to communicate with my X-10 devices.
I couldn't get any of the previous answers to work (on macOS).
A combination worked for me -
IO.write "\e[H\e[2J\e[3J"
This clears the buffer and the screen.
This maybe a bit off topic.
I was looking for a way to write this kind of information to the Docker log of my PHP-FPM container and came up with the snippet below. I'm sure this can be used by Docker PHP-FPM users.
fwrite(fopen('php://stdout', 'w'), var_export($object, true));
The hide selector was incorrect. I hid the blocks at page load and showed the selected value. I also changed the car div id's to make it easier to append the radio button value and create the proper id selector.
<div id="myRadioGroup">
2 Cars<input type="radio" name="cars" checked="checked" value="2" />
3 Cars<input type="radio" name="cars" value="3" />
<div id="car-2">
2 Cars
</div>
<div id="car-3">
3 Cars
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("div div").hide();
$("#car-2").show();
$("input[name$='cars']").click(function() {
var test = $(this).val();
$("div div").hide();
$("#car-"+test).show();
});
});
</script>
I slightly modified the answer of opsb and made in support fill for the circle sector. http://codepen.io/anon/pen/AkoGx
JS
function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
}
function describeArc(x, y, radius, startAngle, endAngle){
var start = polarToCartesian(x, y, radius, endAngle);
var end = polarToCartesian(x, y, radius, startAngle);
var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";
var d = [
"M", start.x, start.y,
"A", radius, radius, 0, arcSweep, 0, end.x, end.y,
"L", x,y,
"L", start.x, start.y
].join(" ");
return d;
}
document.getElementById("arc1").setAttribute("d", describeArc(200, 400, 100, 0, 220));
HTML
<svg>
<path id="arc1" fill="orange" stroke="#446688" stroke-width="0" />
</svg>
byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
System.out.format("%d ", c);
}
System.out.println();
gets you
1 -2 5 66
Thread is a class, not an instance; currentThread() is a static method that returns the Thread instance corresponding to the calling thread.
Use (2). interrupt() is a bit brutal for normal use.
Firstly freq_series.plot
returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax
rather than fig
to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches
member. Then you can use the technique demonstrated in this matplotlib
gallery example to add the labels using the ax.text
method.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
ha='center', va='bottom')
This produces a labeled plot that looks like:
const a = [1, 2, 3]; // -> [2, 3]
// Mutable solutions: update array 'a', 'c' will contain the removed item
const c = a.shift(); // prefered mutable way
const [c] = a.splice(0, 1);
// Immutable solutions: create new array 'b' and leave array 'a' untouched
const b = a.slice(1); // prefered immutable way
const b = a.filter((_, i) => i > 0);
const [c, ...b] = a; // c: the removed item
To install an APK on your mobile, you can either:
adb install filename.apk
.
Note, you'll need to enable USB debugging for this to work.Note, that you'll have to enable installing packages from Unknown Sources in your Applications settings.
As for getting USB to work, I suggest consulting the Android StackExchange for advice.
If you download the jquery easing plugin (check it out),then you just have to add this to your main.js file:
$('a.smooth-scroll').on('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top + 20
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
and also dont forget to add the smooth-scroll class to your a tags like this:
<li><a href="#about" class="smooth-scroll">About Us</a></li>
If your Web Host is through C Panel Enable G ZIP Compression on Apache C Panel
Go to CPanel and check for software tab.
Previously Optimize website used to work but now a new option is available i.e "MultiPHP INI Editor".
Select the domain name you want to compress.
Scroll down to bottom until you find zip output compression and enable it.
Now check again for the G ZIP Compression.
You can follow the video tutorial also. https://www.youtube.com/watch?v=o0UDmcpGlZI
For those of us that learn by example...
Write text to a file like this:
IO.write('/tmp/msg.txt', 'hi')
BONUS INFO ...
Read it back like this
IO.read('/tmp/msg.txt')
Frequently, I want to read a file into my clipboard ***
Clipboard.copy IO.read('/tmp/msg.txt')
And other times, I want to write what's in my clipboard to a file ***
IO.write('/tmp/msg.txt', Clipboard.paste)
*** Assumes you have the clipboard gem installed
Answer https://stackoverflow.com/a/21369918/2526049 from dcodesmith has a side effect that turns all types of lists numeric.
<ol type="a">
will show 1. 2. 3. 4. rather than a. b. c. d.
ol {
margin: 0 0 1.5em;
padding: 0;
counter-reset: item;
}
ol > li {
margin: 0;
padding: 0 0 0 2em;
text-indent: -2em;
list-style-type: none;
counter-increment: item;
}
ol > li:before {
display: inline-block;
width: 1em;
padding-right: 0.5em;
font-weight: bold;
text-align: right;
content: counter(item) ".";
}
/* Add support for non-numeric lists */
ol[type="a"] > li:before {
content: counter(item, lower-alpha) ".";
}
ol[type="i"] > li:before {
content: counter(item, lower-roman) ".";
}
The above code adds support for lowercase letters, lowercase roman numerals. At the time of writing browsers do not differentiate between upper and lower case selectors for type so you can only pick uppercase or lowercase for your alternate ol types I guess.
Handle the onError
event for the image to reassign its source using JavaScript:
function imgError(image) {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
<img src="image.png" onerror="imgError(this);"/>
Or without a JavaScript function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
The following compatibility table lists the browsers that support the error facility:
Close: first you call ExcelFile
, but then you call the .parse
method and pass it the sheet name.
>>> xl = pd.ExcelFile("dummydata.xlsx")
>>> xl.sheet_names
[u'Sheet1', u'Sheet2', u'Sheet3']
>>> df = xl.parse("Sheet1")
>>> df.head()
Tid dummy1 dummy2 dummy3 dummy4 dummy5 \
0 2006-09-01 00:00:00 0 5.894611 0.605211 3.842871 8.265307
1 2006-09-01 01:00:00 0 5.712107 0.605211 3.416617 8.301360
2 2006-09-01 02:00:00 0 5.105300 0.605211 3.090865 8.335395
3 2006-09-01 03:00:00 0 4.098209 0.605211 3.198452 8.170187
4 2006-09-01 04:00:00 0 3.338196 0.605211 2.970015 7.765058
dummy6 dummy7 dummy8 dummy9
0 0.623354 0 2.579108 2.681728
1 0.554211 0 7.210000 3.028614
2 0.567841 0 6.940000 3.644147
3 0.581470 0 6.630000 4.016155
4 0.595100 0 6.350000 3.974442
What you're doing is calling the method which lives on the class itself, rather than the instance, which is okay (although not very idiomatic), but if you're doing that you would also need to pass the sheet name:
>>> parsed = pd.io.parsers.ExcelFile.parse(xl, "Sheet1")
>>> parsed.columns
Index([u'Tid', u'dummy1', u'dummy2', u'dummy3', u'dummy4', u'dummy5', u'dummy6', u'dummy7', u'dummy8', u'dummy9'], dtype=object)
With HTML5, you can do this natively with: <input name="first_name" placeholder="First Name">
This is not supported with all browsers though (IE)
This may work:
<input type="first_name" value="First Name" onfocus="this.value==this.defaultValue?this.value='':null">
Otherwise, if you are using jQuery, you can use .focus and .css to change the color.
I'm not quite sure what your problem is, but you need to specify the parameter name like so.
-(void) changeCellText:(NSIndexPath *) nowIndex{
UILabel *content = (UILabel *)[[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex] contentView] viewWithTag:contentTag];
content.text = [formatter stringFromDate:checkInDate.date];
}
HTML:
<div class="foo">
/* whatever is required */
</div>
CSS:
.foo {
top: 0;
transition: top ease 0.5s;
}
.foo:hover{
top: -10px;
}
This is just a basic transition to ease the div tag up by 10px when it is hovered on. The transition property's values can be edited along with the class.hover properties to determine how the transition works.
You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go
You should probably use either DateTime.ParseExact
or DateTime.TryParseExact
instead. They allow you to specify specific formats. I personally prefer the Try
-versions since I think they produce nicer code for the error cases.
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Java 8 provides the option of using streams which can be used to sort int[] array
as:
int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2
As mentioned in doc for parallelSort
:
The sorting algorithm is a parallel sort-merge that breaks the array into sub-arrays that are themselves sorted and then merged. When the sub-array length reaches a minimum granularity, the sub-array is sorted using the appropriate Arrays.sort method. If the length of the specified array is less than the minimum granularity, then it is sorted using the appropriate Arrays.sort method. The algorithm requires a working space no greater than the size of the original array. The ForkJoin common pool is used to execute any parallel tasks.
So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort
simply calls sequential sort algorithm.
Just in case we want to reverse sort the integer array we can make use of comparator as:
int[] reverseSorted = IntStream.of(array).boxed()
.sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting.
Here the solution.
To copy an img from an URL.
this URL: http://url/img.jpg
$image_Url=file_get_contents('http://url/img.jpg');
create the desired path finish the name with .jpg
$file_destino_path="imagenes/my_image.jpg";
file_put_contents($file_destino_path, $image_Url)
Interesting results on windows 8:
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'
Edit: That's a bug
I usually do as you describe:
Add a separate column with a random value (=RAND()
) and then perform a sort on that column.
Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.
You don't need jQuery for that, you can do it with normal javascript:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "a,b,c,d";
var res = str.split(","); // this returns an array
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
Useful simple class are forked by me on: https://gist.github.com/kiuz/816e24aa787c2d102dd0
public class OSValidator {
private static String OS = System.getProperty("os.name").toLowerCase();
public static void main(String[] args) {
System.out.println(OS);
if (isWindows()) {
System.out.println("This is Windows");
} else if (isMac()) {
System.out.println("This is Mac");
} else if (isUnix()) {
System.out.println("This is Unix or Linux");
} else if (isSolaris()) {
System.out.println("This is Solaris");
} else {
System.out.println("Your OS is not support!!");
}
}
public static boolean isWindows() {
return OS.contains("win");
}
public static boolean isMac() {
return OS.contains("mac");
}
public static boolean isUnix() {
return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
}
public static boolean isSolaris() {
return OS.contains("sunos");
}
public static String getOS(){
if (isWindows()) {
return "win";
} else if (isMac()) {
return "osx";
} else if (isUnix()) {
return "uni";
} else if (isSolaris()) {
return "sol";
} else {
return "err";
}
}
}
I suggest you put this code into a method and create a unit test.
public static boolean isLeapYear(int year) {
assert year >= 1583; // not valid before this date.
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
In the unit test
assertTrue(isLeapYear(2000));
assertTrue(isLeapYear(1904));
assertFalse(isLeapYear(1900));
assertFalse(isLeapYear(1901));
There are awk
built-in variables.
NR
- It gives the total number of records processed.
FNR
- It gives the total number of records for each input file.
If you've been using the OnDestry lifecycle hook, you might be interested in using something like this before calling window.location.href=...
this.router.ngOnDestroy();
window.location.href = 'http://www.cnn.com/';
that will trigger the OnDestry callback in your component that you might like.
Ohh, and also:
import { Router } from '@angular/router';
is where you find the router.
---EDIT--- Sadly, I might have been wrong in the example above. At least it's not working as exepected in my production code right now - so, until I have time to investigate further, I solve it like this (since my app really need the hook when possible)
this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});
Basically routing to any (dummy) route to force the hook, and then navigate as requested.
First create HashMap.
HashMap> mapList = new HashMap>();
Get value from HashMap against your input key.
ArrayList arrayList = mapList.get(key);
Add value to arraylist.
arrayList.add(addvalue);
Then again put arraylist against that key value. mapList.put(key,arrayList);
It will work.....
The best way to work with args for your winforms app is to use
string[] args = Environment.GetCommandLineArgs();
You can probably couple this with the use of an enum to solidify the use of the array througout your code base.
"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."
Found at:HERE
I assume this is *nix?
Use "here document":
sqlplus -s user/pass <<+EOF
select 1 from dual;
+EOF
EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):
$ echo 'select 1 from dual;'|sqlplus -s user/pw
1
----------
1
$
CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA
// files to upload
$filename = "https://example.s3.amazonaws.com/0.jpg";
// URL to upload to (Destination server)
$url = "https://otherserver/image";
AND
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($filename),
CURLOPT_HTTPHEADER => array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data",
"Content-Length: " . strlen(file_get_contents($filename)),
"API-Key: abcdefghi" //Optional if required
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";
//print_r($info['request_header']);
var_dump($response);
$err = curl_error($curl);
echo "error";
var_dump($err);
curl_close($curl);
Webkit's support for scrollbars is quite sophisticated. This CSS gives a very minimal scrollbar, with a light grey track and a darker thumb:
::-webkit-scrollbar
{
width: 12px; /* for vertical scrollbars */
height: 12px; /* for horizontal scrollbars */
}
::-webkit-scrollbar-track
{
background: rgba(0, 0, 0, 0.1);
}
::-webkit-scrollbar-thumb
{
background: rgba(0, 0, 0, 0.5);
}
This answer is a fantastic source of additional information.
For visualization our group had some success with prefuse. We extended it to handle architectural floorplates and bubble diagraming, and it didn't complain too much. They have a new Flex toolkit out too called Flare that uses a very similar API.
UPDATE: I'd have to agree with the comment, we ended up writing a lot of custom functionality/working around prefuse limitations. I can't say that starting from scratch would have been better though as we were able to demonstrate progress from day 1 by using prefuse. On the other hand if we were doing a second implementation of the same stuff, I might skip prefuse since we'd understand the requirements a lot better.
Update
While what I write below is true as a general answer about shared libraries, I think the most frequent cause of these sorts of message is because you've installed a package, but not installed the "-dev" version of that package.
Well, it's not lying - there is no libpthread_rt.so.1
in that listing. You probably need to re-configure and re-build it so that it depends on the library you have, or install whatever provides libpthread_rt.so.1
.
Generally, the numbers after the .so are version numbers, and you'll often find that they are symlinks to each other, so if you have version 1.1 of libfoo.so, you'll have a real file libfoo.so.1.0, and symlinks foo.so and foo.so.1 pointing to the libfoo.so.1.0. And if you install version 1.1 without removing the other one, you'll have a libfoo.so.1.1, and libfoo.so.1 and libfoo.so will now point to the new one, but any code that requires that exact version can use the libfoo.so.1.0 file. Code that just relies on the version 1 API, but doesn't care if it's 1.0 or 1.1 will specify libfoo.so.1. As orip pointed out in the comments, this is explained well at http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html.
In your case, you might get away with symlinking libpthread_rt.so.1
to libpthread_rt.so
. No guarantees that it won't break your code and eat your TV dinners, though.
$xml="l\rn";
$xml.="vv";
echo $xml;
But you should really look into http://us3.php.net/simplexml
Do you mean something like:
SELECT COLUMN1, COLUMN2 FROM MY_TABLE WHERE COLUMN1 = 'Value' OR COLUMN1 IS NULL
?
Vincent Marchetti has the right idea, but str.decode
has been deprecated in Python 3. In Python 3 you can make the same test with str.encode
:
try:
mystring.encode('ascii')
except UnicodeEncodeError:
pass # string is not ascii
else:
pass # string is ascii
Note the exception you want to catch has also changed from UnicodeDecodeError
to UnicodeEncodeError
.
To iterate through the keys of an object, use a for .. in
loop:
for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}
To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.
Removing a property of an object can be done by using the delete
keyword:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
Documentation:
Using file explorer, you can locate your database file like this:
data-->data-->your.package.name-->databases--->yourdbfile.db
Then you can use any SQLite fronted to explore your database. I use the SQLite Manager Firefox addon. It's nice, small, and fast.
Here is an example straight from PHP.net
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
in the foreach you can do a comparison of each key to something that you are looking for
If str
is null, undefined or 0, this code will set it to "hai"
function(nodeBox, str) {
str = str || "hai";
.
.
.
If you also need to pass 0, you can use:
function(nodeBox, str) {
if (typeof str === "undefined" || str === null) {
str = "hai";
}
.
.
.
Another thing: you could use reflection. If you'll cache this properly, then it'll clone 1,000,000 objects in 5.6 seconds (sadly, 16.4 seconds with inner objects).
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class Person
{
...
Job JobDescription
...
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class Job
{...
}
private static readonly Type stringType = typeof (string);
public static class CopyFactory
{
static readonly Dictionary<Type, PropertyInfo[]> ProperyList = new Dictionary<Type, PropertyInfo[]>();
private static readonly MethodInfo CreateCopyReflectionMethod;
static CopyFactory()
{
CreateCopyReflectionMethod = typeof(CopyFactory).GetMethod("CreateCopyReflection", BindingFlags.Static | BindingFlags.Public);
}
public static T CreateCopyReflection<T>(T source) where T : new()
{
var copyInstance = new T();
var sourceType = typeof(T);
PropertyInfo[] propList;
if (ProperyList.ContainsKey(sourceType))
propList = ProperyList[sourceType];
else
{
propList = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ProperyList.Add(sourceType, propList);
}
foreach (var prop in propList)
{
var value = prop.GetValue(source, null);
prop.SetValue(copyInstance,
value != null && prop.PropertyType.IsClass && prop.PropertyType != stringType ? CreateCopyReflectionMethod.MakeGenericMethod(prop.PropertyType).Invoke(null, new object[] { value }) : value, null);
}
return copyInstance;
}
I measured it in a simple way, by using the Watcher class.
var person = new Person
{
...
};
for (var i = 0; i < 1000000; i++)
{
personList.Add(person);
}
var watcher = new Stopwatch();
watcher.Start();
var copylist = personList.Select(CopyFactory.CreateCopyReflection).ToList();
watcher.Stop();
var elapsed = watcher.Elapsed;
RESULT: With inner object PersonInstance - 16.4, PersonInstance = null - 5.6
CopyFactory is just my test class where I have dozen of tests including usage of expression. You could implement this in another form in an extension or whatever. Don't forget about caching.
I didn't test serializing yet, but I doubt in an improvement with a million classes. I'll try something fast protobuf/newton.
P.S.: for the sake of reading simplicity, I only used auto-property here. I could update with FieldInfo, or you should easily implement this by your own.
I recently tested the Protocol Buffers serializer with the DeepClone function out of the box. It wins with 4.2 seconds on a million simple objects, but when it comes to inner objects, it wins with the result 7.4 seconds.
Serializer.DeepClone(personList);
SUMMARY: If you don't have access to the classes, then this will help. Otherwise it depends on the count of the objects. I think you could use reflection up to 10,000 objects (maybe a bit less), but for more than this the Protocol Buffers serializer will perform better.
If the Exception is being thrown in that try
block then at worst case scenario Exception
should be catching anything uncaught.
Consider that the first part of the test is throwing the Exception and wrap that in the try
block as well.
Assuming that you have your data in a 2d array, this should work:
import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()
You can also set a cmap
attribute to control which colors will appear through use of a colormap; i.e. replace the pylab.scatter
line with:
pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)
A list of color maps can be found here
This error might also occur if you have require.js (requirejs) implemented and you did not wrap some lib that you are using inside
define(['jquery'], function( jQuery ) {
... lib function ...
});
NOTE: you do not have to do this if this lib has AMD support. You can quickly check this by opening this lib and just ctrl+f "amd" :)
In Django 1.8, this is how I did mine.
from django.views.generic.base import RedirectView
url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))
Instead of using url
, you can use the pattern_name
, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.
To solve this with homebrew
, you can temporarily backdate homebrew-core
and set the HOMEBREW_NO_AUTO_UPDATE
variable to hold it in place:
cd `brew --repo homebrew/core`
git checkout f2a764ef944b1080be64bd88dca9a1d80130c558
export HOMEBREW_NO_AUTO_UPDATE=1
brew install python
I don't recommend permanently backdating homebrew-core, as you will miss out on security patches, but it is useful for testing purposes.
You can also extract old versions of homebrew formulae into your own tap (tap_owner/tap_name) using the brew extract
command:
brew extract python tap_owner/tap_name --version=3.6.5
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.
I was looking for slightly different task, but this looks like what you want:
git archive --remote=$REPO_URL HEAD:$DIR_NAME -- $FILE_NAME |
tar xO > /where/you/want/to/have.it
I mean, if you want to fetch path/to/file.xz
, you will set DIR_NAME
to path/to
and FILE_NAME
to file.xz
.
So, you'll end up with something like
git archive --remote=$REPO_URL HEAD:path/to -- file.xz |
tar xO > /where/you/want/to/have.it
And nobody keeps you from any other form of unpacking instead of tar xO
of course (It was me who need a pipe here, yeah).
Yes, ToList
will create a new list, but because in this case MyObject
is a reference type then the new list will contain references to the same objects as the original list.
Updating the SimpleInt
property of an object referenced in the new list will also affect the equivalent object in the original list.
(If MyObject
was declared as a struct
rather than a class
then the new list would contain copies of the elements in the original list, and updating a property of an element in the new list would not affect the equivalent element in the original list.)
On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
You have something like this:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
This answer is widely oriented around Git Flow. The tables have been generated with the nice ASCII Table Generator, and the history trees with this wonderful command (aliased as git lg
):
git log --graph --abbrev-commit --decorate --date=format:'%Y-%m-%d %H:%M:%S' --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%ad%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(dim white)- %an%C(reset)'
Tables are in reverse chronological order to be more consistent with the history trees. See also the difference between git merge
and git merge --no-ff
first (you usually want to use git merge --no-ff
as it makes your history look closer to the reality):
git merge
Commands:
Time Branch "develop" Branch "features/foo"
------- ------------------------------ -------------------------------
15:04 git merge features/foo
15:03 git commit -m "Third commit"
15:02 git commit -m "Second commit"
15:01 git checkout -b features/foo
15:00 git commit -m "First commit"
Result:
* 142a74a - YYYY-MM-DD 15:03:00 (XX minutes ago) (HEAD -> develop, features/foo)
| Third commit - Christophe
* 00d848c - YYYY-MM-DD 15:02:00 (XX minutes ago)
| Second commit - Christophe
* 298e9c5 - YYYY-MM-DD 15:00:00 (XX minutes ago)
First commit - Christophe
git merge --no-ff
Commands:
Time Branch "develop" Branch "features/foo"
------- -------------------------------- -------------------------------
15:04 git merge --no-ff features/foo
15:03 git commit -m "Third commit"
15:02 git commit -m "Second commit"
15:01 git checkout -b features/foo
15:00 git commit -m "First commit"
Result:
* 1140d8c - YYYY-MM-DD 15:04:00 (XX minutes ago) (HEAD -> develop)
|\ Merge branch 'features/foo' - Christophe
| * 69f4a7a - YYYY-MM-DD 15:03:00 (XX minutes ago) (features/foo)
| | Third commit - Christophe
| * 2973183 - YYYY-MM-DD 15:02:00 (XX minutes ago)
|/ Second commit - Christophe
* c173472 - YYYY-MM-DD 15:00:00 (XX minutes ago)
First commit - Christophe
git merge
vs git rebase
First point: always merge features into develop, never rebase develop from features. This is a consequence of the Golden Rule of Rebasing:
The golden rule of
git rebase
is to never use it on public branches.
Never rebase anything you've pushed somewhere.
I would personally add: unless it's a feature branch AND you and your team are aware of the consequences.
So the question of git merge
vs git rebase
applies almost only to the feature branches (in the following examples, --no-ff
has always been used when merging). Note that since I'm not sure there's one better solution (a debate exists), I'll only provide how both commands behave. In my case, I prefer using git rebase
as it produces a nicer history tree :)
git merge
Commands:
Time Branch "develop" Branch "features/foo" Branch "features/bar"
------- -------------------------------- ------------------------------- --------------------------------
15:10 git merge --no-ff features/bar
15:09 git merge --no-ff features/foo
15:08 git commit -m "Sixth commit"
15:07 git merge --no-ff features/foo
15:06 git commit -m "Fifth commit"
15:05 git commit -m "Fourth commit"
15:04 git commit -m "Third commit"
15:03 git commit -m "Second commit"
15:02 git checkout -b features/bar
15:01 git checkout -b features/foo
15:00 git commit -m "First commit"
Result:
* c0a3b89 - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\ Merge branch 'features/bar' - Christophe
| * 37e933e - YYYY-MM-DD 15:08:00 (XX minutes ago) (features/bar)
| | Sixth commit - Christophe
| * eb5e657 - YYYY-MM-DD 15:07:00 (XX minutes ago)
| |\ Merge branch 'features/foo' into features/bar - Christophe
| * | 2e4086f - YYYY-MM-DD 15:06:00 (XX minutes ago)
| | | Fifth commit - Christophe
| * | 31e3a60 - YYYY-MM-DD 15:05:00 (XX minutes ago)
| | | Fourth commit - Christophe
* | | 98b439f - YYYY-MM-DD 15:09:00 (XX minutes ago)
|\ \ \ Merge branch 'features/foo' - Christophe
| |/ /
|/| /
| |/
| * 6579c9c - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| | Third commit - Christophe
| * 3f41d96 - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/ Second commit - Christophe
* 14edc68 - YYYY-MM-DD 15:00:00 (XX minutes ago)
First commit - Christophe
git rebase
Commands:
Time Branch "develop" Branch "features/foo" Branch "features/bar"
------- -------------------------------- ------------------------------- -------------------------------
15:10 git merge --no-ff features/bar
15:09 git merge --no-ff features/foo
15:08 git commit -m "Sixth commit"
15:07 git rebase features/foo
15:06 git commit -m "Fifth commit"
15:05 git commit -m "Fourth commit"
15:04 git commit -m "Third commit"
15:03 git commit -m "Second commit"
15:02 git checkout -b features/bar
15:01 git checkout -b features/foo
15:00 git commit -m "First commit"
Result:
* 7a99663 - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\ Merge branch 'features/bar' - Christophe
| * 708347a - YYYY-MM-DD 15:08:00 (XX minutes ago) (features/bar)
| | Sixth commit - Christophe
| * 949ae73 - YYYY-MM-DD 15:06:00 (XX minutes ago)
| | Fifth commit - Christophe
| * 108b4c7 - YYYY-MM-DD 15:05:00 (XX minutes ago)
| | Fourth commit - Christophe
* | 189de99 - YYYY-MM-DD 15:09:00 (XX minutes ago)
|\ \ Merge branch 'features/foo' - Christophe
| |/
| * 26835a0 - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| | Third commit - Christophe
| * a61dd08 - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/ Second commit - Christophe
* ae6f5fc - YYYY-MM-DD 15:00:00 (XX minutes ago)
First commit - Christophe
develop
to a feature branchgit merge
Commands:
Time Branch "develop" Branch "features/foo" Branch "features/bar"
------- -------------------------------- ------------------------------- -------------------------------
15:10 git merge --no-ff features/bar
15:09 git commit -m "Sixth commit"
15:08 git merge --no-ff develop
15:07 git merge --no-ff features/foo
15:06 git commit -m "Fifth commit"
15:05 git commit -m "Fourth commit"
15:04 git commit -m "Third commit"
15:03 git commit -m "Second commit"
15:02 git checkout -b features/bar
15:01 git checkout -b features/foo
15:00 git commit -m "First commit"
Result:
* 9e6311a - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\ Merge branch 'features/bar' - Christophe
| * 3ce9128 - YYYY-MM-DD 15:09:00 (XX minutes ago) (features/bar)
| | Sixth commit - Christophe
| * d0cd244 - YYYY-MM-DD 15:08:00 (XX minutes ago)
| |\ Merge branch 'develop' into features/bar - Christophe
| |/
|/|
* | 5bd5f70 - YYYY-MM-DD 15:07:00 (XX minutes ago)
|\ \ Merge branch 'features/foo' - Christophe
| * | 4ef3853 - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| | | Third commit - Christophe
| * | 3227253 - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/ / Second commit - Christophe
| * b5543a2 - YYYY-MM-DD 15:06:00 (XX minutes ago)
| | Fifth commit - Christophe
| * 5e84b79 - YYYY-MM-DD 15:05:00 (XX minutes ago)
|/ Fourth commit - Christophe
* 2da6d8d - YYYY-MM-DD 15:00:00 (XX minutes ago)
First commit - Christophe
git rebase
Commands:
Time Branch "develop" Branch "features/foo" Branch "features/bar"
------- -------------------------------- ------------------------------- -------------------------------
15:10 git merge --no-ff features/bar
15:09 git commit -m "Sixth commit"
15:08 git rebase develop
15:07 git merge --no-ff features/foo
15:06 git commit -m "Fifth commit"
15:05 git commit -m "Fourth commit"
15:04 git commit -m "Third commit"
15:03 git commit -m "Second commit"
15:02 git checkout -b features/bar
15:01 git checkout -b features/foo
15:00 git commit -m "First commit"
Result:
* b0f6752 - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\ Merge branch 'features/bar' - Christophe
| * 621ad5b - YYYY-MM-DD 15:09:00 (XX minutes ago) (features/bar)
| | Sixth commit - Christophe
| * 9cb1a16 - YYYY-MM-DD 15:06:00 (XX minutes ago)
| | Fifth commit - Christophe
| * b8ddd19 - YYYY-MM-DD 15:05:00 (XX minutes ago)
|/ Fourth commit - Christophe
* 856433e - YYYY-MM-DD 15:07:00 (XX minutes ago)
|\ Merge branch 'features/foo' - Christophe
| * 694ac81 - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| | Third commit - Christophe
| * 5fd94d3 - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/ Second commit - Christophe
* d01d589 - YYYY-MM-DD 15:00:00 (XX minutes ago)
First commit - Christophe
git cherry-pick
When you just need one specific commit, git cherry-pick
is a nice solution (the -x
option appends a line that says "(cherry picked from commit...)" to the original commit message body, so it's usually a good idea to use it - git log <commit_sha1>
to see it):
Commands:
Time Branch "develop" Branch "features/foo" Branch "features/bar"
------- -------------------------------- ------------------------------- -----------------------------------------
15:10 git merge --no-ff features/bar
15:09 git merge --no-ff features/foo
15:08 git commit -m "Sixth commit"
15:07 git cherry-pick -x <second_commit_sha1>
15:06 git commit -m "Fifth commit"
15:05 git commit -m "Fourth commit"
15:04 git commit -m "Third commit"
15:03 git commit -m "Second commit"
15:02 git checkout -b features/bar
15:01 git checkout -b features/foo
15:00 git commit -m "First commit"
Result:
* 50839cd - YYYY-MM-DD 15:10:00 (XX minutes ago) (HEAD -> develop)
|\ Merge branch 'features/bar' - Christophe
| * 0cda99f - YYYY-MM-DD 15:08:00 (XX minutes ago) (features/bar)
| | Sixth commit - Christophe
| * f7d6c47 - YYYY-MM-DD 15:03:00 (XX minutes ago)
| | Second commit - Christophe
| * dd7d05a - YYYY-MM-DD 15:06:00 (XX minutes ago)
| | Fifth commit - Christophe
| * d0d759b - YYYY-MM-DD 15:05:00 (XX minutes ago)
| | Fourth commit - Christophe
* | 1a397c5 - YYYY-MM-DD 15:09:00 (XX minutes ago)
|\ \ Merge branch 'features/foo' - Christophe
| |/
|/|
| * 0600a72 - YYYY-MM-DD 15:04:00 (XX minutes ago) (features/foo)
| | Third commit - Christophe
| * f4c127a - YYYY-MM-DD 15:03:00 (XX minutes ago)
|/ Second commit - Christophe
* 0cf894c - YYYY-MM-DD 15:00:00 (XX minutes ago)
First commit - Christophe
git pull --rebase
I am not sure I can explain it better than Derek Gourlay... Basically, use git pull --rebase
instead of git pull
:) What's missing in the article though, is that you can enable it by default:
git config --global pull.rebase true
git rerere
Again, nicely explained here. But put simply, if you enable it, you won't have to resolve the same conflict multiple times anymore.
This error started out of the blue for me, on a test that had always worked. I couldn't find any suggestions that helped until I noticed my Macbook was running sluggishly. I noticed the CPU was pegged by another process, which I killed. The Jasmine async error disappeared and my tests are fine once again.
Don't ask me why, I don't know. But in my circumstance it seemed to be a lack of system resources at fault.
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
In modern browsers you do not need JQuery for this. Instead use
document.querySelectorAll('option:checked')
Or specify any DOM element instead of document
I built a plugin to inject parameters from the commandline into the task callback.
gulp.task('mytask', function (production) {
console.log(production); // => true
});
// gulp mytask --production
https://github.com/stoeffel/gulp-param
If someone finds a bug or has a improvement to it, I am happy to merge PRs.
I use Xcode 4.3.2, and my problem was that in there where a folder inside another folder with the same name, e.g myFolder/myFolder/.
The solution was to change the second folder's name e.g myFolder/_myFolder and the problem was solved.
I hope this can help some one.
I may be misunderstanding your question but it seems you should just be able to use a relative path as long as the production and development servers use the same path structure.
<script language="javascript" src="js/myLib.js" />
To add UNIQUE constraint using phpmyadmin, go to the structure of that table and find below and click that,
To remove the UNIQUE constraint, same way, go to the structure and scroll down till Indexes Tab and find below and click drop,
Hope this works.
Enjoy ;)
You can use Paros to sniff the network traffic from your iPhone. See this excellent step by step post for more information: http://blog.jerodsanto.net/2009/06/sniff-your-iphones-network-traffic/. Also, look in the comments for some advice for using other proxies to get the same job done.
One caveat is that Paras only sniffs HTTP GET/POST requests using the method above, so to sniff all network traffic, try the following:
- Just turn on network sharing over WiFi and run a packet sniffer like Cocoa Packet Analyzer (in OSX).
- Then connect to the new network from iPhone over WiFi. (SystemPreferences->Sharing->InternetSharing)
If you're after sniffing these packets on Windows, connect to the internet using Ethernet, share your internet connection, and use the Windows computer as your access point. Then, just run Wireshark as normal and intercept the packets flowing through, filtering by their startpoints. Alternatively, try using a network hub as Wireshark can trace all packets flowing through a network if they are using the same router endpoint address (as in a hub).
The answer is surprisingly simple - export the folder to itself! TortoiseSVN detects this special case and asks if you want to make the working copy unversioned. If you answer yes the control directories will be removed and you will have a plain, unversioned directory tree.
Given that your date format follows : "YYYY-MM-DD HH:MM:SS", if you need to find the difference between two dates in number of months :
(strftime('%m', date1) + 12*strftime('%Y', date1)) -
(strftime('%m', date2) + 12*strftime('%Y', date2))
Suppose you need only x:target/classes in your classpath. Then you just add this folder to your classpath and %IDEA%\lib\idea_rt.jar. Now it will work. That's it.
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});
I encountered this problem when I import GridSearchCV
.
Just changed sklearn.model_selection
to sklearn.grid_search
.
You can use here String literals
const Angle = ({show}) => {
const angle = `fa ${show ? 'fa-angle-down' : 'fa-angle-right'}`;
return <i className={angle} />
}
If you want to align the div
with pixel accurate, then use float. inline-block
seems to always requires you to chop off a few pixels (at least in IE)
A simple method of creating the service, adding headers and reading the JSON response,
private static void WebRequest()
{
const string WEBSERVICE_URL = "<<Web Service URL>>";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
Console.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
This part has problems:
Card* cardArray;
void Deck() {
cardArray = new Card[NUM_TOTAL_CARDS];
int cardCount = 0;
for (int i = 0; i > NUM_SUITS; i++) { //Error
for (int j = 0; j > NUM_RANKS; j++) { //Error
cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
cardCount++;
}
}
}
cardArray
is a dynamic array, but not a member of Card
class. It is strange if you would like to initialize a dynamic array which is not member of the classvoid Deck()
is not constructor of class Deck since you missed the
scope resolution operator. You may be confused with defining the constructor and the function with name Deck
and return type void
.<
not >
otherwise, loop will never
be executed.C:\xampp>mysql -u root -p mydatabase < C:\DB_Backups\stage-new.sql
Enter password:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the ma
nual that corresponds to your MySQL server version for the right syntax to use n
ear 'stage-new.sql
----lot of space----
' at line 1
The reason was when I dumped the DB I used following command :
mysqldump -h <host> -u <username> -p <database> > dumpfile.sql
dumpfile.sql
By mistaken dumpfile.sql added twice in the syntax.
Solution : I removed the dumpfile.sql text added to first line of the exported dumpfile.
every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:
var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;
javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode()
function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)
2020 Update:
javascript today supports other datatypes as well: Map
and WeakMap
. They behave more closely as hash maps than traditional objects.
I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.
map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });
<div id="map_canvas2" style="width: 850px; height: 600px">
</div>
The best way is
AddTaskViewController * add = [self.storyboard instantiateViewControllerWithIdentifier:@"addID"];
[self presentViewController:add animated:YES completion:nil];
Try this:
Now you can extend %base-class in any of your classes (e.g. .my-class).
%base-class {
width: 80%;
margin-left: 10%;
margin-right: 10%;
}
.my-base-class {
@extend %base-class;
}
.my-class {
@extend %base-class;
margin-bottom: 40px;
}
you should set document title in the life cycle of 'componentWillMount':
componentWillMount() {
document.title = 'your title name'
},
Syntax of waitpid()
:
pid_t waitpid(pid_t pid, int *status, int options);
The value of pid
can be:
pid
.pid
.The value of options is an OR of zero or more of the following constants:
WNOHANG
: Return immediately if no child has exited.WUNTRACED
: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.WCONTINUED
: Also return if a stopped child has been resumed by delivery of SIGCONT
.For more help, use man waitpid
.
You can use the ElementAt extension method on the list.
For example:
// Get the first item from the list
using System.Linq;
var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);
// Do something with firstItem
You can also try Mail.dll mail component, it has SSL support, unicode, and multi-national email support:
using(Pop3 pop3 = new Pop3())
{
pop3.Connect("mail.host.com"); // Connect to server and login
pop3.Login("user", "password");
foreach(string uid in pop3.GetAll())
{
IMail email = new MailBuilder()
.CreateFromEml(pop3.GetMessageByUID(uid));
Console.WriteLine( email.Subject );
}
pop3.Close(false);
}
You can download it here at https://www.limilabs.com/mail
Please note that this is a commercial product I've created.
I found this extension for VS code called Git Merger. It adds Git: Merge from
to the commands.
You can find the source images by extracting them from Other.artwork in UIKit ${SDKROOT}/System/Library/Frameworks/UIKit.framework/Other.artwork. The modding community has some tools for extracting them, here. Once you extract the image you can write some code to recolor it as necessary and set it as the button image. Whether or not you can actually ship such a thing (since you are embedding derived artwork) might be a little dicey, so maybe you want to talk to a lawyer.
Set DateFirst 1;
Select
Datepart(wk, TimeByDay) [Week]
,Dateadd(d,
CASE
WHEN Datepart(dw, TimeByDay) = 1 then 0
WHEN Datepart(dw, TimeByDay) = 2 then -1
WHEN Datepart(dw, TimeByDay) = 3 then -2
WHEN Datepart(dw, TimeByDay) = 4 then -3
WHEN Datepart(dw, TimeByDay) = 5 then -4
WHEN Datepart(dw, TimeByDay) = 6 then -5
WHEN Datepart(dw, TimeByDay) = 7 then -6
END
, TimeByDay) as StartOfWeek
from TimeByDay_Tbl
This is my logic. Set the first of the week to be Monday then calculate what is the day of the week a give day is, then using DateAdd and Case I calculate what the date would have been on the previous Monday of that week.
I use some css like this (based on css tricks):
@media screen and (min-width: 320px) and (max-width: 767px) and (orientation: portrait) {
html {
transform: rotate(-90deg);
transform-origin: left top;
width: 100vh;
height: 100vw;
overflow-x: hidden;
position: absolute;
top: 100%;
left: 0;
}
}
Here is a version that works in all modern browsers. The key is using appearance:none
which removes the default formatting. Since all of the formatting is gone, you have to add back in the arrow that visually differentiates the select from the input. Note: appearance
is not supported in IE.
Working example: https://jsfiddle.net/gs2q1c7p/
select:not([multiple]) {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
background-position: right 50%;_x000D_
background-repeat: no-repeat;_x000D_
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAMCAYAAABSgIzaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDZFNDEwNjlGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDZFNDEwNkFGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0NkU0MTA2N0Y3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0NkU0MTA2OEY3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuGsgwQAAAA5SURBVHjaYvz//z8DOYCJgUxAf42MQIzTk0D/M+KzkRGPoQSdykiKJrBGpOhgJFYTWNEIiEeAAAMAzNENEOH+do8AAAAASUVORK5CYII=);_x000D_
padding: .5em;_x000D_
padding-right: 1.5em_x000D_
}_x000D_
_x000D_
#mySelect {_x000D_
border-radius: 0_x000D_
}
_x000D_
<select id="mySelect">_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
</select>
_x000D_
Based on Arno Tenkink's suggestion in the comments, here is an example using a svg instead of a png for the arrow icon.
select:not([multiple]) {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
background-position: right 50%;_x000D_
background-repeat: no-repeat;_x000D_
background-image: url('data:image/svg+xml;utf8,<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" version="1"><path d="M4 8L0 4h8z"/></svg>');_x000D_
padding: .5em;_x000D_
padding-right: 1.5em_x000D_
}_x000D_
_x000D_
#mySelect {_x000D_
border-radius: 0_x000D_
}
_x000D_
<select id="mySelect">_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
</select>
_x000D_
```yaml
{
"this-json": "looks awesome..."
}
If you want to have keys a different colour to the parameters, set your language as yaml
@Ankanna's answer gave me the idea of going through github's supported language list and yaml
was my best find.
The items should be removed in reverse, otherwise it will cause an error. Also, I do not recommended simply setting the values to null
, as that may cause unexpected behaviour.
var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
Or if you prefer, you can make it a function:
function clearOptions(id)
{
var select = document.getElementById(id);
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
}
clearOptions("myselect");
If you just need to change some parameters of the View and the default behavior of ArrayAdapter its OK for you:
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CustomArrayAdapter<T> extends ArrayAdapter<T> {
public CustomArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
// Here all your customization on the View
view.setBackgroundColor(.......);
...
return view;
}
}
Just use like this somewhere inside the form
@method('PUT')
Mark the test with the ExpectedExceptionAttribute (this is the term in NUnit or MSTest; users of other unit testing frameworks may need to translate).
It might be an easiest way-
String recipientList = mEditTextTo.getText().toString();
String[] recipients = recipientList.split(",");
String subject = mEditTextSubject.getText().toString();
String message = mEditTextMessage.getText().toString();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Choose an email client"));
Use following JQuery. Demo
$(function() {
$('#row_dim').hide();
$('#type').change(function(){
if($('#type').val() == 'parcel') {
$('#row_dim').show();
} else {
$('#row_dim').hide();
}
});
});
Another take on @???'s answer (originally ), making less assumptions about the prefix and suffix specifics, and inspired by @Val's answer - but without polluting the global namespace; without any conditions; and hopefully easier to read.
The popular compilers provide a macro with the current function's signature. Now, functions are templatable; so the signature contains the template arguments. So, the basic approach is: Given a type, be in a function with that type as a template argument.
Unfortunately, the type name is wrapped in text describing the function, which is different between compilers. For example, with GCC, the signature of template <typename T> int foo()
with type double
is: int foo() [T = double]
.
So, how do you get rid of the wrapper text? @HowardHinnant's solution is the shortest and most "direct": Just use per-compiler magic numbers to remove a prefix and a suffix. But obviously, that's very brittle; and nobody likes magic numbers in their code. Instead, you get the macro value for a type with a known name, you can determine what prefix and suffix constitute the wrapping.
#include <string_view>
template <typename T> constexpr std::string_view type_name();
template <>
constexpr std::string_view type_name<void>()
{ return "void"; }
namespace detail {
using type_name_prober = void;
template <typename T>
constexpr std::string_view wrapped_type_name()
{
#ifdef __clang__
return __PRETTY_FUNCTION__;
#elif defined(__GNUC__)
return __PRETTY_FUNCTION__;
#elif defined(_MSC_VER)
return __FUNCSIG__;
#else
#error "Unsupported compiler"
#endif
}
constexpr std::size_t wrapped_type_name_prefix_length() {
return wrapped_type_name<type_name_prober>().find(type_name<type_name_prober>());
}
constexpr std::size_t wrapped_type_name_suffix_length() {
return wrapped_type_name<type_name_prober>().length()
- wrapped_type_name_prefix_length()
- type_name<type_name_prober>().length();
}
} // namespace detail
template <typename T>
constexpr std::string_view type_name() {
constexpr auto wrapped_name = detail::wrapped_type_name<T>();
constexpr auto prefix_length = detail::wrapped_type_name_prefix_length();
constexpr auto suffix_length = detail::wrapped_type_name_suffix_length();
constexpr auto type_name_length = wrapped_name.length() - prefix_length - suffix_length;
return wrapped_name.substr(prefix_length, type_name_length);
}
See it on GodBolt. This should be working with MSVC as well.
Option 1
Use float:left
on both div
elements and set a % width for both div elements with a combined total width of 100%.
Use box-sizing: border-box;
on the floating div elements. The value border-box forces the padding and borders into the width and height instead of expanding it.
Use clearfix on the <div id="wrapper">
to clear the floating child elements which will make the wrapper div scale to the correct height.
.clearfix:after {
content: " ";
visibility: hidden;
display: block;
height: 0;
clear: both;
}
#first, #second{
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
#wrapper {
width: 500px;
border: 1px solid black;
}
#first {
border: 1px solid red;
float:left;
width:50%;
}
#second {
border: 1px solid green;
float:left;
width:50%;
}
http://jsfiddle.net/dqC8t/3381/
Option 2
Use position:absolute
on one element and a fixed width on the other element.
Add position:relative to <div id="wrapper">
element to make child elements absolutely position to the <div id="wrapper">
element.
#wrapper {
width: 500px;
border: 1px solid black;
position:relative;
}
#first {
border: 1px solid red;
width:100px;
}
#second {
border: 1px solid green;
position:absolute;
top:0;
left:100px;
right:0;
}
http://jsfiddle.net/dqC8t/3382/
Option 3
Use display:inline-block
on both div
elements and set a % width for both div elements with a combined total width of 100%.
And again (same as float:left
example) use box-sizing: border-box;
on the div elements. The value border-box forces the padding and borders into the width and height instead of expanding it.
NOTE: inline-block elements can have spacing issues as it is affected by spaces in HTML markup. More information here: https://css-tricks.com/fighting-the-space-between-inline-block-elements/
#first, #second{
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
#wrapper {
width: 500px;
border: 1px solid black;
position:relative;
}
#first {
width:50%;
border: 1px solid red;
display:inline-block;
}
#second {
width:50%;
border: 1px solid green;
display:inline-block;
}
http://jsfiddle.net/dqC8t/3383/
A final option would be to use the new display option named flex, but note that browser compatibility might come in to play:
http://caniuse.com/#feat=flexbox
http://www.sketchingwithcss.com/samplechapter/cheatsheet.html
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
@mplungjan, @eduard-luca
function isDate(str) {
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2],10);
var mm = parseInt(parms[1],10);
var dd = parseInt(parms[0],10);
var date = new Date(yyyy,mm-1,dd,12,0,0,0);
return mm === (date.getMonth()+1) &&
dd === date.getDate() &&
yyyy === date.getFullYear();
}
new Date() uses local time, hour 00:00:00 will show the last day when we have "Summer Time" or "DST (Daylight Saving Time)" events.
Example:
new Date(2010,9,17)
Sat Oct 16 2010 23:00:00 GMT-0300 (BRT)
Another alternative is to use getUTCDate().
Take a look at this page for general Boostrap layout information http://getbootstrap.com/css/#grid-offsetting
Try this:
<div class="col-xs-2" id="p1">One</div>
<div class="col-xs-3">
<div class="col-xs-8 col-xs-offset-2" id="p2">Two</div>
</div>
<div class="col-xs-2" id="p3">Three</div>
<div class="col-xs-3">
<div class="col-xs-8 col-xs-offset-2" id="p4">Four</div>
</div>
<div class="col-xs-2" id="p5">Five</div>
I've split the width into 5 uneven div
with col-xs- 2,3,2,3,2
respectively. The two div
with col-xs-3
are 1.5x the size of the col-xs-2 div
, so the column width needs to be 2/3x (1.5 x 2/3 = 1
) the col-xs-3
widths to match the rest.
to convert YYYY-MM-DD string to datetime object, datetime.fromisoformat
could be used.
from datetime import datetime
date_string = "2012-12-12 10:10:10"
print (datetime.fromisoformat(date_string))
2012-12-12 10:10:10
im
is "image process name"
example /f /im notepad.exe
is specified to kill image process name (program) notepad.exe
This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks. When we get browser support for css 3 you'll get your vertical centering without sinning.
For a better explanation of the technique you can look the article I adapted it from, but basically it involves adding an extra element and applying different styles in IE and browsers that support position:table\table-cell
on non-table elements.
<div class="valign-outer">
<div class="valign-middle">
<div class="valign-inner">
Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.
</div>
</div>
</div>
<style>
/* Non-structural styling */
.valign-outer { height: 400px; border: 1px solid red; }
.valign-inner { border: 1px solid blue; }
</style>
<!--[if lte IE 7]>
<style>
/* For IE7 and earlier */
.valign-outer { position: relative; overflow: hidden; }
.valign-middle { position: absolute; top: 50%; }
.valign-inner { position: relative; top: -50% }
</style>
<![endif]-->
<!--[if gt IE 7]> -->
<style>
/* For other browsers */
.valign-outer { position: static; display: table; overflow: hidden; }
.valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }
</style>
There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.
Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases. If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.
Update: We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See this other question for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.
CSS has many pseudo selector like, :active, :hover, :focus, so you can use.
Html
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css
.btn{
background: #ccc;
} .btn:focus{
background: red;
}
Go to httpd.conf
on /Applications/MAMP/conf/apache
and see if the LoadModule rewrite_module modules/mod_rewrite.so
line is un-commented (without the # at the beginning)
and change these from ...
<VirtualHost *:80>
ServerName ...
DocumentRoot /....
</VirtualHost>
To this:
<VirtualHost *:80>
ServerAdmin ...
ServerName ...
DocumentRoot ...
<Directory ...>
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory ...>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
Two approaches that come to mind:
>>> df
A B C D
0 0.424634 1.716633 0.282734 2.086944
1 -1.325816 2.056277 2.583704 -0.776403
2 1.457809 -0.407279 -1.560583 -1.316246
3 -0.757134 -1.321025 1.325853 -2.513373
4 1.366180 -1.265185 -2.184617 0.881514
>>> df.iloc[:, 2]
0 0.282734
1 2.583704
2 -1.560583
3 1.325853
4 -2.184617
Name: C
>>> df[df.columns[2]]
0 0.282734
1 2.583704
2 -1.560583
3 1.325853
4 -2.184617
Name: C
Edit: The original answer suggested the use of df.ix[:,2]
but this function is now deprecated. Users should switch to df.iloc[:,2]
.
Commands listed for use in normal mode (prefix with : for command mode).
Tested in Vim.
By line amount:
By line numbers:
Backwards range given, OK to swap (y/n)?
In bash version 4 associative arrays were introduced.
declare -A arr
arr["key1"]=val1
arr+=( ["key2"]=val2 ["key3"]=val3 )
The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.
for key in ${!arr[@]}; do
echo ${key} ${arr[${key}]}
done
Will loop over all key values and echo them out.
Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Please find below a way that works on all browsers. Basically I put the input on top the image. I make it huge using font-size so the user is always clicking the upload button.
.myFile {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
float: left;_x000D_
clear: left;_x000D_
}_x000D_
.myFile input[type="file"] {_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
opacity: 0;_x000D_
font-size: 100px;_x000D_
filter: alpha(opacity=0);_x000D_
cursor: pointer;_x000D_
}
_x000D_
<label class="myFile">_x000D_
<img src="http://wscont1.apps.microsoft.com/winstore/1x/c37a9d99-6698-4339-acf3-c01daa75fb65/Icon.13385.png" alt="" />_x000D_
<input type="file" />_x000D_
</label>
_x000D_
Your submission will cancel the redirect or vice versa.
I do not see the reason for the redirect in the first place since why do you have an order form that does nothing.
That said, here is how to do it. Firstly NEVER put code on the submit button but do it in the onsubmit, secondly return false to stop the submission
NOTE This code will IGNORE the action and ONLY execute the script due to the return false/preventDefault
function redirect() {
window.location.replace("login.php");
return false;
}
using
<form name="form1" id="form1" method="post" onsubmit="return redirect()">
<input type="submit" class="button4" name="order" id="order" value="Place Order" >
</form>
Or unobtrusively:
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
window.location.replace("login.php");
return false;
}
}
using
<form id="form1" method="post">
<input type="submit" class="button4" value="Place Order" >
</form>
jQuery:
$("#form1").on("submit",function(e) {
e.preventDefault(); // cancel submission
window.location.replace("login.php");
});
Example:
$("#form1").on("submit", function(e) {_x000D_
e.preventDefault(); // cancel submission_x000D_
alert("this could redirect to login.php"); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<form id="form1" method="post" action="javascript:alert('Action!!!')">_x000D_
<input type="submit" class="button4" value="Place Order">_x000D_
</form>
_x000D_
I made the following filter:
angular.module('app').filter('ifEmpty', function() {
return function(input, defaultValue) {
if (angular.isUndefined(input) || input === null || input === '') {
return defaultValue;
}
return input;
}
});
To be used like this:
<span>{{aPrice | currency | ifEmpty:'N/A'}}</span>
<span>{{aNum | number:3 | ifEmpty:0}}</span>
On strings and memory allocation:
A string in C is just a sequence of char
s, so you can use char *
or a char
array wherever you want to use a string data type:
typedef struct {
int number;
char *name;
char *address;
char *birthdate;
char gender;
} patient;
Then you need to allocate memory for the structure itself, and for each of the strings:
patient *createPatient(int number, char *name,
char *addr, char *bd, char sex) {
// Allocate memory for the pointers themselves and other elements
// in the struct.
patient *p = malloc(sizeof(struct patient));
p->number = number; // Scalars (int, char, etc) can simply be copied
// Must allocate memory for contents of pointers. Here, strdup()
// creates a new copy of name. Another option:
// p->name = malloc(strlen(name)+1);
// strcpy(p->name, name);
p->name = strdup(name);
p->address = strdup(addr);
p->birthdate = strdup(bd);
p->gender = sex;
return p;
}
If you'll only need a few patient
s, you can avoid the memory management at the expense of allocating more memory than you really need:
typedef struct {
int number;
char name[50]; // Declaring an array will allocate the specified
char address[200]; // amount of memory when the struct is created,
char birthdate[50]; // but pre-determines the max length and may
char gender; // allocate more than you need.
} patient;
On linked lists:
In general, the purpose of a linked list is to prove quick access to an ordered collection of elements. If your llist
contains an element called num
(which presumably contains the patient number), you need an additional data structure to hold the actual patient
s themselves, and you'll need to look up the patient number every time.
Instead, if you declare
typedef struct llist
{
patient *p;
struct llist *next;
} list;
then each element contains a direct pointer to a patient
structure, and you can access the data like this:
patient *getPatient(list *patients, int num) {
list *l = patients;
while (l != NULL) {
if (l->p->num == num) {
return l->p;
}
l = l->next;
}
return NULL;
}
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
The best way is to use the ncurses library - though this might be a sledgehammer to crack a nut if you just want to output a simple coloured string
One-liner using spread operator.
const updatedData = originalData.map(x => (x.id === id ? { ...x, updatedField: 1 } : x));
BigDecimal no = new BigDecimal(10); //you can add like this also
no = no.add(new BigDecimal(10));
System.out.println(no);
20
Use:
x.astype(int)
Here is the reference.
I am brand new to WindowBuilder, and, in fact, just getting back into Java after a few years, but I implemented "something", then thought I'd look it up and came across this thread.
I'm in the middle of testing this, so, based on being new to all this, I'm sure I must be missing something.
Here's what I did, where "runTxt" is a textbox and "runName" is a data member of the class:
public void focusGained(FocusEvent e) {
if (e.getSource() == runTxt) {
System.out.println("runTxt got focus");
runTxt.selectAll();
}
}
public void focusLost(FocusEvent e) {
if (e.getSource() == runTxt) {
System.out.println("runTxt lost focus");
if(!runTxt.getText().equals(runName))runName= runTxt.getText();
System.out.println("runText.getText()= " + runTxt.getText() + "; runName= " + runName);
}
}
Seems a lot simpler than what's here so far, and seems to be working, but, since I'm in the middle of writing this, I'd appreciate hearing of any overlooked gotchas. Is it an issue that the user could enter & leave the textbox w/o making a change? I think all you've done is an unnecessary assignment.
Close Android Studio Go to C:\Users\UserName.android and rename the folder:
Go to C:\Users\UserName.AndroidStudio3.x\system OR (Android studio 4 and Higher) Go to C:\Users\UserName\AppData\Local\Google\AndroidStudio4.x and rename these folders:
caches to caches_old
compiler to compiler_old
compile-server to compile-server_old
conversion to conversion_old
external_build_system to external_build_system_old
frameworks to frameworks_old
gradle to gradle_old
resource_folder_cache to resource_folder_cache_old
Open the Android Studio and open your project again.
Android complete source code for adding events and reminders with start and end time format.
/** Adds Events and Reminders in Calendar. */
private void addReminderInCalendar() {
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(true) + "events");
ContentResolver cr = getContentResolver();
TimeZone timeZone = TimeZone.getDefault();
/** Inserting an event in calendar. */
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.TITLE, "Sanjeev Reminder 01");
values.put(CalendarContract.Events.DESCRIPTION, "A test Reminder.");
values.put(CalendarContract.Events.ALL_DAY, 0);
// event starts at 11 minutes from now
values.put(CalendarContract.Events.DTSTART, cal.getTimeInMillis() + 11 * 60 * 1000);
// ends 60 minutes from now
values.put(CalendarContract.Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.HAS_ALARM, 1);
Uri event = cr.insert(EVENTS_URI, values);
// Display event id
Toast.makeText(getApplicationContext(), "Event added :: ID :: " + event.getLastPathSegment(), Toast.LENGTH_SHORT).show();
/** Adding reminder for event added. */
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(true) + "reminders");
values = new ContentValues();
values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
values.put(CalendarContract.Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(CalendarContract.Reminders.MINUTES, 10);
cr.insert(REMINDERS_URI, values);
}
/** Returns Calendar Base URI, supports both new and old OS. */
private String getCalendarUriBase(boolean eventUri) {
Uri calendarURI = null;
try {
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/") : Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri.parse("content://com.android.calendar/") : Uri
.parse("content://com.android.calendar/calendars");
}
} catch (Exception e) {
e.printStackTrace();
}
return calendarURI.toString();
}
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
Hope this is something what you are trying to do :
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
private Map ttp = new HashMap();
public void test() {
Field declaredField = null;
try {
declaredField = Test.class.getDeclaredField("ttp");
boolean accessible = declaredField.isAccessible();
declaredField.setAccessible(true);
ConcurrentHashMap<Object, Object> concHashMap = new ConcurrentHashMap<Object, Object>();
concHashMap.put("key1", "value1");
declaredField.set(this, concHashMap);
Object value = ttp.get("key1");
System.out.println(value);
declaredField.setAccessible(accessible);
} catch (NoSuchFieldException
| SecurityException
| IllegalArgumentException
| IllegalAccessException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
Test test = new Test();
test.test();
}
}
It prints :
value1
You can take advantage of the fact that span
is an inline element
span{
word-spacing:10px;
}
However, this solution will break if you have more than one word of text in your span
Yes, you can do it by:
-- Install Atom
-- Install Python on your system. Atom requires the latest version of Python (currently 3.8.5). Note that Anaconda sometimes may not have this version, and depending on how you installed it, it may not have been added to the PATH. Install Python via https://www.python.org/ and make sure to check the option of "Add to PATH"
-- Install "scripts" on Atom via "Install packages"
-- Install any other autocomplete package like Kite on Atom if you want that feature.
-- Run it
I tried the normal way (I had Python installed via Anaconda) but Atom did not detect it & gave me an error when I tried to run Python. This is the way around it.
On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<newBooks>
<xsl:for-each select="books/book">
<newBook>
<countNo><xsl:value-of select="position()"/></countNo>
<title>
<xsl:value-of select="title"/>
</title>
</newBook>
</xsl:for-each>
</newBooks>
</xsl:template>
</xsl:stylesheet>
http://locomotivejs.org/ provides a way to structure an app built with Node.js and Express.
From the website:
"Locomotive is a web framework for Node.js. Locomotive supports MVC patterns, RESTful routes, and convention over configuration, while integrating seamlessly with any database and template engine. Locomotive builds on Express, preserving the power and simplicity you've come to expect from Node."
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
Here is the working solution:
table {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
thead, tbody, tr, td, th { display: block; }_x000D_
_x000D_
tr:after {_x000D_
content: ' ';_x000D_
display: block;_x000D_
visibility: hidden;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
thead th {_x000D_
height: 30px;_x000D_
_x000D_
/*text-align: left;*/_x000D_
}_x000D_
_x000D_
tbody {_x000D_
height: 120px;_x000D_
overflow-y: auto;_x000D_
}_x000D_
_x000D_
thead {_x000D_
/* fallback */_x000D_
}_x000D_
_x000D_
_x000D_
tbody td, thead th {_x000D_
width: 19.2%;_x000D_
float: left;_x000D_
}
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<table class="table table-striped">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Make</th>_x000D_
<th>Model</th>_x000D_
<th>Color</th>_x000D_
<th>Year</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="filterable-cell">Ford</td>_x000D_
<td class="filterable-cell">Escort</td>_x000D_
<td class="filterable-cell">Blue</td>_x000D_
<td class="filterable-cell">2000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="filterable-cell">Ford</td>_x000D_
<td class="filterable-cell">Escort</td>_x000D_
<td class="filterable-cell">Blue</td>_x000D_
<td class="filterable-cell">2000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="filterable-cell">Ford</td>_x000D_
<td class="filterable-cell">Escort</td>_x000D_
<td class="filterable-cell">Blue</td>_x000D_
<td class="filterable-cell">2000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="filterable-cell">Ford</td>_x000D_
<td class="filterable-cell">Escort</td>_x000D_
<td class="filterable-cell">Blue</td>_x000D_
<td class="filterable-cell">2000</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
Link to jsfiddle
You can also do it this way
private static string GetPaddingSequence(int padding)
{
StringBuilder SB = new StringBuilder();
for (int i = 0; i < padding; i++)
{
SB.Append("0");
}
return SB.ToString();
}
public static string FormatNumber(int number, int padding)
{
return number.ToString(GetPaddingSequence(padding));
}
Finally call the function FormatNumber
string x = FormatNumber(1,2);
Output will be 01 which is based on your padding parameter. Increasing it will increase the number of 0s
An alternate solution, use concatenation and the chr function:
select 'J' || chr(38) || 'J Construction' from dual;
I was having the same problem here. Found out that the problem was with an Advanced Property of the file. There is there an option with the name 'Compilation Action' (may be not with the exact words, I am translating - my VS is in Portuguese).
My Class1.cs file was there as "Content" and I just had to change it to "Compile" to make it work, and have the classes recognized by the others files in the same project.
Use this...
$('#cat_icon').click(function () {
$('#categories').toggle("slow");
//$('#cat_icon').hide();
});
$('.panel_title').click(function () {
$('#categories').toggle("slow");
//$('#cat_icon').show();
});
See this Example
Greetings.
You have to first escape the backslash because it's a literal (yielding \\
), and then escape it again because of the regular expression (yielding \\\\
). So, Try:
s.replaceAll("'", "\\\\'");
output:
You\'ll be totally awesome, I\'m really terrible
You could give your hidden field an id:
<input type="hidden" id="myField" value="" />
and then when you want to assign its value:
document.getElementById('myField').value = product(2, 3);
Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load
event.
Earlier this could be achieved using DOCKER_OPTS
in the /etc/default/docker
config file which worked on Ubuntu 14:04 and had some issues on Ubuntu 15:04. Not sure if this has been fixed.
The below line needs to go into the file /etc/default/docker
on the host which runs the docker daemon. The change points to the private registry is installed in your local network. Note: you would require to restart the docker service followed with this change.
DOCKER_OPTS="--insecure-registry <priv registry hostname/ip>:<port>"
I had the same problem, I was trying to listen the change on some select and actually the problem was I was using the event instead of the event.target which is the select object.
INCORRECT :
$(document).on('change', $("select"), function(el) {
console.log($(el).val());
});
CORRECT :
$(document).on('change', $("select"), function(el) {
console.log($(el.target).val());
});
You may also try appending a space at the start and end of keyword: /\s+123456\s+/i
.
Once you have made your choice of the exit command, press enter to finally quit Vim and close the editor (but not the terminal).
Do note that when you press shift + “:”
the editor will have the next keystrokes displayed at the bottom left of the terminal. Now if you want to simply quit, write exit or wq (save and exit)
Here is an example of an AWK I used a while ago. It is an AWK that prints new AWKS. AWK and SED being similar it may be a good template.
ls | awk '{ print "awk " "'"'"'" " {print $1,$2,$3} " "'"'"'" " " $1 ".old_ext > " $1 ".new_ext" }' > for_the_birds
It looks excessive, but somehow that combination of quotes works to keep the ' printed as literals. Then if I remember correctly the vaiables are just surrounded with quotes like this: "$1". Try it, let me know how it works with SED.
Use List<Integer> list = new ArrayList<Integer>();
It depends on various things. But in general algorithms using a Divide-and-Conquer / dichotomic approach will perform well for sorting problems as they present interesting average-case complexities.
To understand which algorithms work best, you will need basic knowledge of algorithms complexity and big-O notation, so you can understand how they rate in terms of average case, best case and worst case scenarios. If required, you'd also have to pay attention to the sorting algorithm's stability.
For instance, usually an efficient algorithm is quicksort. However, if you give quicksort a perfectly inverted list, then it will perform poorly (a simple selection sort will perform better in that case!). Shell-sort would also usually be a good complement to quicksort if you perform a pre-analysis of your list.
Have a look at the following, for "advanced searches" using divide and conquer approaches:
And these more straighforward algorithms for less complex ones:
The above are the usual suspects when getting started, but there are countless others.
As pointed out by R. in the comments and by kriss in his answer, you may want to have a look at HeapSort, which provides a theoretically better sorting complexity than a quicksort (but will won't often fare better in practical settings). There are also variants and hybrid algorithms (e.g. TimSort).
.py
: This is normally the input source code that you've written..pyc
: This is the compiled bytecode. If you import a module, python will build a *.pyc
file that contains the bytecode to make importing it again later easier (and faster)..pyo
: This was a file format used before Python 3.5 for *.pyc
files that were created with optimizations (-O
) flag. (see the note below).pyd
: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dllAlso for some further discussion on .pyc
vs .pyo
, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)
- When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
- Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only
__doc__
strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.- A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
- When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.
Note:
On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo
files.
This means that .pyc
files represent both unoptimized and optimized bytecode.
x = [1, 10, 100]
for i in x:
print '%02d' % i
results in:
01
10
100
Read more information about string formatting using % in the documentation.
You can sort by values in reverse order (largest to smallest) using a dictionary comprehension:
{k: d[k] for k in sorted(d, key=d.get, reverse=True)}
# {'b': 4, 'a': 3, 'c': 2, 'd': 1}
If you want to sort by values in ascending order (smallest to largest)
{k: d[k] for k in sorted(d, key=d.get)}
# {'d': 1, 'c': 2, 'a': 3, 'b': 4}
If you want to sort by the keys in ascending order
{k: d[k] for k in sorted(d)}
# {'a': 3, 'b': 4, 'c': 2, 'd': 1}
This works on CPython 3.6+ and any implementation of Python 3.7+ because dictionaries keep insertion order.
you can follow the below command to install using the wheel file at your local
pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl
Try this:
public static int? ParseNullableInt(this string value)
{
int intValue;
if (int.TryParse(value, out intValue))
return intValue;
return null;
}
Just simply use isset($_POST['radio']) so that whenever i click any of the radio button, the one that is clicked is set to the post.
<form method="post" action="sample.php">
select sex:
<input type="radio" name="radio" value="male">
<input type="radio" name="radio" value="female">
<input type="submit" value="submit">
</form>
<?php
if (isset($_POST['radio'])){
$Sex = $_POST['radio'];
}
?>
Here is an example from my code (for threaded pool, but just change class name and you'll have process pool):
def execute_run(rp):
... do something
pool = ThreadPoolExecutor(6)
for mat in TESTED_MATERIAL:
for en in TESTED_ENERGIES:
for ecut in TESTED_E_CUT:
rp = RunParams(
simulations, DEST_DIR,
PARTICLE, mat, 960, 0.125, ecut, en
)
pool.submit(execute_run, rp)
pool.join()
Basically:
pool = ThreadPoolExecutor(6)
creates a pool for 6 threadspool.submit(execute_run, rp)
adds a task to pool, first arogument is a function called in in a thread/process, rest of the arguments are passed to the called function. pool.join
waits until all tasks are done. Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship. If you want the same user record to have the possibility of having more than 1 related profile record, go with a separate primary key, otherwise stick with what you have.
As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.
I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).
Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.
orderedtest - it works but I don't recommend it because:
Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.
You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.
The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.
This means the test method that is declared in the first place executes before the one that is declared in second place, etc.
To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.
I strongly suggest some old and tested rules:
VERY IMPORTANT
In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.
Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.
Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach($preparedManufacturers as $optionId => $value) {
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect('manufacturer');
$products->addFieldToFilter(array(
array('attribute'=>'manufacturer', 'eq'=> $optionId,
));
echo "<li>" . $value . " - (" . $optionId . ") - (Products: ".count($products).")</li>";
}
echo "</ul>";
}
Even I too faced similar issue,
fatal error RC1015: cannot open include file 'afxres.h'. from this code
Replacing afxres.h with Winresrc.h and declaring IDC_STATIC as -1 worked for me. (Using visual studio Premium 2012)
//#include "afxres.h"
#include "WinResrc.h"
#define IDC_STATIC -1
The standard Java classloader is a stickler for directory structure. Each entry in the classpath is a directory or jar file (or zip file, really), which it then searches for the given class file. For example, if your classpath is ".;my.jar", it will search for com.example.Foo in the following locations:
./com/example/
my.jar:/com/example/
That is, it will look in the subdirectory that has the 'modified name' of the package, where '.' is replaced with the file separator.
Also, it is noteworthy that you cannot nest .jar files.
Another python3 implementation that involves the use of Abstract classes with super(). You should remember that
super().__init__(name, 10)
has the same effect as
Person.__init__(self, name, 10)
Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it.
Hence super()
gets translated to Person
and then if you include the hidden self, you get the above code frag.
from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
name = ""
age = 0
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
@abstractmethod
def showName(self):
pass
@abstractmethod
def showAge(self):
pass
class Man(Person):
def __init__(self, name, height):
self.height = height
# Person.__init__(self, name, 10)
super().__init__(name, 10) # same as Person.__init__(self, name, 10)
# basically used to call the superclass init . This is used incase you want to call subclass init
# and then also call superclass's init.
# Since there's a hidden self in the super's parameters, when it's is called,
# the superclasses attributes are a part of the same object that was sent out in the super() method
def showIdentity(self):
return self.name, self.age, self.height
def showName(self):
pass
def showAge(self):
pass
a = Man("piyush", "179")
print(a.showIdentity())
<>
is generally a good replacement for XOR wherever it can apply to booleans.
If you cannot use TRUNCATE
(e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:
ALTER TABLE mytable AUTO_INCREMENT = 1
perl -0pE 's{^KEY.*?\K\s+(\d+)$}{ $1}msg;' data.txt > data_merged-lines.txt
-0
gobbles the whole file instead of reading it line-by-line;
pE
wraps code with loop and prints the output, see details in http://perldoc.perl.org/perlrun.html;
^KEY
match "KEY" in the beginning of line, followed by non-greedy match of anything (.*?
) before sequence of
\s+
of any kind including line breaks;(\d+)
which we capture and later re-insert as $1
;followed by the end of line $
.
\K
conveniently excludes everything on its left hand side from substitution so { $1}
replaces only 1-2 sequence, see http://perldoc.perl.org/perlre.html.
It is stretching because align-self
default value is stretch
.
Set align-self
to center
.
align-self: center;
See documentation here: align-self