This works perfectly for me. Just put the button first since you're starting on the right. If FlowDirection becomes a problem just add a StackPanel around it and specify FlowDirection="LeftToRight" for that portion. Or simply specify FlowDirection="LeftToRight" for the relevant control.
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" FlowDirection="RightToLeft">
<Button Width="40" HorizontalAlignment="Right" Margin="3">Right</Button>
<TextBlock Margin="5">Left</TextBlock>
<StackPanel FlowDirection="LeftToRight">
<my:DatePicker Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />
</StackPanel>
<my:DatePicker FlowDirection="LeftToRight" Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />
</StackPanel>
Grid.ColumnSpacing, Grid.RowSpacing, StackPanel.Spacing are now on UWP preview, all will allow to better acomplish what is requested here.
These properties are currently only available with the Windows 10 Fall Creators Update Insider SDK, but should make it to the final bits!
You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.
If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)
It works like this:
<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
<StackPanel Name="stackPanel1" Width="311">
</StackPanel>
</ScrollViewer>
TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);
<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>
another solution is to override the join operator of the str class.
Let us define a new class my_string as follows
class my_string(str):
def join(self, l):
l_tmp = [str(x) for x in l]
return super(my_string, self).join(l_tmp)
Then you can do
class Obj:
def __str__(self):
return 'name'
list = [Obj(), Obj(), Obj()]
comma = my_string(',')
print comma.join(list)
and you get
name,name,name
BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.
Hope you'll find my answer useful.
append the revision using an "@" character:
svn copy http://src@REV http://dev
Or, use the -r [--revision] command line argument.
The following line replaces None
with NaN
:
df['column'].replace('None', np.nan, inplace=True)
I could not make @Clockwork-Muse work actually. But I could make this variation work:
WITH Tmp AS (SELECT * FROM (VALUES (id1, newsPosX1, newPosY1),
(id2, newsPosX2, newPosY2),
......................... ,
(idN, newsPosXN, newPosYN)) d(id, px, py))
UPDATE t
SET posX = (SELECT px FROM Tmp WHERE t.id = Tmp.id),
posY = (SELECT py FROM Tmp WHERE t.id = Tmp.id)
FROM TableToUpdate t
I hope this works for you too!
No, it isn't valid HTML5 according to the HTML5 Spec Document from W3C:
Content model: Transparent, but there must be no interactive content descendant.
The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).
In other words, you can nest any elements inside an <a>
except the following:
<a>
<audio>
(if the controls attribute is present)
<button>
<details>
<embed>
<iframe>
<img>
(if the usemap attribute is present)
<input>
(if the type attribute is not in the hidden state)
<keygen>
<label>
<menu>
(if the type attribute is in the toolbar state)
<object>
(if the usemap attribute is present)
<select>
<textarea>
<video>
(if the controls attribute is present)
If you are trying to have a button that links to somewhere, wrap that button inside a <form>
tag as such:
<form style="display: inline" action="http://example.com/" method="get">
<button>Visit Website</button>
</form>
However, if your <button>
tag is styled using CSS and doesn't look like the system's widget... Do yourself a favor, create a new class for your <a>
tag and style it the same way.
Win10 with French / English Keyboard CTRL + / , ctrl+k+u and ctrl+k+l don't work.
Here's how it works:
/* */
SHIFT
+ALT
+A
//
CTRL
+É
É key is next to right Shift.
You don't need jQuery for this. Here's a vanilla JS proof of concept using an event listener on a parent container (checkbox-group-required
) of the checkboxes, the checkbox element's .checked
property and Array#some
.
const validate = el => {
const checkboxes = el.querySelectorAll('input[type="checkbox"]');
return [...checkboxes].some(e => e.checked);
};
const formEl = document.querySelector("form");
const statusEl = formEl.querySelector(".status-message");
const checkboxGroupEl = formEl.querySelector(".checkbox-group-required");
checkboxGroupEl.addEventListener("click", e => {
statusEl.textContent = validate(checkboxGroupEl) ? "valid" : "invalid";
});
formEl.addEventListener("submit", e => {
e.preventDefault();
if (validate(checkboxGroupEl)) {
statusEl.textContent = "Form submitted!";
// Send data from e.target to your backend
}
else {
statusEl.textContent = "Error: select at least one checkbox";
}
});
_x000D_
<form>
<div class="checkbox-group-required">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
<input type="submit" />
<div class="status-message"></div>
</form>
_x000D_
If you have multiple groups to validate, add a loop over each group, optionally adding error messages or CSS to indicate which group fails validation:
const validate = el => {
const checkboxes = el.querySelectorAll('input[type="checkbox"]');
return [...checkboxes].some(e => e.checked);
};
const allValid = els => [...els].every(validate);
const formEl = document.querySelector("form");
const statusEl = formEl.querySelector(".status-message");
const checkboxGroupEls = formEl.querySelectorAll(".checkbox-group-required");
checkboxGroupEls.forEach(el =>
el.addEventListener("click", e => {
statusEl.textContent = allValid(checkboxGroupEls) ? "valid" : "invalid";
})
);
formEl.addEventListener("submit", e => {
e.preventDefault();
if (allValid(checkboxGroupEls)) {
statusEl.textContent = "Form submitted!";
}
else {
statusEl.textContent = "Error: select at least one checkbox from each group";
}
});
_x000D_
<form>
<div class="checkbox-group-required">
<label>
Group 1:
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</label>
</div>
<div class="checkbox-group-required">
<label>
Group 2:
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</label>
</div>
<input type="submit" />
<div class="status-message"></div>
</form>
_x000D_
I found this works:
window = Tk()
window.title('Window')
Maybe this helps?
7 years passed and...
actually there's this new SQL Server 2016 feature that does exactly what you need.
It is called AT TIME ZONE and it converts date to a specified time zone considering DST (daylight saving time) changes.
More info here:
https://msdn.microsoft.com/en-us/library/mt612795.aspx
To remove the .html extension from your URLs, you can use the following code in root/htaccess :
#mode_rerwrite start here
RewriteEngine On
# does not apply to existing directores, meaning that if the folder exists on server then don't change anything and don't run the rule.
RewriteCond %{REQUEST_FILENAME} !-d
#Check for file in directory with .html extension
RewriteCond %{REQUEST_FILENAME}\.html !-f
#Here we actually show the page that has .html extension
RewriteRule ^(.*)$ $1.html [NC,L]
Thanks
Here is my solution to a modal that can be rendered on any screen and initialized in App.tsx
ModalComponent.tsx
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet, Platform } from 'react-native';
import EventEmitter from 'events';
// I keep localization files for strings and device metrics like height and width which are used for styling
import strings from '../../config/strings';
import metrics from '../../config/metrics';
const emitter = new EventEmitter();
export const _modalEmitter = emitter
export class ModalView extends Component {
state: {
modalVisible: boolean,
text: string,
callbackSubmit: any,
callbackCancel: any,
animation: any
}
constructor(props) {
super(props)
this.state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {}),
animation: new Animated.Value(0)
}
}
componentDidMount() {
_modalEmitter.addListener(strings.modalOpen, (event) => {
var state = {
modalVisible: true,
text: event.text,
callbackSubmit: event.onSubmit,
callbackCancel: event.onClose,
animation: new Animated.Value(0)
}
this.setState(state)
})
_modalEmitter.addListener(strings.modalClose, (event) => {
var state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {}),
animation: new Animated.Value(0)
}
this.setState(state)
})
}
componentWillUnmount() {
var state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {})
}
this.setState(state)
}
closeModal = () => {
_modalEmitter.emit(strings.modalClose)
}
startAnimation=()=>{
Animated.timing(this.state.animation, {
toValue : 0.5,
duration : 500
}).start()
}
body = () => {
const animatedOpacity ={
opacity : this.state.animation
}
this.startAnimation()
return (
<View style={{ height: 0 }}>
<Modal
animationType="fade"
transparent={true}
visible={this.state.modalVisible}>
// render a transparent gray background over the whole screen and animate it to fade in, touchable opacity to close modal on click out
<Animated.View style={[styles.modalBackground, animatedOpacity]} >
<TouchableOpacity onPress={() => this.closeModal()} activeOpacity={1} style={[styles.modalBackground, {opacity: 1} ]} >
</TouchableOpacity>
</Animated.View>
// render an absolutely positioned modal component over that background
<View style={styles.modalContent}>
<View key="text_container">
<Text>{this.state.text}?</Text>
</View>
<View key="options_container">
// keep in mind the content styling is very minimal for this example, you can put in your own component here or style and make it behave as you wish
<TouchableOpacity
onPress={() => {
this.state.callbackSubmit();
}}>
<Text>Confirm</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.state.callbackCancel();
}}>
<Text>Cancel</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
}
render() {
return this.body()
}
}
// to center the modal on your screen
// top: metrics.DEVICE_HEIGHT/2 positions the top of the modal at the center of your screen
// however you wanna consider your modal's height and subtract half of that so that the
// center of the modal is centered not the top, additionally for 'ios' taking into consideration
// the 20px top bunny ears offset hence - (Platform.OS == 'ios'? 120 : 100)
// where 100 is half of the modal's height of 200
const styles = StyleSheet.create({
modalBackground: {
height: '100%',
width: '100%',
backgroundColor: 'gray',
zIndex: -1
},
modalContent: {
position: 'absolute',
alignSelf: 'center',
zIndex: 1,
top: metrics.DEVICE_HEIGHT/2 - (Platform.OS == 'ios'? 120 : 100),
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
height: 200,
width: '80%',
borderRadius: 27,
backgroundColor: 'white',
opacity: 1
},
})
App.tsx render and import
import { ModalView } from './{your_path}/ModalComponent';
render() {
return (
<React.Fragment>
<StatusBar barStyle={'dark-content'} />
<AppRouter />
<ModalView />
</React.Fragment>
)
}
and to use it from any component
SomeComponent.tsx
import { _modalEmitter } from './{your_path}/ModalComponent'
// Some functions within your component
showModal(modalText, callbackOnSubmit, callbackOnClose) {
_modalEmitter.emit(strings.modalOpen, { text: modalText, onSubmit: callbackOnSubmit.bind(this), onClose: callbackOnClose.bind(this) })
}
closeModal() {
_modalEmitter.emit(strings.modalClose)
}
Hope I was able to help some of you, I used a very similar structure for in-app notifications
Happy coding
Bootstrap v4.1 uses new classnames for hiding columns on their grid system.
For hiding columns depending on the screen width, use d-none
class or any of the d-{sm,md,lg,xl}-none
classes.
To show columns on certain screen sizes, combine the above mentioned classes with d-block
or d-{sm,md,lg,xl}-block
classes.
Examples are:
<div class="d-lg-none">hide on screens wider than lg</div>_x000D_
<div class="d-none d-lg-block">hide on screens smaller than lg</div>
_x000D_
More of these here.
In case if Parent class is singleton use following way:
Parent.Child childObject = (Parent.getInstance()).new Child();
where getInstance()
will return parent class singleton object.
any hashing method that evenly distributes the hash value over the possible range is a good implementation. See effective java ( http://books.google.com.au/books?id=ZZOiqZQIbRMC&dq=effective+java&pg=PP1&ots=UZMZ2siN25&sig=kR0n73DHJOn-D77qGj0wOxAxiZw&hl=en&sa=X&oi=book_result&resnum=1&ct=result ) , there is a good tip in there for hashcode implementation (item 9 i think...).
I'm not saying this is a good way to solve this problem, however this does seem to work-for-me.
git branch --contains $(cat .git/ORIG_HEAD)
The issue being that cat'ing a file is peeking into the inner working of git so this is not necessarily forwards-compatible (or backwards-compatible).
read this, split function has an overload takes an array consist of seperators http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx
You didn't mention which version of Eclipse you are using, but others have already posted good answers for modern versions of Eclipse. Unfortunately one of my legacy projects requires Eclipse Europa; the old EGit project homepage states the following:
The plugin only works on Eclipse 3.4 (Ganymede) or newer. Eclipse 3.3 (Europa) is not supported anymore. Since the plugin is still very much work-in-progress we want to take advantage of new platforms features to facilitate progress.
So I guess I'm SOL - back to the graphical GitHub client for me! Lucky it's a legacy project.
If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:
function interval(date1, date2) {_x000D_
if (date1 > date2) { // swap_x000D_
var result = interval(date2, date1);_x000D_
result.years = -result.years;_x000D_
result.months = -result.months;_x000D_
result.days = -result.days;_x000D_
result.hours = -result.hours;_x000D_
return result;_x000D_
}_x000D_
result = {_x000D_
years: date2.getYear() - date1.getYear(),_x000D_
months: date2.getMonth() - date1.getMonth(),_x000D_
days: date2.getDate() - date1.getDate(),_x000D_
hours: date2.getHours() - date1.getHours()_x000D_
};_x000D_
if (result.hours < 0) {_x000D_
result.days--;_x000D_
result.hours += 24;_x000D_
}_x000D_
if (result.days < 0) {_x000D_
result.months--;_x000D_
// days = days left in date1's month, _x000D_
// plus days that have passed in date2's month_x000D_
var copy1 = new Date(date1.getTime());_x000D_
copy1.setDate(32);_x000D_
result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();_x000D_
}_x000D_
if (result.months < 0) {_x000D_
result.years--;_x000D_
result.months+=12;_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
// Be aware that the month argument is zero-based (January = 0)_x000D_
var date1 = new Date(2015, 4-1, 6);_x000D_
var date2 = new Date(2015, 5-1, 9);_x000D_
_x000D_
document.write(JSON.stringify(interval(date1, date2)));
_x000D_
This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).
So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.
Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).
In your binding configuration, there are four timeout values you can tweak:
<bindings>
<basicHttpBinding>
<binding name="IncreasedTimeout"
sendTimeout="00:25:00">
</binding>
</basicHttpBinding>
The most important is the sendTimeout
, which says how long the client will wait for a response from your WCF service. You can specify hours:minutes:seconds
in your settings - in my sample, I set the timeout to 25 minutes.
The openTimeout
as the name implies is the amount of time you're willing to wait when you open the connection to your WCF service. Similarly, the closeTimeout
is the amount of time when you close the connection (dispose the client proxy) that you'll wait before an exception is thrown.
The receiveTimeout
is a bit like a mirror for the sendTimeout
- while the send timeout is the amount of time you'll wait for a response from the server, the receiveTimeout
is the amount of time you'll give you client to receive and process the response from the server.
In case you're send back and forth "normal" messages, both can be pretty short - especially the receiveTimeout
, since receiving a SOAP message, decrypting, checking and deserializing it should take almost no time. The story is different with streaming - in that case, you might need more time on the client to actually complete the "download" of the stream you get back from the server.
There's also openTimeout, receiveTimeout, and closeTimeout. The MSDN docs on binding gives you more information on what these are for.
To get a serious grip on all the intricasies of WCF, I would strongly recommend you purchase the "Learning WCF" book by Michele Leroux Bustamante:
and you also spend some time watching her 15-part "WCF Top to Bottom" screencast series - highly recommended!
For more advanced topics I recommend that you check out Juwal Lowy's Programming WCF Services book.
This is how I add a row if the dgrview is empty: (myDataGridView has two columns in my example)
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(myDataGridView);
row.Cells[0].Value = "some value";
row.Cells[1].Value = "next columns value";
myDataGridView.Rows.Add(row);
According to docs: "CreateCells() clears the existing cells and sets their template according to the supplied DataGridView template".
64-bit binaries are stored in PE32+ format. Try reading http://www.masm32.com/board/index.php?action=dlattach;topic=6687.0;id=3486
I overloaded the console methods.
var colors={
Reset: "\x1b[0m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m"
};
var infoLog = console.info;
var logLog = console.log;
var errorLog = console.error;
var warnLog = console.warn;
console.info= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Green);
copyArgs.push(colors.Reset);
infoLog.apply(null,copyArgs);
};
console.warn= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Yellow);
copyArgs.push(colors.Reset);
warnLog.apply(null,copyArgs);
};
console.error= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Red);
copyArgs.push(colors.Reset);
errorLog.apply(null,copyArgs);
};
// examples
console.info("Numeros",1,2,3);
console.warn("pares",2,4,6);
console.error("reiniciandooo");
The output is.
Assuming your process is a single thread, and that you're using blocking I/O, your process will block waiting for the I/O to complete. The kernel will pick another process to run in the meantime based on niceness, priority, last run time, etc. If there are no other runnable processes, the kernel won't run any; instead, it'll tell the hardware the machine is idle (which will result in lower power consumption).
Processes that are waiting for I/O to complete typically show up in state D in, e.g., ps
and top
.
Try the following:
MemoryStream stream = new MemoryStream();
Bitmap bitmap = new Bitmap();
bitmap.Save(stream, ImageFormat.Jpeg);
byte[] byteArray = stream.GetBuffer();
Make sure you are using:
System.Drawing & using System.Drawing.Imaging;
For a full list of available solutions, see this answer: UILabel text margin
Try subclassing UILabel, like @Tommy Herbert suggests in the answer to [this question][1]. Copied and pasted for your convenience:
I solved this by subclassing UILabel and overriding drawTextInRect: like this:
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = {0, 5, 0, 5};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
Most other answers are either incomplete or don't deal with stuff coming after the path (query string/hash).
readonly static Uri SomeBaseUri = new Uri("http://canbeanything");
static string GetFileNameFromUrl(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
uri = new Uri(SomeBaseUri, url);
return Path.GetFileName(uri.LocalPath);
}
Test results:
GetFileNameFromUrl(""); // ""
GetFileNameFromUrl("test"); // "test"
GetFileNameFromUrl("test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3#aidjsf"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/a/b/c/d"); // "d"
GetFileNameFromUrl("http://www.a.com/a/b/c/d/e/"); // ""
app.factory('persistObject', function () {
var persistObject = [];
function set(objectName, data) {
persistObject[objectName] = data;
}
function get(objectName) {
return persistObject[objectName];
}
return {
set: set,
get: get
}
});
Fill it with data like this
persistObject.set('objectName', data);
Get the object data like this
persistObject.get('objectName');
BigDecimal pi = new BigDecimal(3.14);
BigDecimal pi4 = new BigDecimal(12.56);
System.out.printf("%.2f",pi);
// prints 3.14
System.out.printf("%.0f",pi4);
// prints 13
Java didn't provide multiple inheritance.
When you say A extends B then it means that A extends B and B extends Object.
It doesn't mean A extends B, Object.
class A extends Object
class B extends A
You can accomplish using my library Expansive. Also available on nuget here.
It was designed with this as a primary use-case.
In app.config:
<configuration>
<appSettings>
<add key="Domain" value="mycompany.com"/>
<add key="ServerName" value="db01.{Domain}"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid=uid;pwd=pwd;Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
or
Use the Dynamic ConfigurationManager wrapper "Config" as follows (Explicit call to Expand() not necessary):
var serverName = Config.AppSettings.ServerName;
// returns "db01.mycompany.com"
var connectionString = Config.ConnectionStrings.Default;
// returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
In app.config:
<configuration>
<appSettings>
<add key="Environment" value="dev"/>
<add key="Domain" value="mycompany.com"/>
<add key="UserId" value="uid"/>
<add key="Password" value="pwd"/>
<add key="ServerName" value="db01-{Environment}.{Domain}"/>
<add key="ReportPath" value="\\{ServerName}\SomeFileShare"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid={UserId};pwd={Password};Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01-dev.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
Digging up the old thread because all solutions have missed the simplest fix...
It is failing because the substitution of the time variable results in a space in the filename, meaning it treats the last part of the filename as a parameter into the command.
The simplest solution is to just surround the desired filename in quotes "filename"
.
Then you can have any date pattern you want (with the exception of those illegal characters such as /
,\
,...)
I would suggest reverse date order YYYYMMDD-HHMM:
ren "somefile.txt" "somefile-%date:~10,4%%date:~7,2%%date:~4,2%-%time:~0,2%%time:~3,2%.txt"
By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.
the different log levels are helpful for tools, whose can anaylse you log files. Normally a logfile contains lots of information. To avoid an information overload (or here an stackoverflow^^) you can use the log levels for grouping the information.
so weird but this worked for me.
close eclipse
start eclipse as eclipse --clean
Another way would be creating a mutable integer:
class MutableInt {
int value = 0;
public void inc () { ++value; }
public int get () { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt> ();
MutableInt value = map.get (key);
if (value == null) {
value = new MutableInt ();
map.put (key, value);
} else {
value.inc ();
}
of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.
My problem was that I needed to have the ""
outside the expression since I have a dynamic variable inside the sed expression itself. So than the actual solution is that one from lenn jackman that you replace the "
inside the sed regex with [\"]
.
So my complete bash is:
RELEASE_VERSION="0.6.6"
sed -i -e "s#value=[\"]trunk[\"]#value=\"tags/$RELEASE_VERSION\"#g" myfile.xml
Here is:
#
is the sed separator
[\"]
= "
in regex
value = \"tags/$RELEASE_VERSION\"
= my replacement string, important it has just the \"
for the quotes
This creates backup files. E.g. sed -i -e 's/hello/hello world/' testfile
for me, creates a backup file, testfile-e, in the same dir.
Just to confirm: You are sure you are running MySQL 5.7, and not MySQL 5.6 or earlier version. And the plugin column contains "mysql_native_password". (Before MySQL 5.7, the password hash was stored in a column named password. Starting in MySQL 5.7, the password column is removed, and the password has is stored in the authentication_string column.) And you've also verified the contents of authentication string matches the return from PASSWORD('mysecret'). Also, is there a reason we are using DML against the mysql.user table instead of using the SET PASSWORD FOR syntax? – spencer7593
So Basically Just make sure that the Plugin Column contains "mysql_native_password".
Not my work but I read comments and noticed that this was stated as the answer but was not posted as a possible answer yet.
Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.
The following is from the Secure Coding Guidelines 2.0.
Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).
Just because it happened to me and can be useful. If you do this
try {
...
} catch (Exception e) {
log.error( "failed! {}", e );
}
you will get the header of the exception and not the whole stacktrace. Because the logger will think that you are passing a String.
Do it without {}
as skaffman said
Using @EmbeddableId for the PK entity has solved my issue.
@Entity
@Table(name="SAMPLE")
public class SampleEntity implements Serializable{
private static final long serialVersionUID = 1L;
@EmbeddedId
SampleEntityPK id;
}
You can first check that the destination file exists or not and then make a decision based on the output of its result:
tasks:
- name: Check that the somefile.conf exists
stat:
path: /etc/file.txt
register: stat_result
- name: Create the file, if it doesnt exist already
file:
path: /etc/file.txt
state: touch
when: not stat_result.stat.exists
In Visual Studio 2019 you can find cl.exe inside
32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64
Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.
32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC
and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.
in C#:
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1)
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1)
A Numpy array is immutable, meaning you technically cannot delete an item from it. However, you can construct a new array without the values you don't want, like this:
b = np.delete(a, [2,3,6])
let heightInPoints = image.size.height
let heightInPixels = heightInPoints * image.scale
let widthInPoints = image.size.width
let widthInPixels = widthInPoints * image.scale
I figured it out!!! Of course I would right after I hit post!
I had the repo set to use the HTTPS url, I changed it to the SSH address, and everything resumed working flawlessly.
If you need to 'see' the list of temporary tables, you could simply log the names used. (and as others have noted, it is possible to directly query this information)
If you need to 'see' the content of temporary tables, you will need to create real tables with a (unique) temporary name.
You can trace the SQL being executed using SQL Profiler:
[These articles target SQL Server versions later than 2000, but much of the advice is the same.]
If you have a lengthy process that is important to your business, it's a good idea to log various steps (step name/number, start and end time) in the process. That way you have a baseline to compare against when things don't perform well, and you can pinpoint which step(s) are causing the problem more quickly.
Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.
Setting the passenger.Title
with a value that equals to a title.Value
should work.
View:
<select [(ngModel)]="passenger.Title">
<option *ngFor="let title of titleArray" [value]="title.Value">
{{title.Text}}
</option>
</select>
TypeScript used:
class Passenger {
constructor(public Title: string) { };
}
class ValueAndText {
constructor(public Value: string, public Text: string) { }
}
...
export class AppComponent {
passenger: Passenger = new Passenger("Lord");
titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
new ValueAndText("Lord", "Lord-Text")];
}
In my case, I was trying to find out if any library I was including in my project was redefining my window.player
. So, at the begining of my code, I just did:
Object.defineProperty(window, 'player', {
get: () => this._player,
set: v => {
console.log('window.player has been redefined!');
this._player = v;
}
});
There is no special git ignore
command.
Edit a .gitignore
file located in the appropriate place within the working copy. You should then add this .gitignore
and commit it. Everyone who clones that repo will than have those files ignored.
Note that only file names starting with /
will be relative to the directory .gitignore
resides in. Everything else will match files in whatever subdirectory.
You can also edit .git/info/exclude
to ignore specific files just in that one working copy. The .git/info/exclude
file will not be committed, and will thus only apply locally in this one working copy.
You can also set up a global file with patterns to ignore with git config --global core.excludesfile
. This will locally apply to all git working copies on the same user's account.
Run git help gitignore
and read the text for the details.
The bash script "corstest" below works for me. It is based on Jun's comment above.
usage
corstest [-v] url
examples
./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *
the positive result is displayed in green
./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS
the negative result is displayed in red and blue
the -v option will show the full curl headers
corstest
#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139
#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'
#
# a colored message
# params:
# 1: l_color - the color of the message
# 2: l_msg - the message to display
#
color_msg() {
local l_color="$1"
local l_msg="$2"
echo -e "${l_color}$l_msg${endColor}"
}
#
# show the usage
#
usage() {
echo "usage: [-v] $0 url"
echo " -v |--verbose: show curl result"
exit 1
}
if [ $# -lt 1 ]
then
usage
fi
# commandline option
while [ "$1" != "" ]
do
url=$1
shift
# optionally show usage
case $url in
-v|--verbose)
verbose=true;
;;
esac
done
if [ "$verbose" = "true" ]
then
curl -s -X GET $url -H 'Cache-Control: no-cache' --head
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)
if [ $? -eq 0 ]
then
color_msg $green "$url $origin"
else
color_msg $red "$url does not support CORS"
color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi
Unfortunately I found solutions presented by @dualed have various flaws.
Using substr($sapi_type, 0, 3) == 'cgi'
is not enogh to detect fast CGI. When using PHP-FPM FastCGI Process Manager, php_sapi_name()
returns fpm not cgi
Fasctcgi and php-fpm expose another bug mentioned by @Josh - using header('X-PHP-Response-Code: 404', true, 404);
does work properly under PHP-FPM (FastCGI)
header("HTTP/1.1 404 Not Found");
may fail when the protocol is not HTTP/1.1 (i.e. 'HTTP/1.0'). Current protocol must be detected using $_SERVER['SERVER_PROTOCOL']
(available since PHP 4.1.0
There are at least 2 cases when calling http_response_code()
result in unexpected behaviour:
For your reference here there is the full list of HTTP response status codes (this list includes codes from IETF internet standards as well as other IETF RFCs. Many of them are NOT currently supported by PHP http_response_code function): http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
You can easily test this bug by calling:
http_response_code(521);
The server will send "500 Internal Server Error" HTTP response code resulting in unexpected errors if you have for example a custom client application calling your server and expecting some additional HTTP codes.
My solution (for all PHP versions since 4.1.0):
$httpStatusCode = 521;
$httpStatusMsg = 'Web server is down';
$phpSapiName = substr(php_sapi_name(), 0, 3);
if ($phpSapiName == 'cgi' || $phpSapiName == 'fpm') {
header('Status: '.$httpStatusCode.' '.$httpStatusMsg);
} else {
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg);
}
Conclusion
http_response_code() implementation does not support all HTTP response codes and may overwrite the specified HTTP response code with another one from the same group.
The new http_response_code() function does not solve all the problems involved but make things worst introducing new bugs.
The "compatibility" solution offered by @dualed does not work as expected, at least under PHP-FPM.
The other solutions offered by @dualed also have various bugs. Fast CGI detection does not handle PHP-FPM. Current protocol must be detected.
Any tests and comments are appreciated.
On Fedora 22, you need to do this instead:
sudo dnf install python-devel
sudo dnf install openldap-devel
Adding to other answers already given above. If case insensivity is of any importance to you, then use Jackson. Gson does not support case insensitivity for key names, while jackson does.
Here are two related links
(No) Case sensitivity support in Gson : GSON: How to get a case insensitive element from Json?
Case sensitivity support in Jackson https://gist.github.com/electrum/1260489
Joshua Bloch says on Effective Java
You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.
Let's try to understand it with an example of what would happen if we override equals()
without overriding hashCode()
and attempt to use a Map
.
Say we have a class like this and that two objects of MyClass
are equal if their importantField
is equal (with hashCode()
and equals()
generated by eclipse)
public class MyClass {
private final String importantField;
private final String anotherField;
public MyClass(final String equalField, final String anotherField) {
this.importantField = equalField;
this.anotherField = anotherField;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((importantField == null) ? 0 : importantField.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final MyClass other = (MyClass) obj;
if (importantField == null) {
if (other.importantField != null)
return false;
} else if (!importantField.equals(other.importantField))
return false;
return true;
}
}
Imagine you have this
MyClass first = new MyClass("a","first");
MyClass second = new MyClass("a","second");
Override only equals
If only equals
is overriden, then when you call myMap.put(first,someValue)
first will hash to some bucket and when you call myMap.put(second,someOtherValue)
it will hash to some other bucket (as they have a different hashCode
). So, although they are equal, as they don't hash to the same bucket, the map can't realize it and both of them stay in the map.
Although it is not necessary to override equals()
if we override hashCode()
, let's see what would happen in this particular case where we know that two objects of MyClass
are equal if their importantField
is equal but we do not override equals()
.
Override only hashCode
If you only override hashCode
then when you call myMap.put(first,someValue)
it takes first, calculates its hashCode
and stores it in a given bucket. Then when you call myMap.put(second,someOtherValue)
it should replace first with second as per the Map Documentation because they are equal (according to the business requirement).
But the problem is that equals was not redefined, so when the map hashes second
and iterates through the bucket looking if there is an object k
such that second.equals(k)
is true it won't find any as second.equals(first)
will be false
.
Hope it was clear
I fixed same issue. Solution for me:
xmlns:tools="http://schemas.android.com/tools"
line in the manifest tagtools:replace=..
in the manifest tagandroid:label=...
in the manifest tagExample:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:replace="allowBackup, label"
android:allowBackup="false"
android:label="@string/all_app_name"/>
char arr[50];
gets(arr);
int c=0,i,l;
l=strlen(arr);
for(i=0;i<l;i++){
if(arr[i]==32){
printf("\n");
}
else
printf("%c",arr[i]);
}
In Kotlin: How to check GPS is enable or not
val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
checkGPSEnable()
}
private fun checkGPSEnable() {
val dialogBuilder = AlertDialog.Builder(this)
dialogBuilder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id
->
startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
})
.setNegativeButton("No", DialogInterface.OnClickListener { dialog, id ->
dialog.cancel()
})
val alert = dialogBuilder.create()
alert.show()
}
All modern browsers support a Map, which is a key/value data structure. There are a couple of reasons that make using a Map better than Object:
- An Object has a prototype, so there are default keys in the map.
- The keys of an Object are strings, where they can be any value for a Map.
- You can get the size of a Map easily while you have to keep track of size for an Object.
Example:
var myMap = new Map();
var keyObj = {},
keyFunc = function () {},
keyString = "a string";
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");
myMap.size; // 3
myMap.get(keyString); // "value associated with 'a string'"
myMap.get(keyObj); // "value associated with keyObj"
myMap.get(keyFunc); // "value associated with keyFunc"
If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.
Essentially, the only thing in Python that introduces a new scope is a function definition. Classes are a bit of a special case in that anything defined directly in the body is placed in the class's namespace, but they are not directly accessible from within the methods (or nested classes) they contain.
In your example there are only 3 scopes where x will be searched in:
spam's scope - containing everything defined in code3 and code5 (as well as code4, your loop variable)
The global scope - containing everything defined in code1, as well as Foo (and whatever changes after it)
The builtins namespace. A bit of a special case - this contains the various Python builtin functions and types such as len() and str(). Generally this shouldn't be modified by any user code, so expect it to contain the standard functions and nothing else.
More scopes only appear when you introduce a nested function (or lambda) into the picture. These will behave pretty much as you'd expect however. The nested function can access everything in the local scope, as well as anything in the enclosing function's scope. eg.
def foo():
x=4
def bar():
print x # Accesses x from foo's scope
bar() # Prints 4
x=5
bar() # Prints 5
Restrictions:
Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope. For example:
global_var1 = []
global_var2 = 1
def func():
# This is OK: It's just accessing, not rebinding
global_var1.append(4)
# This won't affect global_var2. Instead it creates a new variable
global_var2 = 2
local1 = 4
def embedded_func():
# Again, this doen't affect func's local1 variable. It creates a
# new local variable also called local1 instead.
local1 = 5
print local1
embedded_func() # Prints 5
print local1 # Prints 4
In order to actually modify the bindings of global variables from within a function scope, you need to specify that the variable is global with the global keyword. Eg:
global_var = 4
def change_global():
global global_var
global_var = global_var + 1
Currently there is no way to do the same for variables in enclosing function scopes, but Python 3 introduces a new keyword, "nonlocal
" which will act in a similar way to global, but for nested function scopes.
1st Step: Add this content in pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2nd Step : Execute this command line by line.
cd /go/to/myApp
mvn clean
mvn compile
mvn package
java -cp target/myApp-0.0.1-SNAPSHOT.jar go.to.myApp.select.file.to.execute
I had this problem for a different reason. I went to the maven repository https://mvnrepository.com looking for the latest version of spring core, which at the time was 5.0.0.M3/ The repository showed me this entry for my pom.xml:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.0.M3</version>
</dependency>
Naive fool that I am, I assumed that the comment was telling me that the jar is located in the default repository.
However, after a lot of head-banging, I saw a note just below the xml saying "Note: this artifact it located at Alfresco Public repository (https://artifacts.alfresco.com/nexus/content/repositories/public/)"
So the comment in the XML is completely misleading. The jar is located in another archive, which was why Maven couldn't find it!
Consider breaking this problem up into two pieces:
filter
out the items that match
the given regular expression0
matches in itconst sampleStringData = ["frog", "pig", "tiger"];
const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));
if (matches.length === 0) {
console.log("No matches");
}
I have written a function that returns a seeded random number, it uses Math.sin to have a long random number and uses the seed to pick numbers from that.
Use :
seedRandom("k9]:2@", 15)
it will return your seeded number the first parameter is any string value ; your seed. the second parameter is how many digits will return.
function seedRandom(inputSeed, lengthOfNumber){
var output = "";
var seed = inputSeed.toString();
var newSeed = 0;
var characterArray = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','y','x','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','U','R','S','T','U','V','W','X','Y','Z','!','@','#','$','%','^','&','*','(',')',' ','[','{',']','}','|',';',':',"'",',','<','.','>','/','?','`','~','-','_','=','+'];
var longNum = "";
var counter = 0;
var accumulator = 0;
for(var i = 0; i < seed.length; i++){
var a = seed.length - (i+1);
for(var x = 0; x < characterArray.length; x++){
var tempX = x.toString();
var lastDigit = tempX.charAt(tempX.length-1);
var xOutput = parseInt(lastDigit);
addToSeed(characterArray[x], xOutput, a, i);
}
}
function addToSeed(character, value, a, i){
if(seed.charAt(i) === character){newSeed = newSeed + value * Math.pow(10, a)}
}
newSeed = newSeed.toString();
var copy = newSeed;
for(var i=0; i<lengthOfNumber*9; i++){
newSeed = newSeed + copy;
var x = Math.sin(20982+(i)) * 10000;
var y = Math.floor((x - Math.floor(x))*10);
longNum = longNum + y.toString()
}
for(var i=0; i<lengthOfNumber; i++){
output = output + longNum.charAt(accumulator);
counter++;
accumulator = accumulator + parseInt(newSeed.charAt(counter));
}
return(output)
}
I've found the updated answer from this video, the accepted answer didn't work for me.
First clone the latest repo from git (if haven't) using
git clone <HTTPs link of the project>
(or using SSH) then go to the desire branch using
git checkout <branch name>
.
Use the command
git log
to check the latest commits. Copy the shal of the particular commit. Then use the command
git fetch origin <Copy paste the shal here>
After pressing enter key. Now use the command
git checkout FETCH_HEAD
Now the particular commit will be available to your local. Change anything and push the code using git push origin <branch name>
. That's all.
Check the video for reference.
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
If you are entering your credentials into the Visual Studio popup you might see an error that says "Login was not successful". However, this might not be true. Studio will open a browser window saying that it was in fact successful. There is then a dance between the browser and Studio where you need to accept / allow the authentication at certain points.
In my case, I needed an additional command,
git branch --unset-upstream
to get my renamed branch to push up to origin newname
.
(For ease of typing), I first git checkout oldname
.
Then run the following:
git branch -m newname <br/>
git push origin :oldname*or*
git push origin --delete oldname
git branch --unset-upstream
git push -u origin newname
or git push origin newname
This extra step may only be necessary because I (tend to) set up remote tracking on my branches via git push
-u
origin oldname
. This way, when I have oldname
checked out, I subsequently only need to type git push
rather than git push origin oldname
.
If I do not use the command git branch --unset-upstream
before git push origin newbranch
, git re-creates oldbranch
and pushes newbranch
to origin oldbranch
-- defeating my intent.
It sounds like you would benefit from using an automation utility. If you were using a windows PC I would recommend AutoHotkey. I haven't used automation utilities on a Mac, but this Ask Different post has several suggestions, though none appear to be free.
This is not a VBA solution. These macros run outside of Excel and can interact with programs using keyboard strokes, mouse movements and clicks.
Basically you record or write a simple automation macro that waits for the Excel "Save As" dialogue box to become active, hits enter/return to complete the save action and then waits for the "Save As" window to close. You can set it to run in a continuous loop until you manually end the macro.
Here's a simple version of a Windows AutoHotkey script that would accomplish what you are attempting to do on a Mac. It should give you an idea of the logic involved.
; ' Infinite loop. End the macro by closing the program from the Windows taskbar.
Loop {
; ' Wait for ANY "Save As" dialogue box in any program.
; ' BE CAREFUL!
; ' Ignore the "Confirm Save As" dialogue if attempt is made
; ' to overwrite an existing file.
WinWait, Save As,,, Confirm Save As
IfWinNotActive, Save As,,, Confirm Save As
WinActivate, Save As,,, Confirm Save As
WinWaitActive, Save As,,, Confirm Save As
sleep, 250 ; ' 0.25 second delay
Send, {ENTER} ; ' Save the Excel file.
; ' Wait for the "Save As" dialogue box to close.
WinWaitClose, Save As,,, Confirm Save As
}
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
mybtn = (Button)findViewById(R.id.mybtn);
txtView=(TextView)findViewById(R.id.txtView);
mybtn .setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
txtView.SetText("Your Message");
}
});
}
May this also can help using configuration file like java class way.
@Configuration
@PropertySource("classpath:application.properties")
public class DataSourceConfig {
@Autowired
JdbcConfigProperties jdbc;
@Bean(name = "hikariDataSource")
public DataSource hikariDataSource() {
HikariConfig config = new HikariConfig();
HikariDataSource dataSource;
config.setJdbcUrl(jdbc.getUrl());
config.setUsername(jdbc.getUser());
config.setPassword(jdbc.getPassword());
// optional: Property setting depends on database vendor
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
dataSource = new HikariDataSource(config);
return dataSource;
}
}
How to use it:
@Component
public class Car implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(AptSommering.class);
@Autowired
@Qualifier("hikariDataSource")
private DataSource hikariDataSource;
}
If in case you are getting the values as undefined
, then you should consider restarting the node server and recompile again.
In Swift 4.2
UIApplication.shared.keyWindow!.bringSubviewToFront(yourView)
Source: https://developer.apple.com/documentation/uikit/uiview/1622541-bringsubviewtofront#declarations
If you are using a JAX-WS implementation for your client, such as Metro Web Services, the following code shows how to pass username and password in the HTTP headers:
MyService port = new MyService();
MyServiceWS service = port.getMyServicePort();
Map<String, List<String>> credentials = new HashMap<String,List<String>>();
credentials.put("username", Collections.singletonList("username"));
credentials.put("password", Collections.singletonList("password"));
((BindingProvider)service).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, credentials);
Then subsequent calls to the service will be authenticated. Beware that the password is only encoded using Base64, so I encourage you to use other additional mechanism like client certificates to increase security.
float is the closest equivalent.
For Lat/Long as OP mentioned.
A metre is 1/40,000,000 of the latitude, 1 second is around 30 metres. Float/double give you 15 significant figures. With some quick and dodgy mental arithmetic... the rounding/approximation errors would be the about the length of this fill stop -> "."
Using a subshell substitution to parse the words undoes all the work you are doing to put spaces together.
Try instead:
cat CSV_file | sed -n 1'p' | tr ',' '\n' | while read word; do
echo $word
done
That also increases parallelism. Using a subshell as in your question forces the entire subshell process to finish before you can start iterating over the answers. Piping to a subshell (as in my answer) lets them work in parallel. This matters only if you have many lines in the file, of course.
[[UIDevice currentDevice] uniqueIdentifier]
Returns the Unique ID of your iPhone.
EDIT:
-[UIDevice uniqueIdentifier]
is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.
If you need to create several UUID, just use this method (with ARC):
+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (__bridge NSString *)string;
}
EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:
NSString *UUID = [[NSUUID UUID] UUIDString];
<form action="" method="post" enctype="multipart/form-data">
<input type="file" multiple name="img[]"/>
<input type="submit">
</form>
<?php
print_r($_FILES['img']['name']);
?>
This is an Inequality operator.
Also,this might be helpful for future: Operators listed by Functionality
For multi-lines in Chrome use :
display: inline-block;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; // max nb lines to show
-webkit-box-orient: vertical;
Inspired from youtube ;-)
This one $("#yourDiv").load(" #yourDiv > *");
is the best if you are planning to just reload a <div>
Make sure to use an id
and not a class
. Also, remember to paste <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
in the <head>
section of the html file, if you haven't already. In opposite case it won't work.
You could probably write your own custom implementation of click/dblclick to have it wait for an extra click. I don't see anything in the core jQuery functions that would help you achieve this.
Quote from .dblclick() at the jQuery site
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
To quickly and safely compare any two files:
if cmp --silent -- "$FILE1" "$FILE2"; then
echo "files contents are identical"
else
echo "files differ"
fi
It's readable, efficient, and works for any file names including "` $()
Check this out. Just use float and get rid of relative.
#icons{float:left;}
Here's an example which issues the same warning:
import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a
yields
RuntimeWarning: overflow encountered in long_scalars
In the example above it happens because a
is of dtype int32
, and the maximim value storable in an int32
is 2**31-1. Since 10**10 > 2**32-1
, the exponentiation results in a number that is bigger than that which can be stored in an int32
.
Note that you can not rely on np.seterr(all='warn')
to catch all overflow
errors in numpy. For example, on 32-bit NumPy
>>> np.multiply.reduce(np.arange(21)+1)
-1195114496
while on 64-bit NumPy:
>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848
Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals
In [47]: import math
In [48]: math.factorial(21)
Out[50]: 51090942171709440000L
According to numpy developer, Robert Kern,
Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.
So the burden is on you to choose appropriate dtypes
so that no operation overflows.
If you really really need to use map function (like my class assignment here...), you could use a wrapper function with 1 argument, passing the rest to the original one in its body; i.e. :
extraArguments = value
def myFunc(arg):
# call the target function
return Func(arg, extraArguments)
map(myFunc, itterable)
Dirty & ugly, still does the trick
A cleaner alternative would be the following:
Due to the fact that every async function is technically a promise
You can add catches to functions when calling them with await
async function a(){
let error;
// log the error on the parent
await b().catch((err)=>console.log('b.failed'))
// change an error variable
await c().catch((err)=>{error=true; console.log(err)})
// return whatever you want
return error ? d() : null;
}
a().catch(()=>console.log('main program failed'))
No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!
Lets say you are working with mongodb, if there is an error you might prefer to handle it in the function calling it than making wrappers, or using try catches.
To convert an int
ASCII value to character you can also use:
int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z
The prompt command will echo text to the output:
prompt A useful comment.
select(*) from TableA;
Will be displayed as:
SQL> A useful comment.
SQL>
COUNT(*)
----------
0
almost never
Whenever you need to have a vector of char bigger that 2gb on a 32 bit system. In every other use case, using a signed type is much safer than using an unsigned type.
example:
std::vector<A> data;
[...]
// calculate the index that should be used;
size_t i = calc_index(param1, param2);
// doing calculations close to the underflow of an integer is already dangerous
// do some bounds checking
if( i - 1 < 0 ) {
// always false, because 0-1 on unsigned creates an underflow
return LEFT_BORDER;
} else if( i >= data.size() - 1 ) {
// if i already had an underflow, this becomes true
return RIGHT_BORDER;
}
// now you have a bug that is very hard to track, because you never
// get an exception or anything anymore, to detect that you actually
// return the false border case.
return calc_something(data[i-1], data[i], data[i+1]);
The signed equivalent of size_t
is ptrdiff_t
, not int
. But using int
is still much better in most cases than size_t. ptrdiff_t
is long
on 32 and 64 bit systems.
This means that you always have to convert to and from size_t whenever you interact with a std::containers, which not very beautiful. But on a going native conference the authors of c++ mentioned that designing std::vector with an unsigned size_t was a mistake.
If your compiler gives you warnings on implicit conversions from ptrdiff_t to size_t, you can make it explicit with constructor syntax:
calc_something(data[size_t(i-1)], data[size_t(i)], data[size_t(i+1)]);
if just want to iterate a collection, without bounds cheking, use range based for:
for(const auto& d : data) {
[...]
}
here some words from Bjarne Stroustrup (C++ author) at going native
For some people this signed/unsigned design error in the STL is reason enough, to not use the std::vector, but instead an own implementation.
You can also use barcodefragmentlib which is an extension of zxing but provides barcode scanning as fragment library, so can be very easily integrated.
Here is the supporting documentation for usage of library
Close Code 1006
is a special code that means the connection was closed abnormally (locally) by the browser implementation.
If your browser client reports close code 1006
, then you should be looking at the websocket.onerror(evt)
event for details.
However, Chrome will rarely report any close code 1006
reasons to the Javascript side. This is likely due to client security rules in the WebSocket spec to prevent abusing WebSocket. (such as using it to scan for open ports on a destination server, or for generating lots of connections for a denial-of-service attack).
Note that Chrome will often report a close code 1006
if there is an error during the HTTP Upgrade to Websocket (this is the step before a WebSocket is technically "connected"). For reasons such as bad authentication or authorization, or bad protocol use (such as requesting a subprotocol, but the server itself doesn't support that same subprotocol), or even an attempt at talking to a server location that isn't a WebSocket (such as attempting to connect to ws://images.google.com/
)
Fundamentally, if you see a close code 1006
, you have a very low level error with WebSocket itself (similar to "Unable to Open File" or "Socket Error"), not really meant for the user, as it points to a low level issue with your code and implementation. Fix your low level issues, and then when you are connected, you can then include more reasonable error codes. You can accomplish this in terms of scope or severity in your project. Example: info and warning level are part of your project's specific protocol, and don't cause the connection to terminate. With severe or fatal messages reporting also using your project's protocol to convey as much detail as you want, and then closing the connection using the limited abilities of the WebSocket close flow.
Be aware that WebSocket close codes are very strictly defined, and the close reason phrase/message cannot exceed 123 characters in length (this is an intentional WebSocket limitation).
But not all is lost, if you are just wanting this information for debugging reasons, the detail of the closure, and its underlying reason is often reported with a fair amount of detail in Chrome's Javascript console.
Combination of lambda and map function can also do the job:
list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2
The related name parameter is actually an option. If we do not set it, Django
automatically creates the other side of the relation for us. In the case of the Map model,
Django would have created a map_set
attribute, allowing access via m.map_set
in your
example(m being your class instance). The formula Django uses is the name of the model followed by the
string _set
. The related name parameter thus simply overrides Django’s default rather
than providing new behavior.
The following answer is to merge data into same table
MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif')
WHEN NOT MATCHED THEN
INSERT ( d.USERS_ID, d.USER_NAME)
VALUES ('123','itszaif');
This command checks if USER_ID
and USER_NAME
are matched, if not matched then it will insert.
Goto This link its working..
http://www.ttkalec.com/blog/resolving-yellow-wamp-server-status-freeing-up-port-80-for-apache/
Update: Using XAMP
After I’ve written this blog post I’ve figured out that XAMP, although very similar to WAMP, doesn’t force you to run Apache as a service, instead it can run it as a regular process. So I ended up using XAMP, and changed Apache port to 8080 so now everything works.
WAMP Issues
If you have Window 7 or later you may have come across issues with WAMP server trying to start Apache service on port 80 and failing.
There are many conflict and issues that might have come up. Before you try anything, check if you have ZoneAlarm, Nod32, or any other program/firewall that might be blocking Apache server. If you’re sure that firewall isn’t the problem here is a couple of fixes that you can try.
NOTE: After every fix you try, you must click on yellow WAMP icon and choose Restart All Services
Checking which process is causing the problem
Open Command Prompt window by typing cmd in Run command box or Start Search, and hit Enter. Type in the following command: netstat -o -n -a | findstr 0.0:80 The last column of each row is the process identified (process ID or PID). Identify which process or application is using the port by matching the PID against PID number in Task Manager. If you don’t see PID column in your Task Manager you need to go to Processes tab -> View Menu -> Select Columns and choose PID from the list Now, you may have identified application that reserves port 80, or you may have found out that System is using your port 80. That means that one of internal services is using your port, in which case continue reading further. Conflict with Skype
If you found out that Skype is using your port 80, you need to change some settings in Skype. On Windows, Skype reserves port 80 which is used for HTTP. Apache requires this port. So if you’re running Skype, you must go to Tools > Options. Then in the Advanced section, select Connection. Un-check the box that says “Use port 80 and 443 as alternatives for incoming connection“. Quit Skype and restart. The issue should be resolved.
Conflict with IIS Server
IIS Server and Apache are both web server that use port 80 so they might be in conflict. Try stopping IIS by:
Going into Control Panel -> Administrative Tools -> Internet Information Services Right click on Default Web Site Click on Stop option in the popup menu, and see of the listener on port 80 has cleared. Conflict with MS SQL Server
MS SQL Server installs “SQL Server Reporting Services (MSSQLSERVER)” that apparently defaults to 80. You can try stopping it to free up port 80.
Go to Control Panel -> Administrative Tools -> Services There find MSSQLSERVER (might be found also under SQL Server) Double click it -> Click Stop Under Startup type: choose Manual Other Services that can cause conflicts
As described above for MS SQL Server:
Go to Control Panel -> Administrative Tools -> Services You can try stopping: Web Deployment Agent Service Windows Remote Management Autodesk EDM Server World Wide Web Publishing Service There are probably more of them, but this where the ones that I tryed.
Try turning off HTTP driver directly
If you’ve tried everything mentioned above and your WAMP server is still not working you could try this (which eventually helped me).
Right click on My Computer icon -> Properties Go to Device Manager Click on View menu and chooseShow hidden devices Now from the list choose Non-Plug and Play devices Double click HTTP -> go to Driver For Type choose Disabled Restart your computer After your computer boots up you should be able to start up WAMP server.
If everything else fails
You could try changing Apache server to listen to some other port other than port 80.
Click on yellow WAMP icon in your taskbar Choose Apache -> httpd.conf Inside find these two lines of code:
Listen 80 ServerName localhost:80 and change them to something like this (they are not one next to the other):
Listen 8080 ServerName localhost:8080 Restart all services, and try typing localhost:8080 into your browser. WAMP server should now be working.
The @overload
decorator was added with type hints (PEP 484).
While this doesn't change the behaviour of Python, it does make it easier to understand what is going on, and for mypy to detect errors.
See: Type hints and PEP 484
$('#saveBtn').off('click').click(function(){saveQuestion(id)});
Try adding the profile
attribute to your head
tag and use "image/x-icon"
for the type
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">
If the above code doesn't work, try using the full icon path for the href
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">
After reading many resources regarding this topic, including StackOverFlow, I find that not all solutions are working properly. Below is our attempt to fix this.
Basically, We take the friendly name of an Enum from a DescriptionAttribute if it exists.
If it does not We use RegEx to determine the words within the Enum name and add spaces.
Next version, we will use another Attribute to flag whether we can/should take the friendly name from a localizable resource file.
Below are the test cases. Please report if you have another test case that do not pass.
public static class EnumHelper
{
public static string ToDescription(Enum value)
{
if (value == null)
{
return string.Empty;
}
if (!Enum.IsDefined(value.GetType(), value))
{
return string.Empty;
}
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
if (fieldInfo != null)
{
DescriptionAttribute[] attributes =
fieldInfo.GetCustomAttributes(typeof (DescriptionAttribute), false) as DescriptionAttribute[];
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
}
return StringHelper.ToFriendlyName(value.ToString());
}
}
public static class StringHelper
{
public static bool IsNullOrWhiteSpace(string value)
{
return value == null || string.IsNullOrEmpty(value.Trim());
}
public static string ToFriendlyName(string value)
{
if (value == null) return string.Empty;
if (value.Trim().Length == 0) return string.Empty;
string result = value;
result = string.Concat(result.Substring(0, 1).ToUpperInvariant(), result.Substring(1, result.Length - 1));
const string pattern = @"([A-Z]+(?![a-z])|\d+|[A-Z][a-z]+|(?![A-Z])[a-z]+)+";
List<string> words = new List<string>();
Match match = Regex.Match(result, pattern);
if (match.Success)
{
Group group = match.Groups[1];
foreach (Capture capture in group.Captures)
{
words.Add(capture.Value);
}
}
return string.Join(" ", words.ToArray());
}
}
[TestMethod]
public void TestFriendlyName()
{
string[][] cases =
{
new string[] {null, string.Empty},
new string[] {string.Empty, string.Empty},
new string[] {" ", string.Empty},
new string[] {"A", "A"},
new string[] {"z", "Z"},
new string[] {"Pascal", "Pascal"},
new string[] {"camel", "Camel"},
new string[] {"PascalCase", "Pascal Case"},
new string[] {"ABCPascal", "ABC Pascal"},
new string[] {"PascalABC", "Pascal ABC"},
new string[] {"Pascal123", "Pascal 123"},
new string[] {"Pascal123ABC", "Pascal 123 ABC"},
new string[] {"PascalABC123", "Pascal ABC 123"},
new string[] {"123Pascal", "123 Pascal"},
new string[] {"123ABCPascal", "123 ABC Pascal"},
new string[] {"ABC123Pascal", "ABC 123 Pascal"},
new string[] {"camelCase", "Camel Case"},
new string[] {"camelABC", "Camel ABC"},
new string[] {"camel123", "Camel 123"},
};
foreach (string[] givens in cases)
{
string input = givens[0];
string expected = givens[1];
string output = StringHelper.ToFriendlyName(input);
Assert.AreEqual(expected, output);
}
}
}
private boolean isValidEmailID(String email) {
String PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
This worked for me.
def parse_data():
if request.method == "POST":
data = request.get_json()
print(data['answers'])
return render_template('output.html', data=data)
$.ajax({
type: 'POST',
url: "/parse_data",
data: JSON.stringify({values}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data){
// do something with the received data
}
});
In the HTML which you have shared:
<div id="a">This is some
<div id="b">text</div>
</div>
The text This is some
is within a text node. To depict the text node in a structured way:
<div id="a">
This is some
<div id="b">text</div>
</div>
To extract and print the text This is some
from the text node using Selenium's python client you have 2 ways as follows:
Using splitlines()
: You can identify the parent element i.e. <div id="a">
, extract the innerHTML
and then use splitlines()
as follows:
using xpath:
print(driver.find_element_by_xpath("//div[@id='a']").get_attribute("innerHTML").splitlines()[0])
using xpath:
print(driver.find_element_by_css_selector("div#a").get_attribute("innerHTML").splitlines()[0])
Using execute_script()
: You can also use the execute_script()
method which can synchronously execute JavaScript in the current window/frame as follows:
using xpath and firstChild:
parent_element = driver.find_element_by_xpath("//div[@id='a']")
print(driver.execute_script('return arguments[0].firstChild.textContent;', parent_element).strip())
using xpath and childNodes[n]:
parent_element = driver.find_element_by_xpath("//div[@id='a']")
print(driver.execute_script('return arguments[0].childNodes[1].textContent;', parent_element).strip())
<html>
<head>
<title>example</title>
<script>
$(function(){
$('#filename').load("htmlfile.html");
});
</script>
</head>
<body>
<div id="filename">
</div>
</body>
git stash pop
will get everything back in place
as suggested in the comments, you can use git stash branch newbranch
to apply the stash to a new branch, which is the same as running:
git checkout -b newbranch
git stash pop
Yes if the structure is of the same type. Think it as a memory copy.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
# plt.axis([x[0], x[-1], -1, 1]) # disable autoscaling
for point in x:
plt.plot(point, np.sin(2 * point), '.', color='b')
plt.draw()
plt.pause(0.01)
# plt.clf() # clear the current figure
if the amount of data is too much you can lower the update rate with a simple counter
cnt += 1
if (cnt == 10): # update plot each 10 points
plt.draw()
plt.pause(0.01)
cnt = 0
This was my actual problem that couldn't find satisfactory answer for, I wanted plotting that didn't close after the script was finished (like MATLAB),
If you think about it, after the script is finished, the program is terminated and there is no logical way to hold the plot this way, so there are two options
this wasn't satisfactory for me so I found another solution outside of the box
For this the saving and viewing should be both fast and the viewer shouldn't lock the file and should update the content automatically
vector based formats are both small and fast
For PDF there are several good options
On Windows I use SumatraPDF which is free, fast and light (only uses 1.8MB RAM for my case)
On Linux there are several options such as Evince (GNOME) and Ocular (KDE)
Sample code for outputing plot to a file
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(2 * x)
plt.plot(x, y)
plt.savefig("fig.pdf")
after first run, open the output file in one of the viewers mentioned above and enjoy.
Here is a screenshot of VSCode alongside SumatraPDF, also the process is fast enough to get semi-live update rate (I can get near 10Hz on my setup just use time.sleep()
between intervals)
Yes. First, construct a File
representing the image path:
File file = new File(a);
If you're starting from a relative path:
file = new File(file.getAbsolutePath());
Then, get the parent:
String dir = file.getParent();
Or, if you want the directory as a File
object,
File dirAsFile = file.getParentFile();
Consider a task that inputs data from the serial port. When new data arrives the serial port triggers an event. When the software services that event, it reads and processes the new data. The serial port has a hardware to store incoming data (2 on the MSP432, 16 on the TM4C123) such that if the buffer is full and more data arrives, the new data is lost. Is this system hard, firm, or soft real time?
It is hard real time because if the response is late, data may be lost.
Consider a hearing aid that inputs sounds from a microphone, manipulates the sound data, and then outputs the data to a speaker. The system usually has small and bounded jitter, but occasionally other tasks in the hearing aid cause some data to be late, causing a noise pulse on the speaker. Is this system hard, firm or soft real time?
It is firm real time because it causes an error that can be perceived but the effect is harmless and does not significantly alter the quality of the experience.
Consider a task that outputs data to a printer. When the printer is idle the printer triggers an event. When the software services that event, it sends more data to the printer. Is this system hard, firm or soft real time?
It is soft real time because the faster it responses the better, but the value of the system (bandwidth is amount of data printed per second) diminishes with latency.
UTAustinX: UT.RTBN.12.01x Realtime Bluetooth Networks
similar to @python-starter solution. But, commands package is not avilable on python3.x. So Alternative solution is to use subprocess in python3.x
import subprocess
cmd = "hive -S -e 'SELECT * FROM db_name.table_name LIMIT 1;' "
status, output = subprocess.getstatusoutput(cmd)
if status == 0:
print(output)
else:
print("error")
you can use the has_key()
method:
if dict.has_key('xyz')==1:
#update the value for the key
else:
pass
Just check for it before you pass to your function. So you would pass:
thing.foo ? thing.foo.bar : undefined
I know this is pretty old now but I have just had the same issue and the problem was I was allocating to much memory to eclipse that it could not get hold of. So open eclipse.ini and lower the amount of memory that is being allocated to -Xmx
XXMaxPermSize
I changed mine to -Xmx512m
and XXMaxPermSize256m
You can also use glob
for this:
$dirname = "media/images/iconized/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
I would like to expand the answers to whoever might be using this in a bigger project, you could accidentally attach multiple event handlers and the program would behave weirdly.
To get rid of that, I used a singleton function exposed by a factory, from which you would call inactivityTimeoutFactory.switchTimeoutOn()
and inactivityTimeoutFactory.switchTimeoutOff()
in your angular application to respectively activate and deactivate the logout due to inactivity functionality.
This way you make sure you are only running a single instance of the event handlers, no matter how many times you try to activate the timeout procedure, making it easier to use in applications where the user might login from different routes.
Here is my code:
'use strict';
angular.module('YOURMODULENAME')
.factory('inactivityTimeoutFactory', inactivityTimeoutFactory);
inactivityTimeoutFactory.$inject = ['$document', '$timeout', '$state'];
function inactivityTimeoutFactory($document, $timeout, $state) {
function InactivityTimeout () {
// singleton
if (InactivityTimeout.prototype._singletonInstance) {
return InactivityTimeout.prototype._singletonInstance;
}
InactivityTimeout.prototype._singletonInstance = this;
// Timeout timer value
const timeToLogoutMs = 15*1000*60; //15 minutes
const timeToWarnMs = 13*1000*60; //13 minutes
// variables
let warningTimer;
let timeoutTimer;
let isRunning;
function switchOn () {
if (!isRunning) {
switchEventHandlers("on");
startTimeout();
isRunning = true;
}
}
function switchOff() {
switchEventHandlers("off");
cancelTimersAndCloseMessages();
isRunning = false;
}
function resetTimeout() {
cancelTimersAndCloseMessages();
// reset timeout threads
startTimeout();
}
function cancelTimersAndCloseMessages () {
// stop any pending timeout
$timeout.cancel(timeoutTimer);
$timeout.cancel(warningTimer);
// remember to close any messages
}
function startTimeout () {
warningTimer = $timeout(processWarning, timeToWarnMs);
timeoutTimer = $timeout(processLogout, timeToLogoutMs);
}
function processWarning() {
// show warning using popup modules, toasters etc...
}
function processLogout() {
// go to logout page. The state might differ from project to project
$state.go('authentication.logout');
}
function switchEventHandlers(toNewStatus) {
const body = angular.element($document);
const trackedEventsList = [
'keydown',
'keyup',
'click',
'mousemove',
'DOMMouseScroll',
'mousewheel',
'mousedown',
'touchstart',
'touchmove',
'scroll',
'focus'
];
trackedEventsList.forEach((eventName) => {
if (toNewStatus === 'off') {
body.off(eventName, resetTimeout);
} else if (toNewStatus === 'on') {
body.on(eventName, resetTimeout);
}
});
}
// expose switch methods
this.switchOff = switchOff;
this.switchOn = switchOn;
}
return {
switchTimeoutOn () {
(new InactivityTimeout()).switchOn();
},
switchTimeoutOff () {
(new InactivityTimeout()).switchOff();
}
};
}
I had to specify individual commands first and then use the *
to bring all in command.
from tkinter import filedialog
from tkinter import *
Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):
CSS:
.txt-center {
text-align: center;
}
.hide {
display: none;
}
.clear {
float: none;
clear: both;
}
.rating {
width: 90px;
unicode-bidi: bidi-override;
direction: rtl;
text-align: center;
position: relative;
}
.rating > label {
float: right;
display: inline;
padding: 0;
margin: 0;
position: relative;
width: 1.1em;
cursor: pointer;
color: #000;
}
.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
color: transparent;
}
.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
content: "\2605";
position: absolute;
left: 0;
color: #FFD700;
}
HTML:
<div class="txt-center">
<form>
<div class="rating">
<input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
<label for="star5">?</label>
<input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
<label for="star4">?</label>
<input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
<label for="star3">?</label>
<input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
<label for="star2">?</label>
<input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
<label for="star1">?</label>
<div class="clear"></div>
</div>
</form>
</div>
Please check the demo
You need an uppercase M
for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m
is for outputting (and parsing) a minute (such as h:mm
).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM
difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime
format information to use as default
as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator
defined that automatically translates to and from DateTime/string. But that is dangerous territory.
Put this bean in your configuration class.
@Bean
public Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
and then You can use
<T> BindingResult validate(T t) {
DataBinder binder = new DataBinder(t);
binder.setValidator(validator);
binder.validate();
return binder.getBindingResult();
}
for validating a bean manually. Then You will get all result in BindingResult and you can retrieve from there.
Use Jetty. Here's the official example for embedding Jetty. (Here's an outdated tutorial.)
Jetty is pretty lightweight, but it does provide a servlet container, which may contradict your requirement against using an "application server".
You can embed the Jetty server into your application. Jetty allows EITHER embedded OR servlet container options.
Here is one more quick get started tutorial along with the source code.
Columns of data frames are already vectors, you just have to pull them out. Note that you place the column you want after the comma, not before it:
> newV <- df[,1]
> newV
[1] 1 2 4 2
If you actually want a row, then do what Ben said and please use words correctly in the future.
If implementation is not defined, you are writing on a wrong file. On Unity 2019+ the correct file is main template grandle
and not some of the others.
As MadScientist pointed out, you can export individual variables with:
export MY_VAR = foo # Available for all targets
Or export variables for a specific target (target-specific variables):
my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz
my-target: dependency_1 dependency_2
echo do something
You can also specify the .EXPORT_ALL_VARIABLES
target to—you guessed it!—EXPORT ALL THE THINGS!!!:
.EXPORT_ALL_VARIABLES:
MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz
test:
@echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3
Best way to customize Action bar onClickListener is onSupportNavigateUp()
This code will be helpful link for helping code
I was able to edit a large 17GB csv file in Sublime Text without issue (line numbering makes it a lot easier to keep track of manual splitting), and then dump it into Excel in chunks smaller than 1,048,576 lines. Simple and quite quick - less faffy than researching into, installing and learning bespoke solutions. Quick and dirty, but it works.
points
is not within the function's scope. You can grab a reference to the variable by using nonlocal:
points = 0
def test():
nonlocal points
points += 1
If points
inside test()
should refer to the outermost (module) scope, use global:
points = 0
def test():
global points
points += 1
Wrap your two+ function calls in another function/method. Here are a couple variants of that idea:
1) Separate method
var Test = React.createClass({
onClick: function(event){
func1();
func2();
},
render: function(){
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
});
or with ES6 classes:
class Test extends React.Component {
onClick(event) {
func1();
func2();
}
render() {
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
}
2) Inline
<a href="#" onClick={function(event){ func1(); func2()}}>Test Link</a>
or ES6 equivalent:
<a href="#" onClick={() => { func1(); func2();}}>Test Link</a>
On linux we can do like this to remove go completely:
rm -rf "/usr/local/.go/"
rm -rf "/usr/local/go/"
These two command remove go and hidden .go files. Now we also have to update entries in shell profile.
Open your basic file. Mostly I open like this sudo gedit ~/.bashrc
and remove all go mentions.
You can also do by sed command in ubuntu
sed -i '/# GoLang/d' .bashrc
sed -i '/export GOROOT/d' .bashrc
sed -i '/:$GOROOT/d' .bashrc
sed -i '/export GOPATH/d' .bashrc
sed -i '/:$GOPATH/d' .bashrc
It will remove Golang from everywhere. Also run this after running these command
source ~/.bash_profile
Tested on linux 18.04 also. That's All.
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
I upvoted Ricardo. Actually max is much efficient than sorting . See the differences. its excellent.
I had to get the last row/update record (timeStamp)
`sqlite> select timeStamp from mypadatav2 order by timeStamp desc limit 1;
2020-03-11 23:55:00
Run Time: real 1.806 user 1.689242 sys 0.117062`
`sqlite> select max(timeStamp) from mypadatav2;
2020-03-11 23:55:00
Run Time: real 0.553 user 0.412618 sys 0.134340`
Visual Studio Code detects the current indentation per default and uses this - ignoring the .editorconfig
Set also "editor.detectIndentation" to false
(Files -> Preferences -> Settings)
Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).
Example usage:
require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
It depends on the recursion level for triggers currently set on the DB.
If you do this:
SP_CONFIGURE 'nested_triggers',0
GO
RECONFIGURE
GO
Or this:
ALTER DATABASE db_name
SET RECURSIVE_TRIGGERS OFF
That trigger above won't be called again, and you would be safe (unless you get into some kind of deadlock; that could be possible but maybe I'm wrong).
Still, I do not think this is a good idea. A better option would be using an INSTEAD OF trigger. That way you would avoid executing the first (manual) update over the DB. Only the one defined inside the trigger would be executed.
An INSTEAD OF INSERT trigger would be like this:
CREATE TRIGGER setDescToUpper ON part_numbers
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO part_numbers (
colA,
colB,
part_description
) SELECT
colA,
colB,
UPPER(part_description)
) FROM
INSERTED
END
GO
This would automagically "replace" the original INSERT statement by this one, with an explicit UPPER call applied to the part_description
field.
An INSTEAD OF UPDATE trigger would be similar (and I don't advise you to create a single trigger, keep them separated).
Also, this addresses @Martin comment: it works for multirow inserts/updates (your example does not).
An easier way is to use ExecuteTime plugin in jupyter_contrib_nbextensions package.
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime
Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing
/etc/security/limits.conf
by adding something like this
jetty soft nofile 2048
jetty hard nofile 4096
where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf
log off and then log in again and run
ulimit -n
to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.
The default limit 1024 can be too low for large Java applications.
2 things FYI -
You can use bringToFront
:
View view=findViewById(R.id.btnStartGame);
view.bringToFront();
If p is a variable that contains a Promise, then p.then(empty);
should dismiss the promise when it eventually completes or if it is already complete (yes, I know this isn't the original question, but it is my question). "empty" is function empty() {}
. I'm just a beginner and probably wrong, but these other answers seem too complicated. Promises are supposed to be simple.
Check you gradle settings, it may be set to Offline Work
In my case the select2 would open correctly if there was zero or more pills.
But if there was one or more pills, and I deleted them all, it would shrink to the smallest width. My solution was simply:
$("#myselect").select2({ width: '100%' });
Spring Boot do a lot of automatically things to us but when we use the annotation @SpringBootTest
we think that everything will be automatically solved by Spring boot.
There are a lot of documentation, but the minimal is to choose one engine (@RunWith(SpringRunner.class)
) and indicate the class that will be used create the context to load the configuration (resources/applicationl.properties
).
In a simple way you need the engine and the context:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyClassTest .class)
public class MyClassTest {
@Value("${my.property}")
private String myProperty;
@Test
public void checkMyProperty(){
Assert.assertNotNull(my.property);
}
}
Of course, if you look the Spring Boot documentation you will find thousands os ways to do that.
You can use the focusout event to detect keyboard dismissal. It's like blur, but bubbles. It will fire when the keyboard closes (but also in other cases, of course). In Safari and Chrome the event can only be registered with addEventListener, not with legacy methods. Here is an example I used to restore a Phonegap app after keyboard dismissal.
document.addEventListener('focusout', function(e) {window.scrollTo(0, 0)});
Without this snippet, the app container stayed in the up-scrolled position until page refresh.
turn on the org.hibernate.type
Logger to see how the actual parameters are bind to the question marks.
I had the same initial reaction. I too was frustrated at how syntax and objects change so drastically in every major release.
However, I realized from experience how I always eventually suffer the consequences of trying to fight "change" like dealing with multi-byte characters which is inevitable if you're looking at a global audience.
So I decided to recognize and respect the efforts exerted by Apple engineers and do my part by understanding their mindset when they came up with this "horrific" approach.
Instead of creating extensions which is just a workaround to make your life easier (I'm not saying they're wrong or expensive), why not figure out how Strings are now designed to work.
For instance, I had this code which was working on Swift 2.2:
let rString = cString.substringToIndex(2)
let gString = (cString.substringFromIndex(2) as NSString).substringToIndex(2)
let bString = (cString.substringFromIndex(4) as NSString).substringToIndex(2)
and after giving up trying to get the same approach working e.g. using Substrings, I finally understood the concept of treating Strings as a bidirectional collection for which I ended up with this version of the same code:
let rString = String(cString.characters.prefix(2))
cString = String(cString.characters.dropFirst(2))
let gString = String(cString.characters.prefix(2))
cString = String(cString.characters.dropFirst(2))
let bString = String(cString.characters.prefix(2))
I hope this contributes...
The solution (http://expressjs.com/en/starter/static-files.html).
once done this the image folder no longer shalt put it. only be
background-image: url ( "/ image.png");
carpera that the image is already in the static files
window.location.reload() or just location.reload()
I believe this can help you:
$(document).ready(function(){
var temp = {someKey:"temp value", otherKey:"other value", fooKey:"some value"};
for (var key in temp) {
alert('<option value=' + key + '>' + temp[key] + '</option>');
}
});
I have benchmarked these various technics under Python 3.7.0 (IPython).
c
is known): pre-compiled regex.s.partition(c)[0]
.c
may not be in s
): partition, split.import string, random, re
SYMBOLS = string.ascii_uppercase + string.digits
SIZE = 100
def create_test_set(string_length):
for _ in range(SIZE):
random_string = ''.join(random.choices(SYMBOLS, k=string_length))
yield (random.choice(random_string), random_string)
for string_length in (2**4, 2**8, 2**16, 2**32):
print("\nString length:", string_length)
print(" regex (compiled):", end=" ")
test_set_for_regex = ((re.compile("(.*?)" + c).match, s) for (c, s) in test_set)
%timeit [re_match(s).group() for (re_match, s) in test_set_for_regex]
test_set = list(create_test_set(16))
print(" partition: ", end=" ")
%timeit [s.partition(c)[0] for (c, s) in test_set]
print(" index: ", end=" ")
%timeit [s[:s.index(c)] for (c, s) in test_set]
print(" split (limited): ", end=" ")
%timeit [s.split(c, 1)[0] for (c, s) in test_set]
print(" split: ", end=" ")
%timeit [s.split(c)[0] for (c, s) in test_set]
print(" regex: ", end=" ")
%timeit [re.match("(.*?)" + c, s).group() for (c, s) in test_set]
String length: 16
regex (compiled): 156 ns ± 4.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
partition: 19.3 µs ± 430 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
index: 26.1 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
split (limited): 26.8 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
split: 26.3 µs ± 835 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
regex: 128 µs ± 4.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
String length: 256
regex (compiled): 167 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
partition: 20.9 µs ± 694 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
index: 28.6 µs ± 2.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
split (limited): 27.4 µs ± 979 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
split: 31.5 µs ± 4.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
regex: 148 µs ± 7.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
String length: 65536
regex (compiled): 173 ns ± 3.95 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
partition: 20.9 µs ± 613 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
index: 27.7 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
split (limited): 27.2 µs ± 796 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
split: 26.5 µs ± 377 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
regex: 128 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
String length: 4294967296
regex (compiled): 165 ns ± 1.2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
partition: 19.9 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
index: 27.7 µs ± 571 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
split (limited): 26.1 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
split: 28.1 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
regex: 137 µs ± 6.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In XCode 10 (and up) use Option + Command + Slash (that is ? + ? + /)
to write a beautiful comment for your function or class like below:
Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of IPython’s specific magic and use
matplotlib.pyplot.ion()/matplotlib.pyplot.ioff()
which have the advantages of working outside of IPython as well.
In this case, to validate Date (DD-MM-YYYY) or (DD/MM/YYYY), with a year between 1900 and 2099,like this with month and Days validation
if (!Regex.Match(txtDob.Text, @"^(0[1-9]|1[0-9]|2[0-9]|3[0,1])([/+-])(0[1-9]|1[0-2])([/+-])(19|20)[0-9]{2}$").Success)
{
MessageBox.Show("InValid Date of Birth");
txtDob.Focus();
}
In pycharm 2019.2, you can simply do this to run all tests:
For a higher integration of pytest into pycharm, see https://www.jetbrains.com/help/pycharm/pytest.html
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
GRANT
s on different objects are separate. GRANT
ing on a database doesn't GRANT
rights to the schema within. Similiarly, GRANT
ing on a schema doesn't grant rights on the tables within.
If you have rights to SELECT
from a table, but not the right to see it in the schema that contains it then you can't access the table.
The rights tests are done in order:
Do you have `USAGE` on the schema?
No: Reject access.
Yes: Do you also have the appropriate rights on the table?
No: Reject access.
Yes: Check column privileges.
Your confusion may arise from the fact that the public
schema has a default GRANT
of all rights to the role public
, which every user/group is a member of. So everyone already has usage on that schema.
The phrase:
(assuming that the objects' own privilege requirements are also met)
Is saying that you must have USAGE
on a schema to use objects within it, but having USAGE
on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.
It's like a directory tree. If you create a directory somedir
with file somefile
within it then set it so that only your own user can access the directory or the file (mode rwx------
on the dir, mode rw-------
on the file) then nobody else can list the directory to see that the file exists.
If you were to grant world-read rights on the file (mode rw-r--r--
) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.
If you instead set rwx-r-xr-x
on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.
You need to set both permissions for people to actually be able to view the file.
Same thing in Pg. You need both schema USAGE
rights and object rights to perform an action on an object, like SELECT
from a table.
(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT
ing from pg_class
directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
It's possible that the modules are installed, but your PHP.ini still points to an old directory.
Check the contents of /usr/lib/php/extensions. In mine, there were two directories: no-debug-non-zts-20060613 and no-debug-non-zts-20060613. Around line 428 of your php.ini, change:
extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20060613"
to
extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20090626"
Then restart apache. This should resolve the issue.
You need to create folders inside "framework". Please Follow these steps:
cd storage/
mkdir -p framework/{sessions,views,cache}
You also need to set permissions to allow Laravel to write data in this directory.
chmod -R 775 framework
chown -R www-data:www-data framework
this is the best source:
http://www.sommarskog.se/arrays-in-sql.html
create a split function using the link, and use it like:
DELETE YourTable
FROM YourTable d
LEFT OUTER JOIN dbo.splitFunction(@Parameter) s ON d.ID=s.Value
WHERE s.Value IS NULL
I prefer the number table approach
This is code based on the above link that should do it for you...
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
CREATE TABLE Numbers
(Number int NOT NULL,
CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
SET @x=@x+1
INSERT INTO Numbers VALUES (@x)
END
use this function to split your string, which does not loop and is very fast:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
/**
Takes the given @List string and splits it apart based on the given @SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.
Returns a table, one row per item in the list, with a column name "ListValue"
EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')
returns:
ListValue
-----------
1
12
123
1234
54321
6
A
*
|||
B
(10 row(s) affected)
**/
----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO @ParsedList
(ListValue)
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT @SplitOn + @List + @SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = @SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
RETURN
END --Function FN_ListToTable
you can use this function as a table in a join:
SELECT
Col1, COl2, Col3...
FROM YourTable
INNER JOIN dbo.FN_ListToTable(',',@YourString) s ON YourTable.ID = s.ListValue
here is your delete:
DELETE YourTable
FROM YourTable d
LEFT OUTER JOIN dbo.FN_ListToTable(',',@Parameter) s ON d.ID=s.ListValue
WHERE s.ListValue IS NULL
I think your port is probably open, but you don't have anything that listens on it.
The Apple Mac OS X operating system has SSH installed by default but the SSH daemon is not enabled. This means you can’t login remotely or do remote copies until you enable it.
To enable it, go to ‘System Preferences’. Under ‘Internet & Networking’ there is a ‘Sharing’ icon. Run that. In the list that appears, check the ‘Remote Login’ option. In OS X Yosemite and up, there is no longer an 'Internet & Networking' menu; it was moved to Accounts. The Sharing menu now has its own icon on the main System Preferences menu. (thx @AstroCB)
This starts the SSH daemon immediately and you can remotely login using your username. The ‘Sharing’ window shows at the bottom the name and IP address to use. You can also find this out using ‘whoami’ and ‘ifconfig’ from the Terminal application.
These instructions are copied from Enable SSH in Mac OS X, but I wanted to make sure they won't go away and to provide quick access.
I'm using a ajax post to run a delete method (happens to be from a visjs timeline but that's not relelvant). This is what I sis:
This is my Index.cshtml
@Scripts.Render("~/bundles/schedule")
@Styles.Render("~/bundles/visjs")
@Html.AntiForgeryToken()
<!-- div to attach schedule to -->
<div id='schedule'></div>
<!-- div to attach popups to -->
<div id='dialog-popup'></div>
All I added here was @Html.AntiForgeryToken()
to make the token appear in the page
Then in my ajax post I used:
$.ajax(
{
type: 'POST',
url: '/ScheduleWorks/Delete/' + item.id,
data: {
'__RequestVerificationToken':
$("input[name='__RequestVerificationToken']").val()
}
}
);
Which adds the token value, scraped off the page, to the fields posted
Before this I tried putting the value in the headers but I got the same error
Feel free to post improvements. This certainly seems to be a simple approach that I can understand
If you send a PHP array into a function that expects a string like: echo
or print
, then the PHP interpreter will convert your array to the literal string Array
, throw this Notice and keep going. For example:
php> print(array(1,2,3))
PHP Notice: Array to string conversion in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array
In this case, the function print
dumps the literal string: Array
to stdout and then logs the Notice to stderr and keeps going.
Another example in a PHP script:
<?php
$stuff = array(1,2,3);
print $stuff; //PHP Notice: Array to string conversion in yourfile on line 3
?>
$stuff = array(1,2,3);
foreach ($stuff as $value) {
echo $value, "\n";
}
Prints:
1
2
3
Or along with array keys
$stuff = array('name' => 'Joe', 'email' => '[email protected]');
foreach ($stuff as $key => $value) {
echo "$key: $value\n";
}
Prints:
name: Joe
email: [email protected]
Note that array elements could be arrays as well. In this case either use foreach
again or access this inner array elements using array syntax, e.g. $row['name']
In case it's just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:
<?php
$stuff = array(1,2,3);
print implode(", ", $stuff); //prints 1, 2, 3
print join(',', $stuff); //prints 1,2,3
In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode
$stuff = array('name' => 'Joe', 'email' => '[email protected]');
print json_encode($stuff);
Prints
{"name":"Joe","email":"[email protected]"}
If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose
examples
$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);
Prints:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
array(3) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(5)
}
Test: http://jsfiddle.net/brynner/hkwhaqsj/6/
HTML
<div class="input-group-btn select" id="select1">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><span class="selected">One</span> <span class="caret"></span></button>
<ul class="dropdown-menu option" role="menu">
<li id="1"><a href="#">One</a></li>
<li id="2"><a href="#">Two</a></li>
</ul>
</div>
jQuery
$('body').on('click','.option li',function(){
var i = $(this).parents('.select').attr('id');
var v = $(this).children().text();
var o = $(this).attr('id');
$('#'+i+' .selected').attr('id',o);
$('#'+i+' .selected').text(v);
});
CSS
.select button {width:100%; text-align:left;}
.select .caret {position:absolute; right:10px; margin-top:10px;}
.select:last-child>.btn {border-top-left-radius:5px; border-bottom-left-radius:5px;}
.selected {padding-right:10px;}
.option {width:100%;}
Yes, T-SQL can feel extremely primitive at times, and it is things like these that often times push me to doing a lot of my logic in my language of choice (such as C#).
However, when you absolutely need to do some of these things in SQL for performance reasons, then your best bet is to create functions to house these "algorithms."
Take a look at this article. He offers up quite a few handy SQL functions along these lines that I think will help you.
http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx
Wow you're close. Edits in comments:
function add(type) {_x000D_
//Create an input type dynamically. _x000D_
var element = document.createElement("input");_x000D_
//Assign different attributes to the element. _x000D_
element.type = type;_x000D_
element.value = type; // Really? You want the default value to be the type string?_x000D_
element.name = type; // And the name too?_x000D_
element.onclick = function() { // Note this is a function_x000D_
alert("blabla");_x000D_
};_x000D_
_x000D_
var foo = document.getElementById("fooBar");_x000D_
//Append the element in page (in span). _x000D_
foo.appendChild(element);_x000D_
}_x000D_
document.getElementById("btnAdd").onclick = function() {_x000D_
add("text");_x000D_
};
_x000D_
<input type="button" id="btnAdd" value="Add Text Field">_x000D_
<p id="fooBar">Fields:</p>
_x000D_
Now, instead of setting the onclick
property of the element, which is called "DOM0 event handling," you might consider using addEventListener
(on most browsers) or attachEvent
(on all but very recent Microsoft browsers) — you'll have to detect and handle both cases — as that form, called "DOM2 event handling," has more flexibility. But if you don't need multiple handlers and such, the old DOM0 way works fine.
Separately from the above: You might consider using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over browsers differences like the addEventListener
/ attachEvent
thing, provide useful utility features, and various other things. Obviously there's nothing a library can do that you can't do without one, as the libraries are just JavaScript code. But when you use a good library with a broad user base, you get the benefit of a huge amount of work already done by other people dealing with those browsers differences, etc.
The SweetAlert repo seems to be unmaintained. There's a bunch of Pull Requests without any replies, the last merged pull request was on Nov 9, 2014.
I created SweetAlert2 with HTML support in modal and some other options for customization modal window - width, padding, Esc button behavior, etc.
Swal.fire({
title: "<i>Title</i>",
html: "Testno sporocilo za objekt: <b>test</b>",
confirmButtonText: "V <u>redu</u>",
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
_x000D_
You can use readlink
on /proc/self/fd/NNN
where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat
the filename given and fstat
the fd you have, and make sure st_dev
and st_ino
are the same.
Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]
. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.
If you can't close windows that aren't opened by the script, then you can destroy your page using this code:
document.getElementsByTagName ('html') [0] .remove ();
Include below dependency in your pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>{spring-version}</version>
</dependency>
The problem is that your REGX pattern will only match the input "0-9".
To meet your requirement (0-9999999), you should rewrite your regx pattern:
ng-pattern="/^[0-9]{1,7}$/"
My example:
HTML:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="price" name="price_field"
ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<span ng-show="myForm.price_field.$error.required">This field is required!</span>
<input type="submit" value="submit"/>
</form>
</div>
JS:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
Here is a jsFiddle demo.
The clearest explanation I found was not in the current 2.4 apache docs, but in version 2.0.
# /abc/def/.htaccess -- per-dir config file for directory /abc/def
# Remember: /abc/def is the physical path of /xyz, i.e., the server
# has a 'Alias /xyz /abc/def' directive e.g.
RewriteEngine On
# let the server know that we were reached via /xyz and not
# via the physical path prefix /abc/def
RewriteBase /xyz
How does it work? For you apache hackers, this 2.0 doc goes on to give "detailed information about the internal processing steps."
Lesson learned: While we need to be familiar with "current," gems can be found in the annals.
CORS works absolutely fine in Microsoft.AspNet.WebApi.Cors
version 5.2.2. The following steps configured CORS like a charm for me:
Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2"
// run from Package manager consoleIn Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS
GlobalConfiguration.Configure(WebApiConfig.Register);
In the WebApiConfig
Register method, have the following code:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
}
In the web.config, the following handler must be the first one in the pipeline:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
In the controller derived from ApiController
, add the EnableCorsAttribute
:
[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController
That should set you up nicely!
I just had the same issue and was able to solve it by installing Service Pack 1.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
A pure Python equivalent for string comparisons would be:
def less(string1, string2):
# Compare character by character
for idx in range(min(len(string1), len(string2))):
# Get the "value" of the character
ordinal1, ordinal2 = ord(string1[idx]), ord(string2[idx])
# If the "value" is identical check the next characters
if ordinal1 == ordinal2:
continue
# It's not equal so we're finished at this index and can evaluate which is smaller.
else:
return ordinal1 < ordinal2
# We're out of characters and all were equal, so the result depends on the length
# of the strings.
return len(string1) < len(string2)
This function does the equivalent of the real method (Python 3.6 and Python 2.7) just a lot slower. Also note that the implementation isn't exactly "pythonic" and only works for <
comparisons. It's just to illustrate how it works. I haven't checked if it works like Pythons comparison for combined unicode characters.
A more general variant would be:
from operator import lt, gt
def compare(string1, string2, less=True):
op = lt if less else gt
for char1, char2 in zip(string1, string2):
ordinal1, ordinal2 = ord(char1), ord(char1)
if ordinal1 == ordinal2:
continue
else:
return op(ordinal1, ordinal2)
return op(len(string1), len(string2))
Try using the /
from the numeric keyboard.
Ctrl
+ /
in Chrome wasn't working for me, but when I used the /
(division symbol) from the numeric it worked.
I had a similar issue. The root cause was that the sending IP was not in the range of white-listed IPs on the receiving server. So, all requests for communication were killed by the receiving site.
you don't have to use regex. In your favourite language, split on spaces, go over the splitted words, check for cat and mat. eg in Python
>>> for line in open("file"):
... g=0;f=0
... s = line.split()
... for item in s:
... if item =="cat": f=1
... if item =="mat": g=1
... if (g,f)==(1,1): print "found: " ,line.rstrip()
found: The cat slept on the mat in front of the fire.
found: At 5:00 pm, I found the cat scratching the wool off the mat.
It's best if you judge on your own,
1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).
http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text
This Link is no more working so please watch this video for similar details Video
Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)
Some Variation: Some user find plugins useful for PHP coders on that
http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html
although, there are many plugins for Notepad Plus Plus ..
I am not sure of your requirements, nor I am promoter of either of these editors :)
So, judge on basis of your requirements, this should satisfy you query...
Yes we can add that both are evolving and changing fast..
$str = preg_replace('/\?\//', '?', $str);
Edit: See CMS' answer. It's late, I should know better.
You have to use shell=True in subprocess and no shlex.split:
def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout
subprocess_cmd('echo a; echo b')
returns:
a
b
Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.
There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:
{<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}
Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.
The protocol of a socket is set when a socket is created with the socket()
function. The source address and port are set with the bind()
function. The destination address and port are set with the connect()
function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.
If you explicitly bind a socket, it is possible to bind it to port 0
, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0
in case of IPv4 and ::
in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.
By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA
to ipA:portA
and socketB
to ipB:portB
is always possible if ipA != ipB
holds true, even when portA == portB
. E.g. socketA
belongs to a FTP server program and is bound to 192.168.0.1:21
and socketB
belongs to another FTP server program and is bound to 10.0.0.1:21
, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21
, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21
, regardless which specific IP address it tries to bind to, as 0.0.0.0
conflicts with all existing local IP addresses.
Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.
If SO_REUSEADDR
is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR
mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.
Without SO_REUSEADDR
, binding socketA
to 0.0.0.0:21
and then binding socketB
to 192.168.0.1:21
will fail (with error EADDRINUSE
), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1
, too. With SO_REUSEADDR
it will succeed, since 0.0.0.0
and 192.168.0.1
are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA
and socketB
are bound; without SO_REUSEADDR
it will always fail, with SO_REUSEADDR
it will always succeed.
To give you a better overview, let's make a table here and list all possible combinations:
SO_REUSEADDR socketA socketB Result --------------------------------------------------------------------- ON/OFF 192.168.0.1:21 192.168.0.1:21 Error (EADDRINUSE) ON/OFF 192.168.0.1:21 10.0.0.1:21 OK ON/OFF 10.0.0.1:21 192.168.0.1:21 OK OFF 0.0.0.0:21 192.168.1.0:21 Error (EADDRINUSE) OFF 192.168.1.0:21 0.0.0.0:21 Error (EADDRINUSE) ON 0.0.0.0:21 192.168.1.0:21 OK ON 192.168.1.0:21 0.0.0.0:21 OK ON/OFF 0.0.0.0:21 0.0.0.0:21 Error (EADDRINUSE)
The table above assumes that socketA
has already been successfully bound to the address given for socketA
, then socketB
is created, either gets SO_REUSEADDR
set or not, and finally is bound to the address given for socketB
. Result
is the result of the bind operation for socketB
. If the first column says ON/OFF
, the value of SO_REUSEADDR
is irrelevant to the result.
Okay, SO_REUSEADDR
has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR
in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.
A socket has a send buffer and if a call to the send()
function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send()
call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT
when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.
At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER
which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER
, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit()
(pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.
The question is, how does the system treat a socket in state TIME_WAIT
? If SO_REUSEADDR
is not set, a socket in state TIME_WAIT
is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR
is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT
is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT
state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.
There is one final thing you should know about SO_REUSEADDR
. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT
state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR
flag of the socket fed into the bind()
call, for all other sockets inspected, this flag is not even looked at.
SO_REUSEPORT
is what most people would expect SO_REUSEADDR
to be. Basically, SO_REUSEPORT
allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT
set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT
set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT
set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR
the code handling SO_REUSEPORT
will not only verify that the currently bound socket has SO_REUSEPORT
set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT
set when it was bound.
SO_REUSEPORT
does not imply SO_REUSEADDR
. This means if a socket did not have SO_REUSEPORT
set when it was bound and another socket has SO_REUSEPORT
set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT
state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT
state requires either SO_REUSEADDR
to be set on that socket or SO_REUSEPORT
must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT
and SO_REUSEADDR
, on a socket.
There is not much more to say about SO_REUSEPORT
other than that it was added later than SO_REUSEADDR
, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.
Most people know that bind()
may fail with the error EADDRINUSE
, however, when you start playing around with address reuse, you may run into the strange situation that connect()
fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?
As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.
So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect()
will actually fail with the error EADDRINUSE
for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.
Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.
The meaning of SO_REUSEADDR
changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR
behaves exactly as SO_REUSEPORT
for unicast addresses. Actually, the code treats SO_REUSEADDR
and SO_REUSEPORT
identically for multicast addresses, that means you could say that SO_REUSEADDR
implies SO_REUSEPORT
for all multicast addresses and the other way round.
All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.
At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.
iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.
Prior to Linux 3.9, only the option SO_REUSEADDR
existed. This option behaves generally the same as in BSD with two important exceptions:
As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR
option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR
set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR
. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.
The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT
in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT
prior to 3.9, the behavior of SO_REUSEADDR
was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.
Linux 3.9 added the option SO_REUSEPORT
to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.
Yet, there are still two differences to SO_REUSEPORT
on other systems:
To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND
/SO_EXCLUSIVEADDRUSE
flags.
Additionally the kernel performs some "special magic" for SO_REUSEPORT
sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()
) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT
to get a very inexpensive load balancing.
Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.
Windows only knows the SO_REUSEADDR
option, there is no SO_REUSEPORT
. Setting SO_REUSEADDR
on a socket in Windows behaves like setting SO_REUSEPORT
and SO_REUSEADDR
on a socket in BSD, with one exception:
Prior to Windows 2003, a socket with SO_REUSEADDR
could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!
Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE
. Setting SO_EXCLUSIVEADDRUSE
on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR
set.
This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind()
calls are made by the same user, and the third one when the bind()
calls are made by different users.
Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR
, there is no SO_REUSEPORT
. The SO_REUSEADDR
behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT
in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.
Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND
. If this option is set on a socket prior to binding it, setting SO_REUSEADDR
on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA
is bound to a wildcard address and socketB
has SO_REUSEADDR
enabled and is bound to a non-wildcard address and the same port as socketA
, this bind will normally succeed, unless socketA
had SO_EXCLBIND
enabled, in which case it will fail regardless the SO_REUSEADDR
flag of socketB
.
In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.
All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h
and stdbool.h
; e.g. gcc
supported both long before offering full C99 support).
All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".
It tests all possible combinations you can think of:
SO_REUSEADDR
set on socket1, socket2, or both socketsSO_REUSEPORT
set on socket1, socket2, or both sockets0.0.0.0
(wildcard), 127.0.0.1
(specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3
in all tests)and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT
, in which case this option is simply not tested.
What the program cannot easily test is how SO_REUSEADDR
acts on sockets in TIME_WAIT
state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.
Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.
This is how I usually get current logged in user and their id in my templates.
<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is : {{user.id|default: Unknown}} </p>
The OP needed to cast as string outside the {% set ... %}
.
But if that not your case you can do:
{% set curYear = 2013 | string() %}
Note that you need the parenthesis on that jinja filter.
If you're concatenating 2 variables, you can also use the ~
custom operator.
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,
$this->db->where_in()
ex : $this->db->where_in('id', array('1','2','3'));
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate
$this->db->or_where_in()
ex : $this->db->where_in('id', array('1','2','3'));
You can actually have all the code in the aspx page. As explained here.
Sample from here:
<%@ Language=C# %>
<HTML>
<script runat="server" language="C#">
void MyButton_OnClick(Object sender, EventArgs e)
{
MyLabel.Text = MyTextbox.Text.ToString();
}
</script>
<body>
<form id="MyForm" runat="server">
<asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox>
<asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button>
<asp:label id="MyLabel" runat="server"></asp:label>
</form>
</body>
</HTML>
You have to restart Terminal after installing the gem. Or you can simply open a new tab Terminal to fix.
long/int to the byte array looks like exact purpose of struct.pack
. For long integers that exceed 4(8) bytes, you can come up with something like the next:
>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
parts.append(i & limit)
i >>= 32
>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'
>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L
You can use the following:
return Redirect::back()->withInput(Input::all());
If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.
Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests
:
return redirect()->to($this->getRedirectUrl()) ->withInput($request->input()) ->withErrors($errors, $this->errorBag());
What is
<=>
( The 'Spaceship' Operator )
<=>
$b - 0 if $a == $b
- -1 if $a < $b
- 1 if $a > $b
- Return 0 if values on either side are equal
- Return 1 if value on the left is greater
- Return -1 if the value on the right is greater
Example:
//Comparing Integers
echo 1 <=> 1; //ouputs 0
echo 3 <=> 4; //outputs -1
echo 4 <=> 3; //outputs 1
//String Comparison
echo "x" <=> "x"; // 0
echo "x" <=> "y"; //-1
echo "y" <=> "x"; //1
MORE:
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1
// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0
This has a good general description: https://gephi.wordpress.com/tag/maven/
Let me make a few statement that can put the difference in focus:
We migrated our code base from Ant to Maven
All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.
Basic functionalities of a repository manager like Sonatype are:
As ant31 already pointed out you can use the synchronize
module to this. By default, the module transfers files between the control machine and the current remote host (inventory_host
), however that can be changed using the task's delegate_to
parameter (it's important to note that this is a parameter of the task, not of the module).
You can place the task on either ServerA
or ServerB
, but you have to adjust the direction of the transfer accordingly (using the mode
parameter of synchronize
).
Placing the task on ServerB
- hosts: ServerB
tasks:
- name: Transfer file from ServerA to ServerB
synchronize:
src: /path/on/server_a
dest: /path/on/server_b
delegate_to: ServerA
This uses the default mode: push
, so the file gets transferred from the delegate (ServerA
) to the current remote (ServerB
).
This might sound like strange, since the task has been placed on ServerB
(via hosts: ServerB
). However, one has to keep in mind that the task is actually executed on the delegated host, which in this case is ServerA
. So pushing (from ServerA
to ServerB
) is indeed the correct direction. Also remember that we cannot simply choose not to delegate at all, since that would mean that the transfer happens between the control machine and ServerB
.
Placing the task on ServerA
- hosts: ServerA
tasks:
- name: Transfer file from ServerA to ServerB
synchronize:
src: /path/on/server_a
dest: /path/on/server_b
mode: pull
delegate_to: ServerB
This uses mode: pull
to invert the transfer direction. Again, keep in mind that the task is actually executed on ServerB
, so pulling is the right choice.