You got the first part right:
Yes mapStateToProps
has the Store state as an argument/param (provided by react-redux::connect
) and its used to link the component with certain part of the store state.
By linking I mean the object returned by mapStateToProps
will be provided at construction time as props and any subsequent change will be available through componentWillReceiveProps
.
If you know the Observer design pattern it's exactly that or small variation of it.
An example would help make things clearer:
import React, {
Component,
} from 'react-native';
class ItemsContainer extends Component {
constructor(props) {
super(props);
this.state = {
items: props.items, //provided by connect@mapStateToProps
filteredItems: this.filterItems(props.items, props.filters),
};
}
componentWillReceiveProps(nextProps) {
this.setState({
filteredItems: this.filterItems(this.state.items, nextProps.filters),
});
}
filterItems = (items, filters) => { /* return filtered list */ }
render() {
return (
<View>
// display the filtered items
</View>
);
}
}
module.exports = connect(
//mapStateToProps,
(state) => ({
items: state.App.Items.List,
filters: state.App.Items.Filters,
//the State.App & state.App.Items.List/Filters are reducers used as an example.
})
// mapDispatchToProps, that's another subject
)(ItemsContainer);
There can be another react component called itemsFilters
that handle the display and persisting the filter state into Redux Store state, the Demo component is "listening" or "subscribed" to Redux Store state filters so whenever filters store state changes (with the help of filtersComponent
) react-redux detect that there was a change and notify or "publish" all the listening/subscribed components by sending the changes to their componentWillReceiveProps
which in this example will trigger a refilter of the items and refresh the display due to the fact that react state has changed.
Let me know if the example is confusing or not clear enough to provide a better explanation.
As for: This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store.
I didn't get the question, but just know that the react state (this.setState
) is totally different from the Redux Store state!
The react state is used to handle the redraw and behavior of the react component. The react state is contained to the component exclusively.
The Redux Store state is a combination of Redux reducers states, each is responsible of managing a small portion app logic. Those reducers attributes can be accessed with the help of react-redux::connect@mapStateToProps
by any component! Which make the Redux store state accessible app wide while component state is exclusive to itself.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
It is a very murky distinction, and in fact generally not a property of a language itself, but rather of the program you are using to execute code in that language.
However, most languages are used primarily in one form or the other, and yes, Java is essentially always compiled, while javascript is essentially always interpreted.
To compile source code is to run a program on it that generates a binary, executable file that, when run, has the behavior defined by the source. For instance, javac compiles human-readbale .java files into machine-readable .class files.
To interpret source code is run a program on it that produces the defined behavior right away, without generating an intermediary file. For instance, when your web browser loads stackoverflow.com, it interprets a bunch of javascript (which you can look at by viewing the page source) and produces lots of the nice effects these pages have - for instance, upvoting, or the little notifier bars across the top.
with open('path/to/file') as infile: # try open('...', 'rb') as well
answer = [line.strip().split(',') for line in infile]
If you want the numbers as int
s:
with open('path/to/file') as infile:
answer = [[int(i) for i in line.strip().split(',')] for line in infile]
See the answer at: http://omappedia.org/wiki/Android_eMMC_Booting#Modifying_.IMG_Files
First you need to "uncompress" userdata.img
with simg2img
, then you can mount it via the loop device.
I had the same problem and trouble getting it to work on all browsers.
So this is the best font stack for Helvetica Neue Condensed Bold I could find:
font-family: "HelveticaNeue-CondensedBold", "HelveticaNeueBoldCondensed", "HelveticaNeue-Bold-Condensed", "Helvetica Neue Bold Condensed", "HelveticaNeueBold", "HelveticaNeue-Bold", "Helvetica Neue Bold", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosCnBold', "Helvetica", "Tahoma", "Geneva", "Arial Narrow", "Arial", sans-serif; font-weight:600; font-stretch:condensed;
Even more stacks to find at:
http://rachaelmoore.name/posts/design/css/web-safe-helvetica-font-stack/
import binascii
hexa_input = input('Enter hex String to convert to Binary: ')
pad_bits=len(hexa_input)*4
Integer_output=int(hexa_input,16)
Binary_output= bin(Integer_output)[2:]. zfill(pad_bits)
print(Binary_output)
"""zfill(x) i.e. x no of 0 s to be padded left - Integers will overwrite 0 s
starting from right side but remaining 0 s will display till quantity x
[y:] where y is no of output chars which need to destroy starting from left"""
"Only conventions? Or is there more behind the underscore prefix?"
Apart from privacy conventions, I also wanted to help bring awareness that the underscore prefix is also used for arguments that are dependent on independent arguments, specifically in URI anchor maps. Dependent keys always point to a map.
Example ( from https://github.com/mmikowski/urianchor ) :
$.uriAnchor.setAnchor({
page : 'profile',
_page : {
uname : 'wendy',
online : 'today'
}
});
The URI anchor on the browser search field is changed to:
\#!page=profile:uname,wendy|online,today
This is a convention used to drive an application state based on hash changes.
try to ad the following in your CSS:
body, html{
padding:0;
margin:0;
}
In the XML file set the android:checkedButton
field in your RadioGroup
, with the id of your default RadioButton
:
<RadioGroup
....
android:checkedButton="@+id/button_1">
<RadioButton
android:id="@+id/button_1"
...../>
<RadioButton
android:id="@+id/button_2"
...../>
<RadioButton
android:id="@+id/button_3"
...../>
</RadioGroup>
I know it is an old question but still wanted to share how i achieved this. Assuming state in constructor looks like this:
constructor(props) {
super(props);
this.state = {
loading: false,
user: {
email: ""
},
organization: {
name: ""
}
};
this.handleChange = this.handleChange.bind(this);
}
My handleChange
function is like this:
handleChange(e) {
const names = e.target.name.split(".");
const value = e.target.type === "checkbox" ? e.target.checked : e.target.value;
this.setState((state) => {
state[names[0]][names[1]] = value;
return {[names[0]]: state[names[0]]};
});
}
And make sure you name inputs accordingly:
<input
type="text"
name="user.email"
onChange={this.handleChange}
value={this.state.user.firstName}
placeholder="Email Address"
/>
<input
type="text"
name="organization.name"
onChange={this.handleChange}
value={this.state.organization.name}
placeholder="Organization Name"
/>
I have used the extremely handy app_offline.htm trick to shut down/update sites in the past without any issues.
Be sure that you are actually placing the "app_offline.htm" file in the "root" of the website that you have configured within IIS.
Also ensure that the file is named exactly as it should be: app_offline.htm
Other than that, there should be no other changes to IIS that you should need to make since the processing of this file (with this specific name) is handled by the ASP.NET runtime rather than IIS itself (for IIS v6).
Be aware, however, that although placing this file in the root of your site will force the application to "shut down" and display the content of the "app_offline.htm" file itself, any existing requests will still get the real website served up to them. Only new requests will get the app_offline.htm content.
If you're still having issues, try the following links for further info:
App_Offline.htm and working around the "IE Friendly Errors" feature
Will app_offline.htm stop current requests or just new requests?
It's simple:
array = []
will set array
to be an empty list. (They're called lists in Python, by the way, not arrays)
If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.
It seems that it does not matter what timezone is on the server as long as you have the time set right for the current timezone, know the timezone of the datetime columns that you store, and are aware of the issues with daylight savings time.
On the other hand if you have control of the timezones of the servers you work with then you can have everything set to UTC internally and never worry about timezones and DST.
Here are some notes I collected of how to work with timezones as a form of cheatsheet for myself and others which might influence what timezone the person will choose for his/her server and how he/she will store date and time.
Notes:
GMT confuses seconds, which is why UTC was invented.
Warning! different regional timezones might produce the same datetime value due to daylight savings time
Internally a MySQL timestamp column is stored as UTC but when selecting a date MySQL will automatically convert it to the current session timezone.
When storing a date in a timestamp, MySQL will assume that the date is in the current session timezone and convert it to UTC for storage.
no matter what timezone the current MySQL session is in:
SELECT
CONVERT_TZ(`timestamp_field`, @@session.time_zone, '+00:00') AS `utc_datetime`
FROM `table_name`
You can also set the sever or global or current session timezone to UTC and then select the timestamp like so:
SELECT `timestamp_field` FROM `table_name`
SELECT UTC_TIMESTAMP();
SELECT UTC_TIMESTAMP;
SELECT CONVERT_TZ(NOW(), @@session.time_zone, '+00:00');
Example result: 2015-03-24 17:02:41
SELECT NOW();
SELECT CURRENT_TIMESTAMP;
SELECT CURRENT_TIMESTAMP();
SELECT @@system_time_zone;
Returns "MSK" or "+04:00" for Moscow time for example, there is (or was) a MySQL bug where if set to a numerical offset it would not adjust the Daylight savings time
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
It will return 02:00:00 if your timezone is +2:00.
SELECT UNIX_TIMESTAMP(NOW());
SELECT UNIX_TIMESTAMP();
SELECT UNIX_TIMESTAMP(`timestamp`) FROM `table_name`
SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`
SELECT FROM_UNIXTIME(`unix_timestamp_int`) FROM `table_name`
SELECT CONVERT_TZ(FROM_UNIXTIME(`unix_timestamp_int`), @@session.time_zone, '+00:00')
FROM `table_name`
SELECT DATE_ADD('1970-01-01 00:00:00',INTERVAL -957632400 SECOND)
Note: A timezone can be set in 2 formats:
Named time zones can be used only if the time zone information tables in the mysql database have been created and populated.
default_time_zone='+00:00'
or
timezone='UTC'
To see what value they are set to
SELECT @@global.time_zone;
To set a value for it use either one:
SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';
SET @@global.time_zone='+00:00';
SELECT @@session.time_zone;
To set it use either one:
SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET @@session.time_zone = "+00:00";
both "@@global.time_zone variable" and "@@session.time_zone variable" might return "SYSTEM" which means that they use the timezone set in "my.cnf".
For timezone names to work (even for default-time-zone) you must setup your timezone information tables need to be populated: http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html
Note: you can not do this as it will return NULL:
SELECT
CONVERT_TZ(`timestamp_field`, TIMEDIFF(NOW(), UTC_TIMESTAMP), '+00:00') AS `utc_datetime`
FROM `table_name`
For CONVERT_TZ
to work, you need the timezone tables to be populated
SELECT * FROM mysql.`time_zone` ;
SELECT * FROM mysql.`time_zone_leap_second` ;
SELECT * FROM mysql.`time_zone_name` ;
SELECT * FROM mysql.`time_zone_transition` ;
SELECT * FROM mysql.`time_zone_transition_type` ;
If they are empty, then fill them up by running this command
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
if this command gives you the error "data too long for column 'abbreviation' at row 1", then it might be caused by a NULL character being appended at the end of the timezone abbreviation
the fix being to run this
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
(if the above gives error "data too long for column 'abbreviation' at row 1")
mysql_tzinfo_to_sql /usr/share/zoneinfo > /tmp/zut.sql
echo "SET SESSION SQL_MODE = '';" > /tmp/mysql_tzinfo_to.sql
cat /tmp/zut.sql >> /tmp/mysql_tzinfo_to.sql
mysql --defaults-file=/etc/mysql/my.cnf --user=verifiedscratch -p mysql < /tmp/mysql_tzinfo_to.sql
(make sure your servers dst rules are up to date zdump -v Europe/Moscow | grep 2011
https://chrisjean.com/updating-daylight-saving-time-on-linux/)
SELECT
tzn.Name AS tz_name,
tztt.Abbreviation AS tz_abbr,
tztt.Is_DST AS is_dst,
tztt.`Offset` AS `offset`,
DATE_ADD('1970-01-01 00:00:00',INTERVAL tzt.Transition_time SECOND) AS transition_date
FROM mysql.`time_zone_transition` tzt
INNER JOIN mysql.`time_zone_transition_type` tztt USING(Time_zone_id, Transition_type_id)
INNER JOIN mysql.`time_zone_name` tzn USING(Time_zone_id)
-- WHERE tzn.Name LIKE 'Europe/Moscow' -- Moscow has weird DST changes
ORDER BY tzt.Transition_time ASC
CONVERT_TZ
also applies any necessary DST changes based on the rules in the above tables and the date that you use.
Note:
According to the docs, the value you set for time_zone does not change, if you set it as "+01:00" for example, then the time_zone will be set as an offset from UTC, which does not follow DST, so it will stay the same all year round.
Only the named timezones will change time during daylight savings time.
Abbreviations like CET
will always be a winter time and CEST
will be summer time while +01:00 will always be UTC
time + 1 hour and both won't change with DST.
The system
timezone will be the timezone of the host machine where mysql is installed (unless mysql fails to determine it)
You can read more about working with DST here
related questions:
Sources:
If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:
With SQL Developer you should also find it without writing any query. Right click on your Connection/Propriety.
You should see the name on the left under something like "connection details" and should look like "Connectionname@servicename", or on the right, under the connection's details.
From my test (spring 3.0.5), @RequestMapping(value={"", "/"})
- only "/"
works, ""
does not. However I found out this works: @RequestMapping(value={"/", " * "})
, the " * "
matches anything, so it will be the default handler in case no others.
These are equivalent
char buf[10] = "";
char buf[10] = {0};
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
These are equivalent
char buf[10] = " ";
char buf[10] = {' '};
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
These are equivalent
char buf[10] = "a";
char buf[10] = {'a'};
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
The exact solution is;
$("#dialogDiv").dialog({ other options...,
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
Look at the File javadoc, the method createNewFile will create the file only if it doesn't exist, and will return a boolean to say if the file was created.
You may also use the exists() method:
int i = 0;
String filename = Integer.toString(i);
File f = new File(filename);
while (f.exists()) {
i++;
filename = Integer.toString(i);
f = new File(filename);
}
f.createNewFile();
System.out.println("File in use: " + f);
There is a PowerShell script at ratil.life/first-useful-powershell-script-putty-to-ssh-config which can convert the sessions to a format that can be used in .ssh/config
. It can also be found on GitHub.
This excerpt contains the main guts of the code, and will print the resulting config directly to stdout:
# Registry path to PuTTY configured profiles
$regPath = 'HKCU:\SOFTWARE\SimonTatham\PuTTY\Sessions'
# Iterate over each PuTTY profile
Get-ChildItem $regPath -Name | ForEach-Object {
# Check if SSH config
if (((Get-ItemProperty -Path "$regPath\$_").Protocol) -eq 'ssh') {
# Write the Host for easy SSH use
$host_nospace = $_.replace('%20', $SpaceChar)
$hostLine = "Host $host_nospace"
# Parse Hostname for special use cases (Bastion) to create SSH hostname
$puttyHostname = (Get-ItemProperty -Path "$regPath\$_").HostName
if ($puttyHostname -like '*@*') {
$sshHostname = $puttyHostname.split("@")[-1]
}
else { $sshHostname = $puttyHostname }
$hostnameLine = "`tHostName $sshHostname"
# Parse Hostname for special cases (Bastion) to create User
if ($puttyHostname -like '*@*') {
$sshUser = $puttyHostname.split("@")[0..($puttyHostname.split('@').length - 2)] -join '@'
}
else { $sshHostname = $puttyHostname }
$userLine = "`tUser $sshUser"
# Parse for Identity File
$puttyKeyfile = (Get-ItemProperty -Path "$regPath\$_").PublicKeyFile
if ($puttyKeyfile) {
$sshKeyfile = $puttyKeyfile.replace('\', '/')
if ($prefix) { $sshKeyfile = $sshKeyfile.replace('C:', $prefix) }
$identityLine = "`tIdentityFile $sshKeyfile"
}
# Parse Configured Tunnels
$puttyTunnels = (Get-ItemProperty -Path "$regPath\$_").PortForwardings
if ($puttyTunnels) {
$puttyTunnels.split() | ForEach-Object {
# First character denotes tunnel type
$tunnelType = $_.Substring(0,1)
# Digits follow tunnel type is local port
$tunnelPort = $_ -match '\d*\d(?==)' | Foreach {$Matches[0]}
# Text after '=' is the tunnel destination
$tunnelDest = $_.split('=')[1]
if ($tunnelType -eq 'D') {
$tunnelLine = "`tDynamicForward $tunnelPort $tunnelDest"
}
ElseIf ($tunnelType -eq 'R') {
$tunnelLine = "`tRemoteForward $tunnelPort $tunnelDest"
}
ElseIf ($tunnelType -eq 'L') {
$tunnelLine = "`tLocalForward $tunnelPort $tunnelDest"
}
}
# Parse if Forward Agent is required
$puttyAgent = (Get-ItemProperty -Path "$regPath\$_").AgentFwd
if ($puttyAgent -eq 1) { $agentLine = "`tForwardAgent yes" }
# Parse if non-default port
$puttyPort = (Get-ItemProperty -Path "$regPath\$_").PortNumber
if (-Not $puttyPort -eq 22) { $PortLine = "`tPort $puttyPort" }
}
# Build output string
$output = "$hostLine`n$hostnameLine`n$userLine`n$identityLine`n$tunnelLine`n$agentLine`n"
# Output to file if set, otherwise STDOUT
if ($outfile) { $output | Out-File $outfile -Append}
else { Write-Host $output }
}
}
Install sshpass using, apt-get install sshpass
then edit the script and put your linux machines IPs, usernames and password in respective order. After that run that script. Thats it ! This script will install VLC in all systems.
#!/bin/bash
SCRIPT="cd Desktop; pwd; echo -e 'PASSWORD' | sudo -S apt-get install vlc"
HOSTS=("192.168.1.121" "192.168.1.122" "192.168.1.123")
USERNAMES=("username1" "username2" "username3")
PASSWORDS=("password1" "password2" "password3")
for i in ${!HOSTS[*]} ; do
echo ${HOSTS[i]}
SCR=${SCRIPT/PASSWORD/${PASSWORDS[i]}}
sshpass -p ${PASSWORDS[i]} ssh -l ${USERNAMES[i]} ${HOSTS[i]} "${SCR}"
done
You've already stated why np.maximum
is different - it returns an array that is the element-wise maximum between two arrays.
As for np.amax
and np.max
: they both call the same function - np.max
is just an alias for np.amax
, and they compute the maximum of all elements in an array, or along an axis of an array.
In [1]: import numpy as np
In [2]: np.amax
Out[2]: <function numpy.core.fromnumeric.amax>
In [3]: np.max
Out[3]: <function numpy.core.fromnumeric.amax>
Try:
ORDER BY x_field='F', x_field='P', x_field='A', x_field='I'
You were on the right track, but by putting x_field only on the F value, the other 3 were treated as constants and not compared against anything in the dataset.
I had also faced same error when i was trying to call bootstrap modal from jquery. But this happens because we are using bootstrap modal and for this we need to attach one cdn bootstrap.min.js which is
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Hope this will help as I missed that when i was trying to call bootstrap modal from jQuery using
$('#button').on('click',function(){
$('#myModal').modal();
});
myModal
is the id of Bootstrap modal
and you have to give a click event to a button when you call click that button a pop up modal will be displayed.
Use JSON Simple,
http://code.google.com/p/json-simple/
Which has a small foot-print, no dependencies so it's perfect for Android.
You can do something like this,
Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;
I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\
. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version
(Determine installed PowerShell version) shows it's 2.0.
Another option is type $PSVersionTable
at the command prompt. If you are running v2.0, the output will be:
Name Value
---- -----
CLRVersion 2.0.50727.4927
BuildVersion 6.1.7600.16385
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
If you're running version 1.0, the variable doesn't exist and there will be no output.
Localization PowerShell version 1.0, 2.0, 3.0, 4.0:
I added a new environment variable ANDROID_HOME and pointed it to the SDK (C:\Program Files (x86)\Android\android-studio\sdk) that is inside the installation directory of Android Studio. (Environment variables are a part of windows; you access them through the advanced computer properties...google it for more info)
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
Here is a complete, very simple .Net solution that works in all versions of windows. Simply paste it into a new project, run it and try CTRL-C to view how it handles it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace TestTrapCtrlC{
public class Program{
static bool exitSystem = false;
#region Trap application termination
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;
enum CtrlType {
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static bool Handler(CtrlType sig) {
Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");
//do your cleanup here
Thread.Sleep(5000); //simulate some cleanup delay
Console.WriteLine("Cleanup complete");
//allow main to run off
exitSystem = true;
//shutdown right away so there are no lingering threads
Environment.Exit(-1);
return true;
}
#endregion
static void Main(string[] args) {
// Some biolerplate to react to close window event, CTRL-C, kill, etc
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
//start your multi threaded program here
Program p = new Program();
p.Start();
//hold the console so it doesn’t run off the end
while(!exitSystem) {
Thread.Sleep(500);
}
}
public void Start() {
// start a thread and start doing some processing
Console.WriteLine("Thread started, processing..");
}
}
}
isScrolledIntoView is a very needful function, so I tried it, it works for elements not heigher than the viewport, but if the element is bigger as the viewport it does not work. To fix this easily change the condition
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
to this:
return (docViewBottom >= elemTop && docViewTop <= elemBottom);
See demo here: http://jsfiddle.net/RRSmQ/
it doesn't, however, solve the problem, because on e.g. open SUSE Tumbleweed, custom source build is triggering the same 401 error on default web page, which is configured accordingly with Indexes and
Require all granted
class Program
{
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
}
If you are working in asp.net with razor, and you want to control multiple submit button event.then this answer will guide you. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
@{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
Running yarn on Windows Linux subsystem with Ubunto OS, error "running beyond virtual memory limits, Killing container" I resolved it by disabling virtual memory check in the file yarn-site.xml
<property> <name>yarn.nodemanager.vmem-check-enabled</name> <value>false</value> </property>
#printing the variable 'Total:' in a format that looks like this '9,348.237'
print ('Total:', '{:7,.3f}'.format(zum1))
where the '{:7,.3f}' es the number of spaces for formatting the number in this case is a million with 3 decimal points. Then you add the '.format(zum1). The zum1 is tha variable that has the big number for the sum of all number in my particular program. Variable can be anything that you decide to use.
public static void setSelectedValue(JComboBox comboBox, int value)
{
ComboItem item;
for (int i = 0; i < comboBox.getItemCount(); i++)
{
item = (ComboItem)comboBox.getItemAt(i);
if (item.getValue().equalsIgnoreCase(value))
{
comboBox.setSelectedIndex(i);
break;
}
}
}
Hope this help :)
In the case you need to force the reinstallation of pip itself you can do:
python -m pip install --upgrade --force-reinstall pip
This gives you the first few digits of the hash and they are unique enough to use as say a version number.
git rev-parse --short HEAD
We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST
some data to www.abc.com/blog
and with in milliseconds an other request will also go for the same resource i.e. www.abc.com/blog
from the same user. So it'll give the 409
error.
you can directly set boolean value equivalent to any string by System class and access it anywhere..
System.setProperty("n","false");
System.setProperty("y","true");
System.setProperty("yes","true");
System.setProperty("no","false");
System.out.println(Boolean.getBoolean("n")); //false
System.out.println(Boolean.getBoolean("y")); //true
System.out.println(Boolean.getBoolean("no")); //false
System.out.println(Boolean.getBoolean("yes")); //true
I remember from my student days that it was said it's mathematically provable that you can do anything in code without a goto (i.e. there is no situation where goto is the only answer). So, I never use goto's (just my personal preference, not suggesting that i'm right or wrong)
Anyways, to break out of nested loops I do something like this:
var isDone = false;
for (var x in collectionX) {
for (var y in collectionY) {
for (var z in collectionZ) {
if (conditionMet) {
// some code
isDone = true;
}
if (isDone)
break;
}
if (isDone)
break;
}
if (isDone)
break;
}
... i hope that helps for those who like me are anti-goto "fanboys" :)
This is an updated version of Emin's answer for Swift 5 that incorporates the suggestion to use noon instead of midnight as the definitive time for comparing days. It also handles the potential failure of various date functions by returning an optional.
///
/// This is an approximation; it does not account for time differences. It will set the time to 1200 (noon) and provide the absolute number
/// of days between now and the given date. If the result is negative, it should be read as "days ago" instead of "days from today."
/// Returns nil if something goes wrong initializing or adjusting dates.
///
func daysFromToday() -> Int?
{
let calendar = NSCalendar.current
// Replace the hour (time) of both dates with noon. (Noon is less likely to be affected by DST changes, timezones, etc. than midnight.)
guard let date1 = calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: Date())),
let date2 = calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: self)) else
{
return nil
}
return calendar.dateComponents([.day], from: date1, to: date2).day
}
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
There is likely to be a significant difference in real-world speed between fixed-point and floating-point math, but the theoretical best-case throughput of the ALU vs FPU is completely irrelevant. Instead, the number of integer and floating-point registers (real registers, not register names) on your architecture which are not otherwise used by your computation (e.g. for loop control), the number of elements of each type which fit in a cache line, optimizations possible considering the different semantics for integer vs. floating point math -- these effects will dominate. The data dependencies of your algorithm play a significant role here, so that no general comparison will predict the performance gap on your problem.
For example, integer addition is commutative, so if the compiler sees a loop like you used for a benchmark (assuming the random data was prepared in advance so it wouldn't obscure the results), it can unroll the loop and calculate partial sums with no dependencies, then add them when the loop terminates. But with floating point, the compiler has to do the operations in the same order you requested (you've got sequence points in there so the compiler has to guarantee the same result, which disallows reordering) so there's a strong dependency of each addition on the result of the previous one.
You're likely to fit more integer operands in cache at a time as well. So the fixed-point version might outperform the float version by an order of magnitude even on a machine where the FPU has theoretically higher throughput.
I just had this problem and fixed it this way. I noticed the error message has jre in it not jre6 or jre7, so i copied jre6 from program files to eclipse folder then renamed it from jre6 to jre, then it worked :p
I have tried the following method and it even works with the extreme case like:
str1=' I live on earth '
' '.join(str1.split())
But if you prefer a regular expression it can be done as:
re.sub('\s+', ' ', str1)
Although some preprocessing has to be done in order to remove the trailing and ending space.
If you are using pl/sql then the following code should work :
set server output on -- to retrieve and display a buffer
DECLARE
v_text VARCHAR2(10); -- declare
BEGIN
v_text := 'Hello'; --assign
dbms_output.Put_line(v_text); --display
END;
/
-- this must be use to execute pl/sql script
No, there is no way to create an abstract class in Objective-C.
You can mock an abstract class - by making the methods/ selectors call doesNotRecognizeSelector: and therefore raise an exception making the class unusable.
For example:
- (id)someMethod:(SomeObject*)blah
{
[self doesNotRecognizeSelector:_cmd];
return nil;
}
You can also do this for init.
With standart binding you need to use converters that looks little windy. So, I recommend you to look at my project CalcBinding, which was developed specially to resolve this problem and some others. With advanced binding you can write expressions with many source properties directly in xaml. Say, you can write something like:
<Button IsEnabled="{c:Binding Path=!IsReadOnly}" />
or
<Button Content="{c:Binding ElementName=grid, Path=ActualWidth+Height}"/>
or
<Label Content="{c:Binding A+B+C }" />
or
<Button Visibility="{c:Binding IsChecked, FalseToVisibility=Hidden}" />
where A, B, C, IsChecked - properties of viewModel and it will work properly
You can't really. You'll have to have both the drop down, and the text box, and have them pick or fill in the form. Without javascript you could create a separate radio button set where they choose dropdown or text input, but this seems messy to me. With some javascript you could toggle disable one or the other depending on which one they choose, for instance, have an 'other' option in the dropdown that triggers the text field.
I think I encountered the same problem as you. I addressed this problem with the following steps:
1) Go to Google Developers Console
2) Set JavaScript origins:
3) Set Redirect URIs:
I used a simple approach to make this work:
%s is the representation of an array of char
char string[10] // here is a array of chars, they max length is 10;
char character; // just a char 1 letter/from the ascii map
character = 'a'; // assign 'a' to character
printf("character %c ",a); //we will display 'a' to stout
so string is an array of char we can assign multiple character per space of memory
string[0]='h';
string[1]='e';
string[2]='l';
string[3]='l';
string[4]='o';
string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends
this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined
toy can also assign values to the array of chars assigning it with functions like strcpy;
strcpy(string,"hello" );
this do the same as the example and automatically add the (char) 0 at the end
so if you print it with %S printf("my string %s",string);
and how string is a array we can just display part of it
// the array one char
printf("first letter of wrd %s is :%c ",string,string[1] );
I prefer exporting the corresponding pandas series (i.e. the columns I need), using the apply function to split the column content into multiple series and then join the generated columns to the existing DataFrame. Of course, the source column should be removed.
e.g.
col1 = df["<col_name>"].apply(<function>)
col2 = ...
df = df.join(col1.to_frame(name="<name1>"))
df = df.join(col2.toframe(name="<name2>"))
df = df.drop(["<col_name>"], axis=1)
To split two words strings function should be something like that:
lambda x: x.split(" ")[0] # for the first element
lambda x: x.split(" ")[-1] # for the last element
You are asking to initialize four variables using a single float object, which of course is not iterable. You can do -
grade_1, grade_2, grade_3, grade_4 = [0.0 for _ in range(4)]
grade_1 = grade_2 = grade_3 = grade_4 = 0.0
Unless you want to initialize them with different values of course.
This occurred to me after I enabled two-factor authentication in my Apple ID. After I disable two-factor authentication, everything works as expected.
U can get column name and value from resultSet.getMetaData(); This code work for me:
Connection conn = null;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = MySQLJDBCUtil.getConnection();
preparedStatement = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i).getSqlValue());
}
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData();
while (resultSet.next()) {
int counter = md.getColumnCount();
String colName[] = new String[counter];
Map<String, Object> field = new HashMap<>();
for (int loop = 1; loop <= counter; loop++) {
int index = loop - 1;
colName[index] = md.getColumnLabel(loop);
field.put(colName[index], resultSet.getObject(colName[index]));
}
rows.add(field);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
}catch (Exception e1) {
e1.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return rows;
Here's the basic approach,
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");
Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
There is simple way to implement it. We can use Calendar.add method with loop. The minus days between beginDate and endDate, and the implemented code as below,
int minusDays = 0;
while (true) {
minusDays++;
// Day increasing by 1
beginCalendar.add(Calendar.DAY_OF_MONTH, 1);
if (dateFormat.format(beginCalendar.getTime()).
equals(dateFormat.format(endCalendar).getTime())) {
break;
}
}
System.out.println("The subtraction between two days is " + (minusDays + 1));**
Here's another way of doing it with a WHS script:
Set objWMIService = GetObject("Winmgmts:root\cimv2")
For Each objComputer in _
objWMIService.InstancesOf("Win32_ComputerSystem")
objComputer.rename "NewComputerName", NULL, NULL
Next
This is because there is not only 1 answer...
shell
command line expansionxargs
dedicated toolwhile read
with some remarkswhile read -u
using dedicated fd
, for interactive processing (sample)Regarding the OP request: running chmod
on all targets listed in file, xargs
is the indicated tool. But for some other applications, small amount of files, etc...
If your file is not too big and all files are well named (without spaces or other special chars like quotes), you could use shell
command line expansion. Simply:
chmod 755 $(<file.txt)
For small amount of files (lines), this command is the lighter one.
xargs
is the right toolFor bigger amount of files, or almost any number of lines in your input file...
For many binutils tools, like chown
, chmod
, rm
, cp -t
...
xargs chmod 755 <file.txt
If you have special chars and/or a lot of lines in file.txt
.
xargs -0 chmod 755 < <(tr \\n \\0 <file.txt)
if your command need to be run exactly 1 time by entry:
xargs -0 -n 1 chmod 755 < <(tr \\n \\0 <file.txt)
This is not needed for this sample, as chmod
accept multiple files as argument, but this match the title of question.
For some special case, you could even define location of file argument in commands generateds by xargs
:
xargs -0 -I '{}' -n 1 myWrapper -arg1 -file='{}' wrapCmd < <(tr \\n \\0 <file.txt)
seq 1 5
as inputTry this:
xargs -n 1 -I{} echo Blah {} blabla {}.. < <(seq 1 5)
Blah 1 blabla 1..
Blah 2 blabla 2..
Blah 3 blabla 3..
Blah 4 blabla 4..
Blah 5 blabla 5..
Where commande is done once per line.
while read
and variants.As OP suggest cat file.txt | while read in; do chmod 755 "$in"; done
will work, but there is 2 issues:
cat |
is an useless fork, and
| while ... ;done
will become a subshell where environment will disapear after ;done
.
So this could be better written:
while read in; do chmod 755 "$in"; done < file.txt
But,
You may be warned about $IFS
and read
flags:
help read
read: read [-r] ... [-d delim] ... [name ...] ... Reads a single line from the standard input... The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on... Only the characters found in $IFS are recognized as word delimiters. ... Options: ... -d delim continue until the first character of DELIM is read, rather than newline ... -r do not allow backslashes to escape any characters ... Exit Status: The return code is zero, unless end-of-file is encountered...
In some case, you may need to use
while IFS= read -r in;do chmod 755 "$in";done <file.txt
For avoiding problems with stranges filenames. And maybe if you encouter problems with UTF-8
:
while LANG=C IFS= read -r in ; do chmod 755 "$in";done <file.txt
While you use STDIN
for reading file.txt
, your script could not be interactive (you cannot use STDIN
anymore).
while read -u
, using dedicated fd
.Syntax: while read ...;done <file.txt
will redirect STDIN
to file.txt
. That mean, you won't be able to deal with process, until they finish.
If you plan to create interactive tool, you have to avoid use of STDIN
and use some alternative file descriptor.
Constants file descriptors are: 0
for STDIN, 1
for STDOUT and 2
for STDERR. You could see them by:
ls -l /dev/fd/
or
ls -l /proc/self/fd/
From there, you have to choose unused number, between 0
and 63
(more, in fact, depending on sysctl
superuser tool) as file descriptor:
For this demo, I will use fd 7
:
exec 7<file.txt # Without spaces between `7` and `<`!
ls -l /dev/fd/
Then you could use read -u 7
this way:
while read -u 7 filename;do
ans=;while [ -z "$ans" ];do
read -p "Process file '$filename' (y/n)? " -sn1 foo
[ "$foo" ]&& [ -z "${foo/[yn]}" ]&& ans=$foo || echo '??'
done
if [ "$ans" = "y" ] ;then
echo Yes
echo "Processing '$filename'."
else
echo No
fi
done 7<file.txt
done
To close fd/7
:
exec 7<&- # This will close file descriptor 7.
ls -l /dev/fd/
Nota: I let striked version because this syntax could be usefull, when doing many I/O with parallels process:
mkfifo sshfifo
exec 7> >(ssh -t user@host sh >sshfifo)
exec 6<sshfifo
You should try it like this:
var result =
from priceLog in PriceLogList
group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
select new {
LogDateTime = dateGroup.Key,
AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
};
Java 7 introduced stricter verification and changed the class format a bit—to contain a stack map used to verify that code is correct. The exception you see means that some method doesn't have a valid stack map.
Java version or bytecode instrumentation could both be to blame. Usually this means that a library used by the application generates invalid bytecode that doesn't pass the stricter verification. So nothing else than reporting it as a bug to the library can be done by the developer.
As a workaround you can add -noverify
to the JVM arguments in order to disable verification. In Java 7 it was also possible to use -XX:-UseSplitVerifier
to use the less strict verification method, but that option was removed in Java 8.
pip3 install BeautifulSoup4
Try this. It works for me. The reason is well explained here..
Per Open a URL in a new tab (and not a new window) using JavaScript
Nothing an author can do can choose to open in a new tab instead of a new window.
The browser decides between opening a new tab or opening a new window. You cannot control this as a developer.
Try this. I think this will help you.
override fun onBackPressed() {
when (mNavController.getCurrentDestination()!!.getId()) {
R.id.loginFragment -> {
onWarningAlertDialog(this, "Alert", "Do you want to close this application ?")
}
R.id.registerFragment -> {
super.onBackPressed()
}
}
}
private fun onWarningAlertDialog(mainActivity: MainActivity, s: String, s1: String) {
val dialogBuilder = AlertDialog.Builder(this)
dialogBuilder.setMessage(/*""*/s1)
.setCancelable(false)
.setPositiveButton("Proceed", DialogInterface.OnClickListener { dialog, id ->
finish()
})
.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, id ->
dialog.cancel()
})
// create dialog box
val alert = dialogBuilder.create()
// set title for alert dialog box
alert.setTitle("AlertDialogExample")
// show alert dialog
alert.show()
}
With using pathlib module, indentation isn't needed.
import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))
As of python 3.6, f-strings is available.
pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
In Android, application-level meta data is accessed through the Context
reference, which an activity is a descendant of.
For example, you can get the source directory via the getApplicationInfo().sourceDir
property.
There are methods for other folders as well (assets directory, data dir, database dir, etc.).
/**
* execute suppliers as future tasks then wait / join for getting results
* @param functors a supplier(s) to execute
* @return a list of results
*/
private List getResultsInFuture(Supplier<?>... functors) {
CompletableFuture[] futures = stream(functors)
.map(CompletableFuture::supplyAsync)
.collect(Collectors.toList())
.toArray(new CompletableFuture[functors.length]);
CompletableFuture.allOf(futures).join();
return stream(futures).map(a-> {
try {
return a.get();
} catch (InterruptedException | ExecutionException e) {
//logger.error("an error occurred during runtime execution a function",e);
return null;
}
}).collect(Collectors.toList());
};
Try to use toISOString(). It returns string in ISO8601 format.
from javascript
$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
console.log(result);
});
from c#
[HttpGet]
public JsonResult DoGet(DateTime date)
{
return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}
Because you are doing integer division.
As @Noldorin says, if both operators are integers, then integer division is used.
The result 0.33333333 can't be represented as an integer, therefore only the integer part (0) is assigned to the result.
If any of the operators is a double
/ float
, then floating point arithmetic will take place. But you'll have the same problem if you do that:
int n = 1.0 / 3.0;
This is because $pjs
is an one-element-array of objects, so first you should access the array element, which is an object and then access its attributes.
echo $pjs[0]->player_name;
Actually dump result that you pasted tells it very clearly.
Using the standard promise object, and having the promise return the results.
function promiseMap (data, f) {
const reducer = (promise, x) =>
promise.then(acc => f(x).then(y => acc.push(y) && acc))
return data.reduce(reducer, Promise.resolve([]))
}
var emails = []
function getUser(email) {
return db.getUser(email)
}
promiseMap(emails, getUser).then(emails => {
console.log(emails)
})
I was struggling with the same problem and testing everything, not getting error reporting and nothing seemed to be wrong. I had error_reporting(E_ALL) But suddenly I realized that I had not checked the apache log and voilà! There was a syntax error on the script...! (a missing "}" )
So, even though this is something evident to be checked, it can be forgotten... In my case (linux) it is at:
/var/log/apache2/error.log
You are almost there :)
All that is left is to
git checkout featurex
git merge our-team
This will merge our-team into featurex.
The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.
In lieu of a python goto equivalent I use the break statement in the following fashion for quick tests of my code. This assumes you have structured code base. The test variable is initialized at the start of your function and I just move the "If test: break" block to the end of the nested if-then block or loop I want to test, modifying the return variable at the end of the code to reflect the block or loop variable I'm testing.
def x:
test = True
If y:
# some code
If test:
break
return something
With the introduction of (i|android|windows)phones, things have changed, and to get a correct and complete solution that works on any device is really time-consuming.
You can have a peek at https://realfavicongenerator.net/favicon_compatibility or http://caniuse.com/#search=favicon to get an idea on the best way to get something that works on any device.
You should have a look at http://realfavicongenerator.net/ to automate a large part of this work, and probably at https://github.com/audreyr/favicon-cheat-sheet to understand how it works (even if this latter resource hasn't been updated in a loooong time).
One complete solution requires to add to you header the following (with the corresponding pictures and files, of course) :
<link rel="shortcut icon" href="favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160">
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="mstile-144x144.png">
<meta name="msapplication-config" content="browserconfig.xml">
In June 2016, RealFaviconGenerator claimed that the following 5 lines of code were supporting as many devices as the previous 18 lines:
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
One way to test private methods is through reflection. This applies to NUnit and XUnit, too:
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object[] parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
Open the XAMMP php.ini file (the default path is C:\xammp\php\php.ini) and change the code (;extension=ldap) to extension=php_ldap.dll and save. Restart XAMMP and save.
php.ini
; Notes for Windows environments :
;
; - Many DLL files are located in the extensions/ (PHP 4) or ext/ (PHP 5+)
; extension folders as well as the separate PECL DLL download (PHP 5+).
; Be sure to appropriately set the extension_dir directive.
;
extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
extension=php_ldap.dll
You can also stringify the object and then again parse to make the normal object. For example like:-
const obj = JSON.parse(JSON.stringify(mongoObj))
Here's the official line on the problem (I couldn't find the latest, but I don't think the situation has changed for later versions of .net)
Aahh got it... I got it working :)
Thanks Christopher, your suggesion is correct.
But, finding "Default SMTP Virtual Server" was tricky ;)
Even if you use IIS7 to deploy your web site, you have to open IIS6 Manager to configure SMTP server (why?).
I configured SMTP server as follows to make things work:
This is what I usually do to "vertical align" text inside labels:
label {
display: block;
float: left;
padding-top: 2px; /*This needs to be modified to fit */
}
It won't scale very nicely, but it works.
if you want get all values from form in simple array you may be do something like this.
function getValues(form) {
var listvalues = new Array();
var datastring = $("#" + form).serializeArray();
var data = "{";
for (var x = 0; x < datastring.length; x++) {
if (data == "{") {
data += "\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
}
else {
data += ",\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
}
}
data += "}";
data = JSON.parse(data);
listvalues.push(data);
return listvalues;
};
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
_x000D_
While I currently lean toward RDL because it seems more flexible and easier to manage, RDLC has an advantage in that it seems to simplify your licensing. Because RDLC doesn’t need a Reporting Services instance, you won't need a Reporting Services License to use it.
I’m not sure if this still applies with the newer versions of SQL Server, but at one time if you chose to put the SQL Server Database and Reporting Services instances on two separate machines, you were required to have two separate SQL Server licenses:
http://social.msdn.microsoft.com/forums/en-US/sqlgetstarted/thread/82dd5acd-9427-4f64-aea6-511f09aac406/
You can Bing for other similar blogs and posts regarding Reporting Services licensing.
hasOwnProperty() is a nice property to validate object keys. Example:
var obj = {a:1, b:2};
obj.hasOwnProperty('a') // true
Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.
AFAIK, these are your options:
Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters
There also executable wrappers - see How can I convert my Java program to an .exe file?
In Laravel 5.7 you can call specific field like this
$users = App\Book::with('author:id,name')->get();
It is important to add foreign_key
field in the selection.
In our codebase; we typically declare enums in the class that they belong to.
So for your Fruit example, We would have a Fruit class, and inside that an Enum called Fruits.
Referencing it in the code looks like this: Fruit.Fruits.Apple, Fruit.Fruits.Pear
, etc.
Constants follow along the same line, where they either get defined in the class to which they're relevant (so something like Fruit.ORANGE_BUSHEL_SIZE
); or if they apply system-wide (i.e. an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT
). (side note; all our constants are in upper case)
As always, your coding standards probably differ from mine; so YMMV.
Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home'
) in your URL patterns.
The solution is to update your urls.py
to include the view callable. This means that you have to import the view in your urls.py
. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works.
from django.conf.urls import include, url
from django.contrib.auth.views import login
from myapp.views import home, contact
urlpatterns = [
url(r'^$', home, name='home'),
url(r'^contact/$', contact, name='contact'),
url(r'^login/$', login, name='login'),
]
If there are many views, then importing them individually can be inconvenient. An alternative is to import the views module from your app.
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from myapp import views as myapp_views
urlpatterns = [
url(r'^$', myapp_views.home, name='home'),
url(r'^contact/$', myapp_views.contact, name='contact'),
url(r'^login/$', auth_views.login, name='login'),
]
Note that we have used as myapp_views
and as auth_views
, which allows us to import the views.py
from multiple apps without them clashing.
See the Django URL dispatcher docs for more information about urlpatterns
.
const char* text_char = "example of mbstowcs";
size_t length = strlen(text_char );
Example of usage "mbstowcs"
std::wstring text_wchar(length, L'#');
//#pragma warning (disable : 4996)
// Or add to the preprocessor: _CRT_SECURE_NO_WARNINGS
mbstowcs(&text_wchar[0], text_char , length);
Example of usage "mbstowcs_s"
Microsoft suggest to use "mbstowcs_s" instead of "mbstowcs".
Links:
wchar_t text_wchar[30];
mbstowcs_s(&length, text_wchar, text_char, length);
This should would work
List<TestA> testAList = new ArrayList<>();
List<TestB> testBList = new ArrayList<>()
testAList.addAll(new ArrayList<>(testBList));
This code works to insert both header and footer on the first page with header center aligned and footer left aligned
\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
% for the first page
\def\ps@IEEEtitlepagestyle{%
\old@ps@IEEEtitlepagestyle%
\def\@oddhead{\strut\hfill#1\hfill\strut}%
\def\@evenhead{\strut\hfill#1\hfill\strut}%
\def\@oddfoot{\mycopyrightnotice}
\def\@evenfoot{}
}%
\ps@headings%
}
\makeatother
\confheader{%
5$^{th}$ IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}
\def\mycopyrightnotice{
{\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
\gdef\mycopyrightnotice{}
}
\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```
You mean you want to do "aabbab".toCharArray(); ? Which will return an array of chars. Or do you actually want the resulting array to contain single character string objects?
setTimeout
may help out here
$("#message_link").click(function(){
setTimeout(function() {
if (some_conditions...){
$("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\" /></div>");
}
}, 100);
});
That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.
Class Assertions in org.junit.jupiter.api
Use:
public static void assertArrayEquals(int[] expected,
int[] actual)
The only portable way to tail -f
a file appears to be, in fact, to read from it and retry (after a sleep
) if the read
returns 0. The tail
utilities on various platforms use platform-specific tricks (e.g. kqueue
on BSD) to efficiently tail a file forever without needing sleep
.
Therefore, implementing a good tail -f
purely in Python is probably not a good idea, since you would have to use the least-common-denominator implementation (without resorting to platform-specific hacks). Using a simple subprocess
to open tail -f
and iterating through the lines in a separate thread, you can easily implement a non-blocking tail
operation in Python.
Example implementation:
import threading, Queue, subprocess
tailq = Queue.Queue(maxsize=10) # buffer at most 100 lines
def tail_forever(fn):
p = subprocess.Popen(["tail", "-f", fn], stdout=subprocess.PIPE)
while 1:
line = p.stdout.readline()
tailq.put(line)
if not line:
break
threading.Thread(target=tail_forever, args=(fn,)).start()
print tailq.get() # blocks
print tailq.get_nowait() # throws Queue.Empty if there are no lines to read
You can try the following one because it also validates number, null, string but the above-marked answer is not working correctly it's just a fix of the above function:
function isJson(str) {
try {
const obj = JSON.parse(str);
if (obj && typeof obj === `object`) {
return true;
}
} catch (err) {
return false;
}
return false;
}
try :
mvn install:install-file -DgroupId=jdk.tools -DartifactId=jdk.tools -Dversion=1.6 -Dpackaging=jar -Dfile="C:\Program Files\Java\jdk\lib\tools.jar"
also check : http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html
This is one of those instances where jquery actually makes it more complicated than what the DOM already provides.
let { top, bottom, height, width, //etc } = $('#bottom')[0].getBoundingClientRect();
return top;
Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.
To get the file path from the user use this function:
Private Function get_user_specified_filepath() As String
'or use the other code example here.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Please select the file."
get_user_specified_filepath = fd.SelectedItems(1)
End Function
Then just open the file read only and assign it to a variable:
dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
Try to edit your my.cf and comment the original sql_mode and add sql_mode = "".
vi /etc/mysql/my.cnf
sql_mode = ""
save and quit...
service mysql restart
You want the non-locale-aware floatval
function:
float floatval ( mixed $var ) - Gets the float value of a string.
Example:
$string = '122.34343The';
$float = floatval($string);
echo $float; // 122.34343
How about this ? Example illusrated using a file:
f = open('abc.log','r')
content = f.readlines()
for line in content:
m = re.search(r"\[(.*?)\]", line)
print m.group(1)
Hope this helps:
Magic regex : \[(.*?)\]
Explanation:
\[
: [
is a meta char and needs to be escaped if you want to match it literally.
(.*?)
: match everything in a non-greedy way and capture it.
\]
: ]
is a meta char and needs to be escaped if you want to match it literally.
I think LayeredPane is your best bet here. You would need a third panel though to contain A and B. This third panel would be the layeredPane and then panel A and B could still have a nice LayoutManagers. All you would have to do is center B over A and there is quite a lot of examples in the Swing trail on how to do this. Tutorial for positioning without a LayoutManager.
public class Main {
private JFrame frame = new JFrame();
private JLayeredPane lpane = new JLayeredPane();
private JPanel panelBlue = new JPanel();
private JPanel panelGreen = new JPanel();
public Main()
{
frame.setPreferredSize(new Dimension(600, 400));
frame.setLayout(new BorderLayout());
frame.add(lpane, BorderLayout.CENTER);
lpane.setBounds(0, 0, 600, 400);
panelBlue.setBackground(Color.BLUE);
panelBlue.setBounds(0, 0, 600, 400);
panelBlue.setOpaque(true);
panelGreen.setBackground(Color.GREEN);
panelGreen.setBounds(200, 100, 100, 100);
panelGreen.setOpaque(true);
lpane.add(panelBlue, new Integer(0), 0);
lpane.add(panelGreen, new Integer(1), 0);
frame.pack();
frame.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main();
}
}
You use setBounds to position the panels inside the layered pane and also to set their sizes.
Edit to reflect changes to original post You will need to add component listeners that detect when the parent container is being resized and then dynamically change the bounds of panel A and B.
This is a very old thread, but I have found a pure CSS solution to this using some creative nesting. I wasn't a fan of the jQuery method at all...
Fiddle here: https://jsfiddle.net/4jeuv5jq/
<div id="wrapper">
<div id="fixeditem">
Haha, I am a header. Nah.. Nah na na na
</div>
<div id="contentwrapper">
<div id="content">
Lorem ipsum.....
</div>
</div>
</div>
#wrapper {
position: relative;
width: 100%;
overflow: scroll;
}
#fixeditem {
position: absolute;
}
#contentwrapper {
width: 100%;
overflow: scroll;
}
#content {
width: 1000px;
height: 2000px;
}
It seems that
@Column(name="..")
is completely ignored unless there is
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
specified, so to me this is a bug.
I spent a few hours trying to figure out why @Column(name="..") was ignored.
Let's say you have an array of IDs and equivalent array of statuses - here is an example how to do this with a static SQL (a sql query that doesn't change due to different values) of the arrays :
drop table if exists results_dummy;
create table results_dummy (id int, status text, created_at timestamp default now(), updated_at timestamp default now());
-- populate table with dummy rows
insert into results_dummy
(id, status)
select unnest(array[1,2,3,4,5]::int[]) as id, unnest(array['a','b','c','d','e']::text[]) as status;
select * from results_dummy;
-- THE update of multiple rows with/by different values
update results_dummy as rd
set status=new.status, updated_at=now()
from (select unnest(array[1,2,5]::int[]) as id,unnest(array['a`','b`','e`']::text[]) as status) as new
where rd.id=new.id;
select * from results_dummy;
-- in code using **IDs** as first bind variable and **statuses** as the second bind variable:
update results_dummy as rd
set status=new.status, updated_at=now()
from (select unnest(:1::int[]) as id,unnest(:2::text[]) as status) as new
where rd.id=new.id;
Try:
select right ('0'+convert(nvarchar(2), DATEPART(mm, getdate())),2 )
Square brackets are lists while parentheses are tuples.
A list is mutable, meaning you can change its contents:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
while tuples are not:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Note that, as many people have pointed out, you can add tuples together. For example:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
Whereas, if you were to construct this same example with a list, y
would also be updated:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
The way you're writing it is equivalent to
HashMap<Object, Object> map = new HashMap<Object, Object>();
What goes inside the brackets is you communicating to the compiler what you're going to put in the HashMap so that it can do error checking for you. If Object, Object is what you actually want (probably not) you should explicitly declare it. In general you should be as explicit as you can with the declaration to facilitate error checking by the compiler. What you've described should probably be declared like this:
HashMap<String, Object> map = new HashMap<String, Object>();
That way you at least declare that your keys are going to be strings, but your values can be anything. Just remember to use a cast when you get a value back out.
<html>
<head>
<style type="text/css">
.title {
color: blue;
text-decoration: bold;
text-size: 1em;
}
.author {
color: gray;
}
</style>
</head>
<body>
<p>
<span class="title">La super bonne</span>
<span class="author">proposée par Jérém</span>
</p>
</body>
</html>
On a side note, it would have been much easier to just do this.
If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:
public string CreateFile(string id, string name, string description,
/* --> */ SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions // <---
};
return file.Id;
}
If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:
public string CreateFile(string id, string name, string description) // <---
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = SupportedPermissions.basic // <---
};
return file.Id;
}
This happens when your result is not a result (but a "false" instead). You should change this line
$sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';
to this:
$sql = "SELECT * FROM $usertable WHERE PartNumber = $partid";
because the " can interprete $variables while ' cannot.
Works fine with integers (numbers), for strings you need to put the $variable in single quotes, like
$sql = "SELECT * FROM $usertable WHERE PartNumber = '$partid' ";
If you want / have to work with single quotes, then php CAN NOT interprete the variables, you will have to do it like this:
$sql = 'SELECT * FROM '.$usertable.' WHERE string_column = "'.$string.'" AND integer_column = '.$number.';
First Add a Class called Win32.cs
public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
public POINT(int X, int Y)
{
x = X;
y = Y;
}
}
}
You can use it then like this:
Win32.POINT p = new Win32.POINT(xPos, yPos);
Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);
using SimpleDateFormat or DateFormat class through
for e.g.
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}
I think this should be:
$('.home').click(function() {
$(this).css('background', 'url(images/tabs3.png)');
});
and remove this:
<div class="home" onclick="function()">
//-----------^^^^^^^^^^^^^^^^^^^^---------no need for this
You have to make sure you have a correct path to your image.
find the cxfreeze
script and run it. It will be in the same path as your other python helper scripts, such as pip
.
cxfreeze Main.py --target-dir dist
read more at: http://cx-freeze.readthedocs.org/en/latest/script.html#script
In addition to the suggested,
String Text = mySpinner.getSelectedItem().toString();
You can do,
String Text = String.valueOf(mySpinner.getSelectedItem());
IE9+ (Vista+) solution, without creating new text nodes:
var div = document.getElementById("divID");
div.textContent += data + " ";
However, this didn't quite do the trick for me since I needed a new line after each message, so my DIV turned into a styled UL with this code:
var li = document.createElement("li");
var text = document.createTextNode(data);
li.appendChild(text);
ul.appendChild(li);
From https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent :
Differences from innerHTML
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
Independent of your original question, you will get better performance if you capture references to local variables rather than index into your list multiple times:
AllIntegerIDs ids = new AllIntegerIDs();
ids.m_MessageID = (int)IntegerIDsSubstring[IntOffset];
ids.m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
ids.m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
ids.m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
ids.m_MessageText = MessageTextSubstring;
integerList.Add(ids);
And in your for
loop:
for (int cnt3 = 0 ; cnt3 < integerList.Count ; cnt3++) //<----PROBLEM HERE
{
AllIntegerIDs ids = integerList[cnt3];
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n",
ids.m_MessageID,ids.m_MessageType,ids.m_ClassID,ids.m_CategoryID, ids.m_MessageText);
}
Disabling and Enabling All Foreign Keys
CREATE PROCEDURE pr_Disable_Triggers_v2
@disable BIT = 1
AS
DECLARE @sql VARCHAR(500)
, @tableName VARCHAR(128)
, @tableSchema VARCHAR(128)
-- List of all tables
DECLARE triggerCursor CURSOR FOR
SELECT t.TABLE_NAME AS TableName
, t.TABLE_SCHEMA AS TableSchema
FROM INFORMATION_SCHEMA.TABLES t
ORDER BY t.TABLE_NAME, t.TABLE_SCHEMA
OPEN triggerCursor
FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
IF @disable = 1
SET @sql = @sql + ' DISABLE TRIGGER ALL'
ELSE
SET @sql = @sql + ' ENABLE TRIGGER ALL'
PRINT 'Executing Statement - ' + @sql
EXECUTE ( @sql )
FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
END
CLOSE triggerCursor
DEALLOCATE triggerCursor
First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:
0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missingInside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.
Another easy way to get this:
Person myPet = GetPersonFromDatabase();
// check for myPet == null... AND for myPet.PetType == null
if ( myPet.PetType == "cat" ) <--- fall down go boom!
This is just an explanation not addressed in other answers
At least in recent versions of Mysql, your first query is not committed.
If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.
What's going on?
When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.
So BE CAREFUL, any table/row that was locked with a previous query likeSELECT ... FOR SHARE/UPDATE
, UPDATE
, INSERT
or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a subsequent query commits it explicitly (COMMIT
) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).
That's why the solution involves declaring handlers to immediately ROLLBACK
when an error happens.
Extra
Inside the handler you can also re-raise the error using RESIGNAL
, otherwise the stored procedure executes "Successfully"
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
#.. Query 1 ..
#.. Query 2 ..
#.. Query 3 ..
COMMIT;
END
You can presumably pass-in, as a parameter, a delegate which will convert from string to T.
Using this regular expression you can validate different kinds of Date/Time samples, just a little change is needed.
^\d\d\d\d/(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01]) (00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$
-->validate this: 2018/7/12 13:00:00
for your format you cad change it to:
^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[0-2])/\d\d$
--> validates this: 11/12/98
There are already a lot of answer to this question, especially this one https://stackoverflow.com/a/10847618/5515861. I only want to add couple of notes. If you guys using Mac, I don't know how you install the MySQL, but the first thing to investigate is where is your MySQL installation is located. For me, MySQL is installed using brew
for version 5.7
, and the location is /usr/local/opt/[email protected]/
, so add the following to my ~/.zshrc
.
MYSQL=/usr/local/opt/[email protected]/bin/
MYSQL_LIB=/usr/local/opt/[email protected]/lib/
export PATH=$PATH:$MYSQL
export DYLD_LIBRARY_PATH=$MYSQL_LIB:$DYLD_LIBRARY_PATH
Hope you fix your issues
This is the easiest script to test.
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
<script language="C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("From email account");
mail.To.Add("To email account");
//set the content
mail.Subject = "This is a test email from C# script";
mail.Body = "This is a test email from C# script";
//send the message
SmtpClient smtp = new SmtpClient("mail.domainname.com");
NetworkCredential Credentials = new NetworkCredential("to email account", "Password");
smtp.Credentials = Credentials;
smtp.Send(mail);
lblMessage.Text = "Mail Sent";
}
</script>
<html>
<body>
<form runat="server">
<asp:Label id="lblMessage" runat="server"></asp:Label>
</form>
</body>
Writing the whole path/directory eg. (for windows) C:\Programs\Python\Python36-32\Scripts\pip3.exe install mypackage
. This worked well for me when I had trouble with pip.
If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:
const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString); // {object Date}
from here you can extract the desired values by using Date Getters:
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);
// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s); // {object Date}
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
you should return Scaffold widget and add your widget inside Scaffold
suck as this code :
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(child: new Text("Hello, World!"));
);
}
}
Following link Provides JSON document describing metadata about the Keycloak
/auth/realms/{realm-name}/.well-known/openid-configuration
Following information reported with Keycloak 6.0.1 for master
realm
{
"issuer":"http://localhost:8080/auth/realms/master",
"authorization_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/auth",
"token_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token",
"token_introspection_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token/introspect",
"userinfo_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/userinfo",
"end_session_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/logout",
"jwks_uri":"http://localhost:8080/auth/realms/master/protocol/openid-connect/certs",
"check_session_iframe":"http://localhost:8080/auth/realms/master/protocol/openid-connect/login-status-iframe.html",
"grant_types_supported":[
"authorization_code",
"implicit",
"refresh_token",
"password",
"client_credentials"
],
"response_types_supported":[
"code",
"none",
"id_token",
"token",
"id_token token",
"code id_token",
"code token",
"code id_token token"
],
"subject_types_supported":[
"public",
"pairwise"
],
"id_token_signing_alg_values_supported":[
"PS384",
"ES384",
"RS384",
"HS256",
"HS512",
"ES256",
"RS256",
"HS384",
"ES512",
"PS256",
"PS512",
"RS512"
],
"userinfo_signing_alg_values_supported":[
"PS384",
"ES384",
"RS384",
"HS256",
"HS512",
"ES256",
"RS256",
"HS384",
"ES512",
"PS256",
"PS512",
"RS512",
"none"
],
"request_object_signing_alg_values_supported":[
"PS384",
"ES384",
"RS384",
"ES256",
"RS256",
"ES512",
"PS256",
"PS512",
"RS512",
"none"
],
"response_modes_supported":[
"query",
"fragment",
"form_post"
],
"registration_endpoint":"http://localhost:8080/auth/realms/master/clients-registrations/openid-connect",
"token_endpoint_auth_methods_supported":[
"private_key_jwt",
"client_secret_basic",
"client_secret_post",
"client_secret_jwt"
],
"token_endpoint_auth_signing_alg_values_supported":[
"RS256"
],
"claims_supported":[
"aud",
"sub",
"iss",
"auth_time",
"name",
"given_name",
"family_name",
"preferred_username",
"email"
],
"claim_types_supported":[
"normal"
],
"claims_parameter_supported":false,
"scopes_supported":[
"openid",
"address",
"email",
"microprofile-jwt",
"offline_access",
"phone",
"profile",
"roles",
"web-origins"
],
"request_parameter_supported":true,
"request_uri_parameter_supported":true,
"code_challenge_methods_supported":[
"plain",
"S256"
],
"tls_client_certificate_bound_access_tokens":true,
"introspection_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token/introspect"
}
include your Member Class to your jsp :
<%@ page import="pageNumber.*, java.util.*, java.io.*,yourMemberPackage.Member" %>
try this
var fun = (function() {
var called = false;
return function() {
if (!called) {
console.log("I called");
called = true;
}
}
})()
you can use the some Codeigniter functions and some core functions and make combination to achieve your URL with query string. I found solution of this problem.
base_url($this->uri->uri_string()).strrchr($_SERVER['REQUEST_URI'], "?");
and if you loaded URL helper so you can also do this current_url().strrchr($_SERVER['REQUEST_URI'], "?");
My version:
Function Test-RegistryValue($Key, $Name)
{
(Get-ChildItem (Split-Path -Parent -Path $Key) | Where-Object {$_.PSChildName -eq (Split-Path -Leaf $Key)}).Property -contains $Name
}
This is the complete way to omit unneeded redirects, too ;)
These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.
RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]
Eplanations:
RewriteEngine on
==> enable the engine at all
RewriteCond %{HTTPS} off [OR]
==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)
RewriteCond %{HTTP:X-Forwarded-Proto} !https
==> match on forwarded connections (proxy, loadbalancer, etc.) without https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]
==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.
ES6 allows a construct where a function argument is specified with a "..." notation such as
function testArgs (...args) {
// Where you can test picking the first element
console.log(args[0]);
}
Try to use r.hasNext() instead of r.hasNextLine():
while(r.hasNext()) {
scan = r.next();
Either replace double quotes around type="text"
with single quotes, Like
"<form><input type='text'/></form>"
OR
replace double quotes wrapping data-content
with singe quotes, Like
data-content='<form><input type="text"/></form>'
Mads Hansen's solution is good but to succeed in reading the external file in .NET 4 took some time to figure out using hints in the comments about resolvers, ProhibitDTD and so on.
This is how it's done:
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
settings.XmlResolver = resolver;
var reader = XmlReader.Create("logfile.xml", settings);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
foreach (XmlElement element in doc.SelectNodes("//event"))
{
var ch = element.ChildNodes;
var count = ch.Count;
}
logfile.xml:
<?xml version="1.0"?>
<!DOCTYPE logfile [
<!ENTITY events
SYSTEM "events.txt">
]>
<logfile>
&events;
</logfile>
events.txt:
<event>
<item1>item1</item1>
<item2>item2</item2>
</event>
I had this problem too. The route of my problem was I had made a mistake in my vhosts.conf file. If you are using vhosts this is another thing to check
This works recursively for infinitely nested elements:
def iterFlatten(root):
if isinstance(root, (list, tuple)):
for element in root:
for e in iterFlatten(element):
yield e
else:
yield root
Result:
>>> b = [["a", ("b", "c")], "d"] >>> list(iterFlatten(b)) ['a', 'b', 'c', 'd']
Thats all I believe is sufficient enough for basic sec. It should prevent all major attack from hacker.
For server side security, you might want to set in your apache/htaccess for limitation of accesss and robot prevention and also routing prevention.. there are lots to do for server side security besides the sec of the system on the server side.
You can learn and get a copy of the sec from the htaccess apache sec level (common rpactices)
function hasSpaces(str) {
if (str.indexOf(' ') !== -1) {
return true
} else {
return false
}
}
There are some references and pointers in the comments on this page at PHP.net:
Torsten says
"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."
Jetboy says
"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.
Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
implode(' ',$array);
Ensure that you have turned ON the location services on the device. Else you won't get any location related info.
This works for me,
map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange (Location location) {
LatLng loc = new LatLng (location.getLatitude(), location.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
};
map.setOnMyLocationChangeListener(myLocationChangeListener);
}
Same as the other answers (disabled isn't sent to the server, readonly is) but some browsers prevent highlighting of a disabled form, while read-only can still be highlighted (and copied).
http://www.w3schools.com/tags/att_input_disabled.asp
http://www.w3schools.com/tags/att_input_readonly.asp
A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.
I have the same problem and when I digged into the log:
sudo tail -f /var/log/mysqld.log
InnoDB: mmap(137363456 bytes) failed; errno 12
200610 6:27:27 InnoDB: Completed initialization of buffer pool
200610 6:27:27 InnoDB: Fatal error: cannot allocate memory for the buffer pool
200610 6:27:27 [ERROR] Plugin 'InnoDB' init function returned error.
200610 6:27:27 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
200610 6:27:27 [ERROR] Unknown/unsupported storage engine: InnoDB
200610 6:27:27 [ERROR] Aborting
Clearly there's not enough memory and stopping InnoDB to start. I realized I never set up the swap file...
I followed this to set up the swap file and it works.
I found a solution that worked in my case:
<input class="form-control" style="min-width: 100%!important;" type="text" />
You only need to override the min-width set 100% and important and the result is this one:
If you don't apply it, you will always get this:
You could just use a DISTINCT clause to select the "cleaned up" list (and here is a very easy example on how to do that).
One interesting thing is we can view the tables horizontally, without folding. we can use PAGER
environment variable. psql makes use of it. you can set
export PAGER='/usr/bin/less -S'
or just less -S
if its already availble in command line, if not with the proper location. -S to view unfolded lines. you can pass in any custom viewer or other options with it.
I've written more in Psql Horizontal Display
Could someone explain to me, how to call the move method with the variable RIGHT
>>> myMissile = MissileDevice(myBattery) # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)
If you have programmed in any other language with classes, besides python, this sort of thing
class Foo:
bar = "baz"
is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; and variables defined in its scope are attached to the class, not the instances returned by the class. to refer to bar
, above, you can just call it Foo.bar
; you can also access class attributes through instances of the class, like Foo().bar
.
Im utterly baffled about what 'self' refers too,
>>> class Foo:
... def quux(self):
... print self
... print self.bar
... bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>
When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. All this does is arrange for the instance to be passed as the first argument.
You are looking for "|." See http://cran.r-project.org/doc/manuals/R-intro.html#Logical-vectors
my.data.frame <- data[(data$V1 > 2) | (data$V2 < 4), ]
You pass an undefined rAgent_IP parameter in EXEC instead of the local variable @rAgent_IP.
Still, this trigger will fail if you perform a multi-record INSERT statement.
You can use "ComboBoxItem.PreviewMouseDown" event. So each time when mouse is down on some item this event will be fired.
To add this event in XAML use "ComboBox.ItemContainerStyle" like in next example:
<ComboBox x:Name="MyBox"
ItemsSource="{Binding MyList}"
SelectedValue="{Binding MyItem, Mode=OneWayToSource}" >
<ComboBox.ItemContainerStyle>
<Style>
<EventSetter Event="ComboBoxItem.PreviewMouseDown"
Handler="cmbItem_PreviewMouseDown"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
and handle it as usual
void cmbItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
//...do your item selection code here...
}
Thanks to MSDN
Here some useful resource, hope can help you to chose your CDN. MS has recently add a new domain for delivery Libraries trough their CDN.
Old Format: http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.1.js New Format: http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js
This should not send all cookies for microsoft.com. http://www.asp.net/ajaxlibrary/cdn.ashx#Using_jQuery_from_the_CDN_11
Here some statistics about most popular technology used on the web across all technology. http://trends.builtwith.com/
Hope can help you to choose.
You use the Headers
property with a string index:
request.Headers["X-My-Custom-Header"] = "the-value";
According to MSDN, this has been available since:
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx
This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
@{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
The default JavaScript "API" for setting a cookie is as easy as:
document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/'
Use the jQuery cookie plugin like:
$.cookie('mycookie', 'valueOfCookie')
style="text-align:center;"
(i think)
or you could just ignore it, it still works
You should use Merge: For example:
MERGE INTO employees e
USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
or
MERGE INTO employees e
USING hr_records h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
Dragging an object and placing in a different location is part of the standard of HTML5. All the objects can be draggable. But the Specifications of below web browser should be followed. API Chrome Internet Explorer Firefox Safari Opera Version 4.0 9.0 3.5 6.0 12.0
You can find example from below: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop2
Check out this SO question's accepted solution. Substitute your own filename for basename($File)
and change filesize($File) to strlen($your_string)
. (You may want to use mb_strlen just in case the string contains multibyte characters.)
The other Answers are outmoded as of Java 8.
Instant // Represent a moment in UTC.
.parse( "2013-09-29T18:46:19Z" ) // Parse text in standard ISO 8601 format where the `Z` means UTC, pronounces “Zulu”.
.atZone( // Adjust from UTC to a time zone.
ZoneId.of( "Asia/Kolkata" )
) // Returns a `ZonedDateTime` object.
Your string format happens to comply with the ISO 8601 standard. This standard defines sensible formats for representing various date-time values as text.
The old java.util.Date
/.Calendar
and java.text.SimpleDateFormat
classes have been supplanted by the java.time framework built into Java 8 and later. See Tutorial. Avoid the old classes as they have proven to be poorly designed, confusing, and troublesome.
Part of the poor design in the old classes has bitten you, where the toString
method applies the JVM's current default time zone when generating a text representation of the date-time value that is actually in UTC (GMT); well-intentioned but confusing.
The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values. So no need to specify a parsing pattern.
An Instant
is a moment on the timeline in UTC.
Instant instant = Instant.parse( "2013-09-29T18:46:19Z" );
You can apply a time zone as needed to produce a ZonedDateTime
object.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );
Using the date helper worked for me
$this->load->helper('date');
You can find documentation for date_helper
here.
$data = array(
'created' => now(),
'modified' => now()
);
$this->db->insert('TABLENAME', $data);
Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country
, X-AppEngine-Region
, X-AppEngine-City
and X-AppEngine-CityLatLong
headers.
An example looks like this:
X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733
@Resource
is often used by high-level objects, defined via JNDI. @Autowired
or @Inject
will be used by more common beans.
As far as I know, it's not a specification, nor even a convention. It's more the logical way standard code will use these annotations.
$('.input').keypress(function (e) {
if (e.which == 13) {
$('form#login').submit();
return false; //<---- Add this line
}
});
Check out this stackoverflow answer: event.preventDefault() vs. return false
Essentially, "return false" is the same as calling e.preventDefault
and e.stopPropagation()
.
This is a quite old question, still comments show, that still people have problems, so here is my solution with following additional features:
CoordinatorLayout
Function - Example (I have this function in an utility class)
public static void animateViewVisibility(final View view, final int visibility)
{
// cancel runnning animations and remove and listeners
view.animate().cancel();
view.animate().setListener(null);
// animate making view visible
if (visibility == View.VISIBLE)
{
view.animate().alpha(1f).start();
view.setVisibility(View.VISIBLE);
}
// animate making view hidden (HIDDEN or INVISIBLE)
else
{
view.animate().setListener(new AnimatorListenerAdapter()
{
@Override
public void onAnimationEnd(Animator animation)
{
view.setVisibility(visibility);
}
}).alpha(0f).start();
}
}
Adjust animation
After calling view.animate()
you can adjust the animation to whatever you want (set duration, set interpolator and more...). You may as well hide a view by scaling it instead of adjusting it's alpha value, just replace the alpha(...)
with scaleX(...)
or scaleY(...)
in the utility method if you want that
In my case I was getting this error trying to use the IS_ROLEMEMBER()
function on SQL Server 2008 R2. This function isn't valid prior to SQL Server 2012.
Instead of this function I ended up using
select 1
from sys.database_principals u
inner join sys.database_role_members ur
on u.principal_id = ur.member_principal_id
inner join sys.database_principals r
on ur.role_principal_id = r.principal_id
where r.name = @role_name
and u.name = @username
Significantly more verbose, but it gets the job done.
It could be due to the architecture of your OS. Is your OS 64 Bit and have you installed 64 bit version of Python? It may help to install both 32 bit version Python 3.1 and Pygame, which is available officially only in 32 bit and you won't face this problem.
I see that 64 bit pygame is maintained here, you might also want to try uninstalling Pygame only and install the 64 bit version on your existing python3.1, if not choose go for both 32-bit version.
Step 1: Install Graphviz binary
Windows:
Linux:
Step 2: Install graphviz module for python
pip:
conda:
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
You can try this which I find in another question.
Android, Make an image at a URL equal to ImageView's image
try {
ImageView i = (ImageView)findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Are you attempting to do this inside of an XCTest and on the verge of smashing your laptop? This is the thread for you: Why can't code inside unit tests find bundle resources?
Instant stop =
myUtilDateStart.toInstant()
.plus( Duration.ofMinutes( x ) )
;
Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.
The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.
If your Calendar
is actually a GregorianCalendar
you can convert to a ZonedDateTime
. Find new methods added to the old classes to facilitate conversion to/from java.time types.
if( myUtilCalendar instanceof GregorianCalendar ) {
GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
ZonedDateTime zdt = gregCal.toZonedDateTime(); // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if
If your Calendar
is not a Gregorian
, call toInstant
to get an Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myCal.toInstant();
Similarly, if starting with a java.util.Date
object, convert to an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
Apply a time zone to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
To get a java.util.Date
object, go through the Instant
.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );
For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answer to another Question.
Duration
Represent the span of time as a Duration
object. Your input for the duration is a number of minutes as mentioned in the Question.
Duration d = Duration.ofMinutes( yourMinutesGoHere );
You can add that to the start to determine the stop.
Instant stop = startInstant.plus( d );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
To set https
globally instead of git://
:
git config --global url.https://github.com/.insteadOf git://github.com/
Change
try {
myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
to
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
You need the /g
(global) option, like this:
var replaced = str.replace(/ /g, '+');
You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.
Deep copy literally performs a deep copy. It means, that if your class has some fields that are references, their values will be copied, not references themselves. If, for example you have two instances of a class, A & B with fields of reference type, and perform a deep copy, changing a value of that field in A won't affect a value in B. And vise-versa. Things are different with shallow copy, because only references are copied, therefore, changing this field in a copied object would affect the original object.
What type of a copy does a copy constructor does?
It is implementation - dependent. This means that there are no strict rules about that, you can implement it like a deep copy or shallow copy, however as far as i know it is a common practice to implement a deep copy in a copy constructor. A default copy constructor performs a shallow copy though.
A nice WebKit-only solution that takes advantage of the background-clip: text
support: http://jsfiddle.net/sandro_paganotti/wLkVt/
span{
font-size: 100px;
background: linear-gradient(to right, black, black 50%, grey 50%, grey);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
ALTER DATABASE name OWNER TO new_owner;
See the Postgresql manual's entry on this for more details.
To anyone using VS2015: I was encountering a "407 Proxy Authentication required" error, which broke my build. After a few hours investigating, it turns out MSBuild wasn't sending credentials when trying to download Nuget as part of the 'DownloadNuGet' target. The solution was to add the following XML to C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe.config inside the <configuration>
element:
<system.net>
<defaultProxy useDefaultCredentials="true">
</defaultProxy>
</system.net>
There are a lot of answers here, but none of them suited my needs. I wanted an actual answer to the asker's #1 question. How do I know when an image is updated on hub.docker.com?
The below script can be run daily. On first run, it gets a baseline of the tags and update dates from the HUB registry and saves them locally. From then out, every time it is run it checks the registry for new tags and update dates. Since this changes every time a new image exists, it tells us if the base image has changed. Here is the script:
#!/bin/bash
DATAPATH='/data/docker/updater/data'
if [ ! -d "${DATAPATH}" ]; then
mkdir "${DATAPATH}";
fi
IMAGES=$(docker ps --format "{{.Image}}")
for IMAGE in $IMAGES; do
ORIGIMAGE=${IMAGE}
if [[ "$IMAGE" != *\/* ]]; then
IMAGE=library/${IMAGE}
fi
IMAGE=${IMAGE%%:*}
echo "Checking ${IMAGE}"
PARSED=${IMAGE//\//.}
if [ ! -f "${DATAPATH}/${PARSED}" ]; then
# File doesn't exist yet, make baseline
echo "Setting baseline for ${IMAGE}"
curl -s "https://registry.hub.docker.com/v2/repositories/${IMAGE}/tags/" > "${DATAPATH}/${PARSED}"
else
# File does exist, do a compare
NEW=$(curl -s "https://registry.hub.docker.com/v2/repositories/${IMAGE}/tags/")
OLD=$(cat "${DATAPATH}/${PARSED}")
if [[ "${VAR1}" == "${VAR2}" ]]; then
echo "Image ${IMAGE} is up to date";
else
echo ${NEW} > "${DATAPATH}/${PARSED}"
echo "Image ${IMAGE} needs to be updated";
H=`hostname`
ssh -i /data/keys/<KEYFILE> <USER>@<REMOTEHOST>.com "{ echo \"MAIL FROM: root@${H}\"; echo \"RCPT TO: <USER>@<EMAILHOST>.com\"; echo \"DATA\"; echo \"Subject: ${H} - ${IMAGE} needs update\"; echo \"\"; echo -e \"\n${IMAGE} needs update.\n\ndocker pull ${ORIGIMAGE}\"; echo \"\"; echo \".\"; echo \"quit\"; sleep 1; } | telnet <SMTPHOST> 25"
fi
fi
done;
You will want to alter the DATAPATH
variable at the top, and alter the email notification command at the end to suit your needs. For me, I have it SSH into a server on another network where my SMTP is located. But you could easily use the mail
command, too.
Now, you also want to check for updated packages inside the containers themselves. This is actually probably more effective than doing a "pull" once your containers are working. Here's the script to pull that off:
#!/bin/bash
function needsUpdates() {
RESULT=$(docker exec ${1} bash -c ' \
if [[ -f /etc/apt/sources.list ]]; then \
grep security /etc/apt/sources.list > /tmp/security.list; \
apt-get update > /dev/null; \
apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s; \
fi; \
')
RESULT=$(echo $RESULT)
GOODRESULT="Reading package lists... Building dependency tree... Reading state information... Calculating upgrade... 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded."
if [[ "${RESULT}" != "" ]] && [[ "${RESULT}" != "${GOODRESULT}" ]]; then
return 0
else
return 1
fi
}
function sendEmail() {
echo "Container ${1} needs security updates";
H=`hostname`
ssh -i /data/keys/<KEYFILE> <USRER>@<REMOTEHOST>.com "{ echo \"MAIL FROM: root@${H}\"; echo \"RCPT TO: <USER>@<EMAILHOST>.com\"; echo \"DATA\"; echo \"Subject: ${H} - ${1} container needs security update\"; echo \"\"; echo -e \"\n${1} container needs update.\n\n\"; echo -e \"docker exec ${1} bash -c 'grep security /etc/apt/sources.list > /tmp/security.list; apt-get update > /dev/null; apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s'\n\n\"; echo \"Remove the -s to run the update\"; echo \"\"; echo \".\"; echo \"quit\"; sleep 1; } | telnet <SMTPHOST> 25"
}
CONTAINERS=$(docker ps --format "{{.Names}}")
for CONTAINER in $CONTAINERS; do
echo "Checking ${CONTAINER}"
if needsUpdates $CONTAINER; then
sendEmail $CONTAINER
fi
done
Microsoft SQL Server's INTERSECT
"returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand" This is different from a standard INNER JOIN
or WHERE EXISTS
query.
SQL Server
CREATE TABLE table_a (
id INT PRIMARY KEY,
value VARCHAR(255)
);
CREATE TABLE table_b (
id INT PRIMARY KEY,
value VARCHAR(255)
);
INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');
SELECT value FROM table_a
INTERSECT
SELECT value FROM table_b
value
-----
B
(1 rows affected)
MySQL
CREATE TABLE `table_a` (
`id` INT NOT NULL AUTO_INCREMENT,
`value` varchar(255),
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `table_b` LIKE `table_a`;
INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');
SELECT value FROM table_a
INNER JOIN table_b
USING (value);
+-------+
| value |
+-------+
| B |
| B |
+-------+
2 rows in set (0.00 sec)
SELECT value FROM table_a
WHERE (value) IN
(SELECT value FROM table_b);
+-------+
| value |
+-------+
| B |
| B |
+-------+
With this particular question, the id column is involved, so duplicate values will not be returned, but for the sake of completeness, here's a MySQL alternative using INNER JOIN
and DISTINCT
:
SELECT DISTINCT value FROM table_a
INNER JOIN table_b
USING (value);
+-------+
| value |
+-------+
| B |
+-------+
And another example using WHERE ... IN
and DISTINCT
:
SELECT DISTINCT value FROM table_a
WHERE (value) IN
(SELECT value FROM table_b);
+-------+
| value |
+-------+
| B |
+-------+
I had to add one more line to REVOKE...
After running:
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;
I was still receiving the error: username cannot be dropped because some objects depend on it DETAIL: privileges for schema public
I was missing this:
REVOKE USAGE ON SCHEMA public FROM username;
Then I was able to drop the role.
DROP USER username;
I've rewritten Andre Van Zuydam's answer, which didn't work for me, in jQuery. This caputures both Enter and Shift+Enter. Enter tabs forward, and Shift+Enter tabs back.
I've also rewritten the way self
is initialized by the current item in focus. The form is also selected that way. Here's the code:
// Map [Enter] key to work like the [Tab] key
// Daniel P. Clark 2014
// Catch the keydown for the entire document
$(document).keydown(function(e) {
// Set self as the current item in focus
var self = $(':focus'),
// Set the form by the current item in focus
form = self.parents('form:eq(0)'),
focusable;
// Array of Indexable/Tab-able items
focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');
function enterKey(){
if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key
// If not a regular hyperlink/button/textarea
if ($.inArray(self, focusable) && (!self.is('a,button'))){
// Then prevent the default [Enter] key behaviour from submitting the form
e.preventDefault();
} // Otherwise follow the link/button as by design, or put new line in textarea
// Focus on the next item (either previous or next depending on shift)
focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();
return false;
}
}
// We need to capture the [Shift] key and check the [Enter] key either way.
if (e.shiftKey) { enterKey() } else { enterKey() }
});
textarea
is included is because we "do" want to tab into it. Also, once in, we don't want to stop the default behavior of Enter from putting in a new line.
a
and button
allow the default action, "and" still focus on the next item, is because they don't always load another page. There can be a trigger/effect on those such as an accordion or tabbed content. So once you trigger the default behavior, and the page does its special effect, you still want to go to the next item since your trigger may have well introduced it.
Simplest solution:- I used xCode 7 and iOS 9.
in your .m
delete #import "VC.h"
save .m and link your outlet again it work fine.
/* worked for me */
<div id="divid"> </div>
<script type="text/javascript">
var hold = document.getElementById("divid");
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "chkbox1";
checkbox.id = "cbid";
var label = document.createElement('label');
var tn = document.createTextNode("Not A RoBot");
label.htmlFor="cbid";
label.appendChild(tn);
hold.appendChild(label);
hold.appendChild(checkbox);
</script>
Not the best way but works to Split with Multiple and Different seperators/delimiters
html
<button onclick="myFunction()">Split with Multiple and Different seperators/delimiters</button>
<p id="demo"></p>
javascript
<script>
function myFunction() {
var str = "How : are | you doing : today?";
var res = str.split(' | ');
var str2 = '';
var i;
for (i = 0; i < res.length; i++) {
str2 += res[i];
if (i != res.length-1) {
str2 += ",";
}
}
var res2 = str2.split(' : ');
//you can add countless options (with or without space)
document.getElementById("demo").innerHTML = res2;
</script>
$howmanyuser_query=$conn->query('SELECT COUNT(uno) FROM userentry;');
$howmanyuser=$howmanyuser_query->fetch_array(MYSQLI_NUM);
echo $howmanyuser[0];
after the so many hours excellent :)
Here is a pretty easy way to do it.
val data = List("it", "was", "the", "best", "of", "times", "it", "was",
"the", "worst", "of", "times")
data.foldLeft(Map[String,Int]().withDefaultValue(0)){
case (acc, letter) =>
acc + (letter -> (1 + acc(letter)))
}
// => Map(worst -> 1, best -> 1, it -> 2, was -> 2, times -> 2, of -> 2, the -> 2)