Different Python modules to read wav:
There is at least these following libraries to read wave audio files:
The most simple example:
This is a simple example with SoundFile:
import soundfile as sf
data, samplerate = sf.read('existing_file.wav')
Format of the output:
Warning, the data are not always in the same format, that depends on the library. For instance:
from scikits import audiolab
from scipy.io import wavfile
from sys import argv
for filepath in argv[1:]:
x, fs, nb_bits = audiolab.wavread(filepath)
print('Reading with scikits.audiolab.wavread:', x)
fs, x = wavfile.read(filepath)
print('Reading with scipy.io.wavfile.read:', x)
Output:
Reading with scikits.audiolab.wavread: [ 0. 0. 0. ..., -0.00097656 -0.00079346 -0.00097656]
Reading with scipy.io.wavfile.read: [ 0 0 0 ..., -32 -26 -32]
SoundFile and Audiolab return floats between -1 and 1 (as matab does, that is the convention for audio signals). Scipy and wave return integers, which you can convert to floats according to the number of bits of encoding, for example:
from scipy.io.wavfile import read as wavread
samplerate, x = wavread(audiofilename) # x is a numpy array of integers, representing the samples
# scale to -1.0 -- 1.0
if x.dtype == 'int16':
nb_bits = 16 # -> 16-bit wav files
elif x.dtype == 'int32':
nb_bits = 32 # -> 32-bit wav files
max_nb_bit = float(2 ** (nb_bits - 1))
samples = x / (max_nb_bit + 1) # samples is a numpy array of floats representing the samples
The pyaudio website has many examples that are pretty short and clear: http://people.csail.mit.edu/hubert/pyaudio/
Update 14th of December 2019 - Main example from the above linked website from 2017:
"""PyAudio Example: Play a WAVE file."""
import pyaudio
import wave
import sys
CHUNK = 1024
if len(sys.argv) < 2:
print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
sys.exit(-1)
wf = wave.open(sys.argv[1], 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
while data != '':
stream.write(data)
data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
p.terminate()
The snippet here works fine, tested with windows sound:
public static void main(String[] args) {
AePlayWave aw = new AePlayWave( "C:\\WINDOWS\\Media\\tada.wav" );
aw.start();
}
It's been a while since I used it, but JavaLayer is great for MP3 playback
adding muted="muted"
property to HTML5 tag solved my issue
grecaptcha.reset(opt_widget_id)
Resets the reCAPTCHA widget. An optional widget id can be passed, otherwise the function resets the first widget created. (from Google's web page)
You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. You want a method along the lines of:
public static string GetEnumDescription<TEnum>(int value)
{
return GetEnumDescription((Enum)((TEnum)value)); // error!
}
but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). So you need to fool the compiler by inserting casts to object:
public static string GetEnumDescription<TEnum>(int value)
{
return GetEnumDescription((Enum)(object)((TEnum)(object)value)); // ugly, but works
}
You can now call this to get a description for whatever type of enum is at hand:
GetEnumDescription<MyEnum>(1);
GetEnumDescription<YourEnum>(2);
Why python uses list of tuples instead dict?
In python, you cannot guarantee that the dictionary will be interpreted in the order you declared.
So, in mongo shell you could do .sort({'field1':1,'field2':1})
and the interpreter would sort field1 at first level and field 2 at second level.
If this syntax was used in python, there is a chance of sorting by field2 at first level. With tuple, there is no such risk.
.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])
have at look at the static methods DateTime.Parse()
and DateTime.TryParse()
. They will allow you to pass in your date string and a format string, and get a DateTime object in return.
The main difference is that SurfaceView
can be drawn on by background theads but Views
can't.
SurfaceViews
use more resources though so you don't want to use them unless you have to.
Although this question is old, it is still asked by many who use MSYS2.
I started to use it this year to replace CygWin, and I'm getting pretty satisfied.
To install make
, open the MSYS2 shell and type the following commands:
# Update the package database and core system packages
pacman -Syu
# Close shell and open again if needed
# Update again
pacman -Su
# Install make
pacman -S make
# Test it (show version)
make -v
Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.
#include <stdio.h>
void func(int row, int col, int* matrix){
int i, j;
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
}
printf("\n");
}
}
int main(){
int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
func(2, 3, matrix[0]);
return 0;
}
Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.
The path to the nginx.conf
file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf
.
You may access and edit this file by typing this at the terminal
cd /etc/nginx
/etc/nginx$ sudo nano nginx.conf
Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.
I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf
file which is the primary Configuration file for Nginx.
Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d
. Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-
http{
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
Further to this you may comment out from the PRIMARY Config file , the line
http{
#include /etc/nginx/sites-available/some_file.conf; # Comment Out
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
and need not keep any Config Files in /etc/nginx/sites-available/
and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/
, kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .
EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/
, this was the older practice and is DEPRECIATED now .
Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf;
.
Quote from Nginx CookBook page - 5 .
"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."
from pylab import *
import numpy as np
x1 = arange(data) #for example this is a list
y1 = arange(data) #for example this is a list
x=np.array(x) #this will convert a list in to an array
y=np.array(y)
m,b = polyfit(x, y, 1)
plot(x, y, 'yo', x, m*x+b, '--k')
show()
First of all, use INTEL x86... this as CPU/ABI. Secondly, uncheck Snapshot if it is checked. Keep the Target upto Android 4.2.2
I was facing the same problem today and made up a wrapper class, which checks before every method if the element reference is still valid. My solution to retrive the element is pretty simple so i thought i'd just share it.
private void setElementLocator()
{
this.locatorVariable = "selenium_" + DateTimeMethods.GetTime().ToString();
((IJavaScriptExecutor)this.driver).ExecuteScript(locatorVariable + " = arguments[0];", this.element);
}
private void RetrieveElement()
{
this.element = (IWebElement)((IJavaScriptExecutor)this.driver).ExecuteScript("return " + locatorVariable);
}
You see i "locate" or rather save the element in a global js variable and retrieve the element if needed. If the page gets reloaded this reference will not work anymore. But as long as only changes are made to doom the reference stays. And that should do the job in most cases.
Also it avoids re-searching the element.
John
var array: Int[][] = [[1,2,3],[4,5,6],[7,8,9]]
for first in array {
for second in first {
println("value \(second)")
}
}
To achieve what you're looking for you need to initialize the array to the correct template and then loop to add the row and column arrays:
var NumColumns = 27
var NumRows = 52
var array = Array<Array<Int>>()
var value = 1
for column in 0..NumColumns {
var columnArray = Array<Int>()
for row in 0..NumRows {
columnArray.append(value++)
}
array.append(columnArray)
}
println("array \(array)")
if you remove the float: left
from the a
and add white-space: nowrap
to the outer div
#myWorkContent{
width:530px;
height:210px;
border: 13px solid #bed5cd;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
#myWorkContent a {
display: inline;
}
this should work for any size or amount of images..
or even:
#myWorkContent a {
display: inline-block;
vertical-align: middle;
}
which would also vertically align images of different heights if required
It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]
?
In my case solution is really silly, and strange.
Below code was pre-populated by _Layout.cshtml file. (NOT written by me)
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
But, when I verified in Scripts folder, jquery-1.10.2.min.js was not even available. Hence, replaced code like below where jquery-1.9.1.min.js is an existing file:
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
In python3 the following works:
>>> v=10.4
>>> print('% 6.2f' % v)
10.40
>>> print('% 12.1f' % v)
10.4
>>> print('%012.1f' % v)
0000000010.4
just wanted to put my 2cents in about this issue...
I had a similar need where i was pulling data from another table via INDEX/MATCH, and it was difficult to distinguish between a real 0 value vs. a 0 value because of no match (for example for a column chart that shows the progress of values over the 12 months and where we are only in february but the rest of the months data is not available yet and the column chart still showed 0's everywhere for Mar to Dec)
What i ended up doing is create a new series and plot this new series on the graph as a line chart and then i hid the line chart by choosing not to display the line in the options and i put the data labels on top, the formula for the values for this new series was something like :
=IF(LEN([@[column1]])=0,NA(),[@[column1]])
I used LEN as a validation because ISEMPTY/ISBLANK didn't work because the result of the INDEX/MATCH always returned something other than a blank even though i had put a "" after the IFERROR...
On the line chart the error value NA() makes it so that the value isn't displayed ...so this worked out for me...
I guess it's a bit difficult to follow this procedure without pictures, but i hope it paints some kind of picture to allow you to use a workaround if you have a similar case like mine
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
You can use Google Cloud Messaging or GCM, it's free and easy to use. Also you can use third party push servers like PushWoosh which gives you more flexibility
It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:
Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.
You can run your Python code using sl4a. sl4a supports Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell script.
You can learn sl4a Python Examples.
You don't need to iterate through the DataGrid
rows, you can achieve your goal with a more simple solution.
In order to match your row you can iterate through you collection that was bound to your DataGrid.ItemsSource
property then assign this item to you DataGrid.SelectedItem
property programmatically, alternatively you can add it to your DataGrid.SelectedItems
collection if you want to allow the user to select more than one row. See the code below:
<Window x:Class="ProgGridSelection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<StackPanel>
<DataGrid Name="empDataGrid" ItemsSource="{Binding}" Height="200"/>
<TextBox Name="empNameTextBox"/>
<Button Content="Click" Click="OnSelectionButtonClick" />
</StackPanel>
public partial class MainWindow : Window
{
public class Employee
{
public string Code { get; set; }
public string Name { get; set; }
}
private ObservableCollection<Employee> _empCollection;
public MainWindow()
{
InitializeComponent();
}
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
// Generate test data
_empCollection =
new ObservableCollection<Employee>
{
new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
new Employee {Code = "E013", Name = "Ahmed Yousif"},
new Employee {Code = "E431", Name = "Jasmin Kamal"},
};
/* Set the Window.DataContext, alternatively you can set your
* DataGrid DataContext property to the employees collection.
* on the other hand, you you have to bind your DataGrid
* DataContext property to the DataContext (see the XAML code)
*/
DataContext = _empCollection;
}
private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
{
/* select the employee that his name matches the
* name on the TextBox
*/
var emp = (from i in _empCollection
where i.Name == empNameTextBox.Text.Trim()
select i).FirstOrDefault();
/* Now, to set the selected item on the DataGrid you just need
* assign the matched employee to your DataGrid SeletedItem
* property, alternatively you can add it to your DataGrid
* SelectedItems collection if you want to allow the user
* to select more than one row, e.g.:
* empDataGrid.SelectedItems.Add(emp);
*/
if (emp != null)
empDataGrid.SelectedItem = emp;
}
}
@vj9 thx. I update to xcode 7 . It show me the same error. Build well after set "NO"
set "NO" it works well.
This will show you clues about why the linker doesn't want the installed library:
LD_DEBUG=all make ...
I had the same problem in a different context: my system /lib/libz.so.1 had unsatisfied dependencies on libc because I was trying to relink on a different version of the OS.
Vanilla JDBC only supports named parameters in a CallableStatement
(e.g. setString("name", name)
), and even then, I suspect the underlying stored procedure implementation has to support it.
An example of how to use named parameters:
//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
+ "if @id is not null "
+ "select * from sysobjects where id = @id "
+ "else if @name is not null "
+ "select * from sysobjects where name = @name "
+ " end");
stmt.execute();
//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
Took me a while to find this but note that if you have a spacing error you will also get the same error:
[: =: unary operator expected
Correct:
if [ "$APP_ENV" = "staging" ]
vs
if ["$APP_ENV" = "staging" ]
As always setting -x
debug variable helps to find these:
set -x
Quick solution that worked for me. I see there is already an answer for this and this may not even be the best way to go about it. Also, for my solution you'll need Gson.
However, I ran into a situation where I needed to create an instance of a generic class of type java.lang.reflect.Type
.
The following code will create an instance of the class you want with null instance variables.
T object = new Gson().fromJson("{}", myKnownType);
Where myKnownType
is known before hand and obtained via TypeToken.getType()
.
You can now set appropriate properties on this object. Again, this may not be the best way to do this but it works as a quick solution if that's what you need.
What are native methods in Java and where should they be used?
Once you see a small example, it becomes clear:
Main.java:
public class Main {
public native int intMethod(int i);
public static void main(String[] args) {
System.loadLibrary("Main");
System.out.println(new Main().intMethod(2));
}
}
Main.c:
#include <jni.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_intMethod(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile and run:
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main
Output:
4
Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.
So it is clear that it allows you to:
This could be used to:
with the tradeoff of lower portability.
It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?
Example on GitHub for you to play with.
This gives you just the helper method without the side effects of loading every ActionView::Helpers method into your model:
ActionController::Base.helpers.sanitize(str)
An improvement to the accepted answer.
function strip(html)
{
var tmp = document.implementation.createHTMLDocument("New").body;
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
This way something running like this will do no harm:
strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")
Firefox, Chromium and Explorer 9+ are safe. Opera Presto is still vulnerable. Also images mentioned in the strings are not downloaded in Chromium and Firefox saving http requests.
What Mocha options are you using?
Maybe it is something to do with reporter (-R) or ui (-ui) being used?
console.log(msg);
works fine during my test runs, though sometimes mixed in a little goofy. Presumably due to the async nature of the test run.
Here are the options (mocha.opts) I'm using:
--require should
-R spec
--ui bdd
Hmm..just tested without any mocha.opts and console.log
still works.
This is another way. In my case I have:
Inside the button I have this code:
Image myImage = Image.FromFile(@"C:\imagenes\myImage.gif");
Bitmap croppedBitmap = new Bitmap(myImage);
croppedBitmap = croppedBitmap.Clone(
new Rectangle(
(int)LeftMargin.Value, (int)TopMargin.Value,
myImage.Width - (int)LeftMargin.Value,
myImage.Height - (int)TopMargin.Value),
System.Drawing.Imaging.PixelFormat.DontCare);
pictureBox1.Image = croppedBitmap;
I tried it in Visual studio 2012 using C#. I found this solution from this page
I tried experimenting with the answers given. My personal finding came out to be:
git rm -r --cached .
And then
git add .
This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.
Step 1: Change build.grade
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
dependencies {
...
compile 'com.android.support:multidex:1.0.0'
}
Step 2: Setting on the Application class
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MultiDex.install(this);
}
}
Step 3: Change grade.properties
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
It will work!. Thanks.
If you want to get only ID in array, can use array_map:
$data = array_map(function($object){
return $object->ID;
}, $data);
With that, return an array with ID in every pos.
After getting the help from @Blender, @ekhumoro and @Dan, I understand the Linux and Python more than before. Thank you. I got the an idea by @ekhumoro, it is I didn't install PyQt5 correctly. So I delete PyQt5 folder and download again. And redo everything from very start.
After redoing, I got the error as my last update at my question. So, when I search at stack, I got the following solution from here
sudo ln -s /usr/include/python2.7 /usr/local/include/python2.7
And then, I did "sudo make" and "sudo make install" step by step. After "sudo make install", I got the following error. But I ignored it and I created a simple design with qt designer. And I converted it into python file by pyuic5. Everything are going well.
install -m 755 -p /home/thura/PyQt/pyuic5 /usr/bin/
strip /usr/bin/pyuic5
strip:/usr/bin/pyuic5: File format not recognized
make: [install_pyuic5] Error 1 (ignored)
Search your local system's bash man page for ^INVOCATION for information on which file is going to be read at startup.
man bash
/^INVOCATION
Also in the FILES section,
~/.bash_profile
The personal initialization file, executed for login shells
~/.bashrc
The individual per-interactive-shell startup file
Add your script to the proper file. Make sure the script is in the $PATH, or use the absolute path to the script file.
PagedDataSource objPage = new PagedDataSource();
DataView dataView = listData.DefaultView;
objPage.AllowPaging = true;
objPage.DataSource = dataView;
objPage.PageSize = PageSize;
TotalPages = objPage.PageCount;
objPage.CurrentPageIndex = CurrentPage - 1;
//Convert PagedDataSource to DataTable
System.Collections.IEnumerator pagedData = objPage.GetEnumerator();
DataTable filteredData = new DataTable();
bool flagToCopyDTStruct = false;
while (pagedData.MoveNext())
{
DataRowView rowView = (DataRowView)pagedData.Current;
if (!flagToCopyDTStruct)
{
filteredData = rowView.Row.Table.Clone();
flagToCopyDTStruct = true;
}
filteredData.LoadDataRow(rowView.Row.ItemArray, true);
}
//Here is your filtered DataTable
return filterData;
Piece of cake.
Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.
No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.
Voila. Grids FTW.
function useOnceCall(cb, condition = true) {
const isCalledRef = React.useRef(false);
React.useEffect(() => {
if (condition && !isCalledRef.current) {
isCalledRef.current = true;
cb();
}
}, [cb, condition]);
}
and use it.
useOnceCall(()=>{
console.log('called');
})
or
useOnceCall(()=>{
console.log('isLoading');
},isLoading);
HH:MM 12-hour format, optional leading 0
/^(0?[1-9]|1[0-2]):[0-5][0-9]$/
HH:MM 12-hour format, optional leading 0, mandatory meridiems (AM/PM)
/((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
HH:MM 24-hour with leading 0
/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
HH:MM 24-hour format, optional leading 0
/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
HH:MM:SS 24-hour format with leading 0
/(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)/
Using flexbox, this is easy to achieve.
Set the wrapper containing your 3 compartments to display: flex;
and give it a height of 100%
or 100vh
. The height of the wrapper will fill the entire height, and the display: flex;
will cause all children of this wrapper which has the appropriate flex-properties (for example flex:1;
) to be controlled with the flexbox-magic.
Example markup:
<div class="wrapper">
<header>I'm a 30px tall header</header>
<main>I'm the main-content filling the void!</main>
<footer>I'm a 30px tall footer</footer>
</div>
And CSS to accompany it:
.wrapper {
height: 100vh;
display: flex;
/* Direction of the items, can be row or column */
flex-direction: column;
}
header,
footer {
height: 30px;
}
main {
flex: 1;
}
Here's that code live on Codepen: http://codepen.io/enjikaka/pen/zxdYjX/left
You can see more flexbox-magic here: http://philipwalton.github.io/solved-by-flexbox/
Or find a well made documentation here: http://css-tricks.com/snippets/css/a-guide-to-flexbox/
--[Old answer below]--
Here you go: http://jsfiddle.net/pKvxN/
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Layout</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
header {
height: 30px;
background: green;
}
footer {
height: 30px;
background: red;
}
</style>
</head>
<body>
<header>
<h1>I am a header</h1>
</header>
<article>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a ligula dolor.
</p>
</article>
<footer>
<h4>I am a footer</h4>
</footer>
</body>
</html>
That works on all modern browsers (FF4+, Chrome, Safari, IE8 and IE9+)
Like the other answer says, put the &
after the *
.
This brings up an interesting point that can be confusing sometimes: types should be read from right to left. For example, this is (starting from the rightmost *
) a pointer to a constant pointer to an int.
int * const *x;
What you wrote would therefore be a pointer to a reference, which is not possible.
In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me
If you are deeply in recursion inside recursive method, throwing and catching exception may be an option.
Unlike Return that returns only one level up, exception would break out of recursive method as well into the code that initially called it, where it can be catched.
This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:
I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM")
, drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".
It all depends on exactly what you are trying to undo/revert. Start out by reading the post in Ube's link. But to attempt an answer:
Hard reset
git reset --hard [HEAD]
completely remove all staged and unstaged changes to tracked files.
I find myself often using hard resetting, when I'm like "just undo everything like if I had done a complete re-clone from the remote". In your case, where you just want your repo pristine, this would work.
Clean
git clean [-f]
Remove files that are not tracked.
For removing temporary files, but keep staged and unstaged changes to already tracked files. Most times, I would probably end up making an ignore-rule instead of repeatedly cleaning - e.g. for the bin/obj folders in a C# project, which you would usually want to exclude from your repo to save space, or something like that.
The -f (force) option will also remove files, that are not tracked and are also being ignored by git though ignore-rule. In the case above, with an ignore-rule to never track the bin/obj folders, even though these folders are being ignored by git, using the force-option will remove them from your file system. I've sporadically seen a use for this, e.g. when scripting deployment, and you want to clean your code before deploying, zipping or whatever.
Git clean will not touch files, that are already being tracked.
Checkout "dot"
git checkout .
I had actually never seen this notation before reading your post. I'm having a hard time finding documentation for this (maybe someone can help), but from playing around a bit, it looks like it means:
"undo all changes in my working tree".
I.e. undo unstaged changes in tracked files. It apparently doesn't touch staged changes and leaves untracked files alone.
Stashing
Some answers mention stashing. As the wording implies, you would probably use stashing when you are in the middle of something (not ready for a commit), and you have to temporarily switch branches or somehow work on another state of your code, later to return to your "messy desk". I don't see this applies to your question, but it's definitely handy.
To sum up
Generally, if you are confident you have committed and maybe pushed to a remote important changes, if you are just playing around or the like, using git reset --hard HEAD
followed by git clean -f
will definitively cleanse your code to the state, it would be in, had it just been cloned and checked out from a branch. It's really important to emphasize, that the resetting will also remove staged, but uncommitted changes. It will wipe everything that has not been committed (except untracked files, in which case, use clean).
All the other commands are there to facilitate more complex scenarios, where a granularity of "undoing stuff" is needed :)
I feel, your question #1 is covered, but lastly, to conclude on #2: the reason you never found the need to use git reset --hard
was that you had never staged anything. Had you staged a change, neither git checkout .
nor git clean -f
would have reverted that.
Hope this covers.
For bootstrap 4, here's a matrix image explaining the classes used to show / hide elements depends on the screen size:
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.
I offer this for additional examples. This is the same answer as https://stackoverflow.com/a/28159296/
I'll add other edits to make this post more useful.
pandas.DataFrame.query
query
was made for exactly this purpose. Consider the dataframe df
import pandas as pd
import numpy as np
np.random.seed([3,1415])
df = pd.DataFrame(
np.random.randint(10, size=(10, 5)),
columns=list('ABCDE')
)
df
A B C D E
0 0 2 7 3 8
1 7 0 6 8 6
2 0 2 0 4 9
3 7 3 2 4 3
4 3 6 7 7 4
5 5 3 7 5 9
6 8 7 6 4 7
7 6 2 6 6 5
8 2 8 7 5 8
9 4 7 6 1 5
Let's use query
to filter all rows where D > B
df.query('D > B')
A B C D E
0 0 2 7 3 8
1 7 0 6 8 6
2 0 2 0 4 9
3 7 3 2 4 3
4 3 6 7 7 4
5 5 3 7 5 9
7 6 2 6 6 5
Which we chain
df.query('D > B').query('C > B')
# equivalent to
# df.query('D > B and C > B')
# but defeats the purpose of demonstrating chaining
A B C D E
0 0 2 7 3 8
1 7 0 6 8 6
4 3 6 7 7 4
5 5 3 7 5 9
7 6 2 6 6 5
The ES6 way of doing it would be by using template literals:
const str = `This
is
a
multiline text`;
console.log(str);
More reference here
Table2.Column2 => Table1.Column1
I realize this question is old but the accepted answer did not work for me. For future googlers, this is what worked for me:
UPDATE table1
SET column1 = (
SELECT column2
FROM table2
WHERE table2.id = table1.id
);
Whereby:
run it under a different user. assuming this is a windows box, create a user account for scheduled tasks. run it as that user. The command prompt will only show for the user currently logged in.
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
Bergi's solution works nicely when fs
is promise based.
You can use bluebird
, fs-extra
or fs-promise
for this.
However, solution for node's native fs
libary is as follows:
const result = await Promise.all(filePaths
.map( async filePath => {
const fileContents = await getAssetFromCache(filePath, async function() {
// 1. Wrap with Promise
// 2. Return the result of the Promise
return await new Promise((res, rej) => {
fs.readFile(filePath, 'utf8', function(err, data) {
if (data) {
res(data);
}
});
});
});
return fileContents;
}));
Note:
require('fs')
compulsorily takes function as 3rd arguments, otherwise throws error:
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
Mootools also has a nice 'Tips' class available in their 'more builder'.
Why are you all going the hard way?
with open("myfile") as myfile:
nonempty = filter(str.rstrip, myfile)
Convert nonempty into a list if you have the urge to do so, although I highly suggest keeping nonempty a generator as it is in Python 3.x
In Python 2.x you may use itertools.ifilter
to do your bidding instead.
I see lots of confusion in the comments. Null
, IsNull()
and vbNull
are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.
To test if a variable is uninitialized, use IsEmpty()
. To test if a variable is uninitialized or contains ""
, test on ""
or Empty
. To test if a variable is an object, use IsObject
and to see if this object has no reference test on Is Nothing
.
In your case, you first want to test if the variable is an object, and then see if that variable is Nothing
, because if it isn't an object, you get the "Object Required" error when you test on Nothing
.
snippet to mix and match in your code:
If IsObject(provider) Then
If Not provider Is Nothing Then
' Code to handle a NOT empty object / valid reference
Else
' Code to handle an empty object / null reference
End If
Else
If IsEmpty(provider) Then
' Code to handle a not initialized variable or a variable explicitly set to empty
ElseIf provider = "" Then
' Code to handle an empty variable (but initialized and set to "")
Else
' Code to handle handle a filled variable
End If
End If
To change the encoding of your database:
Make sure the client encoding is set correctly during all this.
Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php
7-Zip is able to extract the contents. It works the same way that a tar.gz file works. A compressed file inside a compressed file.
On Windows 7 Pro with 7-Zip installed:
Right click the rpm file. Mouse over 7-Zip in the context menu. Select extract to "filename".
Enter into the filename folder.
Right click the cpio file. Mouse over 7-Zip in the context menu. Select extract to "filename".
You are done. The folder with "filename" contains the extracted contents for inspecting.
I know you Linux guys despise things being made easy, but in the long run, if you have to spend time hunting down a solution to a simple problem like this; that inefficiency is costing you money.
Given the fact that you Linux guys despise efficient simplicity, I highly doubt that the Linux version of 7-Zip will do the same thing in the exact same way.
Why make it easy when you can make downright stupid hard and claim to be a genius at the same time?
Just to be clear; I'm not a Windows fanboy. I'm actually looking into moving over to Linux. I just couldn't resist the opportunity to rub what Windows developers would see as common sense, best developer practices into your faces.
Just be glad it's me posting this and you don't have Mark Harmon standing next to you cause; Special agent Leroy Jethro Gibbs would have done given you a head slap for not using your head.
I don't know which Gibbs rule it is but the rule is: Don't make things harder for yourself than they have to be.
Now we get to see who needs to take a vacation. Take care!
sleep(1.0/24.0)
As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.
You could try one of these solutions:
This exception is thrown when you try to index to something that isn't there, for example:
Dictionary<String, String> test = new Dictionary<String,String>();
test.Add("Key1","Value1");
string error = test["Key2"];
Often times, something like an object will be the key, which undoubtedly makes it harder to get. However, you can always write the following (or even wrap it up in an extension method):
if (test.ContainsKey(myKey))
return test[myKey];
else
throw new Exception(String.Format("Key {0} was not found", myKey));
Or more efficient (thanks to @ScottChamberlain)
T retValue;
if (test.TryGetValue(myKey, out retValue))
return retValue;
else
throw new Exception(String.Format("Key {0} was not found", myKey));
Microsoft chose not to do this, probably because it would be useless when used on most objects. Its simple enough to do yourself, so just roll your own!
In order to restrict you just need to set the single line option on "true".
android:singleLine="true"
You can just use the built-in function count follow by the groupby function
df.groupby(['col5','col2']).count()
<form name="loginform" onsubmit="validateForm()">
instead of putting the onsubmit on the actual input button
The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...
+----------------+-----------------+----------------+----------------+
| Command | Displays Output | Can Get Output | Gets Exit Code |
+----------------+-----------------+----------------+----------------+
| system() | Yes (as text) | Last line only | Yes |
| passthru() | Yes (raw) | No | Yes |
| exec() | No | Yes (array) | Yes |
| shell_exec() | No | Yes (string) | No |
| backticks (``) | No | Yes (string) | No |
+----------------+-----------------+----------------+----------------+
Other misc things to be aware of:
If your command is available in cmd.exe (something like python ./script.py
, but not PowerShell command like ii .
(this means to open the current directory by Windows Explorer)), you can run cmd.exe within PowerShell. The syntax is like this:
cmd /c "command1 && command2"
Here, &&
is provided by cmd syntax described in this question.
Try pass array to vector:
int arr[] = {2,5,8,11,14};
std::vector<int> TestVector(arr, arr+5);
You could always call std::vector::assign to assign array to vector, call std::vector::insert to add multiple arrays.
If you use C++11, you can try:
std::vector<int> v{2,5,8,11,14};
Or
std::vector<int> v = {2,5,8,11,14};
I have created a JSFiddle with my bindHTML knockout binding handler here: https://jsfiddle.net/glaivier/9859uq8t/
First, save the binding handler into its own (or a common) file and include after Knockout.
If you use this switch your bindings to this:
<div data-bind="bindHTML: htmlValue"></div>
OR
<!-- ko bindHTML: htmlValue --><!-- /ko -->
Additionally, you can change the keys view window -> preferences then type: 'keys' and when the key preference page opens you can type 'toggle block selection' and voila!
and if data in "age" column has similar records (i.e. many people are 25 years old, many others are 32 and so on), it causes confusion in aligning right count to each student. in order to avoid it, I joined the tables on student ID as well.
SELECT S.id, S.age, C.cnt
FROM Students S
INNER JOIN (SELECT id, age, count(age) as cnt FROM Students GROUP BY student,age)
C ON S.age = C.age *AND S.id = C.id*
Your DateFormat
pattern does not match you input date String
. You could use
new SimpleDateFormat("dd-MMM-yyyy")
Below is the code that worked for me. We use jpa 1.0, Apache openjpa implementation.
import java.sql.Connection;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;
public final class MsSqlDaoFactory {
public static final Connection getConnection(final EntityManager entityManager) {
OpenJPAEntityManager openJPAEntityManager = OpenJPAPersistence.cast(entityManager);
Connection connection = (Connection) openJPAEntityManager.getConnection();
return connection;
}
}
It seems that your configuration is using the print
option for numpy.seterr
:
>>> import numpy as np
>>> np.array([1])/0 #'warn' mode
__main__:1: RuntimeWarning: divide by zero encountered in divide
array([0])
>>> np.seterr(all='print')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> np.array([1])/0 #'print' mode
Warning: divide by zero encountered in divide
array([0])
This means that the warning you see is not a real warning, but it's just some characters printed to stdout
(see the documentation for seterr
). If you want to catch it you can:
numpy.seterr(all='raise')
which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.numpy.seterr(all='warn')
, which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.Once you actually have a warning, you can use the warnings
module to control how the warnings should be treated:
>>> import warnings
>>>
>>> warnings.filterwarnings('error')
>>>
>>> try:
... warnings.warn(Warning())
... except Warning:
... print 'Warning was raised as an exception!'
...
Warning was raised as an exception!
Read carefully the documentation for filterwarnings
since it allows you to filter only the warning you want and has other options. I'd also consider looking at catch_warnings
which is a context manager which automatically resets the original filterwarnings
function:
>>> import warnings
>>> with warnings.catch_warnings():
... warnings.filterwarnings('error')
... try:
... warnings.warn(Warning())
... except Warning: print 'Raised!'
...
Raised!
>>> try:
... warnings.warn(Warning())
... except Warning: print 'Not raised!'
...
__main__:2: Warning:
sed
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed
command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated in a single workflow when a Makefile
with build instructions is employed.
PS: This answer was written at a time when extension link_attributes
was not yet available in Pandoc.
A protoype bean injected inside a singelton bean will behave like singelton untill expilictly called for creating a new instance by get bean.
context.getBean("Your Bean")
Edit: Use printf("val = 0x%" PRIx64 "\n", val);
instead.
Try printf("val = 0x%llx\n", val);
. See the printf manpage:
ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.
Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t
is not always a unsigned long long
: PRIx64
see also this stackoverflow answer
As per W3C spec,
The list properties ... do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker ...
But the idea with a span inside the list above should work fine!
There are two methods you can use. Both require creating a user and a database.
By default psql connects to the database with the same name as the user. So there is a convention to make that the "user's database". And there is no reason to break that convention if your user only needs one database. We'll be using mydatabase
as the example database name.
Using createuser and createdb, we can be explicit about the database name,
$ sudo -u postgres createuser -s $USER
$ createdb mydatabase
$ psql -d mydatabase
You should probably be omitting that entirely and letting all the commands default to the user's name instead.
$ sudo -u postgres createuser -s $USER
$ createdb
$ psql
Using the SQL administration commands, and connecting with a password over TCP
$ sudo -u postgres psql postgres
And, then in the psql shell
CREATE ROLE myuser LOGIN PASSWORD 'mypass';
CREATE DATABASE mydatabase WITH OWNER = myuser;
Then you can login,
$ psql -h localhost -d mydatabase -U myuser -p <port>
If you don't know the port, you can always get it by running the following, as the postgres
user,
SHOW port;
Or,
$ grep "port =" /etc/postgresql/*/main/postgresql.conf
postgres
userI suggest NOT modifying the postgres
user.
postgres
. You're supposed to have root to get to authenticate as postgres
.postgres
which is the PostgreSQL equivalent of SQL Server's SA
, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
Is very easy, you just need to use method_field('PUT')
like this:
HTML:
<form action="{{ route('route_name') }}" method="post">
{{ method_field('PUT') }}
{{ csrf_field() }}
</form>
or
<form action="{{ route('route_name') }}" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
Regards!
For both *printf
and *scanf
, %s
expects the corresponding argument to be of type char *
, and for scanf
, it had better point to a writable buffer (i.e., not a string literal).
char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";
printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);
scanf("%55s", str_buf);
Using %s
in scanf
without an explcit field width opens the same buffer overflow exploit that gets
did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf
will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf
, you can't supply the field with as a run time argument:
printf("%*s\n", field_width, string);
One option is to build the format string dynamically:
char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"
EDIT
Using scanf
with the %s
conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like
"This is a test"
then scanf("%55s", str_buf)
will read and assign "This"
to str_buf
. Note that the field with specifier doesn't make a difference in this case.
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
Using this you can check at least one checkbox is selected or not in different checkbox groups or multiple checkboxes.
Reference : Link
<label class="control-label col-sm-4">Check Box 1</label>
<input type="checkbox" name="checkbox1" id="checkbox1" value=Male /> Male<br />
<input type="checkbox" name="checkbox1" id="checkbox1" value=Female /> Female<br />
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<label class="control-label col-sm-4">Check Box 3</label>
<input type="checkbox" name="checkbox3" id="checkbox3" value=ck3 /> ck3<br />
<input type="checkbox" name="checkbox3" id="checkbox3" value=ck4 /> ck4<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox1]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 1 can not be null";
return false;
}
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
if (!$('input[name=checkbox3]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
You can find the current user name with CURRENT_USER() function in MySQL.
for Ex:
SELECT CURRENT_USER();
But CURRENT_USER()
will not always return the logged in user. So in case you want to have the logged in user, then use SESSION_USER()
instead.
Something like this:
$(myObj).attr({"data-test-1": num1, "data-test-2": num2});
i fixed it just this code.
local.properties
org.gradle.jvmargs=-XX\:MaxHeapSize\=512m -Xmx512m
and you should do this changing on gradle
defaultConfig {
applicationId "yourProjectPackage"
minSdkVersion 15
versionCode 1
versionName "1.0"
targetSdkVersion 23
multiDexEnabled true //important
}
.navigationBarItems
modifier takes any view you want:
struct ContentView: View {
var body: some View {
NavigationView {
Text("SwiftUI")
.navigationBarItems(leading:
HStack {
Image(systemName: "trash")
Text("Trash")
}
)
}
}
}
.navigationBarItems(trailing: Image(systemName: "trash") )
.navigationBarItems(leading: Image(systemName: "trash.fill"),
trailing: Image(systemName: "trash")
)
You can use a button for each if you need an action for each of them.
The keys are accessed using an exclamation point: ${!array[@]}
, the values are accessed using ${array[@]}
.
You can iterate over the key/value pairs like this:
for i in "${!array[@]}"
do
echo "key : $i"
echo "value: ${array[$i]}"
done
Note the use of quotes around the variable in the for
statement (plus the use of @
instead of *
). This is necessary in case any keys include spaces.
The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.
I tried replacing value
with Value
and it worked out. It has set the value
in input
tag now.
You want:
git rm --cached [file]
If you omit the --cached
option, it will also delete it from the working tree. git rm
is slightly safer than git reset
, because you'll be warned if the staged content doesn't match either the tip of the branch or the file on disk. (If it doesn't, you have to add --force
.)
Yes:
<input required title="Enter something OR ELSE." />
The title
attribute will be used to notify the user of a problem.
For those who using a newer swagger 3 version org.springdoc:springdoc-openapi-ui
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**");
}
}
use your code within
<script type="text/javascript">
function window.onload()
{
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
The most useful thing you can do here is display/i $pc
, before using stepi
as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi
command.
(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)
There are three ways
1) This runs the GUI editor for the user environment variables. It does exactly what the OP wanted to do and does not prompt for administrative credentials.
rundll32.exe sysdm.cpl,EditEnvironmentVariables
(bonus: This works on Windows Vista to Windows 10 for desktops and Windows Server 2008 through Server 2016. It does not work on Windows NT, 2000, XP, and 2003. However, on the older systems you can use sysdm.cpl without the ",EditEnvironmentVariables" parameter and then navigate to the Advanced tab and then Environment Variables button.)
2) Use the SETX command from the command prompt. This is like the set command but updates the environment that's stored in the registry. Unfortunately, SETX is not as easy to use as the built in SET command. There's no way to list the variables for example. Thus it's impossible to do something such as appending a folder to the user's PATH variable. While SET will display the variables you don't know which ones are user vs. system variables and the PATH that's shown is a combination of both.
3) Use regedit and navigate to HKEY_CURRENT_USER\Environment
Keep in mind that changes to the user's environment does not immediately propagate to all processes currently running for that user. You can see this in a command prompt where your changes will not be visible if you use SET. For example
rem Add a user environment variable named stackoverflow that's set to "test"
setx stackoverflow test
set st
This should show all variables whose names start with the letters "st". If there are none then it displays "Environment variable st not defined
".
Exit the command prompt and start another. Try set st
again
and you'll see
stackoverflow=test
To delete the stackoverflow variable use
setx stackoverflow ""
It will respond with "SUCCESS: Specified value was saved.
" which looks strange given you want to delete the variable. However, if you start a new command prompt then set st
will show that there are no variables starting with the letters "st"
(correction - I discovered that setx stackoverflow ""
did not delete the variable. It's in the registry as an empty string. The SET
command though interprets it as though there is no variable. if not defined stackoverflow echo Not defined
says it's not defined.)
The POST/GET with 204 seems fine in the first sight and will also work.
Documentation says, 2xx -- This class of status codes indicates the action requested by the client was received, understood, accepted, and processed successfully. whereas 4xx -- The 4xx class of status code is intended for situations in which the client seems to have erred.
Since, the request was successfully received, understood and processed on server. The result was that the resource was not found. So, in this case this was not an error on the client side or the client has not erred.
Hence this should be a series 2xx code and not 4xx. Sending 204 (No Content) in this case will be better than a 404 or 410 response.
I have got a answer for Hibernate Query Language to use Distinct fields. You can use *SELECT DISTINCT(TO_CITY) FROM FLIGHT_ROUTE*. If you use SQL query, it return String List. You can't use it return value by Entity Class. So the Answer to solve that type of Problem is use HQL with SQL.
FROM FLIGHT_ROUTE F WHERE F.ROUTE_ID IN (SELECT SF.ROUTE_ID FROM FLIGHT_ROUTE SF GROUP BY SF.TO_CITY);
From SQL query statement it got DISTINCT ROUTE_ID and input as a List. And IN query filter the distinct TO_CITY from IN (List).
Return type is Entity Bean type. So you can it in AJAX such as AutoComplement.
May all be OK
I have made a function that deletes invalid UTF-8 characters from a string. I'm using it to clear description of 27000 products before it generates the XML export file.
public function stripInvalidXml($value) {
$ret = "";
$current;
if (empty($value)) {
return $ret;
}
$length = strlen($value);
for ($i=0; $i < $length; $i++) {
$current = ord($value{$i});
if (($current == 0x9) || ($current == 0xA) || ($current == 0xD) || (($current >= 0x20) && ($current <= 0xD7FF)) || (($current >= 0xE000) && ($current <= 0xFFFD)) || (($current >= 0x10000) && ($current <= 0x10FFFF))) {
$ret .= chr($current);
}
else {
$ret .= "";
}
}
return $ret;
}
I don't think your problem is related to Windows global PATH, as remote
is specific to repo.
I recommend you to use Git under Cygwin. Git could work under Windows command line, but there may be some weird problems hard to figure out. Under Cygwin it's more nature and has less error.
All you need is to type bash
in Window CMD then start to use the Unix tools and commands. You can use a shortcut to load bash
, it's as easy as use normal Windows CMD.
The same is true for Rails and Ruby. I used RailsInstaller before, but found using Cygwin to install Rails is more stable.
Finally I'll suggest to install Ubuntu dual boot if you have time(about a month to get familiar). Windows is not very friendly to every Unix tools ultimately. You'll find all pain stopped.
What about paint.getTextBounds() (object method)
The scoping is correct as you've noted. However, you are not calling the inner
function anywhere.
You can do either:
function outer() {
// when you define it this way, the inner function will be accessible only from
// inside the outer function
function inner() {
alert("hi");
}
inner(); // call it
}
Or
function outer() {
this.inner = function() {
alert("hi");
}
}
<input type="button" onclick="(new outer()).inner();" value="ACTION">?
its an implementation of anonymouse class object creation to give ease of writing less code and to save time
I can see its already been answered but still hope one liner will help in better way.
import UIKit
let requiredColor = UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16)/255,
green: CGFloat((rgbValue & 0x00FF00) >> 8)/255,
blue: CGFloat(rgbValue & 0x0000FF)/255, alpha :1)
Updated: :Changes done as per example explained by Author of question to provide hex values
I modified my less variables.less file I modified the variable
@icon-font-path: "fonts/";
the original was
@icon-font-path: "../fonts/";
It was causing a problem
UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.
If your project uses Maven you can simply include UCanAccess via the following coordinates:
groupId: net.sf.ucanaccess
artifactId: ucanaccess
The following is an excerpt from pom.xml
, you may need to update the <version>
to get the most recent release:
<dependencies>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>4.0.4</version>
</dependency>
</dependencies>
As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:
UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)
Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like
ucanaccess-4.0.1.jar
/lib/
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.6.jar
All you need to do is add all five (5) JARs to your project.
NOTE: Do not add
loader/ucanload.jar
to your build path if you are adding the other five (5) JAR files. TheUcanloadDriver
class is only used in special circumstances and requires a different setup. See the related answer here for details.
Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path...
. Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this
NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.
After adding all five (5) JAR files the "Libraries" folder should look something like this:
IntelliJ IDEA: Choose File > Project Structure...
from the main menu. In the "Libraries" pane click the "Add" (+
) button and add the five (5) JAR files. Once that is done the project should look something like this:
Now "U Can Access" data in .accdb and .mdb files using code like this
// assumes...
// import java.sql.*;
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
System.out.println(rs.getString(1));
}
At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.
No, there is no way to only set the opacity of a border with css.
For example, if you did not know the color, there is no way to only change the opacity of the border by simply using rgba()
.
Just to summarize, here's a complete answer, that worked for me.
My problem was that when I used
[NSString stringWithUTF8String:(char *)data.bytes];
The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with Null
or even worse: garbaged at the end of the string.
After some digging I switched to
[[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];
And got the expected result every time.
You probably have a forward declaration of the class, but haven't included the header:
#include <sstream>
//...
QString Stats_Manager::convertInt(int num)
{
std::stringstream ss; // <-- also note namespace qualification
ss << num;
return ss.str();
}
I managed to regenerate R: File->Settings->Compiler
then UNCHECK "Use in-process build"
Rebuild Project
%USERNAME% will get you the username of the currently running process. Depending on how you are running your batch file, this is not necessarily the same as the name of the current user. For example, you might be running your batch file through a scheduled task, from a service, etc.
Here is a more sure way of getting the username of the currently logged on user by scraping the name of the user that started the explorer.exe task:
for /f "TOKENS=1,2,*" %%a in ('tasklist /FI "IMAGENAME eq explorer.exe" /FO LIST /V') do if /i "%%a %%b"=="User Name:" set _currdomain_user=%%c
for /f "TOKENS=1,2 DELIMS=\" %%a in ("%_currdomain_user%") do set _currdomain=%%a & set _curruser=%%b
What about
now()::timestamp
If your other timestamp are without time zone then this cast will yield the matching type "timestamp without time zone" for the current time.
I would like to read what others think about that option, though. I still don't trust in my understanding of this "with/without" time zone stuff.
EDIT: Adding Michael Ekoka's comment here because it clarifies an important point:
Caveat. The question is about generating default timestamp in UTC for a timestamp column that happens to not store the time zone (perhaps because there's no need to store the time zone if you know that all your timestamps share the same). What your solution does is to generate a local timestamp (which for most people will not necessarily be set to UTC) and store it as a naive timestamp (one that does not specify its time zone).
the easiest way is using command line. Just type in directory of your .xsd file:
xjc myFile.xsd.
So, the java will generate all Pojos.
string cat = "cat";
string human = "human";
cout << cat.compare(human) << endl;
This code will give -1 as a result. This is due to the first non-matching character of the compared string 'h' is lower or appears after 'c' in alphabetical order, even though the compared string, 'human' is longer than 'cat'.
I find the return value described in cplusplus.com is more accurate which are-:
0 : They compare equal
<0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.
more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.
Moreover, IMO cppreference.com's description is simpler and so far best describe to my own experience.
negative value if
*this
appears before the character sequence specified by the arguments, in lexicographical orderzero if both character sequences compare equivalent
positive value if
*this
appears after the character sequence specified by the arguments, in lexicographical order
Function matmul (since numpy 1.10.1) works fine for both types and return result as a numpy matrix class:
import numpy as np
A = np.mat('1 2 3; 4 5 6; 7 8 9; 10 11 12')
B = np.array(np.mat('1 1 1 1; 1 1 1 1; 1 1 1 1'))
print (A, type(A))
print (B, type(B))
C = np.matmul(A, B)
print (C, type(C))
Output:
(matrix([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]]), <class 'numpy.matrixlib.defmatrix.matrix'>)
(array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]), <type 'numpy.ndarray'>)
(matrix([[ 6, 6, 6, 6],
[15, 15, 15, 15],
[24, 24, 24, 24],
[33, 33, 33, 33]]), <class 'numpy.matrixlib.defmatrix.matrix'>)
Since python 3.5 as mentioned early you also can use a new matrix multiplication operator @
like
C = A @ B
and get the same result as above.
For Query parameters like domain.com/test?format=json&type=mini
format, then you can easily receive it via - req.query.
app.get('/test', function(req, res){
var format = req.query.format,
type = req.query.type;
});
Laravel 5:
return redirect(...)->withInput();
for back only:
return back()->withInput();
Use HttpUrlConnection by calling openConnection()
on your URL object.
getResponseCode() will give you the HTTP response once you've read from the connection.
e.g.
URL u = new URL("http://www.example.com/");
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
huc.setRequestMethod("GET");
huc.connect() ;
OutputStream os = huc.getOutputStream();
int code = huc.getResponseCode();
(not tested)
The usual way is to use UPDATE:
UPDATE mytable
SET new_column = <expr containing old_column>
You should be able to do this is a single transaction.
Try this:
;WITH CTE
AS
(
SELECT DISTINCT
M1.Product_ID Group_ID,
M1.Product_ID
FROM matches M1
LEFT JOIN matches M2
ON M1.Product_Id = M2.matching_Product_Id
WHERE M2.matching_Product_Id IS NULL
UNION ALL
SELECT
C.Group_ID,
M.matching_Product_Id
FROM CTE C
JOIN matches M
ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID
You can use OPTION(MAXRECURSION n)
to control recursion depth.
For a quick, modern solution, use the JSONify jQuery plugin. The example below is taken verbatim from the GitHub README. All credit to Kushal Pandya, author of the plugin.
Given:
<form id="myform">
<label>Name:</label>
<input type="text" name="name"/>
<label>Email</label>
<input type="text" name="email"/>
<label>Password</label>
<input type="password" name="password"/>
</form>
Running:
$('#myform').jsonify();
Produces:
{"name":"Joe User","email":"[email protected]","password":"mypass"}
If you want to do a jQuery POST with this JSON object:
$('#mybutton').click(function() {
$.post('/api/user', JSON.stringify($('#myform').jsonify()));
}
Query the sysdepends table:
SELECT distinct schema_name(dependentObject.uid) as schema,
dependentObject.*
FROM sysdepends d
INNER JOIN sysobjects o on d.id = o.id
INNER JOIN sysobjects dependentObject on d.depid = dependentObject.id
WHERE o.name = 'TableName'
A way to look just for views/functions/triggers/procedures that reference the object (or any given text) by name is:
SELECT distinct schema_name(so.uid) + '.' + so.name
FROM syscomments sc
INNER JOIN sysobjects so on sc.id = so.id
WHERE sc.text like '%Name%'
jps & jcmd wasn't showing me any results when I tried it using using openjdk-1.8 on redhat linux. But even if it did it only shows processes under the current user which doesn't work in my case. Using the ps|grep is what I ended up doing but the class path for some java apps can be extremely long which makes results illegible so I used sed to remove it. This is a bit rough still but removes everything except: PID, User, java-class/jar, args.
ps -o pid,user,cmd -C java | sed -e 's/\([0-9]\+ *[^ ]*\) *[^ ]* *\([^$]*\)/\1 \2/' -e 's/-c[^ ]* [^ ]* \|-[^ ]* //g'
Results look something like:
PID USER CMD
11251 userb org.apache.zookeeper.server.quorum.QuorumPeerMain ../config/zookeeper.properties
19574 userb com.intellij.idea.Main
28807 root org.apache.nifi.bootstrap.RunNiFi run
28829 root org.apache.nifi.NiFi
An alternative on windows to list all processes is:
WMIC path win32_process where "Caption='java.exe'" get ProcessId,Commandline
But that is going to need some parsing to make it more legible.
11. R (or another dependency) is out of date and you don't want to update it.
Warning this is not exactly best practice.
DESCRIPTION
file.Remove the offending line with your text editor e.g.
Depends: R (>= 3.1.1)
Install from local (i.e. from the parent directory of DESCRIPTION
) e.g.
install.packages("foo", type="source", repos=NULL)
Starting with v0.20.0
, the dtype
keyword argument in read_excel()
function could be used to specify the data types that needs to be applied to the columns just like it exists for read_csv()
case.
Using converters
and dtype
arguments together on the same column name would lead to the latter getting shadowed and the former gaining preferance.
1) Inorder for it to not interpret the dtypes
but rather pass all the contents of it's columns as they were originally in the file before, we could set this arg to str
or object
so that we don't mess up our data. (one such case would be leading zeros in numbers which would be lost otherwise)
pd.read_excel('file_name.xlsx', dtype=str) # (or) dtype=object
2) It even supports a dict mapping wherein the keys
constitute the column names and values
it's respective data type to be set especially when you want to alter the dtype
for a subset of all the columns.
# Assuming data types for `a` and `b` columns to be altered
pd.read_excel('file_name.xlsx', dtype={'a': np.float64, 'b': np.int32})
It is a class that extends another class.
example taken from https://www.java-tips.org/java-se-tips-100019/24-java-lang/784-what-is-a-java-subclass.html, Cat is a sub class of Animal :-)
public class Animal {
public static void hide() {
System.out.println("The hide method in Animal.");
}
public void override() {
System.out.println("The override method in Animal.");
}
}
public class Cat extends Animal {
public static void hide() {
System.out.println("The hide method in Cat.");
}
public void override() {
System.out.println("The override method in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = (Animal)myCat;
myAnimal.hide();
myAnimal.override();
}
}
Sometimes, Clover is configured to provide code coverage reports for all non-test code. If you wish to override these preferences, you may use configuration elements to exclude and include source files from being instrumented:
<plugin>
<groupId>com.atlassian.maven.plugins</groupId>
<artifactId>maven-clover2-plugin</artifactId>
<version>${clover-version}</version>
<configuration>
<excludes>
<exclude>**/*Dull.java</exclude>
</excludes>
</configuration>
</plugin>
Also, you can include the following Sonar configuration:
<properties>
<sonar.exclusions>
**/domain/*.java,
**/transfer/*.java
</sonar.exclusions>
</properties>
What about this one? :) It uses correct formula, avoids math.factorial
and takes less multiplication operations:
import math
import operator
product = lambda m,n: reduce(operator.mul, xrange(m, n+1), 1)
x = max(0, int(input("Enter a value for x: ")))
y = max(0, int(input("Enter a value for y: ")))
print product(y+1, x) / product(1, x-y)
Also, in order to avoid big-integer arithmetics you may use floating point numbers, convert
product(a[i])/product(b[i])
to product(a[i]/b[i])
and rewrite the above program as:
import math
import operator
product = lambda iterable: reduce(operator.mul, iterable, 1)
x = max(0, int(input("Enter a value for x: ")))
y = max(0, int(input("Enter a value for y: ")))
print product(map(operator.truediv, xrange(y+1, x+1), xrange(1, x-y+1)))
As already mentioned in the answer by robertc, Chrome blocks certain functionality, like the geo location with local files. An easier alternative to setting up an own web server would be to just start Chrome with the parameter --allow-file-access-from-files
. Then you can use the geo location, provided you didn't turn it off in your settings.
String methodName= "...";
String[] args = {};
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName())) {
// for static methods we can use null as instance of class
m.invoke(null, new Object[] {args});
break;
}
}
You can use the following to programmatically center TextView
text in Kotlin:
textview.gravity = Gravity.CENTER
Probably you have this:
const db = mongoose.connect('mongodb://localhost:27017/db');
// Do some stuff
db.disconnect();
but you can also have something like this:
mongoose.connect('mongodb://localhost:27017/db');
const model = mongoose.model('Model', ModelSchema);
model.find().then(doc => {
console.log(doc);
}
you cannot call db.disconnect()
but you can close the connection after you use it.
model.find().then(doc => {
console.log(doc);
}).then(() => {
mongoose.connection.close();
});
Here you go:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String oeStartDateStr = "04/01/";
String oeEndDateStr = "11/14/";
Calendar cal = Calendar.getInstance();
Integer year = cal.get(Calendar.YEAR);
oeStartDateStr = oeStartDateStr.concat(year.toString());
oeEndDateStr = oeEndDateStr.concat(year.toString());
Date startDate = sdf.parse(oeStartDateStr);
Date endDate = sdf.parse(oeEndDateStr);
Date d = new Date();
String currDt = sdf.format(d);
if((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) ||currDt.equals(sdf.format(endDate)))){
System.out.println("Date is between 1st april to 14th nov...");
}
else{
System.out.println("Date is not between 1st april to 14th nov...");
}
}
You don't mention if this is a GUI program or not, but most GUI packages include a way to capture and handle keyboard input. For example, with tkinter
(in Py3), you can bind to a certain event and then handle it in a function. For example:
import tkinter as tk
def key_handler(event=None):
if event and event.keysym in ('s', 'p'):
'do something'
r = tk.Tk()
t = tk.Text()
t.pack()
r.bind('<Key>', key_handler)
r.mainloop()
With the above, when you type into the Text widget, the key_handler
routine gets called for each (or almost each) key you press.
Here is the latest example from the Firestore documentation:
firebase.firestore.FieldValue.ArrayUnion
var washingtonRef = db.collection("cities").doc("DC");
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
// Atomically remove a region from the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});
In Objective-C, if you wanted to use a class in another file you had to import it:
#import "SomeClass.h"
However, in Swift, you don't have to import at all. Simply use it as if it was already imported.
// This is a file named SomeClass.swift
class SomeClass : NSObject {
}
// This is a different file, named OtherClass.swift
class OtherClass : NSObject {
let object = SomeClass()
}
As you can see, no import was needed. Hope this helps.
Your missing a ' after night. right here getElementById('Night
C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.
In this answer, I will consider practical examples.
The first one, is of pandas.concat
.
The second one, of merging dataframes from the index of one and the column of another one.
Considering the following DataFrames
with the same column names:
Preco2018 with size (8784, 5)
Preco 2019 with size (8760, 5)
That have the same column names.
You can combine them using pandas.concat
, by simply
import pandas as pd
frames = [Preco2018, Preco2019]
df_merged = pd.concat(frames)
Which results in a DataFrame with the following size (17544, 5)
If you want to visualize, it ends up working like this
(Source)
2. Merge by Column and Index
In this part, I will consider a specific case: If one wants to merge the index of one dataframe and the column of another dataframe.
Let's say one has the dataframe Geo
with 54 columns, being one of the columns the Date Data
, which is of type datetime64[ns]
.
And the dataframe Price
that has one column with the price and the index corresponds to the dates
In this specific case, to merge them, one uses pd.merge
merged = pd.merge(Price, Geo, left_index=True, right_on='Data')
Which results in the following dataframe
Erik, You can just kill all the other node processes by
pkill -f node
and then restart your server again. It'll work just fine then.
Be aware that, as written, Peter's solution will "accept" 0000
. If you want to validate numbers between 1000
and 999999
, then that is another problem :-)
^[1-9][0-9]{3,5}$
for example will block inserting 0
at the beginning of the string.
If you want to accept 0 padding, but only up to a lengh of 6, so that 001000
is valid, then it becomes more complex. If we use look-ahead then we can write something like
^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$
This first checks if the string is long 4-6 (?=[0-9]{4,6}$)
, then skips the 0s 0*
and search for a non-zero [1-9]
followed by at least 3 digits [0-9]{3,}
.
gstreamer can handle webcam input. If I remeber well, there are python bindings for it!
Cookie is just another HTTP header.
import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")
See urllib2 examples for other ways how to add HTTP headers to your request.
There are more ways how to handle cookies. Some modules like cookielib try to behave like web browser - remember what cookies did you get previously and automatically send them again in following requests.
An Ad-Hoc query is:
To use Beyond Compare as the difftool for directory diff, remember enable follow symbolic links like so:
In a Folder Compare View → Rules (Referee Icon):
And then, enable follow symbolic links and update session defaults:
OR,
set up the alias like so:
git config --global alias.diffdir "difftool --dir-diff --tool=bc3 --no-prompt --no-symlinks"
Note that in either case, any edits made to the side (left or right) that refers to the current working tree are preserved.
nothing special
let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, LONG_VALUE, STRING_VALUE)
Please try this
error_reporting = E_ALL & ~E_NOTICE
in php.ini
The following should fix it for every client.
//Gather output (if it is not already in a variable, use ob_start() and ob_get_clean() )
// Before sending output:
header('Content-length: ' . strlen($output));
But in my case the following was a better option and fixed it as well:
.htaccess:
php_value opcache.enable 0
Note that it may be important to use the "inplace" command when you want to do the drop in line.
df.drop(df.index[[1,3]], inplace=True)
Because your original question is not returning anything, this command should be used. http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.drop.html
A few months ago I had the same problem and every library I found provides too much functionality and complexity for my final goal. So I end up developing my own library - HtmlFlow - that provides a very simple and intuitive API that allows me to write HTML in a fluent style. Check it here: https://github.com/fmcarvalho/HtmlFlow (it also supports dynamic binding to HTML elements)
Here is an example of binding the properties of a Task
object into HTML elements. Consider a Task
Java class with three properties: Title
, Description
and a Priority
and then we can produce an HTML document for a Task
object in the following way:
import htmlflow.HtmlView;
import model.Priority;
import model.Task;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class App {
private static HtmlView<Task> taskDetailsView(){
HtmlView<Task> taskView = new HtmlView<>();
taskView
.head()
.title("Task Details")
.linkCss("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css");
taskView
.body().classAttr("container")
.heading(1, "Task Details")
.hr()
.div()
.text("Title: ").text(Task::getTitle)
.br()
.text("Description: ").text(Task::getDescription)
.br()
.text("Priority: ").text(Task::getPriority);
return taskView;
}
public static void main(String [] args) throws IOException{
HtmlView<Task> taskView = taskDetailsView();
Task task = new Task("Special dinner", "Have dinner with someone!", Priority.Normal);
try(PrintStream out = new PrintStream(new FileOutputStream("Task.html"))){
taskView.setPrintStream(out).write(task);
Desktop.getDesktop().browse(URI.create("Task.html"));
}
}
}
In Visual Studio 2008 it is Ctrl + E + W.
Try this;
Add-Content -path $logpath @"
$((get-date).tostring()) Error $keyPath $value
key $key expected: $policyValue
local value is: $localValue
"@
Here's a simple function:
CREATE FUNCTION fn_which_edition
RETURN VARCHAR2
IS
/*
Purpose: determine which database edition
MODIFICATION HISTORY
Person Date Comments
--------- ------ -------------------------------------------
dcox 6/6/2013 Initial Build
*/
-- Banner
CURSOR c_get_banner
IS
SELECT banner
FROM v$version
WHERE UPPER(banner) LIKE UPPER('Oracle Database%');
vrec_banner c_get_banner%ROWTYPE; -- row record
v_database VARCHAR2(32767); --
BEGIN
-- Get banner to get edition
OPEN c_get_banner;
FETCH c_get_banner INTO vrec_banner;
CLOSE c_get_banner;
-- Check for Database type
IF INSTR( UPPER(vrec_banner.banner), 'EXPRESS') > 0
THEN
v_database := 'EXPRESS';
ELSIF INSTR( UPPER(vrec_banner.banner), 'STANDARD') > 0
THEN
v_database := 'STANDARD';
ELSIF INSTR( UPPER(vrec_banner.banner), 'PERSONAL') > 0
THEN
v_database := 'PERSONAL';
ELSIF INSTR( UPPER(vrec_banner.banner), 'ENTERPRISE') > 0
THEN
v_database := 'ENTERPRISE';
ELSE
v_database := 'UNKNOWN';
END IF;
RETURN v_database;
EXCEPTION
WHEN OTHERS
THEN
RETURN 'ERROR:' || SQLERRM(SQLCODE);
END fn_which_edition; -- function fn_which_edition
/
Done.
I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).
URL for accessing my app:
http://myapp.com/amazing_url?token=super_token
Then when the user loads the page:
http://myapp.com/amazing_url?token=super_token#/amazing_url
Then when the user navigates:
http://myapp.com/amazing_url?token=super_token#/another_url
With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.
So don't enable the HTML5 mode and then add this controller:
.config ($stateProvider)->
$stateProvider.state('home-loading', {
url: '/',
controller: 'homeController'
})
.controller 'homeController', ($state, $location)->
if window.location.pathname != '/'
$location.url(window.location.pathname+window.location.search).replace()
else
$state.go('home', {}, { location: 'replace' })
Simply floating both elements left achieves the same result.
div {
background:yellow;
vertical-align:middle;
margin:10px;
}
a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}
span {
background:red;
display:inline-block;
float:left;
}
This should do it, let me know if you have trouble with it:
Sub foo()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy
'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial
'Close x:
x.Close
End Sub
Alternatively, you could just:
Sub foo2()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1")
'Close x:
x.Close
End Sub
To extend this to the entire sheet:
With x.Sheets("name of copying sheet").UsedRange
'Now, paste to y worksheet:
y.Sheets("sheet name").Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
And yet another way, store the value as a variable and write the variable to the destination:
Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value
'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals
'Close x:
x.Close
End Sub
The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:
Copy/PasteSpecial vs Range.Value = Range.Value
That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
A PivotTable might suit, though I am not quite certain of the layout of your data:
The bold numbers (one of each pair of duplicates) need not be shown as the field does not have to be subtotalled eg:
In the documentaion http://contactform7.com/text-fields/#textarea
[textarea* message id:contact-message 10x2 placeholder "Your Message"]
The above will generate a textarea with cols="10" and rows="2"
<textarea name="message" cols="10" rows="2" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="contact-message" aria-required="true" aria-invalid="false" placeholder="Your Message"></textarea>
The NoClassDefFoundError description is, from the SO tag:
The Java Error thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
Or better:
NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.
from this page. Check it, there are some ways to solve the error. I hope it helps.
You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//Email is valid
}
You can add another check if you want. Parse the domain out and then run checkdnsrr
if(checkdnsrr($domain)) {
// Domain at least has an MX record, necessary to receive email
}
Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:
Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat
Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.
In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.
Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?
If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.
-ArgumentList
is based on use with scriptblock commands, like:
Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True
When you call it with a -File
it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).
So, you have two options:
If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug
is implied because when I use the Parameter
attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):
param(
[Parameter(Position=0)]
$one
,
[Parameter(Position=1)]
$two
,
[Parameter()]
[Switch]$Clear
)
"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."
Without getting hung up on the meaning of $Clear
... if you wanted to invoke that you could use either of the following Invoke-Command
syntaxes:
icm -cn (gc Servers.txt) {
param($one,$two,$Debug=$False,$Clear=$False)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true
In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters
, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:
icm -cn $Env:ComputerName {
param([bool]$Clear)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)
If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:
$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )
Invoke-Command -Script $script -Args "uno", "dos", $false, $true
If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script
or an environment variable $Env:Script
with the name of a script, you can execute it with the call operator (&): &$Script
or &$Env:Script
If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:
Invoke-Command -cn $Env:ComputerName {
param([String]$Script, [bool]$Clear)
& $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)
you can use decoration like this :
Container(
width: 60,
height: 60,
child: Icon(CustomIcons.option, size: 20,),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Color(0xFFe0f2f1)),
)
Now you have circle shape and Icon on it.
/**
* @param filePath
* @param fs
* @return list of absolute file path present in given path
* @throws FileNotFoundException
* @throws IOException
*/
public static List<String> getAllFilePath(Path filePath, FileSystem fs) throws FileNotFoundException, IOException {
List<String> fileList = new ArrayList<String>();
FileStatus[] fileStatus = fs.listStatus(filePath);
for (FileStatus fileStat : fileStatus) {
if (fileStat.isDirectory()) {
fileList.addAll(getAllFilePath(fileStat.getPath(), fs));
} else {
fileList.add(fileStat.getPath().toString());
}
}
return fileList;
}
Quick Example : Suppose you have the following file structure:
a -> b
-> c -> d
-> e
-> d -> f
Using the code above, you get:
a/b
a/c/d
a/c/e
a/d/f
If you want only the leaf (i.e. fileNames), use the following code in else
block :
...
} else {
String fileName = fileStat.getPath().toString();
fileList.add(fileName.substring(fileName.lastIndexOf("/") + 1));
}
This will give:
b
d
e
f
An other solution (if possible) would be to use TomEE instead of Tomcat, which has a working maven plugin:
<plugin>
<groupId>org.apache.tomee.maven</groupId>
<artifactId>tomee-maven-plugin</artifactId>
<version>7.1.1</version>
</plugin>
Version 7.1.1 wraps a Tomcat 8.5.41
If you want the jar
task to behave normally and also have an additional fatJar
task, use the following:
task fatJar(type: Jar) {
classifier = 'all'
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
The important part is with jar
. Without it, the classes of this project are not included.
Converting Jason Coco's answer to Swift for the profoundly lazy :)
if ("Some String" .caseInsensitiveCompare("some string") == .OrderedSame)
{
// Strings are equal.
}
Swift 4
If you are trying to change your keyboard type when a condition is met, follow this. For example: If we want to change the keyboard type from Default to Number Pad when the count of the textfield is 4 or 5, then do this:
textField.addTarget(self, action: #selector(handleTextChange), for: .editingChanged)
@objc func handleTextChange(_ textChange: UITextField) {
if textField.text?.count == 4 || textField.text?.count == 5 {
textField.keyboardType = .numberPad
textField.reloadInputViews() // need to reload the input view for this to work
} else {
textField.keyboardType = .default
textField.reloadInputViews()
}
This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.
As pointed out, the lubridate package has nice extraction functions.
For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.
Below code worked for me for getting a pdf file from an API service and response it out to the browser - hope it helps;
public async Task<FileResult> PrintPdfStatements(string fileName)
{
var fileContent = await GetFileStreamAsync(fileName);
var fileContentBytes = ((MemoryStream)fileContent).ToArray();
return File(fileContentBytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
}
If you have a table with an IDENTITY column that you want to reset the next value for you can use the following command:
ALTER TABLE <table name>
ALTER COLUMN <column name>
RESTART WITH <new value to restart with>;
//sample01_x000D_
(function(_){_[0]()})([_x000D_
function(){$('#art1').animate({'width':'10px'},100,this[1].bind(this))},_x000D_
function(){$('#art2').animate({'width':'10px'},100,this[2].bind(this))},_x000D_
function(){$('#art3').animate({'width':'10px'},100)},_x000D_
])_x000D_
_x000D_
//sample02_x000D_
(function(_){_.next=function(){_[++_.i].apply(_,arguments)},_[_.i=0]()})([_x000D_
function(){$('#art1').animate({'width':'10px'},100,this.next)},_x000D_
function(){$('#art2').animate({'width':'10px'},100,this.next)},_x000D_
function(){$('#art3').animate({'width':'10px'},100)},_x000D_
]);_x000D_
_x000D_
//sample03_x000D_
(function(_){_.next=function(){return _[++_.i].bind(_)},_[_.i=0]()})([_x000D_
function(){$('#art1').animate({'width':'10px'},100,this.next())},_x000D_
function(){$('#art2').animate({'width':'10px'},100,this.next())},_x000D_
function(){$('#art3').animate({'width':'10px'},100)},_x000D_
]);
_x000D_
You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.
import threading
import time
import inspect
class Thread(threading.Thread):
def __init__(self, t, *args):
threading.Thread.__init__(self, target=t, args=args)
self.start()
count = 0
lock = threading.Lock()
def incre():
global count
caller = inspect.getouterframes(inspect.currentframe())[1][3]
print "Inside %s()" % caller
print "Acquiring lock"
with lock:
print "Lock Acquired"
count += 1
time.sleep(2)
def bye():
while count < 5:
incre()
def hello_there():
while count < 5:
incre()
def main():
hello = Thread(hello_there)
goodbye = Thread(bye)
if __name__ == '__main__':
main()
Sample output:
...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...
Totally agree with Joseph.
Here is a fiddle to test this: http://jsfiddle.net/nicocube/63s2s/
In the context of the fiddle, the string argument do not work, in my opinion because the function is not defined in the global scope.
I wrote the following method which works for me.
protected bool isDirectoryFound(string path, string pattern)
{
bool success = false;
DirectoryInfo directories = new DirectoryInfo(@path);
DirectoryInfo[] folderList = directories.GetDirectories();
Regex rx = new Regex(pattern);
foreach (DirectoryInfo di in folderList)
{
if (rx.IsMatch(di.Name))
{
success = true;
break;
}
}
return success;
}
The lines most pertinent to your question being:
DirectoryInfo directories = new DirectoryInfo(@path); DirectoryInfo[] folderList = directories.GetDirectories();
Use SET
command in Windows CMD to temporarily set the default python for the current session.
SET PATH=C:\Program Files\Python 3.5
You build the object before encoding it to a JSON string:
import json
data = {}
data['key'] = 'value'
json_data = json.dumps(data)
JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.
In a nutshell:
Mono = Compiler for C#
Mono Develop = Compiler+IDE
.Net Core = ASP Compiler
Current case for .Net Core is web only as soon as it adopts some open winform standard and wider language adoption, it could finally be the Microsoft killer dev powerhouse. Considering Oracle's recent Java licensing move, Microsoft have a huge time to shine.
If you have separated files for angular app\resources\directives and other stuff then you can just disable minification of your angular app bundle like this (use new Bundle() instead of ScriptBundle() in your bundle config file):
bundles.Add(
new Bundle("~/bundles/angular/SomeBundleName").Include(
"~/Content/js/angular/Pages/Web/MainPage/angularApi.js",
"~/Content/js/angular/Pages/Web/MainPage/angularApp.js",
"~/Content/js/angular/Pages/Web/MainPage/angularCtrl.js"));
And angular app would appear in bundle unmodified.
If you're treating it as a tuple (see section 3.3.3 of the language spec), then:
var t:[number, string] = [1, "message"]
or
interface NumberStringTuple extends Array<string|number>{0:number; 1:string}
var t:NumberStringTuple = [1, "message"];
Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.
Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.
I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.
In addition I have a resource, /admin, which requires higher privledges than the rest of the site.
The following is working for me.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
.antMatchers("/static/**").permitAll()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/**").access("hasRole('ROLE_USER')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();
}
NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)
Eclipse does not have internal Subversion connectivity. After you've downloaded and unzipped Eclipse, you have to install a Subversion plug-in. Check with the other developers as to which Subversion plug-in you're using. Subclipse is one Subversion plug-in.
After you've installed the Subversion plug-in, you have to give Eclipse the repository information in the SVN Repositories view of the SVN Repositories perspective. One of the other developers should have that information.
Finally, you check out the project from Subversion, by left clicking on the Package Explorer, selecting New -> Project, and in the New Project wizard,left clicking on SVN -> Checkout projects from SVN.
Changing the format but not changing the type:
df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))
You can see this reference but if this link has been removed, read this description:
Call a modal with id myModal with a single line of JavaScript:
$('#myModal').modal(options)
Options
Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as in data-backdrop="".
|-----------|-------------|--------|---------------------------------------------|
| Name | Type | Default| Description |
|-----------|-------------|--------|---------------------------------------------|
| backdrop | boolean or | true | Includes a modal-backdrop element. |
| | the string | | Alternatively, specify static for a |
| | 'static' | | backdrop which doesn't close the modal |
| | | | on click. |
| | | | |
| keyboard | boolean | true | Closes the modal when escape key is pressed.|
| | | | |
| focus | boolean | true | Puts the focus on the modal when initialized|
| | | | |
| show | boolean | true | Shows the modal when initialized. |
|-----------|-------------|--------|---------------------------------------------|
Methods
Asynchronous methods and transitions
All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started but before it ends. In addition, a method call on a transitioning component will be ignored.
.modal(options)
Activates your content as a modal. Accepts an optional options object.
$('#myModal').modal({
keyboard: false
})
.modal('toggle')
Manually toggles a modal. Returns to the caller before the modal has actually been shown or hidden (i.e. before the shown.bs.modal or hidden.bs.modal event occurs).
$('#myModal').modal('toggle')
.modal('show')
Manually opens a modal. Returns to the caller before the modal has actually been shown (i.e. before the shown.bs.modal event occurs).
$('#myModal').modal('show')
.modal('hide')
Manually hides a modal. Returns to the caller before the modal has actually been hidden (i.e. before the hidden.bs.modal event occurs).
$('#myModal').modal('hide')
.modal('handleUpdate')
Manually readjust the modal’s position if the height of a modal changes while it is open (i.e. in case a scrollbar appears).
$('#myModal').modal('handleUpdate')
.modal('dispose')
Destroys an element’s modal.
Events
Bootstrap’s modal class exposes a few events for hooking into modal functionality. All modal events are fired at the modal itself (i.e. at the **). Type Description
|----------------|--------------------------------------------------------------|
| Event Type | Description |
|----------------|--------------------------------------------------------------|
| show.bs.modal | This event fires immediately when the **show** instance |
| | method is called. If caused by a click, the clicked element |
| | is available as the **relatedTarget** property of the event. |
| | |
| shown.bs.modal | This event is fired when the modal has been made visible to |
| | the user (will wait for CSS transitions to complete). If |
| | caused by a click, the clicked element is available as the |
| | **relatedTarget** property of the event. |
| | |
| hide.bs.modal | This event is fired immediately when the **hide** instance |
| | method has been called. |
| | |
| hidden.bs.modal| This event is fired when the modal has finished being hidden |
| | from the user (will wait for CSS transitions to complete). |
|----------------|--------------------------------------------------------------|
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
})
Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.
With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/google_blue" />
Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.
If you want to use the same set of arguments all the time, the following is all you need.
run {
args = ["--myarg1", "--myarg2"]
}
You shouldn't be calling .ToString()
.
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString
and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString()
.
Html.Raw
returns an HtmlString
instance that wraps the original string.
The Razor page output knows not to escape HtmlString
instances.
However, calling HtmlString.ToString()
just returns the original string
value again; it doesn't accomplish anything.
SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.
We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.
The accepted answer seems like it will search through the entire response message. This could give you false matches for cookie headers if the word "Set-Cookie" is at the beginning of a line. While it should be fine in most cases. The safer way might be to read through the message from the beginning until the first empty line which indicates the end of the message headers. This is just an alternate solution that should look for the first blank line and then use preg_grep on those lines only to find "Set-Cookie".
curl_setopt($ch, CURLOPT_HEADER, 1);
//Return everything
$res = curl_exec($ch);
//Split into lines
$lines = explode("\n", $res);
$headers = array();
$body = "";
foreach($lines as $num => $line){
$l = str_replace("\r", "", $line);
//Empty line indicates the start of the message body and end of headers
if(trim($l) == ""){
$headers = array_slice($lines, 0, $num);
$body = $lines[$num + 1];
//Pull only cookies out of the headers
$cookies = preg_grep('/^Set-Cookie:/', $headers);
break;
}
}
This should do the trick,
npm install -g typescript
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
Here is a way to solve the problem if your public repo on github.com is working, but your local repo is corrupt. Be aware that you will loose all the commits you've done in the local repo.
Alright, so I have one repo locally that is giving me this object empty error
, and the same repo on github.com, but without this error. So what I simply did was to clone the repo that is working from github, and then copied everything from the corrupt repo (except the .git folder), and paste it the cloned repo that is working.
This may not be a practical solution (since you delete the local commits), however, you maintain the code and a repaired version control.
Remember to back-up before applying this approach.
I don't believe AJAX can handle file uploads but this can be achieved with libraries that leverage flash. Another advantage of the flash implementation is the ability to do multiple files at once (like gmail).
SWFUpload is a good start : http://www.swfupload.org/documentation
jQuery and some of the other libraries have plugins that leverage SWFUpload. On my last project we used SWFUpload and Java without a problem.
Also helpful and worth looking into is Apache's FileUpload : http://commons.apache.org/fileupload/index.html
I don't have enough rep to comment here, so I'm submitting a new answer to improve on dogbane's answer. The dot . in the regexp
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
will actually match any character, not only the literal dot between 'tar.bz2', for example
[[ sed-4.2.2.tar4bz2 =~ tar.bz2$ ]] && echo matched
[[ sed-4.2.2.tar§bz2 =~ tar.bz2$ ]] && echo matched
or anything that doesn't require escaping with '\'. The strict syntax should then be
[[ sed-4.2.2.tar.bz2 =~ tar\.bz2$ ]] && echo matched
or you can go even stricter and also include the previous dot in the regex:
[[ sed-4.2.2.tar.bz2 =~ \.tar\.bz2$ ]] && echo matched