In index.js file, simply replace App component with "React.version". E.g.
ReactDOM.render(React.version, document.getElementById('root'));
I have checked this with React v16.8.1
If you need to concatenate paths with quotes, you can use =
to replace quotes in a variable. This does not require you to know if the path already contains quotes or not. If there are no quotes, nothing is changed.
@echo off
rem Paths to combine
set DIRECTORY="C:\Directory with spaces"
set FILENAME="sub directory\filename.txt"
rem Combine two paths
set COMBINED="%DIRECTORY:"=%\%FILENAME:"=%"
echo %COMBINED%
rem This is just to illustrate how the = operator works
set DIR_WITHOUT_SPACES=%DIRECTORY:"=%
echo %DIR_WITHOUT_SPACES%
Try this code:
<form id="myform">
<!-- form elements -->
<a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>
But users with disabled JavaScript won't be able to submit the form, so you could add the following code:
<noscript>
<input type="submit" value="Submit form!" />
</noscript>
Edit:
Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs
See the working example: http://jsfiddle.net/U6aKT/
<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>
Aha!
This can be done with the following PHP function:
error_log('Some message here.');
Found the answer here: Print something in PHP built-in web server
Here's a way that allows for ties for the cut-off score.
author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')
You may get more than 30 authors in top_authors this way and the min(30,author_count)
is there incase you have fewer than 30 authors.
If you are experiencing the OP's problem where your cookies have been set using JavaScript - for example:
document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/";
you could instead use:
document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/; SameSite=None; Secure";
It worked for me. More info here.
To get the value of the Value attribute you can do something like this:
$("input[type='checkbox']").val();
Or if you have set a class
or id
for it, you can:
$('#check_id').val();
$('.check_class').val();
However this will return the same value whether it is checked or not, this can be confusing as it is different to the submitted form behaviour.
To check whether it is checked or not, do:
if ($('#check_id').is(":checked"))
{
// it is checked
}
Here is a solution using for of
and continue
instead of forEach
:
let elementsCollection = SomeElements.find();
for (let el of elementsCollection) {
// continue will exit out of the current
// iteration and continue on to the next
if (!el.shouldBeProcessed){
continue;
}
doSomeLengthyOperation();
});
This may be a bit more useful if you need to use asynchronous functions inside your loop which do not work inside forEach
. For example:
(async fuction(){
for (let el of elementsCollection) {
if (!el.shouldBeProcessed){
continue;
}
let res;
try {
res = await doSomeLengthyAsyncOperation();
} catch (err) {
return Promise.reject(err)
}
});
})()
You could try using UpdateVersion by Matt Griffith. It's quite old now, but works well. To use it, you simply need to setup a pre-build event which points at your AssemblyInfo.cs file, and the application will update the version numbers accordingly, as per the command line arguments.
As the application is open-source, I've also created a version to increment the version number using the format (Major version).(Minor version).([year][dayofyear]).(increment). I've put the code for my modified version of the UpdateVersion application on GitHub: https://github.com/munr/UpdateVersion
Here's an answer http://wiki.python.org/moin/DictionaryKeys
What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?
Looking up different lists with the same contents would produce different results, even though comparing lists with the same contents would indicate them as equivalent.
What about Using a list literal in a dictionary lookup?
This worked for me:
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
comboBox1.SelectedIndex = comboBox1.FindStringExact(MyEnum.something.ToString());
Have you copied this method from other page/application ? if yes then it will not work, So you need to delete the event and event name assigned to the button then go to design and go to button even properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button. this should work
I use the /^[a-z]+:[^:]+$/i regular expression for URL validation. See an example of my cross-browser InputKeyFilter code with URL validation.
<!doctype html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" >_x000D_
<head>_x000D_
<title>Input Key Filter Test</title>_x000D_
<meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>_x000D_
_x000D_
<!-- For compatibility of IE browser with audio element in the beep() function._x000D_
https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=9"/>_x000D_
_x000D_
<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css"> _x000D_
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>_x000D_
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
URL: _x000D_
<input type="url" id="Url" value=":"/>_x000D_
<script>_x000D_
CreateUrlFilter("Url", function(event){//onChange event_x000D_
inputKeyFilter.RemoveMyTooltip();_x000D_
var elementNewInteger = document.getElementById("NewUrl");_x000D_
elementNewInteger.innerHTML = this.value;_x000D_
}_x000D_
_x000D_
//onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)_x000D_
, function(event){ this.ikf.customFilter(this); }_x000D_
);_x000D_
</script>_x000D_
New URL: <span id="NewUrl"></span>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Also see my page example of the input key filter.
If you need an easier way to do it, and don't want much fuss, a simple execution could be:
raise Exception.new('something bad happened!')
This will raise an exception, say e
with e.message = something bad happened!
and then you can rescue it as you are rescuing all other exceptions in general.
Use ToString("X4")
.
The 4 means that the string will be 4 digits long.
Reference: The Hexadecimal ("X") Format Specifier on MSDN.
That's because the function needs to return a value. Imagine what happens if you execute myMethod()
and it doesn't go into if(condition)
what would your function returns? The compiler needs to know what to return in every possible execution of your function
Checking Java documentation:
Definition: If a method declaration has a return type then there must be a return statement at the end of the method. If the return statement is not there the missing return statement error is thrown.
This error is also thrown if the method does not have a return type and has not been declared using void (i.e., it was mistakenly omitted).
You can do to solve your problem:
public String myMethod()
{
String result = null;
if(condition)
{
result = x;
}
return result;
}
Too late, just in case some one is looking for another way:
void Main()
{
string jsonString = @"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}";
Product product = new Product();
//Serializing to Object
Product obj = JObject.Parse(jsonString).SelectToken("$.Manufacturers[?(@.Name == 'Acme Co' && @.Name != 'Contoso')]").ToObject<Product>();
Console.WriteLine(obj);
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
Here is another easy method to make the variable available in other functions without having to use global variables:
function makeObj() {_x000D_
// var trailimage = 'test';_x000D_
makeObj.trailimage = 'test';_x000D_
}_x000D_
function someOtherFunction() {_x000D_
document.write(makeObj.trailimage);_x000D_
}_x000D_
_x000D_
makeObj();_x000D_
someOtherFunction();
_x000D_
You could just get the input value in the onclick-event like so:
onclick="execute(document.getElementById('textbox1').value);"
You would of course have to add an id to your textbox
With Java 9, Java 8u161, Java 7u171 and Java 6u181 the limitation is now disabled by default. See issue in Java Bug Database.
Beginning with Java 8u151 you can disable the limitation programmatically.
In older releases, JCE jurisdiction files had to be downloaded and installed separately to allow unlimited cryptography to be used by the JDK. The download and install steps are no longer necessary.
Instead you can now invoke the following line before first use of JCE classes (i.e. preferably right after application start):
Security.setProperty("crypto.policy", "unlimited");
My EditText was nested several layers inside my ScrollView, which itself isn't the layout's root view. Because getTop() and getBottom() were seeming to report the coordinates within it's containing view, I had it compute the distance from the top of the ScrollView to the top of the EditText by iterating through the parents of the EditText.
// Scroll the view so that the touched editText is near the top of the scroll view
new Thread(new Runnable()
{
@Override
public
void run ()
{
// Make it feel like a two step process
Utils.sleep(333);
// Determine where to set the scroll-to to by measuring the distance from the top of the scroll view
// to the control to focus on by summing the "top" position of each view in the hierarchy.
int yDistanceToControlsView = 0;
View parentView = (View) m_editTextControl.getParent();
while (true)
{
if (parentView.equals(scrollView))
{
break;
}
yDistanceToControlsView += parentView.getTop();
parentView = (View) parentView.getParent();
}
// Compute the final position value for the top and bottom of the control in the scroll view.
final int topInScrollView = yDistanceToControlsView + m_editTextControl.getTop();
final int bottomInScrollView = yDistanceToControlsView + m_editTextControl.getBottom();
// Post the scroll action to happen on the scrollView with the UI thread.
scrollView.post(new Runnable()
{
@Override
public void run()
{
int height =m_editTextControl.getHeight();
scrollView.smoothScrollTo(0, ((topInScrollView + bottomInScrollView) / 2) - height);
m_editTextControl.requestFocus();
}
});
}
}).start();
is it ok? yes, it will compile
is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file
The correct way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Wish I had a dollar for every time I've posted that in a forum.
fieldset {display:inline}
or fieldset {display:inline-block}
If you want to separate two fieldsets vertically, use a single <br/>
between them. This is semantically correct and no harder than it has to be.
echo "$x"
x=10
echo "$y"`enter code here`
y=10
echo $[$x+$y]
Answer: 20
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.
saveData(data:DepartmentModel){
return this.ds.sendDepartmentOnSubmit(data).
subscribe(response=>this.status=response,
()=>{},
()=>this.departmentModel={DepartmentId:0});
}
First, you have to create two animation resources in res/anim dir
slide_up.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:toXDelta="0">
</translate>
</set>
slide_bottom.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="0%p"
android:interpolator="@android:anim/accelerate_interpolator"
android:toYDelta="100%p">
</translate>
</set>
then you have to create a style
<style name="DialogAnimation">
<item name="android:windowEnterAnimation">@anim/slide_up</item>
<item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>
and add this line to your class
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id
Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html
For those using a second view controller with a storyboard in a .xib file, you will want to use the name of the .xib file in your constructor (without the.xib suffix).
let settings_dialog:SettingsViewController = SettingsViewController(nibName: "SettingsViewController", bundle: nil)
self.presentViewController(settings_dialog, animated: true, completion: nil)
It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct:
nb = input('Choose a number: ')
The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input
:
nb = raw_input('Choose a number: ')
If you want to convert that to a number, then you should try:
number = int(nb)
... though you need to take into account that this can raise an exception:
try:
number = int(nb)
except ValueError:
print("Invalid number")
And if you want to print the number using formatting, in Python 3 str.format()
is recommended:
print("Number: {0}\n".format(number))
Instead of:
print('Number %s \n' % (nb))
But both options (str.format()
and %
) do work in both Python 2.7 and Python 3.
Visualizing the tree structure was the most convenient way for me :
public static void main(String[] args) throws IOException {
printTree(0, new File("START/FROM/DIR"));
}
static void printTree(int depth, File file) throws IOException {
StringBuilder indent = new StringBuilder();
String name = file.getName();
for (int i = 0; i < depth; i++) {
indent.append(".");
}
//Pretty print for directories
if (file.isDirectory()) {
System.out.println(indent.toString() + "|");
if(isPrintName(name)){
System.out.println(indent.toString() + "*" + file.getName() + "*");
}
}
//Print file name
else if(isPrintName(name)) {
System.out.println(indent.toString() + file.getName());
}
//Recurse children
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++){
printTree(depth + 4, files[i]);
}
}
}
//Exclude some file names
static boolean isPrintName(String name){
if (name.charAt(0) == '.') {
return false;
}
if (name.contains("svn")) {
return false;
}
//.
//. Some more exclusions
//.
return true;
}
This will do what you want, uses an input file and is super fast
#!/bin/bash
IFS=$'\n'
file=/path/to/input.txt
lines=$(cat ${file})
for line in ${lines}; do
curl "${line}"
done
IFS=""
exit ${?}
one entry per line on your input file, it will follow the order of your input file
save it as whatever.sh and make it executable
I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:
gcc -o exec main.o add.o
But my program is a C++ program. Using the g++
compiler solved my issue:
g++ -o exec main.o add.o
I was always under the impression that gcc
could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.
int[] ids = new[] { 1, 2, 3, 4, 5 };
Parallel.ForEach(ids, i => DoSomething(1, i, blogClient).Wait());
Although you run the operations in parallel with the above code, this code blocks each thread that each operation runs on. For example, if the network call takes 2 seconds, each thread hangs for 2 seconds w/o doing anything but waiting.
int[] ids = new[] { 1, 2, 3, 4, 5 };
Task.WaitAll(ids.Select(i => DoSomething(1, i, blogClient)).ToArray());
On the other hand, the above code with WaitAll
also blocks the threads and your threads won't be free to process any other work till the operation ends.
I would prefer WhenAll
which will perform your operations asynchronously in Parallel.
public async Task DoWork() {
int[] ids = new[] { 1, 2, 3, 4, 5 };
await Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}
In fact, in the above case, you don't even need to
await
, you can just directly return from the method as you don't have any continuations:public Task DoWork() { int[] ids = new[] { 1, 2, 3, 4, 5 }; return Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient))); }
To back this up, here is a detailed blog post going through all the alternatives and their advantages/disadvantages: How and Where Concurrent Asynchronous I/O with ASP.NET Web API
The capitalization is wrong, and you have an extra argument.
Do this instead:
$('img#thumb').removeAttr('id');
For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.
In your Environement variable :
new system variable:
M2_HOME
Your mvn directroy "C:\......\bin"
new user variable:
M2
%M2_HOME%
edit the CLASSPATH
by adding %M2%
finally open the cmd and write
path=%CLASSPATH%
enjoy
You can filter for HTTP POST requests with the Chrome DevTools. Just do the following:
method:POST
Screenshot
Tested with Chrome Version 53.
Parameter Options FollowSymLinks
enables you to have a symlink in your webroot pointing to some other file/dir. With this disabled, Apache will refuse to follow such symlink. More secure Options SymLinksIfOwnerMatch
can be used instead - this will allow you to link only to other files which you do own.
If you use Options
directive in .htaccess
with parameter which has been forbidden in main Apache config, server will return HTTP 500 error code.
Allowed .htaccess
options are defined by directive AllowOverride
in the main Apache config file. To allow symlinks, this directive need to be set to All
or Options
.
Besides allowing use of symlinks, this directive is also needed to enable mod_rewrite in .htaccess
context. But for this, also the more secure SymLinksIfOwnerMatch
option can be used.
Emacs takes many launch options. The one that you are looking for is
emacs -nw
. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set.
The long form of this flag is emacs --no-window-system
.
More information about Emacs launch options can be found in the manual.
I had the same issue and after I installed MinGW I could see the variables.
Also, change this:
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
to
SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
The reason is that for the first time the variable SelBranchVal
will be empty
If using a pojo class based on JSON response. If chances are there that json changes frequently declare at pojo class level:
@JsonIgnoreProperties(ignoreUnknown = true)
and at the objectMapper add this if you are converting:
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
So that code will not break.
I'm running Windows 7 with git bash console. The above commands wouldn't work for me.
So I did it via Windows Explorer. I checked show hidden files, went to my projects directory and manually deleted the .git folder. Then back in the command line I checked by running git status.
Which returned...
fatal: Not a git repository (or any of the parent directories): .git
Which is exactly the result I wanted. It returned that the directory is not a git repository (anymore!).
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
Generally speaking when you are trying to 'just get a working example' it is best to 'just start writing code'. There is no code here to help you with, so it makes answering the question a lot more work for us.
If you want to grab a file, you need something like this in an html file somewhere:
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile" />
<input type="submit" name="submit" value="Upload" />
</form>
That will give you the browse button, an upload button to start the action (submit the form) and note the enctype so Django knows to give you request.FILES
In a view somewhere you can access the file with
def myview(request):
request.FILES['myfile'] # this is my file
There is a huge amount of information in the file upload docs
I recommend you read the page thoroughly and just start writing code - then come back with examples and stack traces when it doesn't work.
Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call
with an assertion about call_count
.
>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
'%s call not found' % expected_string
AssertionError: mock(4) call not found
I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.
If you do care about order or you expect multiple identical calls, assert_has_calls
might be more appropriate.
Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.
Add
android:configChanges="keyboardHidden|orientation|screenSize"
to your manifest.
I personally avoid else
blocks when possible. See the Anti-if Campaign
Also, they don't charge 'extra' for the line, you know :p
"Simple is better than complex" & "Readability is king"
delta = 1 if (A > B) else -1
return A + delta
In short: If you'are absolutely sure all new objects fail somecond()
check, then your code works fine, it just wastes some time iterating the newly added objects.
Before giving a proper answer, you have to understand why it considers a bad idea to change list/dict while iterating. When using for
statement, Python
tries to be clever, and returns a dynamically calculated item each time. Take list
as example, python
remembers a index, and each time it returns l[index]
to you. If you are changing l
, the result l[index]
can be messy.
NOTE: Here is a stackoverflow question to demonstrate this.
The worst case for adding element while iterating is infinite loop, try(or not if you can read a bug) the following in a python REPL:
import random
l = [0]
for item in l:
l.append(random.randint(1, 1000))
print item
It will print numbers non-stop until memory is used up, or killed by system/user.
Understand the internal reason, let's discuss the solutions. Here are a few:
Iterating the origin list, and modify the copied one.
result = l[:]
for item in l:
if somecond(item):
result.append(Obj())
Instead of handling control to python, you decides how to iterate the list:
length = len(l)
for index in range(length):
if somecond(l[index]):
l.append(Obj())
Before iterating, calculate the list length, and only loop length
times.
Instead of modifying the origin list, store new object in a new list and concatenate them afterward.
added = [Obj() for item in l if somecond(item)]
l.extend(added)
Alternatively you could update brew
by installing it again. (Think I did this as El Capitan changed something)
Note: this is a heavy handed approach that will remove all applications installed via brew!
Try to install brew a fresh and it will tell how to uninstall.
At original time of writing to uninstall:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Edit: As of 2020 to uninstall:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.
Here is the code for reference.
package com.athanazio.jaga.desktop.sound;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Sound {
AudioInputStream in;
AudioFormat decodedFormat;
AudioInputStream din;
AudioFormat baseFormat;
SourceDataLine line;
private boolean loop;
private BufferedInputStream stream;
// private ByteArrayInputStream stream;
/**
* recreate the stream
*
*/
public void reset() {
try {
stream.reset();
in = AudioSystem.getAudioInputStream(stream);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = getLine(decodedFormat);
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
line.close();
din.close();
in.close();
} catch (IOException e) {
}
}
Sound(String filename, boolean loop) {
this(filename);
this.loop = loop;
}
Sound(String filename) {
this.loop = false;
try {
InputStream raw = Object.class.getResourceAsStream(filename);
stream = new BufferedInputStream(raw);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// byte[] buffer = new byte[1024];
// int read = raw.read(buffer);
// while( read > 0 ) {
// out.write(buffer, 0, read);
// read = raw.read(buffer);
// }
// stream = new ByteArrayInputStream(out.toByteArray());
in = AudioSystem.getAudioInputStream(stream);
din = null;
if (in != null) {
baseFormat = in.getFormat();
decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, baseFormat
.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat
.getSampleRate(), false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
line = getLine(decodedFormat);
}
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
private SourceDataLine getLine(AudioFormat audioFormat)
throws LineUnavailableException {
SourceDataLine res = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}
public void play() {
try {
boolean firstTime = true;
while (firstTime || loop) {
firstTime = false;
byte[] data = new byte[4096];
if (line != null) {
line.start();
int nBytesRead = 0;
while (nBytesRead != -1) {
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1)
line.write(data, 0, nBytesRead);
}
line.drain();
line.stop();
line.close();
reset();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
As a complement to other answers note that you can also put the lang
attribute on various HTML tags inside a page.
For example to give a hint to the spellchecker that the input text should be in english:
<input ... spellcheck="true" lang="en"> ...
See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input name="q1_a" type="text" value="1A"/>
<input name="q1_b" type="text" value="1B"/>
<input name="q1_c" type="text" value="1C"/>
<input name="q2_d" type="text" value="2D"/>
<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for (x = 0 ; x < inputs.length ; x++){
myname = inputs[x].getAttribute("name");
if(myname.indexOf("q1_")==0){
alert(myname);
// do more stuff here
}
}
</script>
</body>
</html>
Single quotes work fine too, even without escaping the double quotes, at least in Excel 2016:
'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'
Excel will put that in 5 columns (if you choose the single quote as "Text qualifier" in the "Text to columns" wizard)
$(function() {
$("#txtConfirmPassword").keyup(function() {
var password = $("#txtNewPassword").val();
$("#divCheckPasswordMatch").html(password == $(this).val()
? "Passwords match."
: "Passwords do not match!"
);
});
});?
There is no need to use the Third loop to check the second largest number in the array. You can only use two loops(one for insertion and another is for checking.
Refer this code.
#include <stdio.h>
int main()
{
int a[10], n;
int i;
printf("enter number of elements you want in array");
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int largest1 = a[0],largest2 = a[0];
for (i = 0; i < n; i++)
{
if (a[i] > largest1)
{
largest2=largest1;
largest1 = a[i];
}
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}
Hope this code will work for you.
Enjoy Coding :)
This is the default behavior of display: block
The fastest way that you can fix it in 2020 is to set display: 'flex'
of parent element and padding e.g. 20px then all its children will have 100% height relative to its height.
String validNumber = "^[+]?[0-9]{8,15}$";
if (number.matches(validNumber)) {
Uri call = Uri.parse("tel:" + number);
Intent intent = new Intent(Intent.ACTION_DIAL, call);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
return;
} else {
Toast.makeText(EditorActivity.this, "no phone number available", Toast.LENGTH_SHORT).show();
}
Get the field value through the id and send with ajax
var field = $("#field").val();
$.ajax({
type: "POST",
url: "db.php",
data: {variable_name:field},
async:false,
dataType:"json",
success: function(response) {
alert(response);
}
});
At db.php file get the variable name
$variable_name = $_GET['variable_name'];
mysql_query("SELECT password FROM table_name WHERE password='".md5($variable_name)."'");
object.setForeground(Color.green);
*any colour you wish *object being declared earlier
When you got few list but you don't know how many exactly, use this:
listsOfProducts
contains few lists filled with objects.
List<Product> productListMerged = new List<Product>();
listsOfProducts.ForEach(q => q.ForEach(e => productListMerged.Add(e)));
Select * from emp where joindate between date1 and date2;
But this query not show proper data.
Eg
1-jan-2013 to 12-jan-2013.
But it's show data
1-jan-2013 to 11-jan-2013.
For those looking for an inline example, here is one:
<audio controls style="width: 200px;">
<source src="http://somewhere.mp3" type="audio/mpeg">
</audio>
It doesn't seem to respect a "height" setting, at least not awesomely. But you can always "customize" the controls but creating your own controls (instead of using the built-in ones) or using somebody's widget that similarly creates its own :)
For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.
<html>
<head>
<script>
var div, container = document.getElementById("container")
for(var i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
https://codepen.io/pcwanderer/pen/MMEREr
Looking at the error in the console for the above code.
Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.
<html>
<head>
<style>
#container{
height: 200px;
width: 700px;
background-color: red;
margin: 10px;
}
div{
height: 100px;
width: 100px;
background-color: purple;
margin: 20px;
display: inline-block;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var div, container = document.getElementById("container")
for(let i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</body>
</html>
https://codepen.io/pcwanderer/pen/pXWBQL
I hope this helps. :)
use
keyword from Command Line Interface:PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.
Create a new directory /home/el/bin
Make a new file called namespace_example.php
and put this code in there:
<?php
require '/home/el/bin/mylib.php';
use foobarwhatever\dingdong\penguinclass;
$mypenguin = new penguinclass();
echo $mypenguin->msg();
?>
Make another file called mylib.php
and put this code in there:
<?php
namespace foobarwhatever\dingdong;
class penguinclass
{
public function msg() {
return "It's a beautiful day chris, come out and play! " .
"NO! *SLAM!* taka taka taka taka.";
}
}
?>
Run it from commandline like this:
el@apollo:~/bin$ php namespace_example.php
Which prints:
It's a beautiful day chris, come out and play!
NO! *SLAM!* taka taka taka taka
See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php
There is text-decoration-thickness
, currently part of CSS Text Decoration Module Level 4. It's at "Editor's Draft" stage - so it's a work in progress and subject to change. As of January 2020, it is only supported in Firefox and Safari.
The text-decoration-thickness CSS property sets the thickness, or width, of the decoration line that is used on text in an element, such as a line-through, underline, or overline.
a {
text-decoration-thickness: 2px;
}
Codepen: https://codepen.io/mrotaru/pen/yLyLOgr (Firefox only)
There's also text-decoration-color
, which is part of CSS Text Decoration Module Level 3. This is more mature (Candidate Recommendation) and is supported in most major browsers (exceptions are Edge and IE). Of course it can't be used to alter the thickness of the line, but can be used to achieve a more "muted" underline (also shown in the codepen).
As of python 2.7
, optparse
is deprecated, and will hopefully go away in the future.
argparse
is better for all the reasons listed on its original page (https://code.google.com/archive/p/argparse/):
+
and /
More information is also in PEP 389, which is the vehicle by which argparse
made it into the standard library.
For a new project select the home directory of the jdk
eg C:\Java\jdk1.7.0_99
or C:\Program Files\Java\jdk1.7.0_99
For an existing project.
1) You need to have a jdk
installed on the system.
for instance in
C:\Java\jdk1.7.0_99
2) go to project structure
under File
menu ctrl+alt+shift+S
3) SDKs
is located under Platform Settings
. Select it.
4) click the green +
up the top of the window.
5) select JDK
(I have to use keyboard to select it do not know why).
select the home directory for your jdk installation.
should be good to go.
outgoing url in mvc generated based on the current routing schema.
because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.
to solve this problem you should use UrlParameter.Optional:
<a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
This does not work any more - as an exercise, see if you can replace it with the Github API:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
alert(JSON.stringify(data));
You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>
WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.
The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).
Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.
To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).
JLabel label = new JLabel("Hello World");
label.setFont(new Font("Calibri", Font.BOLD, 20));
Array.prototype.swap = function(a, b) {
var temp = this[a];
this[a] = this[b];
this[b] = temp;
};
Usage:
var myArray = [0,1,2,3,4...];
myArray.swap(4,1);
// Prepared By Muhammad Mubashir.
// 26, August, 2011.
// Chnage Back Ground Image of Activity.
package com.ChangeBg_01;
import com.ChangeBg_01.R;
import android.R.color;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ChangeBg_01Activity extends Activity
{
TextView tv;
int[] arr = new int[2];
int i=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
arr[0] = R.drawable.icon1;
arr[1] = R.drawable.icon;
// Load a background for the current screen from a drawable resource
//getWindow().setBackgroundDrawableResource(R.drawable.icon1) ;
final Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
//tv.append("Hello World");
if(i== 2){
i=0;
}
getWindow().setBackgroundDrawableResource(arr[i]);
handler.postDelayed(this, 1000);
i++;
}
};
handler.postDelayed(r, 1000);
Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true)
{
if(i== 2){
//finish();
i=0;
}
sleep(1000);
handler.post(r);
//i++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
}
/*android:background="#FFFFFF"*/
/*
ImageView imageView = (ImageView) findViewById(R.layout.main);
imageView.setImageResource(R.drawable.icon);*/
// Now get a handle to any View contained
// within the main layout you are using
/* View someView = (View)findViewById(R.layout.main);
// Find the root view
View root = someView.getRootView();*/
// Set the color
/*root.setBackgroundColor(color.darker_gray);*/
After spend a lot time, trying follow these answers actually after code below it worked for me. Before do it just but be sure that there is no problem in update :)
gem update --system
In addition to registering a ByteArrayHttpMessageConverter
, you may want to use a ResponseEntity
instead of @ResponseBody
. The following code works for me :
@RequestMapping("/photo2")
public ResponseEntity<byte[]> testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}
You can use a background image to accomplish this;
From MDN - Background Size: Contain:
This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.
CSS:
#im {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-image: url("path/to/img");
background-repeat: no-repeat;
background-size: contain;
}
HTML:
<div id="wrapper">
<div id="im">
</div>
</div>
There's another method shown at this Google Groups post. In short, you could try detecting whether the extension icon loads successfully. This may be helpful if the extension you're checking for isn't your own.
All Java objects have a toString()
method, which is invoked when you try to print the object.
System.out.println(myObject); // invokes myObject.toString()
This method is defined in the Object
class (the superclass of all Java objects). The Object.toString()
method returns a fairly ugly looking string, composed of the name of the class, an @
symbol and the hashcode of the object in hexadecimal. The code for this looks like:
// Code of Object.toString()
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
A result such as com.foo.MyType@2f92e0f4
can therefore be explained as:
com.foo.MyType
- the name of the class, i.e. the class is MyType
in the package com.foo
.@
- joins the string together2f92e0f4
the hashcode of the object.The name of array classes look a little different, which is explained well in the Javadocs for Class.getName()
. For instance, [Ljava.lang.String
means:
[
- an single-dimensional array (as opposed to [[
or [[[
etc.)L
- the array contains a class or interfacejava.lang.String
- the type of objects in the arrayTo print something different when you call System.out.println(myObject)
, you must override the toString()
method in your own class. Here's a simple example:
public class Person {
private String name;
// constructors and other methods omitted
@Override
public String toString() {
return name;
}
}
Now if we print a Person
, we see their name rather than com.foo.Person@12345678
.
Bear in mind that toString()
is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString()
for our Person
class might be:
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + name + "]";
}
Which would print, e.g., Person[name=Henry]
. That's a really useful piece of data for debugging/testing.
If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}
.
Many IDEs offer support for auto-generating a toString()
method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.
Several popular Java libraries offer this feature as well. Some examples include:
@ToString
annotation from Project Lombok
So you've created a nice toString()
for your class. What happens if that class is placed into an array or a collection?
If you have an array of objects, you can call Arrays.toString()
to produce a simple representation of the contents of the array. For instance, consider this array of Person
objects:
Person[] people = { new Person("Fred"), new Person("Mike") };
System.out.println(Arrays.toString(people));
// Prints: [Fred, Mike]
Note: this is a call to a static method called toString()
in the Arrays class, which is different to what we've been discussing above.
If you have a multi-dimensional array, you can use Arrays.deepToString()
to achieve the same sort of output.
Most collections will produce a pretty output based on calling .toString()
on every element.
List<Person> people = new ArrayList<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));
System.out.println(people);
// Prints [Alice, Bob]
So you just need to ensure your list elements define a nice toString()
as discussed above.
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
select *
from TABLE_NAME
where dbms_lob.instr(COLUMNNAME,'searchtext') > 0;
Remove this from #info
:
margin-left:auto;
Add this for your header:
#info p {
text-align: center;
}
Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align
.
Sample
http://jsfiddle.net/Vc8CB/
You can solve this fully in the html:
<div>
<input ng-model=collapse type=checkbox>Title
<div ng-show=collapse>
Only shown when checkbox is clicked
</div>
</div>
This also works well with ng-repeat since it will create a local scope for each member.
<table>
<tbody ng-repeat='m in members'>
<tr>
<td><input type=checkbox ng-model=collapse></td>
<td>{{m.title}}</td>
</tr>
<tr ng-show=collapse>
<td> </td>
<td>{{ m.content }}</td>
</tr>
</tbody>
</table>
Be aware that even though a repeat has its own scope, initially it will inherit the value from collapse from super scopes. This allows you to set the initial value in one place but it can be surprising.
You can of course restyle the checkbox. See http://jsfiddle.net/azD5m/5/
Updated fiddle: http://jsfiddle.net/azD5m/374/ Original fiddle used closing </input>
tags to add the HTML text label instead of using <label>
tags.
You can create a countdown timer using applet, below is the code,
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer; // not java.util.Timer
import java.text.NumberFormat;
import java.net.*;
/**
* An applet that counts down from a specified time. When it reaches 00:00,
* it optionally plays a sound and optionally moves the browser to a new page.
* Place the mouse over the applet to pause the count; move it off to resume.
* This class demonstrates most applet methods and features.
**/
public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00
// Called when the applet is first loaded
public void init() {
// Figure out how long to count for by reading the "minutes" parameter
// defined in a <param> tag inside the <applet> tag. Convert to ms.
String minutes = getParameter("minutes");
if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
else remaining = 600000; // 10 minutes by default
// Create a JLabel to display remaining time, and set some properties.
label = new JLabel();
label.setHorizontalAlignment(SwingConstants.CENTER );
label.setOpaque(true); // So label draws the background color
// Read some parameters for this JLabel object
String font = getParameter("font");
String foreground = getParameter("foreground");
String background = getParameter("background");
String imageURL = getParameter("image");
// Set label properties based on those parameters
if (font != null) label.setFont(Font.decode(font));
if (foreground != null) label.setForeground(Color.decode(foreground));
if (background != null) label.setBackground(Color.decode(background));
if (imageURL != null) {
// Load the image, and save it so we can release it later
image = getImage(getDocumentBase(), imageURL);
// Now display the image in the JLabel.
label.setIcon(new ImageIcon(image));
}
// Now add the label to the applet. Like JFrame and JDialog, JApplet
// has a content pane that you add children to
getContentPane().add(label, BorderLayout.CENTER);
// Get an optional AudioClip to play when the count expires
String soundURL = getParameter("sound");
if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);
// Obtain a NumberFormat object to convert number of minutes and
// seconds to strings. Set it up to produce a leading 0 if necessary
format = NumberFormat.getNumberInstance();
format.setMinimumIntegerDigits(2); // pad with 0 if necessary
// Specify a MouseListener to handle mouse events in the applet.
// Note that the applet implements this interface itself
addMouseListener(this);
// Create a timer to call the actionPerformed() method immediately,
// and then every 1000 milliseconds. Note we don't start the timer yet.
timer = new Timer(1000, this);
timer.setInitialDelay(0); // First timer is immediate.
}
// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }
// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates
// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates
// Return information about the applet
public String getAppletInfo() {
return "Countdown applet Copyright (c) 2003 by David Flanagan";
}
// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }
// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
{"minutes", "number", "time, in minutes, to countdown from"},
{"font", "font", "optional font for the time display"},
{"foreground", "color", "optional foreground color for the time"},
{"background", "color", "optional background color"},
{"image", "image URL", "optional image to display next to countdown"},
{"sound", "sound URL", "optional sound to play when we reach 00:00"},
{"newpage", "document URL", "URL to load when timer expires"},
};
// Start or resume the countdown
void resume() {
// Restore the time we're counting down from and restart the timer.
lastUpdate = System.currentTimeMillis();
timer.start(); // Start the timer
}
// Pause the countdown
void pause() {
// Subtract elapsed time from the remaining time and stop timing
long now = System.currentTimeMillis();
remaining -= (now - lastUpdate);
timer.stop(); // Stop the timer
}
// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
long now = System.currentTimeMillis(); // current time in ms
long elapsed = now - lastUpdate; // ms elapsed since last update
remaining -= elapsed; // adjust remaining time
lastUpdate = now; // remember this update time
// Convert remaining milliseconds to mm:ss format and display
if (remaining < 0) remaining = 0;
int minutes = (int)(remaining/60000);
int seconds = (int)((remaining)/1000);
label.setText(format.format(minutes) + ":" + format.format(seconds));
// If we've completed the countdown beep and display new page
if (remaining == 0) {
// Stop updating now.
timer.stop();
// If we have an alarm sound clip, play it now.
if (sound != null) sound.play();
// If there is a newpage URL specified, make the browser
// load that page now.
String newpage = getParameter("newpage");
if (newpage != null) {
try {
URL url = new URL(getDocumentBase(), newpage);
getAppletContext().showDocument(url);
}
catch(MalformedURLException ex) { showStatus(ex.toString()); }
}
}
}
// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }
// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
pause(); // pause countdown
showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
resume(); // resume countdown
showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
You can use this variation:
import pandas as pd
vals = {
'name' : ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
'gender' : ['m', 'f', 'f', 'f', 'f', 'c', 'c'],
'age' : [39, 12, 27, 13, 36, 29, 10],
'education' : ['ma', None, 'school', None, 'ba', None, None]
}
df_vals = pd.DataFrame(vals) #converting dict to dataframe
This will output(** - highlighting only desired rows):
age education gender name
0 39 ma m n1 **
1 12 None f n2
2 27 school f n3 **
3 13 None f n4
4 36 ba f n5 **
5 29 None c n6
6 10 None c n7
So to drop everything that does not have an 'education' value, use the code below:
df_vals = df_vals[~df_vals['education'].isnull()]
('~' indicating NOT)
Result:
age education gender name
0 39 ma m n1
2 27 school f n3
4 36 ba f n5
If you want to import A.ipynb
in B.ipynb
write
import import_ipynb
import A
in B.ipynb
.
The import_ipynb
module I've created is installed via pip:
pip install import_ipynb
It's just one file and it strictly adheres to the official howto on the jupyter site.
PS It also supports things like from A import foo
, from A import *
etc
JLS Standard
JLS 7 15.17.2. Division Operator / says:
Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| = |n|. Moreover, q is positive when |n| = |d| and n and d have the same sign, but q is negative when |n| = |d| and n and d have opposite signs.
This is why 1/2
does not give a float.
Converting just either one to float as in (float)1/2
suffices because 15.17. Multiplicative Operators says:
Binary numeric promotion is performed on the operands
and 5.6.2. Binary Numeric Promotion says:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float
https://gist.github.com/danomanion/6175687 proposes an elegant solution, using a custom bullet in place of a background image:
a.logo {
display: list-item;
list-style-image: url("../images/desired-background.png");
list-style-position: inside;
}
By including this within a
@media print {
}
block, I'm able to replace a white-on-transparent logo on the screen, rendered as a background-image, with a black-on-transparent logo for print.
Put your SSH key into your Jenkins profile, then use the declarative linter as follows:
ssh jenkins.hostname.here declarative-linter < Jenkinsfile
This will do a static analysis on your Jenkinsfile. In the editor of your choice, define a keyboard shortcut that runs that command automatically. In Visual Studio Code, which is what I use, go to Tasks > Configure Tasks, then use the following JSON to create a Validate Jenkinsfile command:
{
"version": "2.0.0",
"tasks": [
{
"label": "Validate Jenkinsfile",
"type": "shell",
"command": "ssh jenkins.hostname declarative-linter < ${file}"
}
]
}
you could just contain the div in anchor tag like this:
a{_x000D_
text-decoration:none;_x000D_
color:#ffffff;_x000D_
}_x000D_
a div{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background:#ff4500;_x000D_
}_x000D_
a div:hover{_x000D_
background:#0078d7;_x000D_
}
_x000D_
<body>_x000D_
<a href="http://example.com">_x000D_
<div>_x000D_
Hover me_x000D_
</div>_x000D_
</a>_x000D_
</body>
_x000D_
EF Core: Using "ThenInclude" to load mutiple levels: For example:
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ThenInclude(author => author.Photo)
.ToList();
Add environment variable for Android Home Targetting Platform Tools
echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
Restart Bash
source ~/.bash_profile
Now Check adb
Simply type
adb
on terminal
I overloaded the console methods.
var colors={
Reset: "\x1b[0m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m"
};
var infoLog = console.info;
var logLog = console.log;
var errorLog = console.error;
var warnLog = console.warn;
console.info= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Green);
copyArgs.push(colors.Reset);
infoLog.apply(null,copyArgs);
};
console.warn= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Yellow);
copyArgs.push(colors.Reset);
warnLog.apply(null,copyArgs);
};
console.error= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Red);
copyArgs.push(colors.Reset);
errorLog.apply(null,copyArgs);
};
// examples
console.info("Numeros",1,2,3);
console.warn("pares",2,4,6);
console.error("reiniciandooo");
The output is.
Check out AdvancedTableViewCells
in Apple's sample code.
You'll want to use the composite cell pattern.
In Sublime Text 3....Try changing the above code to this, note the addition of "start".....
"variants" : [
{ "name": "Run",
"cmd" : ["start", "${file_base_name}.exe"]
}
From the docs:
Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.
http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing
Try:
alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]
The FacetGrid
plot does produce pretty small labels. While @paul-h has described the use of sns.set
as a way to the change the font scaling, it may not be the optimal solution since it will change the font_scale
setting for all plots.
You could use the seaborn.plotting_context
to change the settings for just the current plot:
with sns.plotting_context(font_scale=1.5):
sns.factorplot(x, y ...)
Get items when the date is between fromdate and toDate.
where convert(date, fromdate, 103 ) <= '2016-07-26' and convert(date, toDate, 103) >= '2016-07-26'
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
JSON.parse
All of the answers here use JSON.parse()
in an unsafe way.
You should always put all calls to JSON.parse()
in a try/catch
block especially when you parse JSON coming from an external source, like you do here.
You can use request
to parse the JSON automatically which wasn't mentioned here in other answers. There is already an answer using request
module but it uses JSON.parse()
to manually parse JSON - which should always be run inside a try {} catch {}
block to handle errors of incorrect JSON or otherwise the entire app will crash. And incorrect JSON happens, trust me.
Other answers that use http
also use JSON.parse()
without checking for exceptions that can happen and crash your application.
Below I'll show few ways to handle it safely.
All examples use a public GitHub API so everyone can try that code safely.
request
Here's a working example with request
that automatically parses JSON:
'use strict';
var request = require('request');
var url = 'https://api.github.com/users/rsp';
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.html_url);
}
});
http
and try/catch
This uses https
- just change https
to http
if you want HTTP connections:
'use strict';
var https = require('https');
var options = {
host: 'api.github.com',
path: '/users/rsp',
headers: {'User-Agent': 'request'}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
try {
var data = JSON.parse(json);
// data is available here:
console.log(data.html_url);
} catch (e) {
console.log('Error parsing JSON!');
}
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
http
and tryjson
This example is similar to the above but uses the tryjson
module. (Disclaimer: I am the author of that module.)
'use strict';
var https = require('https');
var tryjson = require('tryjson');
var options = {
host: 'api.github.com',
path: '/users/rsp',
headers: {'User-Agent': 'request'}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
var data = tryjson.parse(json);
console.log(data ? data.html_url : 'Error parsing JSON!');
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
The example that uses request
is the simplest. But if for some reason you don't want to use it then remember to always check the response code and to parse JSON safely.
for (Object key : meMap.keySet()) {
String value=(String)meMap.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
First you need to load the user details somehow
Then you need to find your EditText if you don't have it-
EditText et = (EditText)findViewById(R.id.youredittext);
after you've found your EditText, call
et.setText(theUserName);
I was in same problem.
Below command solved my problem
pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.0.0-py3-none-any.whl
to find the list of all the urls based on the python version and CPU or GPU only refer to: https://www.tensorflow.org/install/pip
A further clarification to the use of DISTINCT to resolve error ORA-30926 in the general case:
You need to ensure that the set of data specified by the USING() clause has no duplicate values of the join columns, i.e. the columns in the ON() clause.
In OP's example where the USING clause only selects a key, it was sufficient to add DISTINCT to the USING clause. However, in the general case the USING clause may select a combination of key columns to match on and attribute columns to be used in the UPDATE ... SET clause. Therefore in the general case, adding DISTINCT to the USING clause will still allow different update rows for the same keys, in which case you will still get the ORA-30926 error.
This is an elaboration of DCookie's answer and point 3.1 in Tagar's answer, which from my experience may not be immediately obvious.
This one works even with spaces:
format="\t%2s - %s\n"
function doAction
{
local_array=("$@")
for (( i = 0 ; i < ${#local_array[@]} ; i++ ))
do
printf "${format}" $i "${local_array[$i]}"
done
echo -n "Choose: "
option=""
read -n1 option
echo ${local_array[option]}
return
}
#the call:
doAction "${tools[@]}"
I had the same problem while following a tutorial on setting up Laravel Homestead for Windows 10. The tutorial provides an example IP address 192.168.10.10
to use for the server. The problem with their example IP is that if you already have a VirtualBox Host-Only Adapter set up, the IP you use for your vagrant server must have the same first three parts of the IP address of your current adapter.
You can check what your current Virtualbox Host-Only Adapter IP address is by running ipconfig
(windows) ifconfig
(mac/linux) and looking for VirtualBox Host-Only Adapter's IPv4 address. 192.168.56.1
was mine. Usually if the host IP is 192.168.56.1
then the guest IP will be 192.168.56.101
so instead of using the example IP I used 192.168.56.102
. Any IP that is within 192.168.56.*
that is not already taken should work.
After this homestead up
worked perfectly for me.
TL;DR - If your current VirtualBox Host-Only Adapter IP is 192.168.56.1, make your Vagrant server IP 192.168.56.102.
I found a solution that works exactly how I want.
I changed
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');
To
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Document', 'required');
}
You may use Symfony's Filesystem (code):
// composer require symfony/filesystem
use Symfony\Component\Filesystem\Filesystem;
(new Filesystem)->remove($dir);
However I couldn't delete some complex directory structures with this method, so first you should try it to ensure it's working properly.
I could delete the said directory structure using a Windows specific implementation:
$dir = strtr($dir, '/', '\\');
// quotes are important, otherwise one could
// delete "foo" instead of "foo bar"
system('RMDIR /S /Q "'.$dir.'"');
And just for the sake of completeness, here is an old code of mine:
function xrmdir($dir) {
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir.'/'.$item;
if (is_dir($path)) {
xrmdir($path);
} else {
unlink($path);
}
}
rmdir($dir);
}
Goto Properties -> maven Remove the pom.xml from the activate profiles and follow the below steps.
Steps :
I know this is an old post, but just thought I'd share our solution. In the quest for shortest code (doesn't everyone just love terse regex), one could instead use:
title = title.replace(/(^\s+|\s+$)/g, '');
BTW: I ran this same test through the link shared above blog.stevenlevithan.com -- Faster JavaScript Trim and this pattern beat all the other HANDS down!
Using IE8, added test as test13. The results were:
Original length: 226002
trim1: 110ms (length: 225994)
trim2: 79ms (length: 225994)
trim3: 172ms (length: 225994)
trim4: 203ms (length:225994)
trim5: 172ms (length: 225994)
trim6: 312ms (length: 225994)
trim7: 203ms (length: 225994)
trim8: 47ms (length: 225994)
trim9: 453ms (length: 225994)
trim10: 15ms (length: 225994)
trim11: 16ms (length: 225994)
trim12: 31ms (length: 225994)
trim13: 0ms (length: 226002)
in Terminal.app
Preferences > Profiles > (Select a Profile) > Shell.
on 'When the shell exits' chosen 'Close the window'
The following code works:
@Override
protected synchronized void onDraw(Canvas canvas)
{
int stars = getNumStars();
float rating = getRating();
try
{
bitmapWidth = getWidth() / stars;
}
catch (Exception e)
{
bitmapWidth = getWidth();
}
float x = 0;
for (int i = 0; i < stars; i++)
{
Bitmap bitmap;
Resources res = getResources();
Paint paint = new Paint();
if ((int) rating > i)
{
bitmap = BitmapFactory.decodeResource(res, starColor);
}
else
{
bitmap = BitmapFactory.decodeResource(res, starDefault);
}
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, getHeight(), getHeight(), true);
canvas.drawBitmap(scaled, x, 0, paint);
canvas.save();
x += bitmapWidth;
}
super.onDraw(canvas);
}
A lock occurs when multiple processes try to access the same resource at the same time.
One process loses out and must wait for the other to finish.
A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish.
So, an example:
Resource A and resource B are used by process X and process Y
The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can.
In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible.
May use this-
#if defined CONDITION1 || defined CONDITION2
//your code here
#endif
This also does the same-
#if defined(CONDITION1) || defined(CONDITION2)
//your code here
#endif
Further-
#if defined CONDITION1 && defined CONDITION2
#if defined CONDITION1 ^ defined CONDITION2
#if defined CONDITION1 && !defined CONDITION2
Based on Thoku's answer above, here's an answer that resolves the time zone to the nearest half hour (which is relevant for some timezones eg South Australia's) :
from datetime import datetime
round((round((datetime.now()-datetime.utcnow()).total_seconds())/1800)/2)
First declare a class that will return later:
public void date()
{
Datetime startdate;
Datetime enddate;
Timespan remaindate;
startdate = DateTime.Parse(txtstartdate.Text).Date;
enddate = DateTime.Parse(txtenddate.Text).Date;
remaindate = enddate - startdate;
if (remaindate != null)
{
lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
}
else
{
lblmsg.Text = "correct your code again.";
}
}
protected void btncal_Click(object sender, EventArgs e)
{
date();
}
Use a button control to call the above class. Here is an example:
A C solution.
int two(int a, int b, int c) {
return !a + !b + !c < 2;
}
or you may prefer:
int two(int a, int b, int c) {
return !!a + !!b + !!c >= 2;
}
I had similiar problem and this is how I solved it:
In index.html
file I've added manifest:
<html manifest="cache.manifest">
In <head>
section included script updating the cache:
<script type="text/javascript" src="update_cache.js"></script>
In <body>
section I've inserted onload function:
<body onload="checkForUpdate()">
In cache.manifest
I've put all files I want to cache. It is important now that it works in my case (Apache) just by updating each time the "version" comment. It is also an option to name files with "?ver=001" or something at the end of name but it's not needed. Changing just # version 1.01
triggers cache update event.
CACHE MANIFEST
# version 1.01
style.css
imgs/logo.png
#all other files
It's important to include 1., 2. and 3. points only in index.html. Otherwise
GET http://foo.bar/resource.ext net::ERR_FAILED
occurs because every "child" file tries to cache the page while the page is already cached.
In update_cache.js
file I've put this code:
function checkForUpdate()
{
if (window.applicationCache != undefined && window.applicationCache != null)
{
window.applicationCache.addEventListener('updateready', updateApplication);
}
}
function updateApplication(event)
{
if (window.applicationCache.status != 4) return;
window.applicationCache.removeEventListener('updateready', updateApplication);
window.applicationCache.swapCache();
window.location.reload();
}
Now you just change files and in manifest you have to update version comment. Now visiting index.html page will update the cache.
The parts of solution aren't mine but I've found them through internet and put together so that it works.
$broadcast
or $emit
.Cloning a git repository, aptly, clones the entire repository: there isn't a way to select only one revision to clone. However, once you perform git clone
, you can checkout a specific revision by doing checkout <rev>
.
AtomicBoolean
The succinct Answer by NPE sums up your three options. I'll add some example code for the second item listed there: AtomicBoolean
.
You can think of the AtomicBoolean
class as providing some thread-safety wrapping around a boolean
value.
If you instantiate the AtomicBoolean
only once, then you need not worry about the visibility issue in the Java Memory Model that requires volatile
as a solution (the first item in that other Answer). Also, you need not concern yourself with synchronization (the third item in that other Answer) because AtomicBoolean
performs that function of protecting multi-threaded access to its internal boolean value.
Let's look at some example code.
Firstly, in modern Java we generally do not address the Thread
class directly. We now have the Executors framework to simplify handling of threads.
This code below is using Project Loom technology, coming to a future version of Java. Preliminary builds available now, built on early-access Java 16. This makes for simpler coding, with ExecutorService
being AutoCloseable
for convenient use with try-with-resources syntax. But Project Loom is not related to the point of this Answer; it just makes for simpler code that is easier to understand as “structured concurrency”.
The idea here is that we have three threads: the original thread, plus a ExecutorService
that will create two more threads. The two new threads both report the value of our AtomicBoolean
. The first new thread does so immediately, while the other waits 10 seconds before reporting. Meanwhile, our main thread sleeps for 5 seconds, wakes, changes the AtomicBoolean
object’s contained value, and then waits for that second thread to wake and complete its work the report on the now-altered AtomicBoolean
contained value. While we are installing seconds between each event, this is merely for dramatic demonstration. The real point is that these threads could coincidently try to access the AtomicBoolean
simultaneously, but that object will protect access to its internal boolean value in a thread-safe manner. Protecting against simultaneous access is the job of the Atomic…
classes.
try (
ExecutorService executorService = Executors.newVirtualThreadExecutor() ;
)
{
AtomicBoolean flag = new AtomicBoolean( true );
// This task, when run, will immediately report the flag.
Runnable task1 = ( ) -> System.out.println( "First task reporting flag = " + flag.get() + ". " + Instant.now() );
// This task, when run, will wait several seconds, then report the flag. Meanwhile, code below waits a shorter time before *changing* the flag.
Runnable task2 = ( ) -> {
try { Thread.sleep( Duration.ofSeconds( 10 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
System.out.println( "Second task reporting flag = " + flag.get() + ". " + Instant.now() );
};
executorService.submit( task1 );
executorService.submit( task2 );
// Wait for first task to complete, so sleep here briefly. But wake before the sleeping second task awakens.
try { Thread.sleep( Duration.ofSeconds( 5 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
System.out.println( "INFO - Original thread waking up, and setting flag to false. " + Instant.now() );
flag.set( false );
}
// At this point, with Project Loom technology, the flow-of-control blocks until the submitted tasks are done.
// Also, the `ExecutorService` is automatically closed/shutdown by this point, via try-with-resources syntax.
System.out.println( "INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone." + Instant.now() );
Methods such as AtomicBoolean#get
and AtomicBoolean#set
are built to be thread-safe, to internally protect access to the boolean value nested within. Read up on the various other methods as well.
When run:
First task reporting flag = true. 2021-01-05T06:42:17.367337Z
INFO - Original thread waking up, and setting flag to false. 2021-01-05T06:42:22.367456Z
Second task reporting flag = false. 2021-01-05T06:42:27.369782Z
INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone.2021-01-05T06:42:27.372597Z
Pro Tip: When engaging in threaded code in Java, always study the excellent book, Java Concurrency in Practice by Brian Goetz et al.
JSON is essentially a String in PHP or JAVA context. That means string which is valid JSON can be returned in response. Following should work.
@RequestMapping(value="/user/addUser", method=RequestMethod.POST)
@ResponseBody
public String addUser(@ModelAttribute("user") User user) {
if (user != null) {
logger.info("Inside addIssuer, adding: " + user.toString());
} else {
logger.info("Inside addIssuer...");
}
users.put(user.getUsername(), user);
return "{\"success\":1}";
}
This is okay for simple string response. But for complex JSON response you should use wrapper class as described by Shaun.
I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".
To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P
So maybe:
def super_cool_logic():
# execute common code here
@app.route("/foo")
def do_foo():
# do some logic here
super_cool_logic()
return render_template("foo.html")
@app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
super_cool_logic()
return render_template("foo.html", messages={"main":"Condition failed on page baz"})
I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)
emplace_back
shouldn't take an argument of type vector::value_type
, but instead variadic arguments that are forwarded to the constructor of the appended item.
template <class... Args> void emplace_back(Args&&... args);
It is possible to pass a value_type
which will be forwarded to the copy constructor.
Because it forwards the arguments, this means that if you don't have rvalue, this still means that the container will store a "copied" copy, not a moved copy.
std::vector<std::string> vec;
vec.emplace_back(std::string("Hello")); // moves
std::string s;
vec.emplace_back(s); //copies
But the above should be identical to what push_back
does. It is probably rather meant for use cases like:
std::vector<std::pair<std::string, std::string> > vec;
vec.emplace_back(std::string("Hello"), std::string("world"));
// should end up invoking this constructor:
//template<class U, class V> pair(U&& x, V&& y);
//without making any copies of the strings
Example here.
Pasted below:
This is about how to launch android application from the adb shell.
Command: am
Look for invoking path in AndroidManifest.xml
Browser app::
# am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
Starting: Intent { action=android.intent.action.MAIN comp={com.android.browser/com.android.browser.BrowserActivity} }
Warning: Activity not started, its current task has been brought to the front
Settings app::
# am start -a android.intent.action.MAIN -n com.android.settings/.Settings
Starting: Intent { action=android.intent.action.MAIN comp={com.android.settings/com.android.settings.Settings} }
I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot
is capable of plotting multiple lines with one command. If x
and y
are arrays, then plot
draws one line for every column.
In your case, you can do the following:
x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5, 1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')
Have a long list of x's and y's, and want to connect adjacent pairs?
xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])
Want a specified (different) color for the dots and the lines?
plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')
Additionally if you need to restrict the grouping you can use:
db.events.aggregate(
{$match: {province: "ON"}},
{$group: {_id: "$date", number: {$sum: 1}}}
)
Take screenshot of a view in android.
public static Bitmap getViewBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
Change "Data" to whatever sheet name you're testing for...
On Error Resume Next
Set DataSheet = Sheets("Data")
If DataSheet Is Nothing Then
Sheets.Add(after:=ActiveSheet).Name = "Data"
''or whatever alternate code you want to execute''
End If
On Error GoTo 0
Also had this issue (windows), the fix was a complete closure of all terminal instances, then retry.
If you want to open a page or window with sending data POST or GET method you can use a code like this:
$.ajax({
type: "get", // or post method, your choice
url: yourFileForInclude.php, // any url in same origin
data: data, // data if you need send some data to page
success: function(msg){
console.log(msg); // for checking
window.open('about:blank').document.body.innerHTML = msg;
}
});
We can use title()
function with negative line
value to bring down the title.
See this example:
plot(1, 1)
title("Title", line = -2)
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
try port 25 instead of 456.
I got the same error when using port 456, and changing it to 25 worked for me.
If we don't provide any scope then the default scope is compile, If you want to confirm, simply go to Effective pom tab in eclipse editor, it will show you as compile.
Now you can!
var parts = [_x000D_
new Blob(['you construct a file...'], {type: 'text/plain'}),_x000D_
' Same way as you do with blob',_x000D_
new Uint16Array([33])_x000D_
];_x000D_
_x000D_
// Construct a file_x000D_
var file = new File(parts, 'sample.txt', {_x000D_
lastModified: new Date(0), // optional - default = now_x000D_
type: "overide/mimetype" // optional - default = ''_x000D_
});_x000D_
_x000D_
var fr = new FileReader();_x000D_
_x000D_
fr.onload = function(evt){_x000D_
document.body.innerHTML = evt.target.result + "<br><a href="+URL.createObjectURL(file)+" download=" + file.name + ">Download " + file.name + "</a><br>type: "+file.type+"<br>last modified: "+ file.lastModifiedDate_x000D_
}_x000D_
_x000D_
fr.readAsText(file);
_x000D_
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';
Switch the table format InnoDB to MyISAM
for change table format
run this query
ALTER TABLE table_name ENGINE = MyISAM;
(replace table_name with actual table name)
To solve this problem add tools.jar file in window->preferences->ant-> runtime .
Just small change need in test.ts
file inside src folder:
const context = require.context('./', true, /test-example\.spec\.ts$/);
Here, test-example
is the exact file name which we need to run
In the same way, if you need to test the service file only you can replace the filename like "/test-example.service"
You can use unirest, It provides easy method to post request. `
import unirest
def callback(response):
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# consume async post request
def consumePOSTRequestASync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
unirest.post(url, headers = headers,params = params, callback = callback)
# post async request multipart/form-data
consumePOSTRequestASync()
Best one is Axios library for fetching.
use npm i --save axios
for installng and use it like fetch, just write axios instead of fetch and then get response in then().
Surprised no one has posted the type-safe C++ version yet:
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Benefits:
copysign
is slow, especially if you need to promote and then narrow again. This is branchless and optimizes excellentlyCaveats:
The < 0
part of the check triggers GCC's -Wtype-limits
warning when instantiated for an unsigned type. You can avoid this by using some overloads:
template <typename T> inline constexpr
int signum(T x, std::false_type is_signed) {
return T(0) < x;
}
template <typename T> inline constexpr
int signum(T x, std::true_type is_signed) {
return (T(0) < x) - (x < T(0));
}
template <typename T> inline constexpr
int signum(T x) {
return signum(x, std::is_signed<T>());
}
(Which is a good example of the first caveat.)
<input ... checked />
<input ... checked="checked" />
Those are equally valid. And in JavaScript:
input.checked = true;
input.setAttribute("checked");
input.setAttribute("checked","checked");
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
function routeToRoom(userId, passw, cb) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
cb(roomId);
});
});
}
routeToRoom("alex", "123", function(id) {
console.log(id);
});
You need to use callbacks. That's how asynchronous IO works. Btw sys.puts
is deprecated
With jQuery:
$('form').submit(function () {
// Validate here
if (pass)
return true;
else
return false;
});
No, it's not possible. If it runs on the client browser, it must be downloaded by the client browser. It's pretty trivial to use Fiddler to inspect the HTTP session and get any downloaded js files.
There are tricks you can use. One of the most obvious is to employ a javascript obfuscator.
Then again, obfuscation only prevents casual snooping, and doesnt prevent people from lifting and using your code.
You can try compiled action script in the form of a flash movie.
Open PowerShell and run:
[Environment]::SetEnvironmentVariable("PATH", "$ENV:PATH;<path to exe>", "USER")
According to Reddit, more options icon and kabob menu are popular names. I prefer the latter as it goes well with hamburger menu.
Following code will do the task....
<?php
$contacts = array(
"[email protected]",
"[email protected]",
//....as many email address as you need
);
foreach($contacts as $contact) {
$to = $contact;
$subject = 'the subject';
$message = 'hello';
mail($to, $subject, $message, $headers);
}
?>
The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.
SELECT country.name, country.headofstate
FROM country
WHERE country.headofstate LIKE 'A%' AND
country.id in (SELECT country_id FROM city WHERE population > 100000)
Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?
First you should use print_r($_FILES)
to debug, and see what it contains. :
your uploads.php
would look like:
//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);
//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO picture (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
A web app can request access to a sandboxed file system by calling window.requestFileSystem()
. Works in Chrome.
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var fs = null;
window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (filesystem) {
fs = filesystem;
}, errorHandler);
fs.root.getFile('Hello.txt', {
create: true
}, null, errorHandler);
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
}
More info here.
This is how I solved the problem:
<target name="executeSQLScript">
<exec executable="sqlplus" failonerror="true" errorproperty="exit.status">
<arg value="${dbUser}/${dbPass}@<DBHOST>:<DBPORT>/<SID>"/>
<arg value="@${basedir}/db/scripttoexecute.sql"/>
</exec>
</target>
All the above answers are correct, but I noticed something very important. Leaving a space between the variable and the equal sign might result in a problem. For example, (?variablename =value)
Just to add,
if you're using many of them then you can import all using
import 'rxjs/Rx';
as mentioned by @Thierry Templier. But I think If you are using limited operator then you should import individual operator like
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/observable/of';
as mentioned by @uksz.
Because 'rxjs/Rx' will import all the Rx components which definitely cost performance.
Follow the below steps:
1) Right click on your maven project.
2) Select Maven
3) Update Project
4) check the
update project configuration from pom.xml
refresh workspace resources from local filesystem.
clean projects.
That's it.
SQL Server(2012) provides another way to generate script for the SQL Server databases with its objects and data. This script can be used to copy the tables’ schema and data from the source database to the destination one in our case.
SQL Scripting method is useful to generate one single script for the tables’ schema and data, including the indexes and keys. But again this method doesn’t generate the tables’ creation script in the correct order if there are relations between the tables.
I believe fill
is the fastest way to do this.
a = np.empty(10)
a.fill(7)
You should also always avoid iterating like you are doing in your example. A simple a[:] = v
will accomplish what your iteration does using numpy broadcasting.
If you use
std::vector<std::reference_wrapper<std::string>> names{ };
Do not forget, when you use auto in the for loop, to use also get, like this:
for (auto element in : names)
{
element.get()//do something
}
If anyone was looking for a solution which is working with jQuery, here is the adjusted wiki code (the original breaks jQuery).
Object.defineProperty(Object.prototype, "getClassName", {
value: function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
}
});
There is no platform-neutral way of doing this. In the 1.6 release of Java, a "Desktop" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.
If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.
Try this :
width:auto;
margin-right:50px;
A lower-specificity approach that works in most modern browsers (IE11+, and excluding some mobile Opera & IE browsers -- http://caniuse.com/#feat=pointer-events):
.btn {
/* base styles */
}
.btn[disabled]
opacity: 0.4;
cursor: default;
pointer-events: none;
}
.btn:hover {
color: red;
}
The pointer-events: none
rule will disable hover; you won't need to raise specificity with a .btn[disabled]:hover
selector to nullify the hover style.
(FYI, this is the simple HTML pointer-events, not the contentious abstracting-input-devices pointer-events)
The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion
I had to do this for a project. What I ended up doing was start a separate thread for the function
t = threading.Thread(target =heartbeat, args=(worker,))
t.start()
****heartbeat is my function, worker is one of my arguments****
inside of my heartbeat function:
def heartbeat(worker):
while True:
time.sleep(5)
#all of my code
So when I start the thread the function will repeatedly wait 5 seconds, run all of my code, and do that indefinitely. If you want to kill the process just kill the thread.
You can do as follow :
import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))
https://developer.rhino3d.com/guides/rhinopython/python-xml-json/
session_start(); //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id']; //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);
//print_r($_SESSION['student']);
<table class="table"> //html part
<tr>
<th>Name</th>
<th>City</th>
</tr>
<tr>
<?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
echo '<td>'.$_SESSION['student'][$i].'</td>';
} ?>
</tr>
</table>
I tried to improve the code a bit:
public T LoadEnum<T>(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
return defaultValue;
}
I just read in the MySQL documentation that SHOW FULL PROCESSLIST
by default only lists the threads from your current user connection.
Quote from the MySQL SHOW FULL PROCESSLIST documentation:
If you have the PROCESS privilege, you can see all threads.
So you can enable the Process_priv
column in your mysql.user
table. Remember to execute FLUSH PRIVILEGES
afterwards :)
Based on Joey's answer, I came up with an intended (by jQuery, read about 'queue') solution.
It somewhat follows the jQuery.animate() syntax - allows to be chained with other fx functions, supports 'slow' and other jQuery.fx.speeds as well as being fully jQuery. And will be handled the same way as animations, if you stop those.
jsFiddle test ground with more usages (like showing off .stop()), can be found here.
the core of the solution is:
$('<queue/>')_x000D_
.delay(100 /*ms*/)_x000D_
.queue( (next) => { $('#result').text('done.'); next(); } );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
the whole as a plugin, supporting usage of $.wait() and $(..).wait() :
// add wait as $.wait() standalone and $(elem).wait() for animation chaining_x000D_
(function($) {_x000D_
_x000D_
$.wait = function(duration, completeCallback, target) {_x000D_
$target = $(target || '<queue />');_x000D_
return $target.delay(duration).queue(function(next){completeCallback && completeCallback.call($target); next();});_x000D_
}_x000D_
_x000D_
$.fn.wait = function(duration, completeCallback) {_x000D_
return $.wait.call(this, duration, completeCallback, this);_x000D_
};_x000D_
_x000D_
})(jQuery);_x000D_
_x000D_
//TEST_x000D_
$(function() {_x000D_
_x000D_
// stand alone_x000D_
$.wait(1000, function() {_x000D_
$('#result')_x000D_
.append('...done');_x000D_
});_x000D_
_x000D_
// chained_x000D_
$('#result')_x000D_
.append('go...')_x000D_
.wait('slow', function() {_x000D_
$(this).append('after slow');_x000D_
})_x000D_
.css({color: 'green'});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
Note: since wait adds to the animation stack, $.css() is executed immediately - as it is supposed: expected jQuery behaviour.
You can try this:
SET LANGUAGE SPANISH
DECLARE @startDate DATE = GETDATE() -- Your start date
DECLARE @endDate DATE = DATEADD(MONTH, 16, GETDATE()) -- Your end date
DECLARE @years INT = YEAR(@endDate) - YEAR(@startDate)
CREATE TABLE #TMP_YEARS (
[year] INT
)
-- Get all posible years between the start and end date
WHILE @years >= 0
BEGIN
INSERT INTO #TMP_YEARS
([year])
SELECT YEAR(@startDate) + @years
SET @years = @years - 1
END
;WITH [days]([day]) AS -- Posible days at a month
(
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL -- days lower than 10
SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL -- days lower than 20
SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24 UNION ALL SELECT 25 UNION ALL SELECT 26 UNION ALL SELECT 27 UNION ALL SELECT 28 UNION ALL SELECT 29 UNION ALL -- days lower than 30
SELECT 30 UNION ALL SELECT 31 -- days higher 30
),
[months]([month]) AS -- All months at a year
(
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
)
SELECT CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) as [date]
FROM #TMP_YEARS a
CROSS JOIN [months] n -- Join all years with all months
INNER JOIN [days] d on DAY(EOMONTH(CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + CONVERT(VARCHAR, DAY(EOMONTH(CAST(CONVERT(VARCHAR, a.[year]) + '-' + CONVERT(varchar, n.[month]) + '-15' AS DATE)))))) >= d.[day] AND -- The number of the day can't be higher than the last day of the current month and the current year
CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) <= ISNULL(@endDate, GETDATE()) AND -- The current date can't be higher than the end date
CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) >= ISNULL(@startDate, GETDATE()) -- The current date should be higher than the start date
ORDER BY a.[year] ASC, n.[month] ASC, d.[day] ASC
The output will be something like this, you can format the date as you like:
2019-01-24
2019-01-25
2019-01-26
2019-01-27
2019-01-28
2019-01-29
2019-01-30
2019-01-31
2019-02-01
2019-02-02
2019-02-03
2019-02-04
2019-02-05
2019-02-06
2019-02-07
2019-02-08
2019-02-09
...
A FragmentActivity
is a subclass of Activity
that was built for the Android Support Package.
The FragmentActivity
class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager()
and getFragmentManager()
to getSupportLoaderManager()
and getSupportFragmentManager()
respectively.
Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:
mkdir('path/to/directory', 0755, true);
@noskio is correct... it just means that simplejson
isn't found on your system and you need to install it for Python older than 2.6. one way is to use the setuptools easy_install
tool. with it, you can install it as easily as: easy_install simplejson
UPDATE (Feb 2014): this is probably old news to many of you, but pip is a more modern tool that works in a similar way (i.e., pip install simplejson
), only it can also uninstall apps.
Ted's answer is amazing. I ended up using a smaller version of that in case anyone is interested. Useful when you are looking for one aggregation that depends on values from multiple columns:
df=pd.DataFrame({'a': [1,2,3,4,5,6], 'b': [1,1,0,1,1,0], 'c': ['x','x','y','y','z','z']})
a b c
0 1 1 x
1 2 1 x
2 3 0 y
3 4 1 y
4 5 1 z
5 6 0 z
df.groupby('c').apply(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())
c
x 2.0
y 4.0
z 5.0
I like this approach since I can still use aggregate. Perhaps people will let me know why apply is needed for getting at multiple columns when doing aggregations on groups.
It seems obvious now, but as long as you don't select the column of interest directly after the groupby, you will have access to all the columns of the dataframe from within your aggregation function.
df.groupby('c')['a'].aggregate(lambda x: x[x>1].mean())
df.groupby('c').aggregate(lambda x: x[(x['a']>1) & (x['b']==1)].mean())['a']
df.groupby('c').aggregate(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())
I hope this helps.
To make it work you have to replace a run this line of code
serviceMetadata httpGetEnabled="true"/>
http instead of https
and security mode="None" />
Image.fromarray -> returns an image object
from PIL import Image
import numpy as np
PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
It might be happening that you have the old keys exported via env variables (bash_profile) and since the env variables have higher precedence over credential files it is giving the error "the access key id does not exists".
Remove the old keys from the bash_profile and you would be good to go.
Happened with me once earlier when I forgot I have credentials in bash_profile and gave me headache for quite some time :)
I have created a simple JavaScript function to access GET parameters from URL.
Just include this JavaScript source and you can access get
parameters.
E.g.: in http://example.com/index.php?language=french, the language
variable can be accessed as $_GET["language"]
. Similarly, a list of all parameters will be stored in a variable $_GET_Params
as an array. Both the JavaScript and HTML are provided in the following code snippet:
<!DOCTYPE html>
<html>
<body>
<!-- This script is required -->
<script>
function $_GET() {
// Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india
var href = window.location.href;
// Get the protocol e.g. http
var protocol = window.location.protocol + "//";
// Get the host name e.g. www.google.com
var hostname = window.location.hostname;
// Get the pathname e.g. /files/script.php
var pathname = window.location.pathname;
// Remove protocol part
var queries = href.replace(protocol, '');
// Remove host part
queries = queries.replace(hostname, '');
// Remove pathname part
queries = queries.replace(pathname, '');
// Presently, what is left in the variable queries is : ?v=1.8.7&country=india
// Perform query functions if present
if (queries != "" && queries != "?") {
// Remove question mark '?'
queries = queries.slice(1);
// Split all the different queries
queries = queries.split("&");
// Get the number of queries
var length = queries.length;
// Declare global variables to store keys and elements
$_GET_Params = new Array();
$_GET = {};
// Perform functions per query
for (var i = 0; i < length; i++) {
// Get the present query
var key = queries[i];
// Split the query and the value
key = key.split("=");
// Assign value to the $_GET variable
$_GET[key[0]] = [key[1]];
// Assign value to the $_GET_Params variable
$_GET_Params[i] = key[0];
}
}
}
// Execute the function
$_GET();
</script>
<h1>GET Parameters</h1>
<h2>Try to insert some get parameter and access it through JavaScript</h2>
</body>
</html>
_x000D_
If you are using Modernizr, you can add a custom test for it.
It doesn't matter which detection mode you decide to use (userAgent, navigator.vendor or navigator.platform), you can always wrap it up for a easier use later.
//Add Modernizr test
Modernizr.addTest('isios', function() {
return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
});
//usage
if (Modernizr.isios) {
//this adds ios class to body
Modernizr.prefixed('ios');
} else {
//this adds notios class to body
Modernizr.prefixed('notios');
}
It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.
Check this comment by @PaulIrish:
Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.
you can see workarounds to this in this posts:
String current = elements[i];
if (i != elements.length - 1) {
String next = elements[i+1];
}
This makes sure you don't get an ArrayIndexOutOfBoundsException
for the last element (there is no 'next' there). The other option is to iterate to i < elements.length - 1
. It depends on your requirements.
I dont know whether this is the correct way or not but I have changed my style like this.
<style name="NoActionBarStyle" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
An easy solution that doesn't involve resorting to JavaScript and will not break CSS transforms is to simply have a non-scrolling element, the same size as your scrolling element, absolute-positioned over it.
The basic HTML structure would be
CSS
<style>
.parent-to-position-by {
position: relative;
top: 40px; /* just to show it's relative positioned */
}
.scrolling-contents {
display: inline-block;
width: 100%;
height: 200px;
line-height: 20px;
white-space: nowrap;
background-color: #CCC;
overflow: scroll;
}
.fixed-elements {
display: inline-block;
position: absolute;
top: 0;
left: 0;
}
.fixed {
position: absolute; /* effectively fixed */
top: 20px;
left: 20px;
background-color: #F00;
width: 200px;
height: 20px;
}
</style>
HTML
<div class="parent-to-position-by">
<div class="fixed-elements">
<div class="fixed">
I am "fixed positioned"
</div>
</div>
<div class="scrolling-contents">
Lots of contents which may be scrolled.
</div>
</div>
parent-to-position-by
would be the relative div
to position something fixed with respect to.scrolling-contents
would span the size of this div
and contain its main contentsfixed-elements
is just an absolute-positioned div
spanning the same space over top of the scrolling-contents
div
.div
with the fixed
class, it achieves the same effect as if it were fixed-positioned with respect to the parent div
. (or the scrolling contents, as they span that full space)if, after implementing the above addition into your web.config, you get an “Unrecognized configuration section system.web.extensions.” error then try adding this to your web.config in the <ConfigSections>
section:
<sectionGroup name="system.web.extensions" type="System.Web.Extensions">
<sectionGroup name="scripting" type="System.Web.Extensions">
<sectionGroup name="webServices" type="System.Web.Extensions">
<section name="jsonSerialization" type="System.Web.Extensions"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
Well JavaScript per si can differ greatly from platform to platform as it is always an implementation of the original specification EcmaScript.
In any case, independently of the implementation all JavaScript implementations that follow the EcmaScript specification right, will give you an Object Oriented Language. According to the ES standard:
ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment.
So now that we have agreed that JavaScript is an implementation of EcmaScript and therefore it is an object-oriented language. The definition of the new
operation in any Object-oriented language, says that such keyword is used to create an object instance from a class of a certain type (including anonymous types, in cases like C#).
In EcmaScript we don't use classes, as you can read from the specs:
ECMAScript does not use classes such as those in C++, Smalltalk, or Java. Instead objects may be created in various ways including via a literal notation or via constructors which create objects and then execute code that initializes all or part of them by assigning initial values to their properties. Each constructor is a function that has a property named - prototype ? that is used to implement prototype - based inheritance and shared properties. Objects are created by
using constructors in new expressions; for example, new Date(2009,11) creates a new Date object. Invoking a constructor without using new has consequences that depend on the constructor. For example, Date() produces a string representation of the current date and time rather than an object.
Another option is the static String.valueOf
method.
String.valueOf(i)
It feels slightly more right than Integer.toString(i)
to me. When the type of i changes, for example from int
to double
, the code will stay correct.
Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:
Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.
This can be installed via conda with the command conda install -c anaconda python=3.7
as per https://anaconda.org/anaconda/python.
Though not all packages support 3.7 yet, running conda update --all
may resolve some dependency failures.
The following worked for me:
$(':input').val('');
However, it is submitting the form, so it might not be what you are looking for.
For scala
import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))
Here is a good reference. In this case:
curl 'http://twitter.com/users/username.json' | sed -e 's/[{}]/''/g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) { where = match(a[i], /\"text\"/); if(where) {print a[i]} } }'
My pathetic contribution to this dumb problem. In IB set the style to none so you can set the height, then in IB set the class to be a subclass of UITextField
that forces the style to be rounded rect.
@interface JLTForcedRoundedRectTextField : UITextField
@end
@implementation JLTForcedRoundedRectTextField
- (void)awakeFromNib
{
self.borderStyle = UITextBorderStyleRoundedRect;
}
@end
It kept me from having to hack the XIB file or writing style code into my view controller.