I had the same problem, resolved it by adding
<filtering>true</filtering>
in pom.xml :
before (didn't work):
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
after(it worked):
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
After that you just run mvn clean install and deploy application.
This is an older thread,but I will post my answer for others. I have to recreate the project in a different workspace after the changes to make it work, as discussed in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer
Similarly if you want link through s3Client you can use below.
System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));
Apparently, you did it right. But here is a list of things you'll need with examples from a working application:
1) A context.xml file in META-INF, specifying your data source:
<Context>
<Resource
name="jdbc/DsWebAppDB"
auth="Container"
type="javax.sql.DataSource"
username="sa"
password=""
driverClassName="org.h2.Driver"
url="jdbc:h2:mem:target/test/db/h2/hibernate"
maxActive="8"
maxIdle="4"/>
</Context>
2) web.xml which tells the container that you are using this resource:
<resource-env-ref>
<resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml
, but it's similar in hibernate.cfg.xml
<persistence-unit name="dswebapp">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
</properties>
</persistence-unit>
I used this strategy: i excluded every field which is not marked with @SerializedName annotation, i.e.:
public class Dummy {
@SerializedName("VisibleValue")
final String visibleValue;
final String hiddenValue;
public Dummy(String visibleValue, String hiddenValue) {
this.visibleValue = visibleValue;
this.hiddenValue = hiddenValue;
}
}
public class SerializedNameOnlyStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(SerializedName.class) == null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
Gson gson = new GsonBuilder()
.setExclusionStrategies(new SerializedNameOnlyStrategy())
.create();
Dummy dummy = new Dummy("I will see this","I will not see this");
String json = gson.toJson(dummy);
It returns
{"VisibleValue":"I will see this"}
You can use chosen.i download all file from this link Chosen download Link
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="prism.css" rel="stylesheet" type="text/css" />
<link href="chosen.css" rel="stylesheet" type="text/css" />
<script src="jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="chosen.jquery.js" type="text/javascript"></script>
<script src="prism.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(".chzn-select").chosen();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ion-view view-title="Profile">
<ion-content class="padding">
<div>
<label class="item item-input">
<div class="input-label">Enter Your Option</div>
<select class="chzn-select" multiple="true" name="faculty" style="width:1000px;">
<option value="Option 2.1">Option 2.1</option>
<option value="Option 2.2">Option 2.2</option>
<option value="Option 2.3">Option 2.3</option>
</select>
</label>
</div>
</ion-content>
</ion-view>
</div>
</form>
</body>
</html>
All file on all same folder
You can with HTML5
NB: The file data returned MUST be base64 encoded because you cannot JSON encode binary data
In my AJAX
response I have a data structure that looks like this:
{
result: 'OK',
download: {
mimetype: string(mimetype in the form 'major/minor'),
filename: string(the name of the file to download),
data: base64(the binary data as base64 to download)
}
}
That means that I can do the following to save a file via AJAX
var a = document.createElement('a');
if (window.URL && window.Blob && ('download' in a) && window.atob) {
// Do it the HTML5 compliant way
var blob = base64ToBlob(result.download.data, result.download.mimetype);
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = result.download.filename;
a.click();
window.URL.revokeObjectURL(url);
}
The function base64ToBlob was taken from here and must be used in compliance with this function
function base64ToBlob(base64, mimetype, slicesize) {
if (!window.atob || !window.Uint8Array) {
// The current browser doesn't have the atob function. Cannot continue
return null;
}
mimetype = mimetype || '';
slicesize = slicesize || 512;
var bytechars = atob(base64);
var bytearrays = [];
for (var offset = 0; offset < bytechars.length; offset += slicesize) {
var slice = bytechars.slice(offset, offset + slicesize);
var bytenums = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
bytenums[i] = slice.charCodeAt(i);
}
var bytearray = new Uint8Array(bytenums);
bytearrays[bytearrays.length] = bytearray;
}
return new Blob(bytearrays, {type: mimetype});
};
This is good if your server is dumping filedata to be saved. However, I've not quite worked out how one would implement a HTML4 fallback
As an addition to msangel answer I would like to add the following code block:
private static CompletableFuture<Boolean> redirectToLogger(final InputStream inputStream, final Consumer<String> logLineConsumer) {
return CompletableFuture.supplyAsync(() -> {
try (
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
) {
String line = null;
while((line = bufferedReader.readLine()) != null) {
logLineConsumer.accept(line);
}
return true;
} catch (IOException e) {
return false;
}
});
}
It allows to redirect the input stream (stdout, stderr) of the process to some other consumer. This might be System.out::println or anything else consuming strings.
Usage:
...
Process process = processBuilder.start()
CompletableFuture<Boolean> stdOutRes = redirectToLogger(process.getInputStream(), System.out::println);
CompletableFuture<Boolean> stdErrRes = redirectToLogger(process.getErrorStream(), System.out::println);
System.out.println(stdOutRes.get());
System.out.println(stdErrRes.get());
System.out.println(process.waitFor());
Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.
If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).
This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.
https://support.microsoft.com/en-us/kb/938397
For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:
http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe
"int" is primitive data-type and "Integer" in Wrapper Class in Java. "Integer" can be used as an argument to a method which requires an object, where as "int" can be used as an argument to a method which requires an integer value, that can be used for arithmetic expression.
Ideally runtime exceptions should not be thrown. A checked exception(business exception) should be created for your scenario. Because if either of these exception is thrown and logged, it misguides the developer while going through the logs. Instead business exceptions do not create that panic and usually ignored while troubleshooting logs.
In my case, changing the order of Maven Dependencies from Build Path configuration did not work for me. I changed its order from Run configuration.
Follow these steps:
• Go to Run -> Run Configurations...
• Click on the unit test's run configuration and click on the Classpath tab.
• check Use temporary JAR to specify classpath (to avoid classpath length limitations).
May be it is enough and your test works. You should try, so press Run button. If it did not work. Follow all previous steps again and without pressing Run button, go to the next step.
• In sub branches of User Entries move Maven Dependencies above your project or test class.
• Click Run button.
As of Android O this is now possible to define directly from the XML and my bug is now closed!
TL;DR:
First you must add your fonts to the project
Second you add a font family, like so:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/lobster_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="@font/lobster_italic" />
</font-family>
Finally, you can use the font in a layout or style:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/lobster"/>
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/lobster</item>
</style>
Enjoy!
textTitle.replace(/ /g, '%20');
This answer builds upon the earlier answer by Keith.
egrep -v "^[[:blank:]]*#"
should filter out comment lines.
egrep -v "^[[:blank:]]*(#|$)"
should filter out both comments and empty lines, as is frequently useful.
For information about [:blank:]
and other character classes, refer to https://en.wikipedia.org/wiki/Regular_expression#Character_classes.
If you have installed postgres via the Windows installer you can start it in Services like so:
Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium
Don’t Repeat Your CSS
a.abc, a.xyz{
margin-left:20px;
}
OR
a{
margin-left:20px;
}
I never figured out the root of the problem however I was able to fix this problem. I deleted the Google Chrome app cache folder which solved the problem.
C:\Users[users]\AppData\Local\Google\Chrome
Smarter:
for (String key : hashMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
You can do it with a table, like this:
<table width="100%">
<tr>
<td style="width: 50%">Left Text</td>
<td style="width: 50%; text-align: right;">Right Text</td>
</tr>
</table>
Or, you can do it with CSS like this:
<div style="float: left;">
Left text
</div>
<div style="float: right;">
Right text
</div>
1. Installing latest npm version
npm install –g npm@latest
(You can type "npm –version" to check that)
2. Installing Node
a. Install node new version via following URL: https://nodejs.org/en/download/current/
Follow the default choices
b. Remove C:\Users\\AppData\Roaming\NPM
c. Remove C:\Users\\AppData\Roaming\npm-cache
Optionally:
d. (Delete node_modules folder in your current project folder)
e. npm cache verify
f. npm install
Using join Another variation is to use join. Now the query could look like:
SELECT a.id, a.value, SUM(b.Value)FROM RunTotalTestData a,
RunTotalTestData b
WHERE b.id <= a.id
GROUP BY a.id, a.value
ORDER BY a.id;
for more you can visite this link http://askme.indianyouth.info/details/calculating-simple-running-totals-in-sql-server-12
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
Modify catalina.bat to add
set JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"
and
CATALINA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
Optional: Add below line to run the debug mode by default when you run startup.bat
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
Eclipse or STS select debug configuration right click -> new
connection type -> Standard socket Attach
Port -> 8000 (as given in the CATALINA_OPTS)
Host -> localhost or IP address
For multiple interval types use a nested construction as in:
UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)
For updating a given date in the column date
to 1 year + 1 day
I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.
In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.
In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile
or /etc/.bashrc
but otherwise, they're not permanent. They're stored in RAM.
There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.
You can view shell variables with the set
command (though note that unlike windows, variables are not set in linux with the set command).
set -o posix; set
(doing that set -o posix once first, helps not display too much unnecessary stuff). So set
displays shell variables.
You can view environment variables with the env
command
shell variables are set with e.g. just a = 5
environment variables are set with export, export also sets the shell variable
Here you see shell variable zzz set with zzz = 5, and see it shows when running set
but doesn't show as an environment variable.
Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables
$ zzz=5
$ set | grep zzz
zzz=5
$ env | grep zzz
$ export yyy=5
$ set | grep yyy
yyy=5
$ env | grep yyy
yyy=5
$
other useful threads
https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables
https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference
Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf
then it sets $1 to asdf, and if you do echo $1
you see asdf. If you do set a=5
it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose
, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose
to turn verbose off. Windows has no such usage for its set command.
When you want to edit something in Angular you need to insert an ngModel in your html
try this in your sample:
<input type="text" name="abc" class="color" ng-model="myStyle.color">
You don't need to watch the change at all!
Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.
Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.
Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.
Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?
What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.
To bring Alex L.'s helpful answer, akhan's helpful answer, and Blckknght's helpful answer together with some additional information:
Standard Unix signal SIGPIPE
is sent to a process writing to a pipe when there's no process reading from the pipe (anymore).
head
by design stop reading prematurely from a pipe, once they've received enough data.By default - i.e., if the writing process does not explicitly trap SIGPIPE
- the writing process is simply terminated, and its exit code is set to 141
, which is calculated as 128
(to signal termination by signal in general) + 13
(SIGPIPE
's specific signal number).
By design, however, Python itself traps SIGPIPE
and translates it into a Python IOError
instance with errno
value errno.EPIPE
, so that a Python script can catch it, if it so chooses - see Alex L.'s answer for how to do that.
If a Python script does not catch it, Python outputs error message IOError: [Errno 32] Broken pipe
and terminates the script with exit code 1
- this is the symptom the OP saw.
In many cases this is more disruptive than helpful, so reverting to the default behavior is desirable:
Using the signal
module allows just that, as stated in akhan's answer; signal.signal()
takes a signal to handle as the 1st argument and a handler as the 2nd; special handler value SIG_DFL
represents the system's default behavior:
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
Quoting API on referencedColumnName:
The name of the column referenced by this foreign key column.
Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.
Where this would be used?
When there is a composite PK in referenced table, then you need to specify column name you are referencing.
This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.
Depending on what problem you're trying to solve, there might be a faster algorithm.
Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':
pd.read_csv('sample.csv',dtype={'ID':'string'})
As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').
You can use this simple code:
<a href="" onclick="return false;">add new action</a><br>
Can you test with surefire 2.6 and either configure Surefire with <testFailureIgnore>true</testFailureIgnore>
.
Or on the command line:
mvn install -Dmaven.test.failure.ignore=true
Finally I found solution myself.
I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class)
and implement custom serializer:
public class OrderTypeSerializer extends JsonSerializer<OrderType> {
@Override
public void serialize(OrderType value, JsonGenerator generator,
SerializerProvider provider) throws IOException,
JsonProcessingException {
generator.writeStartObject();
generator.writeFieldName("id");
generator.writeNumber(value.getId());
generator.writeFieldName("name");
generator.writeString(value.getName());
generator.writeEndObject();
}
}
From Django docs :
To handle both of these situations, Django has a consistent way of processing filter() calls. Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects, but for multi-valued relations, they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.
filter()
are applied simultaneously.
That means that doing :objs = Mymodel.objects.filter(a=True, b=False)
will return a queryset with raws from model Mymodel
where a=True
AND b=False
.
filter()
, in some case, will provide the same result. Doing :objs = Mymodel.objects.filter(a=True).filter(b=False)
will return a queryset with raws from model Mymodel
where a=True
AND b=False
too. Since you obtain "first" a queryset with records which have a=True
and then it's restricted to those who have b=False
at the same time.
filter()
comes when there are multi-valued relations
, which means you are going through other models (such as the example given in the docs, between Blog and Entry models). It is said that in that case (...) they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.
Which means that it applies the successives filter()
on the target model directly, not on previous filter()
If I take the example from the docs :
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
remember that it's the model Blog
that is filtered, not the Entry
. So it will treat the 2 filter()
independently.
It will, for instance, return a queryset with Blogs, that have entries that contain 'Lennon' (even if they are not from 2008) and entries that are from 2008 (even if their headline does not contain 'Lennon')
THIS ANSWER goes even further in the explanation. And the original question is similar.
This enhances the accepted answer by decorating the $http service with an abort method as follows ...
'use strict';
angular.module('admin')
.config(["$provide", function ($provide) {
$provide.decorator('$http', ["$delegate", "$q", function ($delegate, $q) {
var getFn = $delegate.get;
var cancelerMap = {};
function getCancelerKey(method, url) {
var formattedMethod = method.toLowerCase();
var formattedUrl = encodeURI(url).toLowerCase().split("?")[0];
return formattedMethod + "~" + formattedUrl;
}
$delegate.get = function () {
var cancelerKey, canceler, method;
var args = [].slice.call(arguments);
var url = args[0];
var config = args[1] || {};
if (config.timeout == null) {
method = "GET";
cancelerKey = getCancelerKey(method, url);
canceler = $q.defer();
cancelerMap[cancelerKey] = canceler;
config.timeout = canceler.promise;
args[1] = config;
}
return getFn.apply(null, args);
};
$delegate.abort = function (request) {
console.log("aborting");
var cancelerKey, canceler;
cancelerKey = getCancelerKey(request.method, request.url);
canceler = cancelerMap[cancelerKey];
if (canceler != null) {
console.log("aborting", cancelerKey);
if (request.timeout != null && typeof request.timeout !== "number") {
canceler.resolve();
delete cancelerMap[cancelerKey];
}
}
};
return $delegate;
}]);
}]);
WHAT IS THIS CODE DOING?
To cancel a request a "promise" timeout must be set. If no timeout is set on the HTTP request then the code adds a "promise" timeout. (If a timeout is set already then nothing is changed).
However, to resolve the promise we need a handle on the "deferred". We thus use a map so we can retrieve the "deferred" later. When we call the abort method, the "deferred" is retrieved from the map and then we call the resolve method to cancel the http request.
Hope this helps someone.
LIMITATIONS
Currently this only works for $http.get but you can add code for $http.post and so on
HOW TO USE ...
You can then use it, for example, on state change, as follows ...
rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
angular.forEach($http.pendingRequests, function (request) {
$http.abort(request);
});
});
How do we retrieve a value from a text field?
mytestField.getText();
ActionListner
example:
mytextField.addActionListener(this);
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
textArea.append(text + newline);
textField.selectAll();
}
Yes, divs and CSS are usually a better and easier way to place your HTML. There are many different ways to do this and it all depends on the context.
For instance, if you want to place an image to the right of your text, you could do it like so:
<p style="width: 500px;">
<img src="image.png" style="float: right;" />
This is some text
</p>
And if you want to display multiple items side by side, float is also usually preferred.For example:
<div>
<img src="image1.png" style="float: left;" />
<img src="image2.png" style="float: left;" />
<img src="image3.png" style="float: left;" />
</div>
Floating these images to the same side will have then laying next to each other for as long as you hava horizontal space.
I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!
Full Example on Codesandbox (DEMO):
https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js
From list of converter tools I found Kexi. It is a UI tool to import from various DB servers (including MySQL) into SQLite. When importing some database (say from MySQL) it stores it in Kexi format. The Kexi format is the 'native' SQLite format. So simply copy the kexi file and have your data in sqlite format
input password program
.modle small
.stack 100h
.data
s pasword db 34
input pasword db "enter pasword","$"
valid db ?
invalid db?
.code
mov ax, @ data
mov db, ax
mov ah,09h
mov dx, offest s pasword
int 21h
mov ah, 01h
cmp al, s pasword
je v
jmp nv
v:
mov ah, 09h
mov dx, offset valid
int 21h
nv:
mov ah, 09h
mov dx, offset invalid
int 21h
mov ah, 04ch
int 21
end
$(".datepicker").datepicker({maxDate: '0'});
This will set the maxDate to +0 days from the current date (i.e. today). See:
What is being returned is an anonymous type so create a new class with 2 fields
class BasicProjectInfo {
string name;
string id;
}
and return new BasicProjectInfo(pro.ProjectName, pro.ProjectId);
. You method in this case will return a List<BasicProjectInfo>
I needed the following bindings to get mine to work:
<binding name="SI_PurchaseRequisition_ISBindingSSL">
<security mode="Transport">
<transport clientCredentialType="Basic" proxyCredentialType="None" realm="" />
</security>
</binding>
Run the command prompt as admin and cd to bin directory of MySQL
Generally it is (C:\Program Files\MySQL\mysql-5.6.36-winx64\bin)
Run command : mysqld --install. (This command will install MySQL services and if services already installed it will prompt.)
Run below commands to start and stop server
To start : net start mysql
To stop : net stop mysql
Run mysql command.
Enjoy !!
By default git revert
refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD
is in fact a merge commit.
If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.
Often this will be parent number one, for example if you were on master
and did git merge unwanted
and then decided to revert the merge of unwanted
. The first parent would be your pre-merge master
branch and the second parent would be the tip of unwanted
.
In this case you could do:
git revert -m 1 HEAD
Weirdness is highly subjective, I just suggest to follow the official recommendation:
Guide to naming conventions on groupId, artifactId and version
groupId
will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.eg.
org.apache.maven
,org.apache.commons
A good way to determine the granularity of the groupId is to use the project structure. That is, if the current project is a multiple module project, it should append a new identifier to the parent's groupId.
eg.
org.apache.maven
,org.apache.maven.plugins
,org.apache.maven.reporting
artifactId
is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.eg.
maven
,commons-math
version
if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.eg.
2.0
,2.0.1
,1.3.1
In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.
But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:
{ Id: 1,
name:'john',
phones:[{title:'home',number:111111,...},
{title:'office',number:22222,...}]
}
sends
{ Id: 1,
name:'john',
phones:[object object]
phones:[object object]
}
You can use this code: You shouldn't use this code:
byte[] bytes = streamReader.CurrentEncoding.GetBytes(streamReader.ReadToEnd());
Please see the comment to this answer as to why. I will leave the answer, so people know about the problems with this approach, because I didn't up till now.
https://groups.google.com/forum/#!topic/google-appengine-stackoverflow/QZGJg2tlfA4
From what I've found online, this is a bug introduced in JDK 1.7.0_45. I've read it will be fixed in the next release of Java, but it's not out yet. Supposedly, it was fixed in 1.7.0_60b01, but I can't find where to download it and 1.7.0_60b02 re-introduces the bug.
I managed to get around the problem by reverting back to JDK 1.7.0_25. Probably not the solution you wanted, but it's the only way I've been able to get it working. Don't forget add JDK 1.7.0_25 in Eclipse after installing the JDK.
Please DO NOT REPLY directly to this email but go to StackOverflow: Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined
I had the same error. The problem was this extra symbol ">" added by mistake between the tags </ComboBox.SelectedValue> and </ComboBox>:
<ComboBox
ItemsSource="{Binding StatusTypes}"
DisplayMemberPath="StatusName"
SelectedValuePath="StatusID">
<ComboBox.SelectedValue>
<Binding Path="StatusID"/>
</ComboBox.SelectedValue>
>
</ComboBox>
and here is the correct code:
<ComboBox
ItemsSource="{Binding StatusTypes}"
DisplayMemberPath="StatusName"
SelectedValuePath="StatusID">
<ComboBox.SelectedValue>
<Binding Path="StatusID"/>
</ComboBox.SelectedValue>
</ComboBox>
Yes, you can get your project back. Just rename the yourproject.apk
file to yourproject.zip
, and you will get all the files inside that ZIP file. We are changing the file extension from .apk to .zip. From that ZIP file, extract the classes.dex
file and decompile it by following way.
First, you need a tool to extract all the (compiled) classes on the DEX to a JAR. There's one called dex2jar, which is made by a Chinese student.
Then, you can use JD-GUI to decompile the classes in the JAR to source code. The resulting source code should be quite readable, as dex2jar applies some optimizations.
They are not doing the same job: $emit
dispatches an event upwards through the scope hierarchy, while $broadcast
dispatches an event downwards to all child scopes.
I use to detect Apple browser engine, this simple JavaScript condition:
navigator.vendor.startsWith('Apple')
I encountered this error, and the fix appears to be turning off SNI, which Python 2.7 does not support:
Actually wrapping of text happens automatically in tables. The blunder people commit while testing is to hypothetically assume a long string like "ggggggggggggggggggggggggggggggggggggggggggggggg" and complain that it doesn't wrap. Practically there is no word in English that is this long and even if there is, there is a faint chance that it will be used within that <td>
.
Try testing with sentences like "Counterposition is superstitious in predetermining circumstances".
This error also can happen when working with http.request
, probably your request is not finished yet.
Example:
const req = https.request(options, res => {})
And you always need to add this line: req.end()
With this function we will order to finish sending request.
As in documentation is said:
With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
It sounds like you're not asking for a general-purpose memoization decorator (i.e., you're not interested in the general case where you want to cache return values for different argument values). That is, you'd like to have this:
x = obj.name # expensive
y = obj.name # cheap
while a general-purpose memoization decorator would give you this:
x = obj.name() # expensive
y = obj.name() # cheap
I submit that the method-call syntax is better style, because it suggests the possibility of expensive computation while the property syntax suggests a quick lookup.
[Update: The class-based memoization decorator I had linked to and quoted here previously doesn't work for methods. I've replaced it with a decorator function.] If you're willing to use a general-purpose memoization decorator, here's a simple one:
def memoize(function):
memo = {}
def wrapper(*args):
if args in memo:
return memo[args]
else:
rv = function(*args)
memo[args] = rv
return rv
return wrapper
Example usage:
@memoize
def fibonacci(n):
if n < 2: return n
return fibonacci(n - 1) + fibonacci(n - 2)
Another memoization decorator with a limit on the cache size can be found here.
To calculate tax, you could use round
(after all, that's what the restaurant does):
def calc_tax(mealPrice):
tax = round(mealPrice*.06,2)
return tax
To display the data, you could use a multi-line string, and the string format method:
def display_data(mealPrice, tax):
total=round(mealPrice+tax,2)
print('''\
Your Meal Price is {m:=5.2f}
Tax {x:=5.2f}
Total {t:=5.2f}
'''.format(m=mealPrice,x=tax,t=total))
Note the format method was introduced in Python 2.6, for earlier versions you'll need to use old-style string interpolation %
:
print('''\
Your Meal Price is %5.2f
Tax %5.2f
Total %5.2f
'''%(mealPrice,tax,total))
Then
mealPrice=input_meal()
tax=calc_tax(mealPrice)
display_data(mealPrice,tax)
yields:
# Enter the meal subtotal: $43.45
# Your Meal Price is 43.45
# Tax 2.61
# Total 46.06
I tried to Resize Canvas using jQuery but it din't work well. I think CSS3 is the best option you can try on, if you want on hover zooming at certain level.
Following hover option from other codepan link:
.style_prevu_kit:hover{
z-index: 2;
-webkit-transition: all 200ms ease-in;
-webkit-transform: scale(1.5);
-ms-transition: all 200ms ease-in;
-ms-transform: scale(1.5);
-moz-transition: all 200ms ease-in;
-moz-transform: scale(1.5);
transition: all 200ms ease-in;
transform: scale(1.5);
}
Follow my codepan link:
Use a progress bar with the style set to Marquee
. This represents an indeterminate progress bar.
myProgressBar.Style = ProgressBarStyle.Marquee;
You can also use the MarqueeAnimationSpeed
property to set how long it will take the little block of color to animate across your progress bar.
Actually, char* name
is not a pointer to a constant, but a pointer to a variable. You might be talking about this other question.
What is the difference between char * const and const char *?
As a developer, you should probably start learning set operations (difference, union, intersection). You can imagine your array as one "set", and the keys you are searching for the other.
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
echo in_array_all( [3,2,5], [5,8,3,1,2] ); // true, all 3, 2, 5 present
echo in_array_all( [3,2,5,9], [5,8,3,1,2] ); // false, since 9 is not present
function in_array_any($needles, $haystack) {
return !empty(array_intersect($needles, $haystack));
}
echo in_array_any( [3,9], [5,8,3,1,2] ); // true, since 3 is present
echo in_array_any( [4,9], [5,8,3,1,2] ); // false, neither 4 nor 9 is present
To build further upon the ajax part which you may or may not use (from the comments)
a simple way to load another page and replace it with your current one is:
<script>
$(document).ready( function() {
$.ajax({
type: 'get',
url: 'http://pageToLoad.from',
success: function(response) {
// response = data which has been received and passed on to the 'success' function.
$('body').html(response);
}
});
});
<script>
Short answer: mathematically speaking, no, in practical terms, yes, for example for Intentional Programming.
Technically, the answer would be "no, it's not needed" because it's expressible using other constructs. But in practice, I use for i in range(len(a)
(or for _ in range(len(a))
if I don't need the index) to make it explicit that I want to iterate as many times as there are items in a sequence without needing to use the items in the sequence for anything.
So: "Is there a need?"? — yes, I need it to express the meaning/intent of the code for readability purposes.
See also: https://en.wikipedia.org/wiki/Intentional_programming
And obviously, if there is no collection that is associated with the iteration at all, for ... in range(len(N))
is the only option, so as to not resort to i = 0; while i < N; i += 1 ...
As the list of possible events is not tied to p:ajax
itself but to the component it is used with, you'll have to ask the component for which ajax events it supports.
There are multiple ways to determine the ajax events for a given component:
1) Ask the component in xhtml:
You can output the list directly in xhtml by binding that component to a request scoped variable and printing the eventNames
property:
<p:autoComplete binding="#{ac}"></p:autoComplete>
<h:outputText value="#{ac.eventNames}" />
This outputs
[blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup,
mousedown, mousemove, mouseout, mouseover, mouseup, select, itemSelect,
itemUnselect, query, moreText, clear]
2) Ask the component in java code:
Figure out the component implementation class and invoke its' implementation of javax.faces.component.UIComponentBase.getEventNames()
method:
import javax.faces.component.UIComponentBase;
public class SomeTest {
public static void main(String[] args) {
dumpEvents(new org.primefaces.component.inputtext.InputText());
dumpEvents(new org.primefaces.component.autocomplete.AutoComplete());
dumpEvents(new org.primefaces.component.datatable.DataTable());
}
private static void dumpEvents(UIComponentBase comp) {
System.out.println(
comp + ":\n\tdefaultEvent: " + comp.getDefaultEventName() + ";\n\tEvents: " + comp.getEventNames());
}
}
This outputs:
org.primefaces.component.inputtext.InputText@239963d8:
defaultEvent: valueChange;
Events: [blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup, select]
org.primefaces.component.autocomplete.AutoComplete@72d818d1:
defaultEvent: valueChange;
Events: [blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup, select, itemSelect, itemUnselect, query, moreText, clear]
org.primefaces.component.datatable.DataTable@614ddd49:
defaultEvent: null;
Events: [rowUnselect, colReorder, tap, rowEditInit, toggleSelect, cellEditInit, sort, rowToggle, cellEdit, rowSelectRadio, filter, cellEditCancel, rowSelect, contextMenu, taphold, rowReorder, colResize, rowUnselectCheckbox, rowDblselect, rowEdit, page, rowEditCancel, virtualScroll, rowSelectCheckbox]
3) 'rtfm' ;-)
Best option is to look into the documentation of the particular component in use as hopefully provided by the component developers, not limited to PrimeFaces btw. (p:ajax
can be attached to any component providing ajax behaviors).
The advantage over previous suggestions is that the documentation not only provides the event names, but also enhanced description of the event potentially enriched with an event type class that can be caught by a listener.
For example the org.primefaces.event.SelectEvent
in case of
<p:ajax event="itemSelect" listener="#{anyBean.onItemSelect}"/>
and listener method signature public void onItemSelect(SelectEvent)
provides additional event contextual data.
Where there is no explicit list of ajax events on a compoment in the PrimeFaces documentation, the list of on* javascript callbacks can be used as events by removing the 'on' and using the remainder as an event name. The other answers in this question provides help on these plain dom events too.
Building on @nad2000's answer and @Pavel's answer here, this is where I ended up for my Flyway migration scripts. Handling for scenarios where the database schema was manually modified.
DO $$
BEGIN
IF NOT EXISTS(
SELECT TRUE FROM pg_attribute
WHERE attrelid = (
SELECT c.oid
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE
n.nspname = CURRENT_SCHEMA()
AND c.relname = 'device_ip_lookups'
)
AND attname = 'active_date'
AND NOT attisdropped
AND attnum > 0
)
THEN
RAISE NOTICE 'ADDING COLUMN';
ALTER TABLE device_ip_lookups
ADD COLUMN active_date TIMESTAMP;
ELSE
RAISE NOTICE 'SKIPPING, COLUMN ALREADY EXISTS';
END IF;
END $$;
Date to LocalDate
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate to Date
LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
How do I invoke a maven task without leaving vi?
Maven is no different than any other shell command:
:!mvn
You can :set makeprg=mvn
if you already have a favourite key mapping for :make
.
Can I get code completion?
Yes, eclim is great, a bridge between vim's editing efficiency and Eclipse's Java language-specific awareness.
<C-n>
and <C-p>
are not-so-great, but amazingly helpful.
How's the syntax highlighting?
More than good enough for a regex-based highligher.
You may want to consider tools for other vim+java purposes, like code templates (snippetEmu—default snippets suck, but customizability shines), searching for usages and going to declarations (eclim, grep, ctags), generating getters and setters (java_getset, or eclim), automatic imports (eclim). You might also need a java shell for quick experiments (the BeanShell, a.k.a. bsh
).
i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application. I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked? I wanted to do this,
if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}
I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,
int i;
private void button1_Click(object sender, EventArgs e)
{
i = 1;
label3.Text = "Principle";
label4.Text = "Rate";
label5.Text = "Time";
label6.Text = "Simple Interest";
}
private void button2_Click(object sender, EventArgs e)
{
i = 2;
label3.Text = "SI";
label4.Text = "Rate";
label5.Text = "Time";
label6.Text = "Principle";
}
private void button5_Click(object sender, EventArgs e)
{
try
{
if (i == 1)
{
si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
textBox4.Text = Convert.ToString(si);
}
if (i == 2)
{
p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
textBox4.Text = Convert.ToString(p);
}
I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function. It worked. Give your suggestions if any. Thank you.
I resolved the same issue by running Workbench as administrator.
...I guess it's because of restrictions on company computers, in my case...
I had the same issue until i close teamviewer
running on my pc. Then it worked fine!
myList.GroupBy(test => test.id)
.Select(grp => grp.First());
Edit: as getting this IEnumerable<>
into a List<>
seems to be a mystery to many people, you can simply write:
var result = myList.GroupBy(test => test.id)
.Select(grp => grp.First())
.ToList();
But one is often better off working with the IEnumerable
rather than IList
as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList
it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)
The flipside to this advice is that each time you enumerate such an IEnumerable
the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable
or to realize it into a List
, Set
, Dictionary
or whatnot.
Looks like there are so many Answers already but the issue I faced was with double quotes. There is a difference in between:
“
and
"
Changing the 1 st double quote to the second worked for me, below is the sample curl:
curl -X PUT -u xxx:xxx -T test.txt "https://test.com/test/test.txt"
Python 3.X
Handles UTF8 BOM + HEADER
It was quite frustrating that the csv
module could not easily get the header, there is also a bug with the UTF-8 BOM (first char in file).
This works for me using only the csv
module:
import csv
def read_csv(self, csv_path, delimiter):
with open(csv_path, newline='', encoding='utf-8') as f:
# https://bugs.python.org/issue7185
# Remove UTF8 BOM.
txt = f.read()[1:]
# Remove header line.
header = txt.splitlines()[:1]
lines = txt.splitlines()[1:]
# Convert to list.
csv_rows = list(csv.reader(lines, delimiter=delimiter))
for row in csv_rows:
value = row[INDEX_HERE]
I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.
The full shortcut target is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
So I put the following at the start of my script and it seemed to function as expected:
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
Notes:
My way of avoiding the force push is to create a new branch and continuing work on that new branch and after some stability, remove the old branch that was rebased:
I am using:
var n = -556.123444444;
var str = n.toString();
var decimalOnly = 0;
if( str.indexOf('.') != -1 ){ //check if has decimal
var decimalOnly = parseFloat(Math.abs(n).toString().split('.')[1]);
}
Input: -556.123444444
Result: 123444444
Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:
var formData = formData;
$.ajax({
type: "POST",
url: url,
async: false,
data: formData, // Only input
processData: false,
contentType: false,
xhr: function ()
{
$("#load_consulting").show();
var xhr = new window.XMLHttpRequest();
// Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('#addLoad .progress-bar').css('width', percentComplete + '%');
}
}, false);
// Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
return xhr;
},
beforeSend: function (xhr) {
qyuraLoader.startLoader();
},
success: function (response, textStatus, jqXHR) {
qyuraLoader.stopLoader();
try {
$("#load_consulting").hide();
var data = $.parseJSON(response);
if (data.status == 0)
{
if (data.isAlive)
{
$('#addLoad .progress-bar').css('width', '00%');
console.log(data.errors);
$.each(data.errors, function (index, value) {
if (typeof data.custom == 'undefined') {
$('#err_' + index).html(value);
}
else
{
$('#err_' + index).addClass('error');
if (index == 'TopError')
{
$('#er_' + index).html(value);
}
else {
$('#er_TopError').append('<p>' + value + '</p>');
}
}
});
if (data.errors.TopError) {
$('#er_TopError').show();
$('#er_TopError').html(data.errors.TopError);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
else
{
$('#headLogin').html(data.loginMod);
}
} else {
//document.getElementById("setData").reset();
$('#myModal').modal('hide');
$('#successTop').show();
$('#successTop').html(data.msg);
if (data.msg != '' && data.msg != "undefined") {
bootbox.alert({closeButton: false, message: data.msg, callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
} else {
bootbox.alert({closeButton: false, message: "Success", callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
}
}
}
catch (e) {
if (e) {
$('#er_TopError').show();
$('#er_TopError').html(e);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
}
});
<!-- index.php -->
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" name="fname" id="fname"/>
<input type="submit" name="click" value="button" />
</form>
<script>
$(document).ready(function(){
$(function(){
$("#myForm").submit(function(event){
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
dataType: "json",
contentType: "application/json",
data : $('#myForm').serialize(),
success: function(data){
alert(data);
},
error: function(xhr, desc, err){
console.log(err);
}
});
});
});
});
</script>
</body>
</html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>
I found this arrow(start, end)
function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.
In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.
In MVC4 & MVC5 It is little bit different, use following
/App_Start/RouteConfig.cs
namespace MyNamespace
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] {"MyNamespace.Controllers"}
);
}
}
}
and in Areas
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "MyNamespace.Areas.Admin.Controllers" }
);
None of the above worked for me, the only one working was
insert into tableName
select 11, 'BALOO' from sysibm.sysdummy1 union all
select 22, nullif('','') AS nullColumn from sysibm.sysdummy1
The nullif is used since it is not possible to pass null in the select statement otherwise.
I like things to happen automatically and for bins to fall on "nice" values. The following seems to work quite well.
import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
def compute_histogram_bins(data, desired_bin_size):
min_val = np.min(data)
max_val = np.max(data)
min_boundary = -1.0 * (min_val % desired_bin_size - min_val)
max_boundary = max_val - max_val % desired_bin_size + desired_bin_size
n_bins = int((max_boundary - min_boundary) / desired_bin_size) + 1
bins = np.linspace(min_boundary, max_boundary, n_bins)
return bins
if __name__ == '__main__':
data = np.random.random_sample(100) * 123.34 - 67.23
bins = compute_histogram_bins(data, 10.0)
print(bins)
plt.hist(data, bins=bins)
plt.xlabel('Value')
plt.ylabel('Counts')
plt.title('Compute Bins Example')
plt.grid(True)
plt.show()
The result has bins on nice intervals of bin size.
[-70. -60. -50. -40. -30. -20. -10. 0. 10. 20. 30. 40. 50. 60.]
If all the other answers do not work for you check the config.inc.php
for the following:
$cfg['Servers'][$i]['host'] = '127.0.0.1';
…and add the port of MySQL set in your XAMPP as shown below:
$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';
Stop MySQL from XAMPP and restart MySQL.
Open a fresh page for http://localhost:8012/phpmyadmin/
and check.
In my case I had to put the icon using:
toolbar.setNavigationIcon(R.drawable.ic_my_home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
And then listen to click events with default onOptionsItemSelected and android.R.id.home id
I was looking for a way to disable my already existing DataGridView
and came across several answers. Oddly enough, the first few results on google were some very old topics. This being the earliest one of them, I decide to put my answer here.
private void dgvDetails_ColumnStateChanged(object sender, DataGridViewColumnStateChangedEventArgs e)
{
e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
The description when you click on ColumStateChanged
in the properties window is:
"Occurs when a column changes state, such as gaining or loosing focus"
Granted there are many ways to do this but I thought I'd add this one here. Can't say I found it anywhere else but then again I only read the first 5 topics I found.
Named exports:
Let's say you create a file called utils.js
, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:
export function add(x, y) {
return x + y
}
export function mutiply(x, y) {
return x * y
}
Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:
import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.
Or if you prefer, place the entire module's contents under a common namespace:
import * as utils from './utils.js';
...
utils.multiply(2,3)
Default exports:
If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js
, with only one function that logs out whatever argument it's called with:
export default function log(message) {
console.log(message);
}
This can now be used like this:
import log from './log.js';
...
log('test') // Would print 'test' in the console.
You don't have to call it log
when you import it, you could actually call it whatever you want:
import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.
Combined:
A module can have both a default export (max 1), and named exports (imported either one by one, or using *
with an alias). React actually has this, consider:
import React, { Component, PropTypes } from 'react';
Simple ready2use snippet, working perfectly for me
static void waitForPageLoad(WebDriver wdriver) {
WebDriverWait wait = new WebDriverWait(wdriver, 60);
Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver input) {
return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
}
};
wait.until(pageLoaded);
}
How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.
As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.
(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).
def read_config(filename):
f = open(filename)
config_dict = {}
for lines in f:
items = lines.split(': ', 1)
config_dict[items[0]] = eval(items[1])
return config_dict
There's no such thing as cross domain cookies. You could share a cookie between foo.example.com
and bar.example.com
but never between example.com
and example2.com
and that's for security reasons.
You can use WANDisco's CentOS repository to install Git 2.x: for CentOS 6, for CentOS 7
Install WANDisco repo package:
yum install http://opensource.wandisco.com/centos/6/git/x86_64/wandisco-git-release-6-1.noarch.rpm
- or -
yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-1.noarch.rpm
- or -
yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-2.noarch.rpm
Install the latest version of Git 2.x:
yum install git
Verify the version of Git that was installed:
git --version
As of 02 Mar. 2020, the latest available version from WANDisco is 2.22.0.
I've dealing too many hours for such task in for node.js. I'm mainly front-end guy.
I find this quite important, because all node methods asyncronous deal with callback, and transform it into Promise is better to handle it.
I Just want to show a possible outcome, more lean and readable. Using ECMA-6 with async you can write it like this.
async function getNameFiles (dirname) {
return new Promise((resolve, reject) => {
fs.readdir(dirname, (err, filenames) => {
err !== (undefined || null) ? reject(err) : resolve(filenames)
})
})
}
the (undefined || null)
is for repl (read event print loop) scenarios,
using undefined also work.
You don't really need jQuery for this as there is a Media API that provides you with all you need.
var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();
The Media API also contains a load()
method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."
(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType()
function to decide on which one to play).
You can then wait for either the loadedmetadata
or loadeddata
(depending on what you want) events to fire:
video.addEventListener('loadeddata', function() {
// Video is loaded and can be played
}, false);
Keyboard accelerators are configurable. You can find out which keyboard accelerators are bound to a command in Tools -> Options
on the Environment -> Keyboard
page.
These commands are named Edit.CommentSelection and Edit.UncommentSelection.
(With my settings, these are bound to Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U. I would guess that these are the defaults, at least in the C++ defaults, but I don't know for sure. The best way to find out is to check your settings.)
I've gotten same problem. The servers logs showed:
DEBUG: <-- origin: null
I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine
json_decode will return the same array that was originally encoded. For instanse, if you
$array = json_decode($json, true);
echo $array['countryId'];
OR
$obj= json_decode($json);
echo $obj->countryId;
These both will echo 84. I think json_encode and json_decode function names are self-explanatory...
you can do it by two ways
import file_name
exec(open('file_name').read())
but make sure that file should be stored where your program is running
One NuGet package can reference another NuGet package. So, please be very careful about inter-package dependencies. I just uninstalled a Google map package and it subsequently uninstalled underlying packages like Newtonsoft, Entity Framework, etc.
So, manually deleting particular package from packages folder would be safer.
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
class timevalues
{
// Database table values:
public $value_hour; // maps to values.value_hour
public $value_day; // maps to values.value_day
public $value_month; // maps to values.value_month
public $values=array();
public function __construct()
{
$this->value_hour=0;
$this->value_day=0;
$this->value_month=0;
$this->values=array(
'hour'=>$this->value_hour,
'day'=>$this->value_day,
'month'=>$this->value_month,
);
}
}
If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:
<Image Source="/Icons/play_small.png" />
That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:
var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;
var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
this.image1.Source = bitmapImage;
The thing that worked for me:
Put your file inside of the folder specified in secure-file-priv
.
To find that type:
mysql> show variables like "secure_file_priv";
Check if you have local_infile = 1
.
Do that typing:
mysql> show variables like "local_infile";
If you get:
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile | OFF |
+---------------+-------+
Then set it to one typing:
mysql> set global local_infile = 1;
Specify the full path for your file. In my case:
mysql> load data infile "C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/file.txt" into table test;
I created a button...
This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button
element instead, you wouldn't have this problem:
<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
Connect
</button>
If you are going to continue using an a
element instead, at the very least you should give it a role
attribute set to "button"
and drop the href
attribute altogether:
<a role="button" ...>
Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault()
- here with event
being your click event.
// @flow
import React from 'react';
import { styleLocal } from './styles';
import {
View,
Text,
TextInput,
Image,
} from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
export default React.forwardRef((props, ref) => {
const { onSeachClick, onChangeTextSearch , ...otherProps } = props;
return (
<View style={styleLocal.sectionStyle}>
<TouchableOpacity onPress={onSeachClick}>
<Image
source={require('../../assets/imgs/search.png')}
style={styleLocal.imageStyle} />
</TouchableOpacity>
<TextInput
style={{ flex: 1, fontSize: 18 }}
placeholder="Search Here"
underlineColorAndroid="transparent"
onChangeText={(text) => { onChangeTextSearch(text) }}
/>
</View>
);
});
import IGPSSearch from '../../components/IGPSSearch';
<Search onSeachClick={onSeachClick} onChangeTextSearch= {onChangeTextSearch}> </Search>
For those who are looking to run a single file but they cannot make it work, what worked for me was that I needed to wrap my test cases in a describe suite as below and then use the describe title e.g. 'My Test Description' as pattern.
describe('My Test Description', () => {
it('test case 1', () => {
// My test code
})
it('test case 2', () => {
// My test code
})
})
then run
yarn test -g "My Test Description"
or
npm run test -g "My Test Description"
Just to add to the thread as a POSSIBLE solution, I faced a similar issue when developing on a Linux system that was behind a company firewall. However, using a Windows XP machine, Eclipse was able to access different update sites just fine as both the manual and native network connection providers worked just fine using the company proxy.
After stumbling around for some time, I came across a discussion about using NTLMv2 and an implementation to be found at http://cntlm.sourceforge.net/. To whomever posted this, I give much credit to as it helped me get past the issue running on Linux. As a side note, I was using Eclipse 3.6.2 / Helios on both the Linux and Windows distros.
Best of luck on finding a solution!
Well this is the MSDN page that deals with IntPtr
.
The first line reads:
A platform-specific type that is used to represent a pointer or a handle.
As to what a pointer or handle is the page goes on to state:
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
A pointer is a reference to an area of memory that holds some data you are interested in.
A handle can be an identifier for an object and is passed between methods/classes when both sides need to access that object.
DataTable dt = new DataTable();
dt.Load(reader);
int numRows= dt.Rows.Count;
Image Viewer with ViewPager Implementation, check this project https://github.com/chiuki/android-swipe-image-viewer
Refer this discussion also Swiping images (not layouts) with viewpager
This should work.
var url = 'http://<your_url_here>';
var headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
'Content-Type' : 'application/x-www-form-urlencoded'
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};
request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
// your callback body
});
Here's an answer covering the more general question of calling another PS script from a PS script, as you may do if you were composing your scripts of many little, narrow-purpose scripts.
I found it was simply a case of using dot-sourcing. That is, you just do:
# This is Script-A.ps1
. ./Script-B.ps1 -SomeObject $variableFromScriptA -SomeOtherParam 1234;
I found all the Q/A very confusing and complicated and eventually landed upon the simple method above, which is really just like calling another script as if it was a function in the original script, which I seem to find more intuitive.
Dot-sourcing can "import" the other script in its entirety, using:
. ./Script-B.ps1
It's now as if the two files are merged.
Ultimately, what I was really missing is the notion that I should be building a module of reusable functions.
git add
selects changes
git commit
records changes LOCALLY
git push
shares changes
sbt eclipse
from the project root directory. Since you already have yarn installed and only want to upgrade/update. you can simply use
yarn self-update
Find ref here https://yarnpkg.com/en/docs/cli/self-update
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:@"UIWindow"]) {
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
if ([NSStringFromClass([window class]) isEqualToString:@"UIWindow"]) {
keyWindow = window;
break;
}
}
}
Add this CSS rule, and yellow background color will disapear. :)
input:-webkit-autofill {
-webkit-box-shadow: 0 0 0px 1000px white inset;
}
Yes.You can try with some hidden params.
$("#form").submit( function(eventObj) {
$("<input />").attr("type", "hidden")
.attr("name", "something")
.attr("value", "something")
.appendTo("#form");
return true;
});
var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)
can also add difference between the dates if we compare two different dates
new TimeSpan(24 * days, 0, 0)
Here is a way to remove the element from the array in the state using ES6 spread syntax.
onRemovePerson: (index) => {
const data = this.state.data;
this.setState({
data: [...data.slice(0,index), ...data.slice(index+1)]
});
}
Got stuck as I was trying to a go get ... I think it was related to git. Here is how was able to fix it ...
I entered the following in terminal:
sudo xcodebuild -license
This will open the agreement. Go all the way to end and type "agree".
That takes care of go get issues.
It was quite interesting how unrelated things were.
An advantage of GC in some situations is an annoyance in others; reliance on GC encourages not thinking much about it. In theory, waits until 'idle' period or until it absolutely must, when it will steal bandwidth and cause response latency in your app.
But you don't have to 'not think about it.' Just as with everything else in multithreaded apps, when you can yield, you can yield. So for example, in .Net, it is possible to request a GC; by doing this, instead of less frequent longer running GC, you can have more frequent shorter running GC, and spread out the latency associated with this overhead.
But this defeats the primary attraction of GC which appears to be "encouraged to not have to think much about it because it is auto-mat-ic."
If you were first exposed to programming before GC became prevalent and were comfortable with malloc/free and new/delete, then it might even be the case that you find GC a little annoying and/or are distrustful(as one might be distrustful of 'optimization,' which has had a checkered history.) Many apps tolerate random latency. But for apps that don't, where random latency is less acceptable, a common reaction is to eschew GC environments and move in the direction of purely unmanaged code (or god forbid, a long dying art, assembly language.)
I had a summer student here a while back, an intern, smart kid, who was weaned on GC; he was so adament about the superiorty of GC that even when programming in unmanaged C/C++ he refused to follow the malloc/free new/delete model because, quote, "you shouldn't have to do this in a modern programming language." And you know? For tiny, short running apps, you can indeed get away with that, but not for long running performant apps.
Ajax call error handler will be triggered if the call itself fails.
You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.
e.preventDefault();
$.ajax(
{
type: 'POST',
url: requestURI,
data: $(formLogin).serialize(),
dataType: 'json',
success: function(result){
if(result.hasError == true)
{
if(result.error_code == 'AUTH_FAILURE')
{
//wrong password
console.log('Recieved authentication error');
$('#login_errors_auth').fadeIn();
}
else
{
//generic error here
$('#login_errors_unknown').fadeIn();
}
}
}
});
Here, "result" is the json object returned form the server which could have a structure like:
$return = array(
'hasError' => !$validPassword,
'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.
#Region " ResizeImage "
Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmSource = New Drawing.Bitmap(SourceImage)
Return ResizeImage(bmSource, TargetWidth, TargetHeight)
End Function
Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
#End Region
As I investigated and I found that UTF-8 is not working well on MAC and Windows so I tried with Windows-1252 , it supports well on both of them but you must select type of encoding on ubuntu.
Here is my code$valueToWrite = mb_convert_encoding($value, 'Windows-1252');
$response->headers->set('Content-Type', $mime . '; charset=Windows-1252');
$response->headers->set('Pragma', 'public');
$response->headers->set('Content-Endcoding','Windows-1252');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
echo "\xEF\xBB\xBF"; // UTF-8 BOM
There are 2 ways to run Selenium python tests in Google Chrome. I'm considering Windows (Windows 10 in my case):
Prerequisite: Download the latest Chrome Driver from: https://sites.google.com/a/chromium.org/chromedriver/downloads
Way 1:
i) Extract the downloaded zip file in a directory/location of your choice
ii) Set the executable path in your code as below:
self.driver = webdriver.Chrome(executable_path='D:\Selenium_RiponAlWasim\Drivers\chromedriver_win32\chromedriver.exe')
Way 2:
i) Simply paste the chromedriver.exe under /Python/Scripts/ (In my case the folder was: C:\Python36\Scripts)
ii) Now write the simple code as below:
self.driver = webdriver.Chrome()
An abstract class is a class that can't be instantiated. It's only purpose is for other classes to extend.
Abstract methods are methods in the abstract class (have to be declared abstract) which means the extending concrete class must override them as they have no body.
The main purpose of an abstract class is if you have common code to use in sub classes but the abstract class should not have instances of its own.
You can read more about it here: Abstract Methods and Classes
If you don't want add the /s
regex modifier (perhaps you still want .
to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:
[\S\s]
a character which is not a space or is a space. In other words, any character.
You can also change modifiers locally in a small part of the regex, like so:
(?s:.)
Before answering, let's add some background, explaining what this HEAD
is.
First of all what is HEAD?
HEAD
is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD
at any given time (excluding git worktree
).
The content of HEAD
is stored inside .git/HEAD
and it contains the 40 bytes SHA-1 of the current commit.
detached HEAD
If you are not on the latest commit - meaning that HEAD
is pointing to a prior commit in history it's called detached HEAD
.
On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD
is not pointing to the tip of the current branch:
git checkout
git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits to go back
This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.
# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>
# Create a new branch forked to the given commit
git checkout -b <branch name>
git reflog
You can always use the reflog
as well.
git reflog
will display any change which updated the HEAD
and checking out the desired reflog entry will set the HEAD
back to this commit.
Every time the HEAD is modified there will be a new entry in the reflog
git reflog
git checkout HEAD@{...}
This will get you back to your desired commit
git reset --hard <commit_id>
"Move" your HEAD back to the desired commit.
# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32
# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
git rebase --no-autostash
as well.git revert <sha-1>
"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.
# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>
This schema illustrates which command does what.
As you can see there, reset && checkout
modify the HEAD
.
In order to hide the default radio button, I'd suggest to remove the button instead of making it transparent as all visual feedback is handled by the drawable background :
android:button="@null"
Also it would be better to use styles as there are several radio buttons :
<RadioButton style="@style/RadioButtonStyle" ... />
<style name="RadioButtonStyle" parent="@android:style/Widget.CompoundButton">
<item name="android:background">@drawable/customButtonBackground</item>
<item name="android:button">@null</item>
</style>
You'll need the Seslyn customButtonBackground drawable too.
String Fpath = getPath(this, uri) ;
File file = new File(Fpath);
String filename = file.getName();
In [44]: df['gdp'] = df['gdp'].shift(-1)
In [45]: df
Out[45]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
4 6 NaN 7
In [46]: df[:-1]
Out[46]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
My config: IIS + php7.4
I had the same issue as @Salman-A, where small attachments were emailed but large were causing the page to error out. I have increased file and attachments limits in php.ini, but this has made no difference.
Then I found a configuration in IIS(6.0), and increased file limits in there.
Also here is my mail.php:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../_PHPMailer-master/src/Exception.php';
require '../_PHPMailer-master/src/PHPMailer.php';
try{
$email = new PHPMailer(true);
$email->SetFrom('[email protected]', 'optional name');
$email->isHTML(true);
$email->Subject = 'my subject';
$email->Body = $emailContent;
$email->AddAddress( $eml_to );
$email->AddAttachment( $file_to_attach );
$email->Send();
}catch(phpmailerException $e){echo $e->errorMessage();}
I hope this helps someone in the future.
dynamic_cast
only supports pointer and reference types. It returns NULL
if the cast is impossible if the type is a pointer or throws an exception if the type is a reference type. Hence, dynamic_cast
can be used to check if an object is of a given type, static_cast
cannot (you will simply end up with an invalid value).
C-style (and other) casts have been covered in the other answers.
Your code already contains a beautiful way to execute all statements from a specified sql file
# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()
# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')
# Execute every command from the input file
for command in sqlCommands:
# This will skip and report errors
# For example, if the tables do not yet exist, this will skip over
# the DROP TABLE commands
try:
c.execute(command)
except OperationalError, msg:
print "Command skipped: ", msg
Wrap this in a function and you can reuse it.
def executeScriptsFromFile(filename):
# Open and read the file as a single buffer
fd = open(filename, 'r')
sqlFile = fd.read()
fd.close()
# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')
# Execute every command from the input file
for command in sqlCommands:
# This will skip and report errors
# For example, if the tables do not yet exist, this will skip over
# the DROP TABLE commands
try:
c.execute(command)
except OperationalError, msg:
print "Command skipped: ", msg
To use it
executeScriptsFromFile('zookeeper.sql')
You said you were confused by
result = c.execute("SELECT * FROM %s;" % table);
In Python, you can add stuff to a string by using something called string formatting.
You have a string "Some string with %s"
with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string
ex:
a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat
Bit of a childish example, but it should be clear.
Now, what
result = c.execute("SELECT * FROM %s;" % table);
means, is it replaces %s with the value of the table variable.
(created in)
for table in ['ZooKeeper', 'Animal', 'Handles']:
# for loop example
for fruit in ["apple", "pear", "orange"]:
print fruit
>>> apple
>>> pear
>>> orange
If you have any additional questions, poke me.
This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:
t := time.Now()
t.Year()
t.Month()
t.Day()
t.Hour()
t.Minute()
t.Second()
For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:
t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
As always, remember that docs are the best source of learning: https://golang.org/pkg/time/
There is a lot of options and they all have their pro and cons.
Pros
Cons
Pros
Cons
Pros
Cons
Pros
Cons
Disclosure: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.
In VSCode for Mac (0.10.6) I opened "Preferences -> User Settings" and placed the following code in the settings.json file
"editor.referenceInfos": false
Saw your problems.
Solutions:
First Download Subversion 1.8.13 ( 1.8 ) client Download link (https://subversion.apache.org/packages.html) at the time of this post the android studio version is less than 1.4 in my case 1.3.2 so you must avoid the issues here subversion command line client version is too old so just download the 1.8 preferably.
Then unzipped in a folder. There will have one folder "bin".
Then
Go to settings - > Version control -> Subversion
Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.
follow the picture:
Don't forget to give the end name like svn.exe last as per image.
Apply -> Ok
Restart your android studio now.
Happy Coding!
Already mentioned previously by swilliams, but with an example below (Javascript):
// Function wrapping inner for loop
function CriteriaMatch(record, criteria) {
for (var k in criteria) {
if (!(k in record))
return false;
if (record[k] != criteria[k])
return false;
}
return true;
}
// Outer for loop implementing continue if inner for loop returns false
var result = [];
for (var i = 0; i < _table.length; i++) {
var r = _table[i];
if (!CriteriaMatch(r[i], criteria))
continue;
result.add(r);
}
Have you considered applying ON DELETE CASCADE
where relevant?
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:
Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:
Now when this task runs it will pass the SSIS variables to the stored proc.
Google brought me here with a very similar problem, I finally figured out a solution that fits my needs, it might help someone else too...
I used this formula:
=IFERROR(MID(Q2, FIND("{",Q2), FIND("}",Q2) - FIND("{",Q2) + 1), "")
Ex:
from boto3 import client
cli = client('iam')
try:
cli.create_user(
UserName = 'Brian'
)
except cli.exceptions.EntityAlreadyExistsException:
pass
a CloudWatch example:
cli = client('logs')
try:
cli.create_log_group(
logGroupName = 'MyLogGroup'
)
except cli.exceptions.ResourceAlreadyExistsException:
pass
Try manually start the service from Windows services, Start -> cmd.exe -> services.msc. Also try to configure the MySQL server to run on another port and try starting it again. Change the my.ini file to change the port number.
Working fiddle:
$.ajax({
url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
}
});
I had to manually set the callback to callback
, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
This is for jQuery UI 1.12. I added the following configuration setting for 'classes' option
classes: {
'ui-dialog-titlebar-close': 'hidden',
},
the whole dialog initialization looks like this:
ConfirmarSiNo(titulo, texto, idPadre, fnCerrar) {
const DATA_RETORNO = 'retval';
$('confirmar-si-no').dialog({
title: titulo,
modal: true,
classes: {
'ui-dialog-titlebar-close': 'hidden',
},
appendTo: `#${idPadre}`,
open: function fnOpen() { $(this).text(texto); },
close: function fnClose() {
let eligioSi = $(this).data(DATA_RETORNO) == true;
setTimeout(function () { fnCerrar(eligioSi); }, 30);
},
buttons: {
'Si, por favor': function si() { $(this).data(DATA_RETORNO, true); $(this).dialog("close"); },
'No, gracias': function no() { $(this).data(DATA_RETORNO, false); $(this).dialog("close"); }
}
});
}
I use following script call to show it:
ConfirmarSiNo('Titulo',
'¿Desea actualizar?',
idModalPadre,
(eligioSi) => {
if (eligioSi) {
this.$tarifa.val(tarifa.tarifa);
this.__ActualizarTarifa(tarifa);
}
});
whithin Html body I have the following div that contains the dialog:
<div class="modal" id="confirmar-si-no" title="" aria-labelledby="confirmacion-label">
mensaje
</div>
final result is:
function 'ConfirmarSiNo' is based on 'Whome' answer on post How to implement “confirmation” dialog in Jquery UI dialog?
Always returning POSITION_NONE
is simple but a little inefficient way because that evoke instantiation of all page that have already instantiated.
I've created a library ArrayPagerAdapter to change items in PagerAdapters dynamically.
Internally, this library's adapters return POSITION_NONE
on getItemPosiition()
only when necessary.
You can change items dynamically like following by using this library.
@Override
protected void onCreate(Bundle savedInstanceState) {
/** ... **/
adapter = new MyStatePagerAdapter(getSupportFragmentManager()
, new String[]{"1", "2", "3"});
((ViewPager)findViewById(R.id.view_pager)).setAdapter(adapter);
adapter.add("4");
adapter.remove(0);
}
class MyPagerAdapter extends ArrayViewPagerAdapter<String> {
public MyPagerAdapter(String[] data) {
super(data);
}
@Override
public View getView(LayoutInflater inflater, ViewGroup container, String item, int position) {
View v = inflater.inflate(R.layout.item_page, container, false);
((TextView) v.findViewById(R.id.item_txt)).setText(item);
return v;
}
}
Thils library also support pages created by Fragments.
Having just encountered this on Arch Linux 4.13.3, I solved the issue by simply reinstalling semver
:
pacman -S semver
You can traverse each string in the list and even you can search in the whole generic using a single statement this makes searching easier.
public static void main(string[] args)
{
List names = new List();
names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);
string stringResult = names.Find( name => name.Equals(“Garima”));
}
Different languages do different things with different levels of efficiency.
The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.
svn revert will undo any local changes you've made
Here is how to modify cron a entry without directly editing the cron file (which is frowned upon).
crontab -l -u <user> | sed 's/find/replace/g' | crontab -u <user> -
If you want to remove a cron entry, use this:
crontab -l -u <user> | sed '/find/d' | crontab -u <user> -
I realize this is not what gaurav was asking for, but why not have all the solutions in one place?
None of the solutions above worked for me straight away. So I followed these steps:
pom.xml:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Go to Project Properties
> Java Build Path
, then remove the JRE
System Library pointing to JRE1.5
.
Force updated the project.
def multiples(n,m,starting_from=1,increment_by=1):
"""
# Where n is the number 10 and m is the number 2 from your example.
# In case you want to print the multiples starting from some other number other than 1 then you could use the starting_from parameter
# In case you want to print every 2nd multiple or every 3rd multiple you could change the increment_by
"""
print [ n*x for x in range(starting_from,m+1,increment_by) ]
Finally found in http://viralpatel.net/blogs/2009/09/setting-height-selectbox-combobox-ie.html a simple solution (at least for IE8):
font-size: 1.0em;
BTW, for Google Chrome, found this workaround at How to standardize the height of a select box between Chrome and Firefox? */
-webkit-appearance: menulist-button;
iPhoney is designed specifically for Mac users
you can read about it and download it here
I know my case is rare, but I'll still add it here for someone who troubleshoots it later. I had a Linux Kernel module target in my Makefile and I tried to compile my user space program together with the kernel module that doesn't have stdio. Making it a separate target solved the problem.
mysql allows you to insert multiple rows at once INSERT manual
Here's what I just used:
ffmpeg -i my.mkv -map 0:3 -vn -b:a 320k my.mp3
Options explanation:
-map 0:3
means I want 3rd stream from video file. Put your N there - video files often has multiple audio streams; you can omit it or use -map 0:a
to take the default audio stream. Run ffprobe my.mkv
to see what streams does the video file have.For a true comparison, you can use:
dateTime1.Date.CompareTo(dateTime2.Date);
IOW, extern is redundant, and does nothing.
That is why, 10 years later:
extern
in function declaration for removal;git/git
follows that conclusion and removes extern
from its code (for Git 2.22, Q2 2019).See commit ad6dad0, commit b199d71, commit 5545442 (29 Apr 2019) by Denton Liu (Denton-L
).
(Merged by Junio C Hamano -- gitster
-- in commit 4aeeef3, 13 May 2019)
*.[ch]
: removeextern
from function declarations usingspatch
There has been a push to remove
extern
from function declarations.Remove some instances of "
extern
" for function declarations which are caught by Coccinelle.
Note that Coccinelle has some difficulty with processing functions with__attribute__
or varargs so someextern
declarations are left behind to be dealt with in a future patch.This was the Coccinelle patch used:
@@ type T; identifier f; @@ - extern T f(...);
and it was run with:
$ git ls-files \*.{c,h} | grep -v ^compat/ | xargs spatch --sp-file contrib/coccinelle/noextern.cocci --in-place
This is not always straightforward though:
See commit 7027f50 (04 Sep 2019) by Denton Liu (Denton-L
).
(Merged by Denton Liu -- Denton-L
-- in commit 7027f50, 05 Sep 2019)
compat/*.[ch]
: removeextern
from function declarations using spatchIn 5545442 (
*.[ch]
: removeextern
from function declarations using spatch, 2019-04-29, Git v2.22.0-rc0), we removed externs from function declarations usingspatch
but we intentionally excluded files undercompat/
since some are directly copied from an upstream and we should avoid churning them so that manually merging future updates will be simpler.In the last commit, we determined the files which taken from an upstream so we can exclude them and run
spatch
on the remainder.This was the Coccinelle patch used:
@@ type T; identifier f; @@ - extern T f(...);
and it was run with:
$ git ls-files compat/\*\*.{c,h} | xargs spatch --sp-file contrib/coccinelle/noextern.cocci --in-place $ git checkout -- \ compat/regex/ \ compat/inet_ntop.c \ compat/inet_pton.c \ compat/nedmalloc/ \ compat/obstack.{c,h} \ compat/poll/
Coccinelle has some trouble dealing with
__attribute__
and varargs so we ran the following to ensure that no remaining changes were left behind:$ git ls-files compat/\*\*.{c,h} | xargs sed -i'' -e 's/^\(\s*\)extern \([^(]*([^*]\)/\1\2/' $ git checkout -- \ compat/regex/ \ compat/inet_ntop.c \ compat/inet_pton.c \ compat/nedmalloc/ \ compat/obstack.{c,h} \ compat/poll/
Note that with Git 2.24 (Q4 2019), any spurious extern
is dropped.
See commit 65904b8 (30 Sep 2019) by Emily Shaffer (nasamuffin
).
Helped-by: Jeff King (peff
).
See commit 8464f94 (21 Sep 2019) by Denton Liu (Denton-L
).
Helped-by: Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 59b19bc, 07 Oct 2019)
promisor-remote.h
: dropextern
from function declarationDuring the creation of this file, each time a new function declaration was introduced, it included an
extern
.
However, starting from 5545442 (*.[ch]
: removeextern
from function declarations usingspatch
, 2019-04-29, Git v2.22.0-rc0), we've been actively trying to prevent externs from being used in function declarations because they're unnecessary.Remove these spurious
extern
s.
#include <iostream>
#include <conio.h>
using namespace std;
double raiseToPow(double ,int) //raiseToPow variable of type double which takes arguments (double, int)
void main()
{
double x; //initializing the variable x and i
int i;
cout<<"please enter the number";
cin>>x;
cout<<"plese enter the integer power that you want this number raised to";
cin>>i;
cout<<x<<"raise to power"<<i<<"is equal to"<<raiseToPow(x,i);
}
//definition of the function raiseToPower
double raiseToPow(double x, int power)
{
double result;
int i;
result =1.0;
for (i=1, i<=power;i++)
{
result = result*x;
}
return(result);
}
There are 2 scenario's where Bash performance is at least equal I believe:
That said, I usually don't really concern myself with performance of the scripting language itself. If performance is a real issue you don't script but program (possibly in Python).
The following Python code will turn your string into a list of strings:
import ast
teststr = "['aaa','bbb','ccc']"
testarray = ast.literal_eval(teststr)
The behavior of the dblclick
event is explained at Quirksmode.
The order of events for a dblclick
is:
The one exception to this rule is (of course) Internet Explorer with their custom order of:
As you can see, listening to both events together on the same element will result in extra calls to your click
handler.
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
You can also do like these
If you don't want a directive
https://stackblitz.com/edit/numeric-only
in component.html
<input (keypress)="numberOnly($event)" type="text">
in component.ts
export class AppComponent {
numberOnly(event): boolean {
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
}
It looks like you did not add a MySQL database to your application, OR you added it after you installed laravel. In that case, you need to stop & start (not restart) your application so that it will pick up your environment variables. (rhc app stop , rhc app start ). If you did not add a database yet, you will need to add one of the mysql cartridges, and then stop & start your application using the previously shown commands.
You can directly download this file using anchor tag without much code.
Copy the snippet and paste in your text-editor and try it...!
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<img src="https://upload.wikimedia.org/wikipedia/commons/1/1f/SMirC-thumbsup.svg" width="200" height="200">_x000D_
<a href="#" download="https://upload.wikimedia.org/wikipedia/commons/1/1f/SMirC-thumbsup.svg"> Download Image </a>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
For PHP 7 and later versions.
/**
* A method for sorting associative arrays by a key and a direction.
* Direction can be ASC or DESC.
*
* @param $array
* @param $key
* @param $direction
* @return mixed $array
*/
function sortAssociativeArrayByKey($array, $key, $direction){
switch ($direction){
case "ASC":
usort($array, function ($first, $second) use ($key) {
return $first[$key] <=> $second[$key];
});
break;
case "DESC":
usort($array, function ($first, $second) use ($key) {
return $second[$key] <=> $first[$key];
});
break;
default:
break;
}
return $array;
}
Usage:
$inventory = sortAssociativeArrayByKey($inventory, "price", "ASC");
It depends on the nature of data. You need to contemplate it beforehand.
Although MySQL lets you use decimal(65,30), 31 for scale and 30 for precision seem to be our limits if we want to leave transfer option open.
Maximum scale and precision in most common RDBMS:
Precision Scale Oracle 31 31 T-SQL 38 38 MySQL 65 30 PostgreSQL 131072 16383
September 2015 Zimbabwean government stated it would exchange Zimbabwean dollars for US dollars at a rate of 1 USD to 35 quadrillion Zimbabwean dollars 5
We tend to say "yeah, sure... I won't need that crazy figures". Well, Zimbabweans used to say that too. Not to long ago.
Let's imagine you need to record a transaction of 1 mln USD in Zimbabwean dollars (maybe unlikely today, but who knows how this will look like in 10 years from now?).
- (1 mln USD) * (35 Quadrylion ZWL) = ( 10^6 ) * (35 * 10^15) = 35 * 10^21
- we need:
- 2 digits to store "35"
- 21 digits to store the zeros
- 4 digits to the right of decimal point
- this makes decimal(27,4) which costs us 15 bytes for each entry
- we may add one more digit on the left at no expense - we have decimal(28,4) for 15 bytes
- Now we can store 10 mln USD transaction expressed in Zimbabwean dollars, or secure from another strike of hiperinflation, which hopefully won't happen
A step by step guide I found here.
To create a read-only database user account for MySQL
At a UNIX prompt, run the MySQL command-line program, and log in as an administrator by typing the following command:
mysql -u root -p
Type the password for the root account. At the mysql prompt, do one of the following steps:
To give the user access to the database from any host, type the following command:
grant select on database_name.* to 'read-only_user_name'@'%' identified by 'password';
If the collector will be installed on the same host as the database, type the following command:
grant select on database_name.* to 'read-only_user_name' identified by 'password';
This command gives the user read-only access to the database from the local host only. If you know the host name or IP address of the host that the collector is will be installed on, type the following command:
grant select on database_name.* to 'read-only_user_name'@'host_name or IP_address' identified by 'password';
The host name must be resolvable by DNS or by the local hosts file. At the mysql prompt, type the following command:
flush privileges;
Type quit
.
The following is a list of example commands and confirmation messages:
mysql> grant select on dbname.* to 'readonlyuser'@'%' identified
by 'pogo$23';
Query OK, 0 rows affected (0.11 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
In case you're having this problem in flex/adobe air and find yourself here first, i've found a solution, and have posted it on a related question: ADD COLUMN to sqlite db IF NOT EXISTS - flex/air sqlite?
My comment here: https://stackoverflow.com/a/24928437/2678219
The correct character (comma or colon) depends on the purpose.
Comma (,
) will sum only the two cells in question.
Colon (:
) will sum all the cells within the range with corners defined by those two cells.
It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:
>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10
I came here looking for the same thing. $ErrorActionPreference="Stop" kills my shell immediately when I'd rather see the error message (pause) before it terminates. Falling back on my batch sensibilities:
IF %ERRORLEVEL% NEQ 0 pause & GOTO EOF
I found that this works pretty much the same for my particular ps1 script:
Import-PSSession $Session
If ($? -ne "True") {Pause; Exit}
Tested and Working procedure:
Goto the file path
..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp
remove the whole content or declare the below lines of code at the top of the index.jsp
<% response.sendRedirect("http://yourRedirectionURL"); %>
Please note that in jsp file you need to start the above line with <% and end with %>
A potential problem with the two solutions offered is that, depending on how they are written, an update query may update zero records and an insert query may insert zero records. In these cases, the Inserted and Deleted recordsets will be empty. In many cases, if both the Inserted and Deleted recordsets are empty you might just want to exit the trigger without doing anything.
Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:
$ date
If the date and/or time is incorrect, try to update using:
$ sudo ntpdate -u time.nist.gov
Use this:
#include <stdlib.h>
#include <string.h>
int main()
{
const char *d1 = "11";
int d1int = atoi(d1);
printf("d1 = %d\n", d1);
return 0;
}
etc.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
Here's example using NotificationCompact.Builder class which is the recent version to build notification.
private void startNotification() {
Log.i("NextActivity", "startNotification");
// Sets an ID for the notification
int mNotificationId = 001;
// Build Notification , setOngoing keeps the notification always in status bar
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ldb)
.setContentTitle("Stop LDB")
.setContentText("Click to stop LDB")
.setOngoing(true);
// Create pending intent, mention the Activity which needs to be
//triggered when user clicks on notification(StopScript.class in this case)
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, StopScript.class), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
// Gets an instance of the NotificationManager service
NotificationManager mNotificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotificationManager.notify(mNotificationId, mBuilder.build());
}
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
You can try using @RequestBodyParam
@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBodyParam String source,@RequestBodyParam JsonDto json) throws MyException {
...
}
I ran into this issue on my Ubuntu-64 system when attempting to import fst within python as such:
Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun 4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ogi/miniconda3/lib/python3.4/site-packages/pyfst-0.2.3.dev0-py3.4-linux-x86_64.egg/fst/__init__.py", line 1, in <module>
from fst._fst import EPSILON, EPSILON_ID, SymbolTable,\
ImportError: /home/ogi/miniconda3/lib/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/local/lib/libfst.so.1)
I then ran:
ogi@ubuntu:~/miniconda3/lib$ find ~/ -name "libstdc++.so.6"
/home/ogi/miniconda3/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-5-5.2.0-2/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-4.8.5-1/lib/libstdc++.so.6
find: `/home/ogi/.local/share/jupyter/runtime': Permission denied
ogi@ubuntu:~/miniconda3/lib$
mv /home/ogi/miniconda3/lib/libstdc++.so.6 /home/ogi/miniconda3/libstdc++.so.6.old
cp /home/ogi/miniconda3/libgcc-5-5.2.0-2/lib/libstdc++.so.6 /home/ogi/miniconda3/lib/
At which point I was then able to load the library
ogi@ubuntu:~/miniconda3/lib$ python
Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun 4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
>>> exit()
I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).
Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
for me below worked:
chown -R ftpusername /var/app/current
h2 { display: inline }
You can use the following to programmatically center TextView
text in Kotlin:
textview.gravity = Gravity.CENTER
In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.
You can avoid making a copy of the object using Wen's solution and inplace=True:
df.fillna({'a':0, 'b':0}, inplace=True)
print(df)
Which yields:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0
for i in `seq 1 20`; do curl http://url; done
Or if you want to get timing information back, use ab
:
ab -n 20 http://url/
Try using this:
$(".move_to").on("click", function(e){
e.preventDefault();
$('#contactsForm').attr('action', "/test1").submit();
});
Moving the order in which you use .preventDefault()
might fix your issue. You also didn't use function(e)
so e.preventDefault();
wasn't working.
Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined
. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1
.
In Swift3:
let fileUrl = Foundation.URL(string: filePath)
urlresolver has been removed in the higher version of Django - Please upgrade your django installation. I fixed it using the following command.
pip install django==2.0 --upgrade
I installed IntelliJ IDEA community version from http://www.jetbrains.com/idea/download/
I tried opening my project that I started in Android studio but it failed when at gradle build. I instead opened both android studio and intellij at same time and placed one screen next to the other and simply drag and dropped my java files, xml layouts, drawables, and manifest into the project hiearchy of a new project started in IntelliJ. It worked around the gradle build issues and now I can start a new project in IntelliJ and design either an android app or a basic Java app. Thankfully this worked because I hated having so many IDEs on my pc.
If all you want to do is conditionally show or hide a <div>, then you could declare it as an <asp:panel > (renders to html as a div tag) and set it's .Visible property.
1) @RequestParam
is used to extract query parameters
http://localhost:3000/api/group/test?id=4
@GetMapping("/group/test")
public ResponseEntity<?> test(@RequestParam Long id) {
System.out.println("This is test");
return ResponseEntity.ok().body(id);
}
while @PathVariable
is used to extract data right from the URI:
http://localhost:3000/api/group/test/4
@GetMapping("/group/test/{id}")
public ResponseEntity<?> test(@PathVariable Long id) {
System.out.println("This is test");
return ResponseEntity.ok().body(id);
}
2) @RequestParam
is more useful on a traditional web application where data is mostly passed in the query parameters while @PathVariable
is more suitable for RESTful web services where URL contains values.
3) @RequestParam
annotation can specify default values if a query parameter is not present or empty by using a defaultValue
attribute, provided the required attribute is false
:
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
return "Required element of request param";
}
}
Try with: $('.onediv').eq(0)
From the demo: Other examples of selectors and methods targeting the first LI
unside an UL
:
.eq()
Method:$('li').eq(0)
:eq()
selector:$('li:eq(0)')
.first()
Method$('li').first()
:first
selector:$('li:first')
:first-child
selector:$('li:first-child')
:lt()
selector:$('li:lt(1)')
:nth-child()
selector:$('li:nth-child(1)')
jQ + JS:
you can also use [i]
to get the JS HTMLelement
index out of the jQuery el. (array) collection like eg:
$('li')[0]
now that you have the JS element representation you have to use JS native methods eg:
$('li')[0].className = 'active'; // Adds class "active" to the first LI in the DOM
or you can (don't - it's bad design) wrap it back into a jQuery object
$( $('li')[0] ).addClass('active'); // Don't. Use .eq() instead
int c;
String raw = "";
do {
c = inputstream.read();
raw+=(char)c;
} while(inputstream.available()>0);
InputStream.available() shows the available bytes only after one byte is read, hence do .. while