In a more basic way to explain: An interface is sort of like an empty muffin pan. It's a class file with a set of method definitions that have no code.
An abstract class is the same thing, but not all functions need to be empty. Some can have code. It's not strictly empty.
Why differentiate: There's not much practical difference in Python, but on the planning level for a large project, it could be more common to talk about interfaces, since there's no code. Especially if you're working with Java programmers who are accustomed to the term.
For command line arguments:
VARIABLE="${1:-$DEFAULTVALUE}"
which assigns to VARIABLE
the value of the 1st argument passed to the script or the value of DEFAULTVALUE
if no such argument was passed. Qouting prevents globbing and word splitting.
For ArrayList the following works:
ArrayList<Foo> list = new ArrayList<Foo>();
//... add values
Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
Old Way (pre-1.7):
$("...").attr("onclick", "").unbind("click");
New Way (1.7+):
$("...").prop("onclick", null).off("click");
(Replace ... with the selector you need.)
// use the "[attr=value]" syntax to avoid syntax errors with special characters (like "$")_x000D_
$('[id="a$id"]').prop('onclick',null).off('click');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<a id="a$id" onclick="alert('get rid of this')" href="javascript:void(0)" class="black">Qualify</a>
_x000D_
You can set the width in pixels via inline styling:
<input type="text" name="text" style="width: 195px;">
You can also set the width with a visible character length:
<input type="text" name="text" size="35">
Because you have used absolute positioning, and specified a top percentage, only margin-top will affect the location of your .item object. If instead you positioned it using bottom: 50%, then you'd need margin-bottom -8px to centre it, and margin-top would have no effect.
Margin affects the boundaries of an element in terms of positioning it, either absolutely as in your case, or relative to neighbouring elements. Imagine that margin is the foundations of your element on which it sits. They are typically the same size as it, but can be made larger or smaller on any or all of the four edges.
Your CSS tells the browser to position the top of your element the margin at a point 50% of the way down the page. However, as all elements are not a single pixel, the browser needs to know which part of it to line up 50% of the way down the page. For lining up the top of the element, it uses the top margin. By default this is in line with the top of the element, but you can alter it with CSS.
In your case, top 50% would result in the top of the element starting in the middle of the page. By applying a negative top margin, the browser uses the point 8px into the element from the top (ie the line across the middle of it) as the place to position at 50%.
If you apply a positive margin to the bottom, this extends the line the browser uses to position the bottom out away from the element itself, giving a gap between it and any adjacent element below, or affecting where it is placed absolutely if positioning based on the bottom.
If you're looking for a ruby based solution for this problem, I recommend using the Google Calculator method a solution similar to the following: http://j.mp/QIC564
require 'faraday'
require 'faraday_middleware'
require 'json'
# Debug:
# require "pry"
country_code_src = "USD"
country_code_dst = "INR"
connection = Faraday.get("http://www.google.com/ig/calculator?hl=en&q=1#{country_code_src}=?#{country_code_dst}")
currency_comparison_hash = eval connection.body #Google's output is not JSON, it's a hash
dst_currency_value, *dst_currency_text = *currency_comparison_hash[:rhs].split(' ')
dst_currency_value = dst_currency_value.to_f
dst_currency_text = dst_currency_text.join(' ')
puts "#{country_code_dst} -> #{dst_currency_value} (#{dst_currency_text} to 1 #{country_code_src})"
If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
Also see this SO thread: Open directory dialog
using FileSaver.js solved my issue thanks for help, below code helped me
'$'
DownloadClaimForm: function (claim)
{
url = baseAddress + "DownLoadFile";
return $http.post(baseAddress + "DownLoadFile", claim, {responseType: 'arraybuffer' })
.success(function (data) {
var file = new Blob([data], { type: 'application/pdf' });
saveAs(file, 'Claims.pdf');
});
}
Never use md5() for securing your password, even with salt, it is always dangerous!!
Make your password secured with latest hashing algorithms as below.
<?php
// Your original Password
$password = '121@121';
//PASSWORD_BCRYPT or PASSWORD_DEFAULT use any in the 2nd parameter
/*
PASSWORD_BCRYPT always results 60 characters long string.
PASSWORD_DEFAULT capacity is beyond 60 characters
*/
$password_encrypted = password_hash($password, PASSWORD_BCRYPT);
For matching with database's encrypted password and user inputted password use the below function.
<?php
if (password_verify($password_inputted_by_user, $password_encrypted)) {
// Success!
echo 'Password Matches';
}else {
// Invalid credentials
echo 'Password Mismatch';
}
If you want to use your own salt, use your custom generated function for the same, just follow below, but I not recommend this as It is found deprecated in latest versions of PHP.
Read about password_hash() before using below code.
<?php
$options = [
'salt' => your_custom_function_for_salt(),
//write your own code to generate a suitable & secured salt
'cost' => 12 // the default cost is 10
];
$hash = password_hash($your_password, PASSWORD_DEFAULT, $options);
For android 2.2+ (api level8), you can use ScaleGestureDetector.
you need a member:
private ScaleGestureDetector mScaleDetector;
in your constructor (or onCreate()) you add:
mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
return false;
}
});
You override onTouchEvent:
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
return true;
}
If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().
I had two problems with the accepted answer.
Screen
class are incorrect when display scaling is used and your application is not declared dpiAware.Here's my updated solution using the Screen.AllScreens
static property and calling EnumDisplaySettings
using p/invoke to get the real screen resolution.
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
const int ENUM_CURRENT_SETTINGS = -1;
static void Main()
{
foreach (Screen screen in Screen.AllScreens)
{
DEVMODE dm = new DEVMODE();
dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));
EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref dm);
using (Bitmap bmp = new Bitmap(dm.dmPelsWidth, dm.dmPelsHeight))
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(dm.dmPositionX, dm.dmPositionY, 0, 0, bmp.Size);
bmp.Save(screen.DeviceName.Split('\\').Last() + ".png");
}
}
}
[DllImport("user32.dll")]
public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
private const int CCHDEVICENAME = 0x20;
private const int CCHFORMNAME = 0x20;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public ScreenOrientation dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
}
References:
https://stackoverflow.com/a/36864741/987968 http://pinvoke.net/default.aspx/user32/EnumDisplaySettings.html?diff=y
Rather going for pop up,I personally liked this solution, mentioned on this Question thread JavaScript: location.href to open in new window/tab?
$(document).on('click','span.external-link',function(){
var t = $(this),
URL = t.attr('data-href');
$('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();
});
Working example.
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
for f in `find -depth`; do mv ${f} ${f,,} ; done
find -depth
prints each file and directory, with a directory's contents printed before the directory itself. ${f,,}
lowercases the file name.
In iOS 6 you can set the tint color of UIPageControl
:
There are 2 new properties:
pageIndicatorTintColor
currentPageIndicatorTintColor
You can also use the appearance API to change the tint color of all page indicators.
If you are targeting iOS 5 make sure it doesn't crash:
if ([pageControl respondsToSelector:@selector(setPageIndicatorTintColor:)]) {
pageControl.pageIndicatorTintColor = [UIColor whiteColor];
}
Use getcwd
#include <stdio.h> /* defines FILENAME_MAX */
//#define WINDOWS /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
int main(){
char buff[FILENAME_MAX];
GetCurrentDir( buff, FILENAME_MAX );
printf("Current working dir: %s\n", buff);
return 1;
}
OR
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
main() {
char *buf;
buf=(char *)malloc(100*sizeof(char));
getcwd(buf,100);
printf("\n %s \n",buf);
}
here is how I handled if else if situation
if %env%==dev (
echo "dev env selected selected"
) else (
if %env%==prod (
echo "prod env selected"
)
)
Note it is not the same as if-elseif block as the other programming languages like C++ or Java but it will do what you need to do
I checked above solutions and found them quite lengthy. It can be accomplished with just one line of code:
currentElement.nextElementSibling.focus();
or
currentElement.previousElementSibling.focus();
here currentElement may be any i.e. document.activeElement or this if current element is in function's context.
I tracked tab and shift-tab events with keydown event Here is a snippet that relies on "JQuery":
let cursorDirection = ''
$(document).keydown(function (e) {
let key = e.which || e.keyCode;
if (e.shiftKey) {
//does not matter if user has pressed tab key or not.
//If it matters for you then compare it with 9
cursorDirection = 'prev';
}
else if (key == 9) {
//if tab key is pressed then move next.
cursorDirection = 'next';
}
else {
cursorDirection == '';
}
});
once you have cursor direction then you can use nextElementSibling.focus
or previousElementSibling.focus
methods
You can do it using pandas
only:
In [235]:
dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],'B':[103.02,107.26,110.35,114.23,114.68], 'C':['big','small','big','small','small']})
df = dfTest[['A', 'B']]
df_norm = (df - df.min()) / (df.max() - df.min())
print df_norm
print pd.concat((df_norm, dfTest.C),1)
A B
0 0.000000 0.000000
1 0.926219 0.363636
2 0.935335 0.628645
3 1.000000 0.961407
4 0.938495 1.000000
A B C
0 0.000000 0.000000 big
1 0.926219 0.363636 small
2 0.935335 0.628645 big
3 1.000000 0.961407 small
4 0.938495 1.000000 small
I found the nice resource Standard C++ Containers. Probably this is what you all looking for.
VECTOR
Constructors
vector<T> v; Make an empty vector. O(1)
vector<T> v(n); Make a vector with N elements. O(n)
vector<T> v(n, value); Make a vector with N elements, initialized to value. O(n)
vector<T> v(begin, end); Make a vector and copy the elements from begin to end. O(n)
Accessors
v[i] Return (or set) the I'th element. O(1)
v.at(i) Return (or set) the I'th element, with bounds checking. O(1)
v.size() Return current number of elements. O(1)
v.empty() Return true if vector is empty. O(1)
v.begin() Return random access iterator to start. O(1)
v.end() Return random access iterator to end. O(1)
v.front() Return the first element. O(1)
v.back() Return the last element. O(1)
v.capacity() Return maximum number of elements. O(1)
Modifiers
v.push_back(value) Add value to end. O(1) (amortized)
v.insert(iterator, value) Insert value at the position indexed by iterator. O(n)
v.pop_back() Remove value from end. O(1)
v.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n)
v.erase(iterator) Erase value indexed by iterator. O(n)
v.erase(begin, end) Erase the elements from begin to end. O(n)
For other containers, refer to the page.
You can use Java 8 Stream API.
You can create a Stream of objects and collect them as a List.
private List<String> symbolsPresent = Stream.of("ONE", "TWO", "THREE", "FOUR")
.collect(Collectors.toList());
It's surprising how tricky it is to find the perfect solution to this problem. I haven't yet found an answer on this page that doesn't fail in at least some situations (especially if the string contains newlines or tabs, or if the word break is anything other than a space, or if the string has UTF-8 multibyte characters).
Here is a simple solution that works in all cases. There were similar answers here, but the "s" modifier is important if you want it to work with multi-line input, and the "u" modifier makes it correctly evaluate UTF-8 multibyte characters.
function wholeWordTruncate($s, $characterCount)
{
if (preg_match("/^.{1,$characterCount}\b/su", $s, $match)) return $match[0];
return $s;
}
One possible edge case with this... if the string doesn't have any whitespace at all in the first $characterCount characters, it will return the entire string. If you prefer it forces a break at $characterCount even if it isn't a word boundary, you can use this:
function wholeWordTruncate($s, $characterCount)
{
if (preg_match("/^.{1,$characterCount}\b/su", $s, $match)) return $match[0];
return mb_substr($return, 0, $characterCount);
}
One last option, if you want to have it add ellipsis if it truncates the string...
function wholeWordTruncate($s, $characterCount, $addEllipsis = ' …')
{
$return = $s;
if (preg_match("/^.{1,$characterCount}\b/su", $s, $match))
$return = $match[0];
else
$return = mb_substr($return, 0, $characterCount);
if (strlen($s) > strlen($return)) $return .= $addEllipsis;
return $return;
}
Explanation and working solution here: Howto: div with onclick inside another div with onclick javascript
by executing this script in your inner click handler:
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
Since you are using this for configuration, your best bet is apache commons-configuration. For simple files it's way easier to use than "raw" XML parsers.
See the XML how-to
That's how Start-Process
was designed for some reason. Here's a way to get it without sending to file:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode
It has a -force
parameter.????
You can give simply hide this by giving a boolean parameter----->
debugShowCheckedModeBanner: false,
void main() {
Bloc.observer = SimpleBlocDelegate();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Prescription Writing Software',
theme: ThemeData(
primarySwatch: Colors.blue,
scaffoldBackgroundColor: Colors.white,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: SplashScreen(),
);
}
}
Start by reading the fork man page as well as the getppid / getpid man pages.
From fork's
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.
So this should be something down the lines of
if ((pid=fork())==0){
printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
printf("Dont yada yada me, im your parent with pid %u ", getpid());
}
As to your question:
This is the child process. My pid is 22163 and my parent's id is 0.
This is the child process. My pid is 22162 and my parent's id is 22163.
fork()
executes before the printf
. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork()
will return 0
to the child process, and the pid
of the child process to the parent process.
You get two running processes, each one will execute this instruction statement:
printf ("... My pid is %d and my parent's id is %d",getpid(),0);
and
printf ("... My pid is %d and my parent's id is %d",getpid(),22163);
~
To wrap it up, the above line is the child, specifying its pid
. The second line is the parent process, specifying its id (22162) and its child's (22163).
This is how i replace diacritic characters to non-diacritic ones in all my .NET program
C#:
//Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter 'é' is substituted by an 'e'
public string RemoveDiacritics(string s)
{
string normalizedString = null;
StringBuilder stringBuilder = new StringBuilder();
normalizedString = s.Normalize(NormalizationForm.FormD);
int i = 0;
char c = '\0';
for (i = 0; i <= normalizedString.Length - 1; i++)
{
c = normalizedString[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().ToLower();
}
VB .NET:
'Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter "é" is substituted by an "e"'
Public Function RemoveDiacritics(ByVal s As String) As String
Dim normalizedString As String
Dim stringBuilder As New StringBuilder
normalizedString = s.Normalize(NormalizationForm.FormD)
Dim i As Integer
Dim c As Char
For i = 0 To normalizedString.Length - 1
c = normalizedString(i)
If CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark Then
stringBuilder.Append(c)
End If
Next
Return stringBuilder.ToString().ToLower()
End Function
This is a security feature in Rails. Add this line of code in the form:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Documentation can be found here: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html
The error Object expected
is raised because Jquery is not loaded. This happens because of browser security (usually IE) which does not allow you executing external javascript source code. You can correct this problem by:
OR
I prefer the first solution.
The following query works. It uses each group to do the select instead of SelectMany
. SelectMany
works on each element from each collection. For example, in your query you have a result of 2 collections. SelectMany
gets all the results, a total of 3, instead of each collection. The following code works on each IGrouping
in the select portion to get your aggregate operations working correctly.
var results = from line in Lines
group line by line.ProductCode into g
select new ResultLine {
ProductName = g.First().Name,
Price = g.Sum(pc => pc.Price).ToString(),
Quantity = g.Count().ToString(),
};
See Tejas Lagvankar's post about this subject. Below are some key differences between Service and IntentService and other components.
Executing PHP functions by the onclick event is a cumbersome task and near impossible.
Instead you can redirect to another PHP page.
Say you are currently on a page one.php and you want to fetch some data from this php script process the data and show it in another page i.e. two.php you can do it by writing the following code
<button onclick="window.location.href='two.php'">Click me</button>
For those who are working with aws I would highly recommend working with EC2 Instance Connect.
Amazon EC2 Instance Connect provides a simple and secure way to connect to your instances using Secure Shell (SSH).
With EC2 Instance Connect, you use AWS Identity and Access Management (IAM) policies and principles to control SSH access to your instances, removing the need to share and manage SSH keys.
After installing the relevant packages (pip install ec2instanceconnectcli
or cloning the repo directly) you can connect very easy to multiple EC2 instances by just changing the instance id:
What is happening behind the scenes?
When you connect to an instance using EC2 Instance Connect, the Instance Connect API pushes a one-time-use SSH public key to the instance metadata where it remains for 60 seconds. An IAM policy attached to your IAM user authorizes your IAM user to push the public key to the instance metadata.
The SSH daemon uses AuthorizedKeysCommand and AuthorizedKeysCommandUser, which are configured when Instance Connect is installed, to look up the public key from the instance metadata for authentication, and connects you to the instance.
(*) Amazon Linux 2 2.0.20190618 or later and Ubuntu 20.04 or later comes preconfigured with EC2 Instance Connect. For other supported Linux distributions, you must set up Instance Connect for every instance that will support using Instance Connect. This is a one-time requirement for each instance.
Links:
Set up EC2 Instance Connect
Connect using EC2 Instance Connect
Securing your bastion hosts with Amazon EC2 Instance Connect
You could solve this with some simple gazpacho parsing:
from gazpacho import Soup
soup = Soup(html)
tds = soup.find("td", {"class": "pos"})
tds[1].find("strong").text
Which will output:
text I am looking for
CREATE USER username SUPERUSER password 'userpass';
ALTER USER username set default_transaction_read_only = on;
You can use getElementsByClassName()
method for what you want.
var elems = document.getElementsByClassName("a b c");_x000D_
elems[0].style.color = "green";_x000D_
console.log(elems[0]);
_x000D_
<ul>_x000D_
<li class="a">a</li>_x000D_
<li class="a b">a, b</li>_x000D_
<li class="a b c">a, b, c</li>_x000D_
</ul>
_x000D_
This is the fastest solution also. you can see a benchmark about that here.
We can use call method to use other class methods as static methods.
class _Callable:
def __init__(self, anycallable):
self.__call__ = anycallable
class Model:
def get_instance(conn, table_name):
""" do something"""
get_instance = _Callable(get_instance)
provs_fac = Model.get_instance(connection, "users")
Why not simply check for dict.keys.contains(key)
?
Checking for dict[key] != nil
will not work in cases where the value is nil.
As with a dictionary [String: String?]
for example.
Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?
There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.
Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.
In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.
Sometimes if there's no any application associated with geo: protocal , you could use try-catch to get the ActivityNotFoundException to handle it.
It happens when you use some emulator like androVM which is not installed google map by default.
I would use a nice UML example.
Take a university that has 1 to 20 different departments and each department has 1 to 5 professors. There is a composition link between a University and its' departments. There is an aggregation link between a department and its' professors.
Composition is just a STRONG aggregation, if the university is destroyed then the departments should also be destroyed. But we shouldn't kill the professors even if their respective departments disappear.
In java :
public class University {
private List<Department> departments;
public void destroy(){
//it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
if(departments!=null)
for(Department d : departments) d.destroy();
departments.clean();
departments = null;
}
}
public class Department {
private List<Professor> professors;
private University university;
Department(University univ){
this.university = univ;
//check here univ not null throw whatever depending on your needs
}
public void destroy(){
//It's aggregation here, we just tell the professor they are fired but they can still keep living
for(Professor p:professors)
p.fire(this);
professors.clean();
professors = null;
}
}
public class Professor {
private String name;
private List<Department> attachedDepartments;
public void destroy(){
}
public void fire(Department d){
attachedDepartments.remove(d);
}
}
Something around this.
EDIT: an example as requested
public class Test
{
public static void main(String[] args)
{
University university = new University();
//the department only exists in the university
Department dep = university.createDepartment();
// the professor exists outside the university
Professor prof = new Professor("Raoul");
System.out.println(university.toString());
System.out.println(prof.toString());
dep.assign(prof);
System.out.println(university.toString());
System.out.println(prof.toString());
dep.destroy();
System.out.println(university.toString());
System.out.println(prof.toString());
}
}
University class
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class University {
private List<Department> departments = new ArrayList<>();
public Department createDepartment() {
final Department dep = new Department(this, "Math");
departments.add(dep);
return dep;
}
public void destroy() {
System.out.println("Destroying university");
//it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
if (departments != null)
departments.forEach(Department::destroy);
departments = null;
}
@Override
public String toString() {
return "University{\n" +
"departments=\n" + departments.stream().map(Department::toString).collect(Collectors.joining("\n")) +
"\n}";
}
}
Department class
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Department {
private final String name;
private List<Professor> professors = new ArrayList<>();
private final University university;
public Department(University univ, String name) {
this.university = univ;
this.name = name;
//check here univ not null throw whatever depending on your needs
}
public void assign(Professor p) {
//maybe use a Set here
System.out.println("Department hiring " + p.getName());
professors.add(p);
p.join(this);
}
public void fire(Professor p) {
//maybe use a Set here
System.out.println("Department firing " + p.getName());
professors.remove(p);
p.quit(this);
}
public void destroy() {
//It's aggregation here, we just tell the professor they are fired but they can still keep living
System.out.println("Destroying department");
professors.forEach(professor -> professor.quit(this));
professors = null;
}
@Override
public String toString() {
return professors == null
? "Department " + name + " doesn't exists anymore"
: "Department " + name + "{\n" +
"professors=" + professors.stream().map(Professor::toString).collect(Collectors.joining("\n")) +
"\n}";
}
}
Professor class
import java.util.ArrayList;
import java.util.List;
public class Professor {
private final String name;
private final List<Department> attachedDepartments = new ArrayList<>();
public Professor(String name) {
this.name = name;
}
public void destroy() {
}
public void join(Department d) {
attachedDepartments.add(d);
}
public void quit(Department d) {
attachedDepartments.remove(d);
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Professor " + name + " working for " + attachedDepartments.size() + " department(s)\n";
}
}
The implementation is debatable as it depends on how you need to handle creation, hiring deletion etc. Unrelevant for the OP
@Query("SELECT rd FROM ReleaseDateType rd, CacheMedia cm WHERE ...")
This answer might not be 100% relevant to the question. But it does address the problem. I found this simple way of achieving this requirement. Code goes below:
<a href="@Url.Action("Display", "Customer")?custId={{cust.Id}}"></a>
In the above example {{cust.Id}} is an AngularJS variable. However one can replace it with a JavaScript variable.
I haven't tried passing multiple variables using this method but I'm hopeful that also can be appended to the Url if required.
I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.
(The strange thing was that all ssh-*
commands were valid, (bash could execute as program) but the openssh package wasn't installed.)
select Qty, vajan, Rate,Amt,nhamali,ncommission,ntolai from SalesDtl,SalesMSt where SalesDtl.PurEntryNo=1 and SalesMST.SaleDate= (22/03/2014) and SalesMST.SaleNo= SalesDtl.SaleNo;
That should work.
So do you want them to get the IE password-challenge box, or should they be directed to your login page and enter their information there? If it's the second option, then you should at least enable Anonymous access to your login page, since the site won't know who they are yet.
If you want the first option, then the login page they're getting forwarded to will need to read the currently logged-in user and act based on that, since they would have had to correctly authenticate to get this far.
I find it easier to remember to just read it and then write it.
For example:
with open('file') as f:
data = f.read()
with open('file', 'w') as f:
f.write('hello')
To exclude any file from a jar / target directory you can use the <excludes>
tag in your pom.xml file.
In the next example, all files with .properties
extension will not be included:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>*.properties</exclude>
</excludes>
<filtering>false</filtering>
</resource>
</resources>
</build>
<select name="owner">
<?php
$sql = mysql_query("SELECT username FROM users");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>
Use
echo "your sql script;" | mysql -u -p -h db_name
From what I know when I look at this question here
It said there that "in PHP, there is a distinct difference in Header output. In the examples below I chose to use a different header but for sake of showing the difference between exit() and die() that doesn't matter", and tested (personally)
Is there any specific reason you would want your buttons in an item template.You can alternatively do it the following way , there by giving you the full power of the grid row editing event.You are also given a bonus of wiring easily the cancel and delete functionality.
Mark up
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit"
CausesValidation="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update"
Text="Update" Visible="true" ImageUrl="~/images/saveHS.png"
/>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/images/Edit_UndoHS.png" />
<asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"
ImageUrl="~/images/delete.png" />
</EditItemTemplate>
<ControlStyle BackColor="Transparent" BorderStyle="None" />
<FooterStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Code behind
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txtledName = (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");
//then do something with the retrieved textbox's text.
}
The order of precedence for resolving TNS names in ODP.NET, Managed Driver is this (see here):
I believe the reason your sample works with Oracle.DataAccess but not with Oracle.ManagedDataAccess is that Windows registry based configuration is not supported for the latter (see documentation) - the ODP.NET installation sets an ORACLE_HOME registry key (HLKM\SOFTWARE\Oracle\Key_NAME\ORACLE_HOME) which is recognized only by the unmanaged part.
You can do:
getMap(locations.toArray(new WorldLocation[locations.size()]));
or
getMap(locations.toArray(new WorldLocation[0]));
or
getMap(new WorldLocation[locations.size()]);
@SuppressWarnings("unchecked")
is needed to remove the ide warning.
I found sudo-for-cygwin, maybe this would work, it is a client/server application that uses a python script to spawn a child process in windows (pty) and bridges user's tty and the process I/O.
It requires python in windows and Python modules greenlet, and eventlet in Cygwin.
String str= "somestring";
String[] values = str.split("\\D+");
I think you missed a key point in the documentation for .add()
Mutates the original moment by adding time.
You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)
If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.
You can work around this behavior by cloning the moment, as described here.
Also, you cannot just use ==
to test. You could format each moment to the same output and compare those, or you could just use the .isSame()
method.
Your code is now:
var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours'); // see the cloning?
returned_endate.isSame(expected_enddate) // true
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
Use re.sub
directly, this allows you to specify a count
:
regex.sub('', url, 1)
(Note that the order of arguments is replacement
, original
not the opposite, as might be suspected.)
First, create the derived value:
df.loc[0, 'C'] = df.loc[0, 'D']
Then iterate through the remaining rows and fill the calculated values:
for i in range(1, len(df)):
df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']
Index_Date A B C D
0 2015-01-31 10 10 10 10
1 2015-02-01 2 3 23 22
2 2015-02-02 10 60 290 280
The solution is:
Update-Database –TargetMigration 201609261919239_yourLastMigrationSucess
I've managed to add a 'hint' that is omitted from the drop down list. If my code looks a bit weird it's because I'm using Xamarin.Android so it's in C# but for all intents (heh) and purposes the Java equivalent should have the same effect.
The gist is that I've created a custom ArrayAdapter that will detect if it is the hint in the GetDropDownView method. If so then it will inflate an empty XML to hide the hint from the drop down.
My spinnerItem.xml is ...
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/text_left_padding"
android:textAppearance="?android:attr/textAppearanceLarge"/>
My 'empty' hintSpinnerDropdownItem.xml which will hide the hint.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
I pass in an array of CustomObj without the hint. That's why I have the additional AddPrompt method to insert the hint at the beginning before it's passed to the parent constructor.
public class CustomArrayAdapter: ArrayAdapter<CustomObj>
{
private const int HintPosition = 0;
private const CustomObj HintValue = null;
private const string Hint = "Hint";
public CustomArrayAdapter(Context context, int textViewResourceId, CustomObj[] customObjs) : base(context, textViewResourceId, AddPrompt(customObjs))
{
private static CustomObj[] AddPrompt(CustomObj[] customObjs)
{
CustomObj[] customObjsWithHint = new CustomObj[customObjs.Length + 1];
CustomObj[] hintPlaceholder = { HintValue };
Array.Copy(hintPlaceholder , customObjsWithHint , 1);
Array.Copy(customObjs, 0, customObjsWithHint , 1, customObjs.Length);
return customObjsWithHint ;
}
public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
{
CustomObj customObj = GetItem(position);
bool isHint = customObj == HintValue;
if (convertView == null)
{
convertView = LayoutInflater.From(base.Context).Inflate(Resource.Layout.spinnerItem, parent, false);
}
TextView textView = convertView.FindViewById<TextView>(Resource.Id.spinnerText);
textView.Text = isHint ? Hint : customObj.Value;
textView.SetTextColor(isHint ? Color.Gray : Color.Black);
return convertView;
public override Android.Views.View GetDropDownView(int position, Android.Views.View convertView, ViewGroup parent)
{
CustomObj customObj = GetItem(position);
if (position == HintPosition)
{
convertView = LayoutInflater.From(base.Context).Inflate(Resource.Layout.hintSpinnerDropdownItem, parent, false);
}
else
{
convertView = LayoutInflater.From(base.Context).Inflate(Resource.Layout.spinnerItem, parent, false);
TextView textView = convertView.FindViewById<TextView>(Resource.Id.spinnerText);
textView.Text = customObj.Value;
}
return convertView;
}
}
This actually depends on your external component. When you reference an external component in a .NET application it generates a GUID to identify that component. This error occurs when the external component referenced by one of your projects has the same name and but different version as another such component in another assembly.
This sometimes happens when you use "Browse" to find references and add the wrong version of the assembly, or you have a different version of the component in your code repository as the one you installed in the local machine.
Do try to find which projects have these conflicts, remove the components from the reference list, then add them again making sure that you're pointing to the same file.
We can use title()
function with negative line
value to bring down the title.
See this example:
plot(1, 1)
title("Title", line = -2)
In your database table list it should show View in Type column. To edit View:
Hope this help
update: in PHPMyAdmin 4.x, it doesn't show View in Type, but you can still recognize it:
Of course it may be just an empty table, but when you open the structure, you will know whether it's a table or a view.
The only things I can think of are
I have recently been using str_replace and setting text in the HTML portion like so
{{TEXT_TO_REPLACE}}
using file_get_contents() you can grab html data and then organise it how you like.
here is a demo
myReplacementCodeFunction(){
$text = '<img src="'.$row['name'].'" />';
$text .= "<div>".$row['name']."</div>";
$text .= "<div>".$row['title']."</div>";
$text .= "<div>".$row['description']."</div>";
$text .= "<div>".$row['link']."</div>";
$text .= "<br />";
return $text;
}
$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;
and now a demo html file:
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
{{TEXT_TO_REPLACE}}
</body>
</html>
From:
http://hivelogic.com/articles/converting-from-mercurial-to-git
Migrating
It’s a relatively simple process. First we download fast-export (the best way is via its Git repository, which I’ll clone right to the desktop), then we create a new git repository, perform the migration, and check out the HEAD. On the command line, it goes like this:
cd ~/Desktop
git clone git://repo.or.cz/fast-export.git
git init git_repo
cd git_repo
~/Desktop/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
git checkout HEAD
You should see a long listing of commits fly by as your project is migrated after running fast-export. If you see errors, they are likely related to an improperly specified Python path (see the note above and customize for your system).
That’s it, you’re done.
JButton#isEnabled
changes the user interactivity of a component, that is, whether a user is able to interact with it (press it) or not.
When a JButton
is pressed, it fires a actionPerformed
event.
You are receiving Add button is pressed
when you press the confirm button because the add button is enabled. As stated, it has nothing to do with the pressed start of the button.
Based on you code, if you tried to check the "pressed" start of the add button within the confirm button's ActionListener
it would always be false, as the button will only be in the pressed state while the add button's ActionListener
s are being called.
Based on all this information, I would suggest you might want to consider using a JCheckBox
which you can then use JCheckBox#isSelected
to determine if it has being checked or not.
Take a closer look at How to Use Buttons for more details
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}
Here's a short example, that creates and array of objects, and sorts numerically or alphabetically:
// Create Objects Array
var arrayCarObjects = [
{brand: "Honda", topSpeed: 45},
{brand: "Ford", topSpeed: 6},
{brand: "Toyota", topSpeed: 240},
{brand: "Chevrolet", topSpeed: 120},
{brand: "Ferrari", topSpeed: 1000}
];
// Sort Objects Numerically
arrayCarObjects.sort((a, b) => (a.topSpeed - b.topSpeed));
// Sort Objects Alphabetically
arrayCarObjects.sort((a, b) => (a.brand > b.brand) ? 1 : -1);
Just to point out that there is an approach using functions from the tidyverse
, which I find more readable than gsub
:
a %>% stringr::str_remove(pattern = ".*_")
The Singleton:
package com.domain.packagename;
import android.content.Context;
/**
* Created by Versa on 10.09.15.
*/
public class ApplicationContextSingleton {
private static PrefsContextSingleton mInstance;
private Context context;
public static ApplicationContextSingleton getInstance() {
if (mInstance == null) mInstance = getSync();
return mInstance;
}
private static synchronized ApplicationContextSingleton getSync() {
if (mInstance == null) mInstance = new PrefsContextSingleton();
return mInstance;
}
public void initialize(Context context) {
this.context = context;
}
public Context getApplicationContext() {
return context;
}
}
Initialize the Singleton in your Application
subclass:
package com.domain.packagename;
import android.app.Application;
/**
* Created by Versa on 25.08.15.
*/
public class mApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ApplicationContextSingleton.getInstance().initialize(this);
}
}
If I´m not wrong, this gives you a hook to applicationContext everywhere, call it with ApplicationContextSingleton.getInstance.getApplicationContext();
You shouldn´t need to clear this at any point, as when application closes, this goes with it anyway.
Remember to update AndroidManifest.xml
to use this Application
subclass:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.domain.packagename"
>
<application
android:allowBackup="true"
android:name=".mApplication" <!-- This is the important line -->
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:icon="@drawable/app_icon"
>
Now you should be able to use ApplicationContextSingleton.getInstance().getApplicationContext().getResources() from anywhere, also the very few places where application subclasses can´t.
Please let me know if you see anything wrong here, thank you. :)
DateTime.Now.ToString("yyyyMMddHHmmss");
if you just want it displayed as a string
'^(part1|part2|part1,part2)$'
does it work?
You can use the stat()
method from the os
module. You can provide it with a path in the form of a string, bytes or even a PathLike object. It works with file descriptors as well.
import os
res = os.stat(filename)
res.st_size # this variable contains the size of the file in bytes
Here is the solution for index variable
Let's say, you have found 5 elements with same locator and you would like to perform action on each element by providing index number (here, variable is used for index as "i")
for(int i=1; i<=5; i++)
{
string xPathWithVariable = "(//div[@class='className'])" + "[" + i + "]";
driver.FindElement(By.XPath(xPathWithVariable)).Click();
}
It takes XPath :
(//div[@class='className'])[1]
(//div[@class='className'])[2]
(//div[@class='className'])[3]
(//div[@class='className'])[4]
(//div[@class='className'])[5]
There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
And when you need it you can get it with :
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.
For me turning on and off the setting on
iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard
proved to fix the issue on simulators.
When you do a cmp a,b
, the flags are set as if you had calculated a - b
.
Then the jmp
-type instructions check those flags to see if the jump should be made.
In other words, the first block of code you have (with my comments added):
cmp al,dl ; set flags based on the comparison
jg label1 ; then jump based on the flags
would jump to label1
if and only if al
was greater than dl
.
You're probably better off thinking of it as al > dl
but the two choices you have there are mathematically equivalent:
al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0 (cancel the terms on the right hand side)
You need to be careful when using jg
inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.
See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JO | Jump if overflow | | OF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNO | Jump if not overflow | | OF = 0 |
+--------+------------------------------+-------------+--------------------+
| JS | Jump if sign | | SF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNS | Jump if not sign | | SF = 0 |
+--------+------------------------------+-------------+--------------------+
| JE/ | Jump if equal | | ZF = 1 |
| JZ | Jump if zero | | |
+--------+------------------------------+-------------+--------------------+
| JNE/ | Jump if not equal | | ZF = 0 |
| JNZ | Jump if not zero | | |
+--------+------------------------------+-------------+--------------------+
| JP/ | Jump if parity | | PF = 1 |
| JPE | Jump if parity even | | |
+--------+------------------------------+-------------+--------------------+
| JNP/ | Jump if no parity | | PF = 0 |
| JPO | Jump if parity odd | | |
+--------+------------------------------+-------------+--------------------+
| JCXZ/ | Jump if CX is zero | | CX = 0 |
| JECXZ | Jump if ECX is zero | | ECX = 0 |
+--------+------------------------------+-------------+--------------------+
Then the unsigned ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JB/ | Jump if below | unsigned | CF = 1 |
| JNAE/ | Jump if not above or equal | | |
| JC | Jump if carry | | |
+--------+------------------------------+-------------+--------------------+
| JNB/ | Jump if not below | unsigned | CF = 0 |
| JAE/ | Jump if above or equal | | |
| JNC | Jump if not carry | | |
+--------+------------------------------+-------------+--------------------+
| JBE/ | Jump if below or equal | unsigned | CF = 1 or ZF = 1 |
| JNA | Jump if not above | | |
+--------+------------------------------+-------------+--------------------+
| JA/ | Jump if above | unsigned | CF = 0 and ZF = 0 |
| JNBE | Jump if not below or equal | | |
+--------+------------------------------+-------------+--------------------+
And, finally, the signed ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JL/ | Jump if less | signed | SF <> OF |
| JNGE | Jump if not greater or equal | | |
+--------+------------------------------+-------------+--------------------+
| JGE/ | Jump if greater or equal | signed | SF = OF |
| JNL | Jump if not less | | |
+--------+------------------------------+-------------+--------------------+
| JLE/ | Jump if less or equal | signed | ZF = 1 or SF <> OF |
| JNG | Jump if not greater | | |
+--------+------------------------------+-------------+--------------------+
| JG/ | Jump if greater | signed | ZF = 0 and SF = OF |
| JNLE | Jump if not less or equal | | |
+--------+------------------------------+-------------+--------------------+
It's very simple javascript code to trigger a download for the user:
window.open("<insert URL here>")
You don't want/need axios for this operation; it should be standard to just let the browser do it's thing.
Note: If you need authorisation for the download then this might not work. I'm pretty sure you can use cookies to authorise a request like this, provided it's within the same domain, but regardless, this might not work immediately in such a case.
As for whether it's possible... not with the in-built file downloading mechanism, no.
Use the same XML file format from Evan's answer, but one drawable file is all you need for formatting.
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button_background"
android:button="@android:color/transparent"
android:checked="true"
android:text="RadioButton1" />
And your separate drawable file:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#333333" />
<solid android:color="#cccccc" />
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#333333" />
<solid android:color="#cccccc" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#cccccc" />
<solid android:color="#ffffff" />
</shape>
</item>
</selector>
You can for example just add a "col-xs-12" class to the <ul>
which holds the list items:
<div class="col-md-6" data-toggle="dropdown">
First column
<ul class="dropdown-menu col-xs-12" role="menu" aria-labelledby="dLabel">
<li>Insert your menus here</li>
<li>Insert your menus here</li>
<li>Insert your menus here</li>
<li>Insert your menus here</li>
<li>Insert your menus here</li>
<li>Insert your menus here</li>
</ul>
</div>
This worked ok on any screen resolution in my site. The class will match the list width to it's containing div I believe:
As of Feb. 2016, CSS 3 has the support mentioned below. Here is a snippet from a WooCommerce's single product page with price discount
/*Price before discount on single product page*/
body.single-product .price del .amount {
color: hsl(0, 90%, 65%);
font-size: 15px;
text-decoration: line-through;
/*noinspection CssOverwrittenProperties*/
text-decoration: white double line-through; /* Ignored in CSS1/CSS2 UAs */
}
CSS 3 will likely have direct support using the text-decoration-color
property. In particular:
The
text-decoration-color
CSS property sets the color used when drawing underlines, overlines, or strike-throughs specified bytext-decoration-line
. This is the preferred way to color these text decorations, rather than using combinations of other HTML elements.
Also see text-decoration-color
in the CSS 3 draft spec.
If you want to use this method immediately, you probably have to prefix it, using -moz-text-decoration-color
. (Also specify it without -moz-
, for forward-compatibility.)
You can try this if you want :)
private void ClearControls(Control.ControlCollection c)
{
foreach (Control control in c)
{
if (control.HasChildren)
{
ClearControls(control.Controls);
}
else
{
if (control is TextBox)
{
TextBox txt = (TextBox)control;
txt.Clear();
}
if (control is ComboBox)
{
ComboBox cmb = (ComboBox)control;
if (cmb.Items.Count > 0)
cmb.SelectedIndex = -1;
}
if (control is CheckBox)
{
CheckBox chk = (CheckBox)control;
chk.Checked = false;
}
if (control is RadioButton)
{
RadioButton rdo = (RadioButton)control;
rdo.Checked = false;
}
if (control is ListBox)
{
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
}
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearControls((ControlCollection)this.Controls);
}
It's not possible using CSS, but using a CSS preprocessor like less or SASS.
I don't believe search and replace will do it for you (doesn't work for me in Excel 2010 Home). Are you sure you want to put "null" in EVERY cell in the sheet? That is millions of cells, in which case there is no way a search and replace would be able to handle it memory-wise (correct me if I am wrong).
In the case I am right and you don't want millions of "null" cells, then here is a macro. It asks you to select the range then put "null" inside every cell that was blank.
Sub FillWithNull()
Dim cell As range
Dim myRange As range
Set myRange = Application.InputBox("Select the range", Type:=8)
Application.ScreenUpdating = False
For Each cell In myRange
If Len(cell) = 0 Then
cell.Value = "Null"
End If
Next
Application.ScreenUpdating = True
End Sub
What you want is the Arrays.toString(int[])
method:
import java.util.Arrays;
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
..
System.out.println(Arrays.toString(array));
There is a static Arrays.toString
helper method for every different primitive java type; the one for int[]
says this:
public static String toString(int[] a)
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (
"[]"
). Adjacent elements are separated by the characters", "
(a comma followed by a space). Elements are converted to strings as byString.valueOf(int)
. Returns"null"
ifa
is null.
ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
I have posted a similar solution for the same problem,
visit How to use javascript to set attribute of selected web element using selenium Webdriver using java?
Here First we have find the element in my case I have found the element using xpath then we have traverse through the list of elements and then We have cast the driver object to the Executor object and create a script here the first argument is the element and second argument is the property and the third argument is the new value
List<WebElement> unselectableDiv = driver
.findElements(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-6']"));
for (WebElement element : unselectableDiv) {
// System.out.println( "**** Checking the size of div "+unselectableDiv.size());
JavascriptExecutor js = (JavascriptExecutor) driver;
String scriptSetAttr = "arguments[0].setAttribute(arguments[1],arguments[2])";
js.executeScript(scriptSetAttr, element, "unselectable", "off");
System.out.println(" ***** check value of Div property " + element.getAttribute("unselectable"));
}
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems)
{
return items.Select((item, index) => new { item, index })
.GroupBy(x => x.index / maxItems)
.Select(g => g.Select(x => x.item));
}
Search till the seconds for the timestamp column in postgress
select * from "TableName" e
where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';
I had a similar problem and what worked for me was to make a new clone from my original repository
This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution
Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.
// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request
var http = require('http');
var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'
var client = http.createClient(80, 'www.example.com');
var headers = {
'Host': 'www.example.com',
'Cookie': cookie,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data,'utf8')
};
var request = client.request('POST', '/', headers);
// listening to the response is optional, I suppose
request.on('response', function(response) {
response.on('data', function(chunk) {
// do what you do
});
response.on('end', function() {
// do what you do
});
});
// you'd also want to listen for errors in production
request.write(data);
request.end();
What you send in the Cookie
value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes
String.format("%15s",s) // pads right
String.format("%-15s",s) // pads left
Great summary here
You most likely did not create your own view engine.
The default view engine looks for the views in ~/Views/[Controller]/
and ~/Views/Shared/
.
You need to create your own view engine to make sure the views are searched in area views folder.
Take a look this post by Phil Haack.
nodemon
is a great one. I just add more parameters for debugging and watching options.
package.json
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon --watch server --inspect ./server/server.js"
}
The command: nodemon --watch server --inspect ./server/server.js
Whereas:
--watch server
Restart the app when changing .js
, .mjs
, .coffee
, .litcoffee
, and .json
files in the server
folder (included subfolders).
--inspect
Enable remote debug.
./server/server.js
The entry point.
Then add the following config to launch.json
(VS Code) and start debugging anytime.
{
"type": "node",
"request": "attach",
"name": "Attach",
"protocol": "inspector",
"port": 9229
}
Note that it's better to install nodemon
as dev dependency of project. So your team members don't need to install it or remember the command arguments, they just npm run dev
and start hacking.
See more on nodemon
docs: https://github.com/remy/nodemon#monitoring-multiple-directories
The best way to send data from a parent component to a child is using props.
props
props
(array or object) in the child<child :name="variableOnParent">
See demo below:
Vue.component('child-comp', {
props: ['message'], // declare the props
template: '<p>At child-comp, using props in the template: {{ message }}</p>',
mounted: function () {
console.log('The props are also available in JS:', this.message);
}
})
new Vue({
el: '#app',
data: {
variableAtParent: 'DATA FROM PARENT!'
}
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
<p>At Parent: {{ variableAtParent }}<br>And is reactive (edit it) <input v-model="variableAtParent"></p>
<child-comp :message="variableAtParent"></child-comp>
</div>
_x000D_
It's a good practice to use a config file like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=MyDB; Integrated Security=SSPI" ;Timeout=30"/>
</connectionStrings>
<appSettings>
<add key="BackupFolder" value="C:/temp/"/>
</appSettings>
</configuration>
Your C# code will be something like this:
// read connectionstring from config file
var connectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
// read backup folder from config file ("C:/temp/")
var backupFolder = ConfigurationManager.AppSettings["BackupFolder"];
var sqlConStrBuilder = new SqlConnectionStringBuilder(connectionString);
// set backupfilename (you will get something like: "C:/temp/MyDatabase-2013-12-07.bak")
var backupFileName = String.Format("{0}{1}-{2}.bak",
backupFolder, sqlConStrBuilder.InitialCatalog,
DateTime.Now.ToString("yyyy-MM-dd"));
using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
{
var query = String.Format("BACKUP DATABASE {0} TO DISK='{1}'",
sqlConStrBuilder.InitialCatalog, backupFileName);
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
There is very new functionality in Azure SQL Database and SQL Server (starting with 2017) to handle this exact scenario. I believe this would serve as a native official method for what you are trying to accomplish with the XML/STUFF method. Example:
select id, STRING_AGG(name, ',') as abc
from temp1
group by id
STRING_AGG - https://msdn.microsoft.com/en-us/library/mt790580.aspx
EDIT: When I originally posted this I made mention of SQL Server 2016 as I thought I saw that on a potential feature that was to be included. Either I remembered that incorrectly or something changed, thanks for the suggested edit fixing the version. Also, pretty impressed and wasn't fully aware of the multi-step review process that just pulled me in for a final option.
@Eddie Loeffen's answer seems to be the most popular answer to this question, but it has some bad long term effects. If you review the documentation page for System.Net.ServicePointManager.SecurityProtocol here the remarks section implies that the negotiation phase should just address this (and forcing the protocol is bad practice because in the future, TLS 1.2 will be compromised as well). However, we wouldn't be looking for this answer if it did.
Researching, it appears that the ALPN negotiation protocol is required to get to TLS1.2 in the negotiation phase. We took that as our starting point and tried newer versions of the .Net framework to see where support starts. We found that .Net 4.5.2 does not support negotiation to TLS 1.2, but .Net 4.6 does.
So, even though forcing TLS1.2 will get the job done now, I recommend that you upgrade to .Net 4.6 instead. Since this is a PCI DSS issue for June 2016, the window is short, but the new framework is a better answer.
UPDATE: Working from the comments, I built this:
ServicePointManager.SecurityProtocol = 0;
foreach (SecurityProtocolType protocol in SecurityProtocolType.GetValues(typeof(SecurityProtocolType)))
{
switch (protocol)
{
case SecurityProtocolType.Ssl3:
case SecurityProtocolType.Tls:
case SecurityProtocolType.Tls11:
break;
default:
ServicePointManager.SecurityProtocol |= protocol;
break;
}
}
In order to validate the concept, I or'd together SSL3 and TLS1.2 and ran the code targeting a server that supports only TLS 1.0 and TLS 1.2 (1.1 is disabled). With the or'd protocols, it seems to connect fine. If I change to SSL3 and TLS 1.1, that failed to connect. My validation uses HttpWebRequest from System.Net and just calls GetResponse(). For instance, I tried this and failed:
HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
request.GetResponse();
while this worked:
HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
request.GetResponse();
This has an advantage over forcing TLS 1.2 in that, if the .Net framework is upgraded so that there are more entries in the Enum, they will be supported by the code as is. It has a disadvantage over just using .Net 4.6 in that 4.6 uses ALPN and should support new protocols if no restriction is specified.
Edit 4/29/2019 - Microsoft published this article last October. It has a pretty good synopsis of their recommendation of how this should be done in the various versions of .net framework.
This is behavior specified in the Java API's String.valueOf(Object)
method. When you do concatenation, valueOf
is used to get the String
representation. There is a special case if the Object is null
, in which case the string "null"
is used.
public static String valueOf(Object obj)
Returns the string representation of the Object argument.
Parameters: obj - an Object.
Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.
Add an attribute colspan
(abbriviation for 'column span') in your top cell (<td>
) and set its value to 2.
Your table should resembles the following;
<table>
<tr>
<td colspan = "2">
<!-- Merged Columns -->
</td>
</tr>
<tr>
<td>
<!-- Column 1 -->
</td>
<td>
<!-- Column 2 -->
</td>
</tr>
</table>
See also
W3 official docs on HTML Tables
No need to use these commands .. you can directly use the nexus web Interface in order to upload your JAR using GAV parameters.
So it is very simple.
Good answers here. Just how you implement it is dependent on what you need it for. I prefer the running average one myself "time = time * 0.9 + last_frame * 0.1" by the guy above.
however I personally like to weight my average more heavily towards newer data because in a game it is SPIKES that are the hardest to squash and thus of most interest to me. So I would use something more like a .7 \ .3 split will make a spike show up much faster (though it's effect will drop off-screen faster as well.. see below)
If your focus is on RENDERING time, then the .9.1 split works pretty nicely b/c it tend to be more smooth. THough for gameplay/AI/physics spikes are much more of a concern as THAT will usually what makes your game look choppy (which is often worse than a low frame rate assuming we're not dipping below 20 fps)
So, what I would do is also add something like this:
#define ONE_OVER_FPS (1.0f/60.0f)
static float g_SpikeGuardBreakpoint = 3.0f * ONE_OVER_FPS;
if(time > g_SpikeGuardBreakpoint)
DoInternalBreakpoint()
(fill in 3.0f with whatever magnitude you find to be an unacceptable spike) This will let you find and thus solve FPS issues the end of the frame they happen.
List<int> first_list = new List<int>() {
1,
12,
12,
5
};
List<int> second_list = new List<int>() {
12,
5,
7,
9,
1
};
var result = first_list.Union(second_list);
SHA1
is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.
However, breaking a SHA1
hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.
So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.
As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod
eliminate information from your input. Suppose you calculate mod 5
and you get 0
. What was the input? Was it 0
, 5
or 500
? You see, you can't really 'go back' in this case.
Your error appears when you have modified a file and the branch that you are switching to has changes for this file too (from latest merge point).
Your options, as I see it, are - commit, and then amend this commit with extra changes (you can modify commits in git, as long as they're not push
ed); or - use stash:
git stash save your-file-name
git checkout master
# do whatever you had to do with master
git checkout staging
git stash pop
git stash save
will create stash that contains your changes, but it isn't associated with any commit or even branch. git stash pop
will apply latest stash entry to your current branch, restoring saved changes and removing it from stash.
Based on Piotr Migdals response I want to give an alternate solution enabling the possibility for a vector of strings:
myVectorOfStrings <- c("foo", "bar")
matchExpression <- paste(myVectorOfStrings, collapse = "|")
# [1] "foo|bar"
df %>% select(matches(matchExpression))
Making use of the regex OR
operator (|
)
ATTENTION: If you really have a plain vector of column names (and do not need the power of RegExpression), please see the comment below this answer (since it's the cleaner solution).
I think that you can use
for j,k in my_list:
[ ... stuff ... ]
The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.
param([String[]] $Hosts, [String] $VLAN)
Instead of
foreach ($i in $args)
you can use
foreach ($hostName in $Hosts)
If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:
myScript.ps1 -Hosts host1,host2,host3 -VLAN 2
...or something similar.
Pls Update .env file
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
After then restart server
You can use the strdup
function which has the following prototype
char *strdup(const char *s1);
Example of use:
#include <string.h>
char * my_str = strdup("My string literal!");
char * my_other_str = strdup(some_const_str);
or strcpy/strncpy to your buffer
or rewrite your functions to use const char *
as parameter instead of char *
where possible so you can preserve the const
I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.
For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.
As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.
This will return the string only if the condition is true.
public String myMethod()
{
if(condition)
{
return x;
}
else
return "";
}
Have a look at the rack-cors middleware. It will handle CORS headers in a configurable manner.
Okay, I'll bite. You want something like this: If you declare a "property" like this:
Update: I'm now pretty sure that Fredrik Mörk answered your question and gave a solution. I'm not really happy with the idea, but it seems to answer exactly what I understood from your question.
public class PropertyFoo {
public MyProp<String> Name;
}
this ends up as
public class PropertyFoo {
public string Name {
get { /* do predefined stuff here */ }
set { /*other predefined stuff here */ }
}
}
No. Not possible and not a property, really. Look for template/snippet support in your IDE.
You can check the return value from scanf
. This code will just sit there until it receives a string.
int a;
do {
// other code
a = scanf("%s", url);
} while (a <= 0);
PNG has 2 advantages: it has smaller size and it's more widely used and supported (except in case favicons). As mentioned before ICO, can have multiple size icons, which is useful for desktop applications, but not too much for websites. I would recommend you to put a favicon.ico in the root of your application. An if you have access to the Head of your website pages use the tag to point to a png file. So older browser will show the favicon.ico and newer ones the png.
To create Png and Icon files I would recommend The Gimp.
I had code that was doing getJSON. I simply replaced it with post. To my surprise, it worked
$.post("@Url.Action("Command")", { id: id, xml: xml })
.done(function (response) {
// stuff
})
.fail(function (jqxhr, textStatus, error) {
// stuff
});
[HttpPost]
public JsonResult Command(int id, string xml)
{
// stuff
}
var someParam = xxxxxxx;
commentbtn.click(function(){
alert(someParam );
});
With namespace declaration and schema location you can also check the syntax of the namespace use for example :-
<beans xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation= http://www.springframework.org/`enter code here`schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-driven/> <!-- This is wrong -->
<context:annotation-config/> <!-- This should work -->
myprocess.out &
would run the process in background using a subshell. If the current shell is terminated (say by logout), all subshells are also terminated so the background process would also be terminated. The nohup command ignores the HUP
signal and thus even if the current shell is terminated, the subshell and myprocess.out
would continue to run in the background. Another difference is that &
alone doesn't redirect the stdout/stderr so if there are any output or error, those are displayed on the terminal. nohup on the other hand redirect the stdout/stderr to nohup.out
or $HOME/nohup.out
.
If you decide to dispatch to FileServlet
then you will also need allowLinking="true"
in context.xml
in order to allow FileServlet
to traverse the symlinks.
See http://tomcat.apache.org/tomcat-6.0-doc/config/context.html
This is not a lambda function. It is a list comprehension.
Just change the order:
[ y for y in a if y not in b]
Consider this question asked at StackOverflow today:
A good test and a practical example is what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.
What's the problem with the code?
The code only works the first time the user clicks the button.
What's the solution?
Add the var
keyword before the variable name.
Try this:
List<Double> list = Arrays.asList(1.38, 2.56, 4.3);
which returns a fixed size list.
If you need an expandable list, pass this result to the ArrayList
constructor:
List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));
Found solution: I had typo in my view, ViewBag.Typo <-- this caused the error, but the debugger placed the exception at a irrelevant place.
To find which library is being used you could run
$ /sbin/ldconfig -p | grep stdc++
libstdc++.so.6 (libc6) => /usr/lib/libstdc++.so.6
The list of compatible versions for libstdc++ version 3.4.0 and above is provided by
$ strings /usr/lib/libstdc++.so.6 | grep LIBCXX
GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
...
For earlier versions the symbol GLIBCPP
is defined.
The date stamp of the library is defined in a macro __GLIBCXX__
or __GLIBCPP__
depending on the version:
// libdatestamp.cxx
#include <cstdio>
int main(int argc, char* argv[]){
#ifdef __GLIBCPP__
std::printf("GLIBCPP: %d\n",__GLIBCPP__);
#endif
#ifdef __GLIBCXX__
std::printf("GLIBCXX: %d\n",__GLIBCXX__);
#endif
return 0;
}
$ g++ libdatestamp.cxx -o libdatestamp
$ ./libdatestamp
GLIBCXX: 20101208
The table of datestamps of libstdc++ versions is listed in the documentation:
arrays:
malloc
);sizeof
(hence the common idiom sizeof(arr)/sizeof(*arr)
, that however fails silently when used inadvertently on a pointer);std::vector
:
&vec[0]
is guaranteed to work as expected);begin()
/end()
methods, the usual STL typedef
s, ...)Also consider the "modern alternative" to arrays - std::array
; I already described in another answer the difference between std::vector
and std::array
, you may want to have a look at it.
Just For Fun..:)
Algorithm (str,len):
char reversedStr[] =new reversedStr[len]
Traverse i from 0 to len/2 and then
reversedStr[i]=str[len-1-i]
reversedStr[len-1=i]=str[i]
return reversedStr;
Time Complexity:O(n) Space Complexity :O(n)
public class Reverse {
static char reversedStr[];
public static void main(String[] args) {
System.out.println(reversestr("jatin"));
}
private static String reversestr(String str) {
int strlen = str.length();
reversedStr = new char[strlen];
for (int i = 0; i <= strlen / 2; i++) {
reversedStr[i] = str.charAt(strlen - 1 - i);
reversedStr[strlen - 1 - i] = str.charAt(i);
}
return new String(reversedStr);
}
}
Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.
Example of parsing using indexOf
to calculate the position of a string in another string:
String s="What a Beautiful day!";
int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8
paresInt
essentially converts a String
to a Integer
.
String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);
Output:
Constructor method: 9876543 parseInt() method: 9876543
INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');
the above mentioned code is not correct because your first parameter POSTCODE is of type VARCHAR(10)
. you should have used ' '
.
try INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
java.time.Month
Java provides you another way to use 1 based indexes for months. Use the java.time.Month
enum. One object is predefined for each of the twelve months. They have numbers assigned to each 1-12 for January-December; call getValue
for the number.
Make use of Month.JULY
(Gives you 7)
instead of Calendar.JULY
(Gives you 6).
(import java.time.*;)
# Linux
kubectl patch deployment <name> -p "{\"spec\":{\"template\":{\"metadata\":{\"annotations\":{\"date\":\"`date +'%s'`\"}}}}}"
# windows
kubectl patch deployment <name> -p (-join("{\""spec\"":{\""template\"":{\""metadata\"":{\""annotations\"":{\""date\"":\""" , $(Get-Date -Format o).replace(':','-').replace('+','_') , "\""}}}}}"))
Use Split-Path
$filePath = "C:\PS\Test.Documents\myTestFile.txt";
$fileName = (Split-Path -Path $filePath -Leaf).Split(".")[0];
$extension = (Split-Path -Path $filePath -Leaf).Split(".")[1];
You can do it with the code you have, you just need to ensure that html
and body
are set to 100% height.
Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/
html, body {
height:100%;
}
body {
background-color: white;
background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
background-size: auto 100%;
background-repeat: no-repeat;
background-position: left top;
}
I always had problems with that, and I made a getx.bat script:
:: getx %envvar% [\m]
:: Reads envvar from user environment variable and stores it in the getxvalue variable
:: with \m read system environment
@SETLOCAL EnableDelayedExpansion
@echo OFF
@set l_regpath="HKEY_CURRENT_USER\Environment"
@if "\m"=="%2" set l_regpath="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
::REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH /t REG_SZ /f /d "%PATH%"
::@REG QUERY %l_regpath% /v %1 /S
@FOR /F "tokens=*" %%A IN ('REG QUERY %l_regpath% /v %1 /S') DO (
@ set l_a=%%A
@ if NOT "!l_a!"=="!l_a: =!" set l_line=!l_a!
)
:: Delimiter is four spaces. Change it to tab \t
@set l_line=!l_line!
@set l_line=%l_line: = %
@set getxvalue=
@FOR /F "tokens=3* delims= " %%A IN ("%l_line%") DO (
@ set getxvalue=%%A
)
@set getxvalue=!getxvalue!
@echo %getxvalue% > getxfile.tmp.txt
@ENDLOCAL
:: We already used tab as a delimiter
@FOR /F "delims= " %%A IN (getxfile.tmp.txt) DO (
@set getxvalue=%%A
)
@del getxfile.tmp.txt
@echo ON
Use Thread.Join(TimeSpan.Zero)
It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle
classes as well.
just pass the date time to this func. it would print out in time ago format for you
date_default_timezone_set('your-time-zone');
function convert($datetime){
$time=strtotime($datetime);
$diff=time()-$time;
$diff/=60;
$var1=floor($diff);
$var=$var1<=1 ? 'min' : 'mins';
if($diff>=60){
$diff/=60;
$var1=floor($diff);
$var=$var1<=1 ? 'hr' : 'hrs';
if($diff>=24){$diff/=24;$var1=floor($diff);$var=$var1<=1 ? 'day' : 'days';
if($diff>=30.4375){$diff/=30.4375;$var1=floor($diff);$var=$var1<=1 ? 'month' : 'months';
if($diff>=12){$diff/=12;$var1=floor($diff);$var=$var1<=1 ? 'year' : 'years';}}}}
echo $var1,' ',$var,' ago';
}
This works for me, I only need first numbers in string:
TO_NUMBER(regexp_substr(h.HIST_OBSE, '\.*[[:digit:]]+\.*[[:digit:]]*'))
the field had the following string: "(43 Paginas) REGLAS DE PARTICIPACION"
.
result field: 43
For Swift 5, here's a quick short class to get the location:
class MyLocationManager: NSObject, CLLocationManagerDelegate {
let manager: CLLocationManager
override init() {
manager = CLLocationManager()
super.init()
manager.delegate = self
manager.distanceFilter = kCLDistanceFilterNone
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// do something with locations
}
}
Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long
and is separate from the int
type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int
type has been dropped completely.
That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.
You can find all the gory details in PEP 0237.
Update
Apple has clarified that slicing occurs independent of enabling bitcode. I've observed this in practice as well where a non-bitcode enabled app will only be downloaded as the architecture appropriate for the target device.
Original
Bitcode. Archive your app for submission to the App Store in an intermediate representation, which is compiled into 64- or 32-bit executables for the target devices when delivered.
Slicing. Artwork incorporated into the Asset Catalog and tagged for a platform allows the App Store to deliver only what is needed for installation.
The way I read this, if you support bitcode, downloaders of your app will only get the compiled architecture needed for their own device.
You can use this:
function isDigit(n) {
return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}
Here, I compared it to the accepted method: http://jsperf.com/isdigittest/5 . I didn't expect much, so I was pretty suprised, when I found out that accepted method was much slower.
Interesting thing is, that while accepted method is faster correct input (eg. '5') and slower for incorrect (eg. 'a'), my method is exact opposite (fast for incorrect and slower for correct).
Still, in worst case, my method is 2 times faster than accepted solution for correct input and over 5 times faster for incorrect input.
here I'm providing solution to setup terraform enviroment variable in windows to beginners.
Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\
and Save it.
Rails 4:
If you want to use both not equal and equal, you can use:
user_id = 4
group_id = 27
GroupUser.where(group_id: group_id).where.not(user_id: user_id)
If you want to use a variety of operators (ie. >
, <
), at some point you may want to switch notations to the following:
GroupUser.where("group_id > ? AND user_id != ?", group_id, user_id)
Follow
Create default db folder.
c:\data\db
and also log folder
c:\data\log\mongo.log
or use following commands in command-prompt
mkdir c:\data\log
mkdir c:\data\db
Create config file in bin folder of mongo (or you may in save your desired destination).
Add following in text file named "mongod" and save it as
mongod.cfg
dbpath=c:\data\db
logpath=c:\data\log\mongo.log
or use following commands in command-prompt
echo dbpath=c:\data\db>> "mongod.cfg"
echo logpath=c:\data\log\mongo.log>> "mongod.cfg"
Now open command-prompt (administrator) and run the following command to start mongo server
mongod
Open another command-prompt (don't close 1st prompt) and run client command:
mongo
Hope this will help or you have done this already.
The official reference is the class Formatter
.
Putting data into a txt file worked for me
bash --version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
curl --version
curl 7.29.0 (x86_64-redhat-linux-gnu)
cat curl_data.txt
{ "type":"index-pattern", "excludeExportDetails": true }
curl -X POST http://localhost:30560/api/saved_objects/_export -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$(cat curl_data.txt)" -o out.json
To understand IoC, we should talk about Dependency Inversion.
Dependency inversion: Depend on abstractions, not on concretions.
Inversion of control: Main vs Abstraction, and how the Main is the glue of the systems.
I wrote about this with some good examples, you can check them here:
https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/
https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/
https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/
You're likely not in the node directory. Try switching to the directory that you unpacked node to and try running the command there.
This is how you can draw a gray line at the end of your view (same idea as b123400's answer)
class CustomView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
if let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(UIColor.gray.cgColor)
context.setLineWidth(1)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
context.strokePath()
}
}
}
Are there any libraries to do this in numpy/SciPy
Sure. You can do this without OpenCV, scikit-image or PIL.
Image resizing is basically mapping the coordinates of each pixel from the original image to its resized position.
Since the coordinates of an image must be integers (think of it as a matrix), if the mapped coordinate has decimal values, you should interpolate the pixel value to approximate it to the integer position (e.g. getting the nearest pixel to that position is known as Nearest neighbor interpolation).
All you need is a function that does this interpolation for you. SciPy has interpolate.interp2d
.
You can use it to resize an image in numpy array, say arr
, as follows:
W, H = arr.shape[:2]
new_W, new_H = (600,300)
xrange = lambda x: np.linspace(0, 1, x)
f = interp2d(xrange(W), xrange(H), arr, kind="linear")
new_arr = f(xrange(new_W), xrange(new_H))
Of course, if your image is RGB, you have to perform the interpolation for each channel.
If you would like to understand more, I suggest watching Resizing Images - Computerphile.
express.basicAuth
is gonebasic-auth-connect
is deprecatedbasic-auth
doesn't have any logichttp-auth
is an overkillexpress-basic-auth
is what you wantSince you're using Express then you can use the express-basic-auth
middleware.
See the docs:
Example:
const app = require('express')();
const basicAuth = require('express-basic-auth');
app.use(basicAuth({
users: { admin: 'supersecret123' },
challenge: true // <--- needed to actually show the login dialog!
}));
It looks like there's something else called Afisho_rankimin
in your DB so the function is not being created. Try calling your function something else. E.g.
CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
BEGIN
Declare @rankimi int
Select @rankimi=dbo.RESTORANTET.Rankimi
From RESTORANTET
Where dbo.RESTORANTET.ID_Rest=@emri_rest
RETURN @rankimi
END
GO
Note that you need to call this only once, not every time you call the function. After that try calling
SELECT dbo.Afisho_rankimin1(5) AS Rankimi
My Bots are running well against ReCaptcha.
Here my Solution.
Let your Bot do this Steps:
First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.
Also use for better results a VPN like https://www.purevpn.com
For every Recpatcha do these Steps:
If you use VPN switch IP first
Clear all Browser Cookies
Clear all Browser Cache
Set one of these Useragents by Random:
a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0
5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange
Then Click ever with random delay between
WM_LBUTTONDOWN
and
WM_LBUTTONUP
Take Screenshot from Image Captcha
Send Screenshot to
or
and let they solve.
After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images
Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button
In 75% all trys Recaptcha will solved
Chears Google
Tom
Other simple tool For VS2008 (open source): http://www.accendo.sk/Download/SourceStat.zip
Make sure that the actual .vim
file is in ~/.vim/plugin/
Depends how much you like the linq query syntax, you can use the extension methods directly like:
var item = Items.First(i => i.Id == 123);
And if you don't want to throw an error if the list is empty, use FirstOrDefault
which returns the default value for the element type (null
for reference types):
var item = Items.FirstOrDefault(i => i.Id == 123);
if (item != null)
{
// found it
}
Single()
and SingleOrDefault()
can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First()
and FirstOrDefault()
stop on the first match, so they are more efficient.
Of the First()
and Single()
family, here's where they throw:
First()
- throws if empty/not found, does not throw if duplicateFirstOrDefault()
- returns default if empty/not found, does not throw if duplicateSingle()
- throws if empty/not found, throws if duplicate existsSingleOrDefault()
- returns default if empty/not found, throws if duplicate existsI wanted animations and auto-shrink. The combination is apparently hard, because people came up with pretty intense solutions for it. I've made it multi-textarea-proof, too. And it isn't as ridiculously heavy as the jQuery plugin.
I've based myself on vsync's answer (and the improvement he made for it), http://codepen.io/anon/pen/vlIwj is the codepen for my improvement.
HTML
<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
CSS
body{ background:#728EB2; }
textarea{
display:block;
box-sizing: padding-box;
overflow:hidden;
padding:10px;
width:250px;
font-size:14px;
margin:50px auto;
border-radius:8px;
border:6px solid #556677;
transition:all 1s;
-webkit-transition:all 1s;
}
JS
var rowheight = 0;
$(document).on('input.textarea', '.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0,
rows = this.value.split("\n").length;
$this = $(this);
var rowz = rows < minRows ? minRows : rows;
var rowheight = $this.attr('data-rowheight');
if(!rowheight){
this.rows = rowz;
$this.attr('data-rowheight', (this.clientHeight - parseInt($this.css('padding-top')) - parseInt($this.css('padding-bottom')))/ rowz);
}else{
rowz++;
this.style.cssText = 'height:' + rowz * rowheight + 'px';
}
});
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
You can also pass in a variable and/or object if you wanted to.
var str1:String = "John"
var str2:String = "Bob"
var myArray = ["Steve", "Bill", "Linus", "Bret"]
//add to the end of the array with append
myArray.append(str1)
myArray.append(str2)
To add them to the front:
//use 'insert' instead of append
myArray.insert(str1, atIndex:0)
myArray.insert(str2, atIndex:0)
//Swift 3
myArray.insert(str1, at: 0)
myArray.insert(str2, at: 0)
As others have already stated, you can no longer use '+=' as of xCode 6.1
You can try this one it is short
SystemClock.sleep(7000);
WARNING: Never, ever, do this on a UI thread.
Use this to sleep eg. background thread.
Full solution for your problem will be: This is available API 1
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View button) {
button.setBackgroundResource(R.drawable.avatar_dead);
final long changeTime = 1000L;
button.postDelayed(new Runnable() {
@Override
public void run() {
button.setBackgroundResource(R.drawable.avatar_small);
}
}, changeTime);
}
});
Without creating tmp Handler. Also this solution is better than @tronman because we do not retain view by Handler. Also we don't have problem with Handler created at bad thread ;)
public static void sleep (long ms)
Added in API level 1
Waits a given number of milliseconds (of uptimeMillis) before returning. Similar to sleep(long), but does not throw InterruptedException; interrupt() events are deferred until the next interruptible operation. Does not return until at least the specified number of milliseconds has elapsed.
Parameters
ms to sleep before returning, in milliseconds of uptime.
Code for postDelayed from View class:
/**
* <p>Causes the Runnable to be added to the message queue, to be run
* after the specified amount of time elapses.
* The runnable will be run on the user interface thread.</p>
*
* @param action The Runnable that will be executed.
* @param delayMillis The delay (in milliseconds) until the Runnable
* will be executed.
*
* @return true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed --
* if the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*
* @see #post
* @see #removeCallbacks
*/
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Assume that post will succeed later
ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
return true;
}
They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"
The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.
Eden Space: The pool from which memory is initially allocated for most objects.
Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.
Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.
Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.
Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
There are many ways to create re-usable objects like this in JavaScript. Mozilla have a nice introduction here:
The following will work in your example:
function Foo(){
this.bar = function (){
alert("Hello World!");
}
}
myFoo = new Foo();
myFoo.bar(); // Hello World?????????????????????????????????
Anything defined as package private can be accessed by the class itself, other classes within the same package, but not outside of the package, and not by sub-classes.
See this page for a handy table of access level modifiers...
I found when i used this there was a problem when d1 fell on saturday. Below is what i used to correct this.
declare @d1 datetime, @d2 datetime
select @d1 = '11/19/2011' , @d2 = '11/28/2011'
select datediff(dd, @d1, @d2) +case when datepart(dw, @d1) = 7 then 1 else 0 end - (datediff(wk, @d1, @d2) * 2) -
case when datepart(dw, @d1) = 1 then 1 else 0 end +
case when datepart(dw, @d2) = 1 then 1 else 0 end
You may want to try View.getRootView()
.
.wrapper{
float: left;
width: 100%;
text-align: center;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.button{
display:inline-block;
}
<div class="wrapper">
<button class="button">Button1</button>
<button class="button">Button2</button>
</div>
Keeping in mind what Etienne Martin says, you can use oninput
, as it detects any change within texarea. Detect if you copy and paste text.
$('#textarea').on('input', function() {
var max = 400;
var len = $(this).val().length;
var char = max - len;
if (len >= max) {
$('#charNum').text(' You have reached the character limit.');
$('#charNum').addClass("text-danger"); // optional, adding a class using bootstrap
} else if (char <= 10) {
$('#charNum').text(char + ' You are reaching the character limit.');
$('#charNum').addClass("text-warning"); // optional, adding a class using bootstrap
} else {
var char = max - len;
$('#charNum').text(char + ' characters remaining.');
$('#charNum').addClass("text-success"); // optional, adding a class using bootstrap
}
});
I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:
<p:pickList id="formPickList"
value="#{mediaDetail.availableMedia}"
converter="MediaPicklistConverter"
widgetVar="formsPicklistWidget"
var="mediaFiles"
itemLabel="#{mediaFiles.mediaTitle}"
itemValue="#{mediaFiles}" >
<f:facet name="sourceCaption">Available Media</f:facet>
<f:facet name="targetCaption">Chosen Media</f:facet>
</p:pickList>
<p:commandButton id="viewStream_btn"
value="Stream chosen media"
icon="fa fa-download"
ajax="true"
action="#{mediaDetail.prepareStreams}"
update=":streamDialogPanel"
oncomplete="PF('streamingDialog').show()"
styleClass="ui-priority-primary"
style="margin-top:5px" >
<p:ajax process="formPickList" />
</p:commandButton>
The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.
As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.
The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" />
bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.
Happy coding!
Better and quicker approach without any software to download.
This should work.
Inside the component, create a computed function
computed:{
myState:function(){
return this.$store.state.my_state; // return the state value in `my_state`
}
}
Now the computed function name can be watched, like
watch:{
myState:function(newVal,oldVal){
// this function will trigger when ever the value of `my_state` changes
}
}
The changes made in the vuex
state my_state
will reflect in the computed function myState
and trigger the watch function.
If the state my_state
is having nested data, then the handler
option will help more
watch:{
myState:{
handler:function(newVal,oldVal){
// this function will trigger when ever the value of `my_state` changes
},
deep:true
}
}
This will watch all the nested values in the store my_state
.
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Medians grouped by dimension:
SELECT your_dimension, avg(t1.val) as median_val FROM (
SELECT @rownum:=@rownum+1 AS `row_number`,
IF(@dim <> d.your_dimension, @rownum := 0, NULL),
@dim := d.your_dimension AS your_dimension,
d.val
FROM data d, (SELECT @rownum:=0) r, (SELECT @dim := 'something_unreal') d
WHERE 1
-- put some where clause here
ORDER BY d.your_dimension, d.val
) as t1
INNER JOIN
(
SELECT d.your_dimension,
count(*) as total_rows
FROM data d
WHERE 1
-- put same where clause here
GROUP BY d.your_dimension
) as t2 USING(your_dimension)
WHERE 1
AND t1.row_number in ( floor((total_rows+1)/2), floor((total_rows+2)/2) )
GROUP BY your_dimension;
process.cwd()
returns directory where command has been executed (not directory of the node package) if it's has not been changed by 'process.chdir' inside of application.__filename
returns absolute path to file where it is placed.__dirname
returns absolute path to directory of __filename
.If you need to load files from your module directory you need to use relative paths.
require('../lib/test');
instead of
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
require(lib + '/test');
It's always relative to file where it called from and don't depend on current work dir.
You are getting the WebView before setting the Content view so the wv is probably null.
public class ViewWeb extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView wv;
wv = (WebView) findViewById(R.id.webView1);
wv.loadUrl("file:///android_asset/aboutcertified.html"); // now it will not fail here
}
}
Give your button an id something like this:
<input id="mybutton" type="button" value="Dont show this again! " />
Then use jquery (to make this unobtrusive) and attach click action like so:
$(document).ready(function (){
$('#mybutton').click(function (){
fbLikeDump();
WriteCookie();
});
});
(this part should be in your .js file too)
I should have mentioned that you will need the jquery libraries on your page, so right before your closing body tag add these:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://PATHTOYOURJSFILE"></script>
The reason to add just before body closing tag is for performance of perceived page loading times
Personally, I'd place it as the background image within the div, the CSS for that being:
#demo {
background: url(bg_apple_little.gif) no-repeat center center;
height: 200px;
width: 200px;
}
(Assumes a div with id="demo"
as you are already specifying height
and width
adding a background
shouldn't be an issue)
Let the browser take the strain.
For those who want a non-zero cellspacing value, the following CSS worked for me, but I'm only able to test it in Firefox.
See the Quirksmode link posted elsewhere for compatibility details. It seems it may not work with older Internet Explorer versions.
table {
border-collapse: separate;
border-spacing: 2px;
}
mysql -u username -p -h localhost DATA-BASE-NAME < data.sql
look here - step 3: this way you dont need the USE statement
Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh
after the last command of st_new.sh
has finished.
Now there is a special command which messes this up: &
cmd &
means: "Start a new background process and execute cmd
in it. After starting the background process, immediately continue with the next command in the script."
That means &
doesn't wait for cmd
to do it's work. My guess is that st_new.sh
contains such a command. If that is the case, then you need to modify the script:
cmd &
BACK_PID=$!
This puts the process ID (PID) of the new background process in the variable BACK_PID
. You can then wait for it to end:
while kill -0 $BACK_PID ; do
echo "Process is still active..."
sleep 1
# You can add a timeout here if you want
done
or, if you don't want any special handling/output simply
wait $BACK_PID
Note that some programs automatically start a background process when you run them, even if you omit the &
. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's &
command instead to get the PID.
The code you have posted here and code on your site both are different. There is a break <br>
after second image, so the third image into new line, remove this <br>
and it will display correctly.
first, you need to delete all old mysql data using
docker-compose down -v
after that add two lines in your docker-compose.yml
volumes:
- mysql-data:/var/lib/mysql
and
volumes:
mysql-data:
your final docker-compose.yml will looks like
version: '3.1'
services:
php:
build:
context: .
dockerfile: Dockerfile
ports:
- 80:80
volumes:
- ./src:/var/www/html/
db:
image: mysql
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: example
volumes:
- mysql-data:/var/lib/mysql
adminer:
image: adminer
restart: always
ports:
- 8080:8080
volumes:
mysql-data:
after that use this command
docker-compose up -d
now your data will persistent and will not be deleted even after using this command
docker-compose down
extra:- but if you want to delete all data then you will use
docker-compose down -v
My answer is intended for comment though but since i havent got enough reputation, i think it will still be relevant as an answer and help some one.
I find datatable
in library DT
robust to handle rownames
, and columnames
Library DT
datatable(df, rownames = FALSE) # no row names
refer to https://rstudio.github.io/DT/ for usage scenarios
Make file executable:
chmod +x file
Find location of perl:
which perl
This should return something like
/bin/perl sometimes /usr/local/bin
Then in the first line of your script add:
#!"path"/perl with path from above e.g.
#!/bin/perl
Then you can execute the file
./file
There may be some issues with the PATH, so you may want to change that as well ...
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
You can use from the pd.to_numeric(s)
Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/
and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1
.
See this link for the official GlassFish documentation about logging.
Rename your file, commit the changes including the "deleted" file, and don't include the new (renamed) file.
Rename your file back.
Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type Grid}">
<Style.Resources>
<Style TargetType="{x:Type Button}" x:Key="ConflictButton">
<Setter Property="Background" Value="Pink"/>
</Style>
</Style.Resources>
</Style>
<Style TargetType="{x:Type Button}" x:Key="ConflictButton">
<Setter Property="Background" Value="LightGreen"/>
</Style>
</ResourceDictionary>
In view:
<Window x:Class="WpfStyleDemo.ConflictingStyleWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ConflictingStyleWindow" Height="100" Width="100">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles/ConflictingStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Button Style="{DynamicResource ConflictButton}" Content="Test"/>
</Grid>
</Window>
StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.
StaticResource
DynamicResource
Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.
StaticResource will throw an error when the root-level style (LightGreen) is removed.
This is a tricky question.
There a set of problems about file permissions. If you can do this at the command line
$ sudo chown myaccount /path/to/file
then you have a standard permissions problem. Make sure you own the file and have permission to modify the directory.
If you cannnot get permissions, then you have probably mounted a FAT-32 filesystem. If you ls -l
the file, and you find it is owned by root and a member of the "plugdev" group, then you are certain its the issue. FAT-32 permissions are set at the time of mounting, using the line of /etc/fstab file. You can set the uid/gid of all the files like this:
UUID=C14C-CE25 /big vfat utf8,umask=007,uid=1000,gid=1000 0 1
Also, note that the FAT-32 won't take symbolic links.
Wrote the whole thing up at http://www.charlesmerriam.com/blog/2009/12/operation-not-permitted-and-the-fat-32-system/
Here is an example using the DOM cookie API (https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie), so we can see for ourselves the behavior.
If we execute the following JavaScript:
document.cookie = "key=value"
It appears to be the same as executing:
document.cookie = "key=value;domain=mydomain.com"
The cookie key becomes available (only) on the domain mydomain.com.
Now, if you execute the following JavaScript on mydomain.com:
document.cookie = "key=value;domain=.mydomain.com"
The cookie key becomes available to mydomain.com as well as subdomain.mydomain.com.
Finally, if you were to try and execute the following on subdomain.mydomain.com:
document.cookie = "key=value;domain=.mydomain.com"
Does the cookie key become available to subdomain.mydomain.com? I was a bit surprised that this is allowed; I had assumed it would be a security violation for a subdomain to be able to set a cookie on a parent domain.
If you do not want to attach code in a file (this was a good tip, ChssPly76, I need to check it out), you can try changing the default message format messages to rich text (Tools - Options - Mail Format - Message format) instead of HTML. I learned that Outlook's HTML formatting screws code layout (btw, Outlook uses MS Word's HTML rendering engine which sucks big time), but rich text works fine. So if I copy code from Visual Studio and paste it in Outlook message, when using rich text, it looks pretty good, but when in HTML mode, it's a disaster. To disable smart quotes, auto-correction, and other artifacts, set up the appropriate option via Tools - Options - Spelling - Spelling and AutoCorrection; you may also want to play with copy-paste settings (Tools - Options - Mail Format - Editor Options - Cut, copy, and paste).
Using awk for it. Test files:
$ cat a.txt
one
two
three
four
four
$ cat b.txt
three
two
one
The awk:
$ awk '
NR==FNR { # process b.txt or the first file
seen[$0] # hash words to hash seen
next # next word in b.txt
} # process a.txt or all files after the first
!($0 in seen)' b.txt a.txt # if word is not hashed to seen, output it
Duplicates are outputed:
four
four
To avoid duplicates, add each newly met word in a.txt to seen
hash:
$ awk '
NR==FNR {
seen[$0]
next
}
!($0 in seen) { # if word is not hashed to seen
seen[$0] # hash unseen a.txt words to seen to avoid duplicates
print # and output it
}' b.txt a.txt
Output:
four
If the word lists are comma-separated, like:
$ cat a.txt
four,four,three,three,two,one
five,six
$ cat b.txt
one,two,three
you have to do a couple of extra laps (for
loops):
awk -F, ' # comma-separated input
NR==FNR {
for(i=1;i<=NF;i++) # loop all comma-separated fields
seen[$i]
next
}
{
for(i=1;i<=NF;i++)
if(!($i in seen)) {
seen[$i] # this time we buffer output (below):
buffer=buffer (buffer==""?"":",") $i
}
if(buffer!="") { # output unempty buffers after each record in a.txt
print buffer
buffer=""
}
}' b.txt a.txt
Output this time:
four
five,six