For a reusable React hook solution
import React, { useEffect } from 'react';
const useEscape = (onEscape) => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27)
onEscape();
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, []);
}
export default useEscape
Usage:
const [isOpen, setIsOpen] = useState(false);
useEscape(() => setIsOpen(false))
You might be trying to access a control inside a control, maybe a GridView or DetailsView.
Try using something like this:
empsalary = Convert.ToInt32(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);
You can specify a DOM attribute that can be used to allow the directive to define a function on the parent scope. The parent scope can then call this method like any other. Here's a plunker. And below is the relevant code.
clearfn
is an attribute on the directive element into which the parent scope can pass a scope property which the directive can then set to a function that accomplish's the desired behavior.
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<style>
my-box{
display:block;
border:solid 1px #aaa;
min-width:50px;
min-height:50px;
padding:.5em;
margin:1em;
outline:0px;
box-shadow:inset 0px 0px .4em #aaa;
}
</style>
</head>
<body ng-controller="mycontroller">
<h1>Call method on directive</h1>
<button ng-click="clear()">Clear</button>
<my-box clearfn="clear" contentEditable=true></my-box>
<script>
var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope){
});
app.directive('myBox', function(){
return {
restrict: 'E',
scope: {
clearFn: '=clearfn'
},
template: '',
link: function(scope, element, attrs){
element.html('Hello World!');
scope.clearFn = function(){
element.html('');
};
}
}
});
</script>
</body>
</html>
if element is hide by jquery then use
if($("#elmentid").is(':hidden'))
this
is a reference for the DOM element for which the event is being handled (the current target). event.target
refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.
You can get a good sense of this by reviewing the jQuery event docs, but in summary:
event.currentTarget
The current DOM element within the event bubbling phase.
event.delegateTarget
The element where the currently-called jQuery event handler was attached.
event.relatedTarget
The other DOM element involved in the event, if any.
event.target
The DOM element that initiated the event.
To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this)
or $(evt.target)
.
The .attr()
method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href')
or simply evt.target.href
will give you what you want.
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
I just had this same problem with the jquery Responsive Slides plugin (http://responsive-slides.viljamis.com/).
I fixed it by not using the jQuery short version $(".rslides").responsiveSlides(..
but rather the long version: jQuery(".rslides").responsiveSlides(...
So switching $
to jQuery
so as not to cause conflict or using the proper jQuery no conflict mode (http://api.jquery.com/jQuery.noConflict/)
Try the Content-Disposition
header
Content-Disposition: attachment; filename=<file name.ext>
Following applies to IIS 7
The error is trying to tell you that one of two things is not working properly:
See the following link for instructions on how to diagnose and fix the above issues.
http://support.microsoft.com/kb/942062/en-us
If neither of these issues is the problem, another thing to check is to make sure that the application pool configured for your website (under IIS Manager, select your website, and click "Basic Settings" on the far right) is configured with the same .Net framework version (in IIS Manager, under "Application Pools") as the targetFramework configured in your web.config, e.g.:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime targetFramework="4.0" />
</system.web>
I'm not sure why this would generate such a seemingly unrelated error message, but it did for me.
It may also be the case that the library containing the class in question is not properly signed with a strong name.
This is how I did it.
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SAP Multiple Entries");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(10,10,10,10));
frame.setLayout(new FlowLayout());
frame.setSize(512, 512);
JButton button = new JButton("Select File");
button.setPreferredSize(new Dimension(256, 256));
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
keep = selectedFile.getAbsolutePath();
// System.out.println(keep);
//out.println(file.flag);
if(file.flag==true) {
JOptionPane.showMessageDialog(null, "It is done! \nLocation: " + file.path , "Success Message", JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "failure", "not okay", JOptionPane.INFORMATION_MESSAGE);
}
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
An alternative approach based on @Sheridan answer here
<TextBox Text="{Binding SomeText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding SomeTextIsFocused, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
In your view model set up your binding in the usual way and then set the SomeTextIsFocused to true to set the focus on your text box
Create a table layout panel with two columns in your form and name it tlpFields
.
Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).
tlpFields.RowStyles.Clear(); //first you must clear rowStyles
for (int ii = 0; ii < 5; ii++)
{
Label l1= new Label();
TextBox t1 = new TextBox();
l1.Text = "field : ";
tlpFields.Controls.Add(l1, 0, ii); // add label in column0
tlpFields.Controls.Add(t1, 1, ii); // add textbox in column1
tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}
Finally, run the code.
Maybe maven encoding you KeyStore, you can set filtering=false to fix this problem.
<build>
...
<resources>
<resource>
...
<!-- set filtering=false to fix -->
<filtering>false</filtering>
...
</resource>
</resources>
</build>
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
It's because there can only be one definition of A::a
that all the translation units use.
If you performed static int a = 3;
in a class in a header included in all a translation units then you'd get multiple definitions. Therefore, non out-of-line definition of a static is forcibly made a compiler error.
Using static inline
or static const
remedies this. static inline
only concretises the symbol if it is used in the translation unit and ensures the linker only selects and leaves one copy if it's defined in multiple translation units due to it being in a comdat group. const
at file scope makes the compiler never emit a symbol because it's always substituted immediately in the code unless extern
is used, which is not permitted in a class.
One thing to note is static inline int b;
is treated as a definition whereas static const int b
or static const A b;
are still treated as a declaration and must be defined out-of-line if you don't define it inside the class. Interestingly static constexpr A b;
is treated as a definition, whereas static constexpr int b;
is an error and must have an initialiser (this is because they now become definitions and like any const/constexpr definition at file scope, they require an initialiser which an int doesn't have but a class type does because it has an implicit = A()
when it is a definition -- clang allows this but gcc requires you to explicitly initialise or it is an error. This is not a problem with inline instead). static const A b = A();
is not allowed and must be constexpr
or inline
in order to permit an initialiser for a static object with class type i.e to make a static member of class type more than a declaration. So yes in certain situations A a;
is not the same as explicitly initialising A a = A();
(the former can be a declaration but if only a declaration is allowed for that type then the latter is an error. The latter can only be used on a definition. constexpr
makes it a definition). If you use constexpr
and specify a default constructor then the constructor will need to be constexpr
#include<iostream>
struct A
{
int b =2;
mutable int c = 3; //if this member is included in the class then const A will have a full .data symbol emitted for it on -O0 and so will B because it contains A.
static const int a = 3;
};
struct B {
A b;
static constexpr A c; //needs to be constexpr or inline and doesn't emit a symbol for A a mutable member on any optimisation level
};
const A a;
const B b;
int main()
{
std::cout << a.b << b.b.b;
return 0;
}
A static member is an outright file scope declaration extern int A::a;
(which can only be made in the class and out of line definitions must refer to a static member in a class and must be definitions and cannot contain extern) whereas a non-static member is part of the complete type definition of a class and have the same rules as file scope declarations without extern
. They are implicitly definitions. So int i[]; int i[5];
is a redefinition whereas static int i[]; int A::i[5];
isn't but unlike 2 externs, the compiler will still detect a duplicate member if you do static int i[]; static int i[5];
in the class.
Currently there is no language support for enum flags, Meta classes might inherently add this feature if it would ever be part of the c++ standard.
My solution would be to create enum-only instantiated template functions adding support for type-safe bitwise operations for enum class using its underlying type:
File: EnumClassBitwise.h
#pragma once
#ifndef _ENUM_CLASS_BITWISE_H_
#define _ENUM_CLASS_BITWISE_H_
#include <type_traits>
//unary ~operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator~ (Enum& val)
{
val = static_cast<Enum>(~static_cast<std::underlying_type_t<Enum>>(val));
return val;
}
// & operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator& (Enum lhs, Enum rhs)
{
return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
}
// &= operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator&= (Enum& lhs, Enum rhs)
{
lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
return lhs;
}
//| operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator| (Enum lhs, Enum rhs)
{
return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
}
//|= operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator|= (Enum& lhs, Enum rhs)
{
lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
return lhs;
}
#endif // _ENUM_CLASS_BITWISE_H_
For convenience and for reducing mistakes, you might want to wrap your bit flags operations for enums and for integers as well:
File: BitFlags.h
#pragma once
#ifndef _BIT_FLAGS_H_
#define _BIT_FLAGS_H_
#include "EnumClassBitwise.h"
template<typename T>
class BitFlags
{
public:
constexpr inline BitFlags() = default;
constexpr inline BitFlags(T value) { mValue = value; }
constexpr inline BitFlags operator| (T rhs) const { return mValue | rhs; }
constexpr inline BitFlags operator& (T rhs) const { return mValue & rhs; }
constexpr inline BitFlags operator~ () const { return ~mValue; }
constexpr inline operator T() const { return mValue; }
constexpr inline BitFlags& operator|=(T rhs) { mValue |= rhs; return *this; }
constexpr inline BitFlags& operator&=(T rhs) { mValue &= rhs; return *this; }
constexpr inline bool test(T rhs) const { return (mValue & rhs) == rhs; }
constexpr inline void set(T rhs) { mValue |= rhs; }
constexpr inline void clear(T rhs) { mValue &= ~rhs; }
private:
T mValue;
};
#endif //#define _BIT_FLAGS_H_
Possible usage:
#include <cstdint>
#include <BitFlags.h>
void main()
{
enum class Options : uint32_t
{
NoOption = 0 << 0
, Option1 = 1 << 0
, Option2 = 1 << 1
, Option3 = 1 << 2
, Option4 = 1 << 3
};
const uint32_t Option1 = 1 << 0;
const uint32_t Option2 = 1 << 1;
const uint32_t Option3 = 1 << 2;
const uint32_t Option4 = 1 << 3;
//Enum BitFlags
BitFlags<Options> optionsEnum(Options::NoOption);
optionsEnum.set(Options::Option1 | Options::Option3);
//Standard integer BitFlags
BitFlags<uint32_t> optionsUint32(0);
optionsUint32.set(Option1 | Option3);
return 0;
}
When this problem comes up with multiprocessing
a simple solution is to switch from Pool
to ThreadPool
. This can be done with no change of code other than the import-
from multiprocessing.pool import ThreadPool as Pool
This works because ThreadPool shares memory with the main thread, rather than creating a new process- this means that pickling is not required.
The downside to this method is that python isn't the greatest language with handling threads- it uses something called the Global Interpreter Lock to stay thread safe, which can slow down some use cases here. However, if you're primarily interacting with other systems (running HTTP commands, talking with a database, writing to filesystems) then your code is likely not bound by CPU and won't take much of a hit. In fact I've found when writing HTTP/HTTPS benchmarks that the threaded model used here has less overhead and delays, as the overhead from creating new processes is much higher than the overhead for creating new threads.
So if you're processing a ton of stuff in python userspace this might not be the best method.
There are two ways that I know of to color plot points by factor and then also have a corresponding legend automatically generated. I'll give examples of both:
colorRampPallete
function (trickier, but many people prefer/need R's built-in plotting facilities)For both examples, I will use the ggplot2 diamonds dataset. We'll be using the numeric columns diamond$carat
and diamond$price
, and the factor/categorical column diamond$color
. You can load the dataset with the following code if you have ggplot2 installed:
library(ggplot2)
data(diamonds)
It's a one liner. Key item here is to give qplot
the factor you want to color by as the color
argument. qplot
will make a legend for you by default.
qplot(
x = carat,
y = price,
data = diamonds,
color = diamonds$color # color by factor color (I know, confusing)
)
Your output should look like this:
Using R's built in plot functionality to get a plot colored by a factor and an associated legend is a 4-step process, and it's a little more technical than using ggplot2.
First, we will make a colorRampPallete
function. colorRampPallete()
returns a new function that will generate a list of colors. In the snippet below, calling color_pallet_function(5)
would return a list of 5 colors on a scale from red to orange to blue:
color_pallete_function <- colorRampPalette(
colors = c("red", "orange", "blue"),
space = "Lab" # Option used when colors do not represent a quantitative scale
)
Second, we need to make a list of colors, with exactly one color per diamond color. This is the mapping we will use both to assign colors to individual plot points, and to create our legend.
num_colors <- nlevels(diamonds$color)
diamond_color_colors <- color_pallet_function(num_colors)
Third, we create our plot. This is done just like any other plot you've likely done, except we refer to the list of colors we made as our col
argument. As long as we always use this same list, our mapping between colors and diamond$colors
will be consistent across our R script.
plot(
x = diamonds$carat,
y = diamonds$price,
xlab = "Carat",
ylab = "Price",
pch = 20, # solid dots increase the readability of this data plot
col = diamond_color_colors[diamonds$color]
)
Fourth and finally, we add our legend so that someone reading our graph can clearly see the mapping between the plot point colors and the actual diamond colors.
legend(
x ="topleft",
legend = paste("Color", levels(diamonds$color)), # for readability of legend
col = diamond_color_colors,
pch = 19, # same as pch=20, just smaller
cex = .7 # scale the legend to look attractively sized
)
Your output should look like this:
Nifty, right?
Actually,
Cursor.Current = Cursors.WaitCursor;
temporarily sets the Wait cursor, but doesn’t ensure that the Wait cursor shows until the end of your operation. Other programs or controls within your program can easily reset the cursor back to the default arrow as in fact happens when you move mouse while operation is still running.
A much better way to show the Wait cursor is to set the UseWaitCursor property in a form to true:
form.UseWaitCursor = true;
This will display wait cursor for all controls on the form until you set this property to false. If you want wait cursor to be shown on Application level you should use:
Application.UseWaitCursor = true;
For efficiency's sake you want to only hit the data once, as Harper does. However you don't want to use rank() because it will give you ties and further you want to group by language rather than order by language. From there you want add an order by clause to distinguish between rows, but you don't want to actually sort the data. To achieve this I would use "order by null" E.g.
count(*) over (group by language order by null)
Assuming you don't have extraneous whitespace:
with open('file') as f:
w, h = [int(x) for x in next(f).split()] # read first line
array = []
for line in f: # read rest of lines
array.append([int(x) for x in line.split()])
You could condense the last for loop into a nested list comprehension:
with open('file') as f:
w, h = [int(x) for x in next(f).split()]
array = [[int(x) for x in line.split()] for line in f]
I found this on web.
http://www.opensource.apple.com/source/Libc/Libc-262/ppc/gen/strcmp.c
int strcmp(const char *s1, const char *s2)
{
for ( ; *s1 == *s2; s1++, s2++)
if (*s1 == '\0')
return 0;
return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}
Up above, you mention having compiling your as part of your steps to reproduce, but then below you made an edit saying,
"is there a way to see on which distro a shared library was compiled on?"
Whether or not you compiled this on the same distro, and even a different version of the same distro is an important detail, especially for c++ applications.
Linking to c++ libraries, including libstdc++ can have mixed results, as far as I can tell. Here is a related question about recompiling with different versions of c++.
do we need to recompile libraries with c++11?
Basically, if you compiled against c++ on a different distro (and possibly different gcc version), this may be causing your trouble.
I think you have two options:
Im using jQuery Lazy. It took me about 10 minutes to test out and an hour or two to add to most of the image links on one of my websites (CollegeCarePackages.com). I have NO (none/zero) relationship of any kind to the dev, but it saved me a lot of time and basically helped improve our bounce rate for mobile users and I appreciate it.
Using the TextBox.ReadOnly
property
TextBox.ReadOnly = true;
For a Non-Grey background you can change the TextBox.BackColor
property to SystemColors.Window
Color
textBox.BackColor = System.Drawing.SystemColors.Window;
When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.
From the moment.js docs: format('E')
stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.
From the moment.js docs again, here is what they suggest:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Here is a JSFiddle for your particular case:
$('#test').click(function() {_x000D_
var startDate = moment("13.04.2016", "DD.MM.YYYY");_x000D_
var endDate = moment("28.04.2016", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer
and java.util.Observable
As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared. You could also use a property of window
or (in the global scope) this
to get the same effect.
// first.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
... in another file ...
// second.js
alert (colorCodes.back); // alerts `#fff`
... in your html file ...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
You could inititialize it with a size of 0, but you will have to reinitialize it, when you know what the size is, as you cannot append to the array.
string[] a = new string[0];
For performing Unmarshall using JAXB:
1) Convert given XML to XSD(by yourself or by online convertor),
2) Create a JAXB project in eclipse,
3) Create XSD file and paste that converted XSD content in it,
4) Right click on **XSD file--> Generate--> JAXB Classes-->follow the instructions(this will create all nessasary .java files in src, i.e., one package-info, object factory and pojo class),
5) Create another .java file in src to operate unmarshall operation, and run it.
Happy Coding !!
I use the following function to format requests. It's like @AntonioHerraizS except it will pretty-print JSON objects in the body as well, and it labels all parts of the request.
format_json = functools.partial(json.dumps, indent=2, sort_keys=True)
indent = functools.partial(textwrap.indent, prefix=' ')
def format_prepared_request(req):
"""Pretty-format 'requests.PreparedRequest'
Example:
res = requests.post(...)
print(format_prepared_request(res.request))
req = requests.Request(...)
req = req.prepare()
print(format_prepared_request(res.request))
"""
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
content_type = req.headers.get('Content-Type', '')
if 'application/json' in content_type:
try:
body = format_json(json.loads(req.body))
except json.JSONDecodeError:
body = req.body
else:
body = req.body
s = textwrap.dedent("""
REQUEST
=======
endpoint: {method} {url}
headers:
{headers}
body:
{body}
=======
""").strip()
s = s.format(
method=req.method,
url=req.url,
headers=indent(headers),
body=indent(body),
)
return s
And I have a similar function to format the response:
def format_response(resp):
"""Pretty-format 'requests.Response'"""
headers = '\n'.join(f'{k}: {v}' for k, v in resp.headers.items())
content_type = resp.headers.get('Content-Type', '')
if 'application/json' in content_type:
try:
body = format_json(resp.json())
except json.JSONDecodeError:
body = resp.text
else:
body = resp.text
s = textwrap.dedent("""
RESPONSE
========
status_code: {status_code}
headers:
{headers}
body:
{body}
========
""").strip()
s = s.format(
status_code=resp.status_code,
headers=indent(headers),
body=indent(body),
)
return s
There are many ways to exit after insert
When you insert data into a table, you can use the OUTPUT clause to return a copy of the data that’s been inserted into the table. The OUTPUT clause takes two basic forms: OUTPUT and OUTPUT INTO. Use the OUTPUT form if you want to return the data to the calling application. Use the OUTPUT INTO form if you want to return the data to a table or a table variable.
DECLARE @MyTableVar TABLE (id INT,NAME NVARCHAR(50));
INSERT INTO tableName
(
NAME,....
)OUTPUT INSERTED.id,INSERTED.Name INTO @MyTableVar
VALUES
(
'test',...
)
IDENT_CURRENT: It returns the last identity created for a particular table or view in any session.
SELECT IDENT_CURRENT('tableName') AS [IDENT_CURRENT]
SCOPE_IDENTITY: It returns the last identity from a same session and the same scope. A scope is a stored procedure/trigger etc.
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
@@IDENTITY: It returns the last identity from the same session.
SELECT @@IDENTITY AS [@@IDENTITY];
For the sake of proper Javascript
HTMLTextAreaElement.prototype.insertAtCaret = function (text) {
text = text || '';
if (document.selection) {
// IE
this.focus();
var sel = document.selection.createRange();
sel.text = text;
} else if (this.selectionStart || this.selectionStart === 0) {
// Others
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
this.value = this.value.substring(0, startPos) +
text +
this.value.substring(endPos, this.value.length);
this.selectionStart = startPos + text.length;
this.selectionEnd = startPos + text.length;
} else {
this.value += text;
}
};
You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix
component is no longer included:
Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.
You can see the history from ~/.mysql_history. However the content of the file is encoded by wctomb. To view the content:
shell> cat ~/.mysql_history | python2.7 -c "import sys; print(''.join([l.decode('unicode-escape') for l in sys.stdin]))"
<button onclick="location.href='@Url.Action("NewCustomer", "Customers")'">Checkout >></button>
Maybe you can use ListBuffers in scala to create empty list and add strings later because ListBuffers are mutable. Also all the List functions are available for the ListBuffers in scala.
import scala.collection.mutable.ListBuffer
val dm = ListBuffer[String]()
dm: scala.collection.mutable.ListBuffer[String] = ListBuffer()
dm += "text1"
dm += "text2"
dm = ListBuffer(text1, text2)
if you want you can convert this to a list by using .toList
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.
Also, this structure is hardly a tree, finding a more representative name might be a good exercise.
Microsoft Excel Miniature, Quick-and-Dirty formula.
Hi,
Here's one way to get the Excel character-column-header from a number....
I created a formula for an Excel cell.
(i.e. I took the approach of not using VBA programming.)
The formula looks at a cell that has a number in it and tells you what the column is -- in letters.
In the attached image:
I did it in this manner to prove that the formula works so you can look at the output from the formula and look at the column header above and easily visually verify that the formula works. :-)
=CONCATENATE(MID("_abcdefghijklmnopqrstuvwxyz",(IF(MOD(K1,26)>0,INT(K1/26)+1,(INT(K1/26)))),1),MID("abcdefghijklmnopqrstuvwxyz",IF(MOD(K1,26)=0,26,MOD(K1,26)),1))
The underscore was there for debugging purposes - to let you know there was an actual space and that it was working correctly.
With this formula above -- whatever you put in K1 - the formula will tell you what the column header will be.
The formula, in its current form, only goes out to 2 digits (ZZ) but could be modified to add the 3rd letter (ZZZ).
Window->Show View->Other…->Android->LogCat
How about this:
SELECT MONTH('March' + ' 1 2014')
Would return 3
.
Why don't you disable the button and enable it after you finish the event?
<input type="button" id="xx" onclick="checkEnableSubmit('true');yourFunction();">
<script type="text/javascript">
function checkEnableSubmit(status) {
document.getElementById("xx").disabled = status;
}
function yourFunction(){
//add your functionality
checkEnableSubmit('false');
}
</script>
Happy coding !!!
NOTE: I apologize in advance for answering only a portion of the above question. However, I found these commands to be useful for my current unix needs.
Uploading specific files from a local machine to a remote machine:
~/Desktop/dump_files$ scp file1.txt file2.txt lab1.cpp etc.ext [email protected]:Folder1/DestinationFolderForFiles/
Uploading an entire directory from a local machine to a remote machine:
~$ scp -r Desktop/dump_files [email protected]:Folder1/DestinationFolderForFiles/
Downloading an entire directory from a remote machine to a local machine:
~/Desktop$ scp -r [email protected]:Public/web/ Desktop/
Facebook use the following algorithm to position their login popup window:
function PopupCenter(url, title, w, h) {
var userAgent = navigator.userAgent,
mobile = function() {
return /\b(iPhone|iP[ao]d)/.test(userAgent) ||
/\b(iP[ao]d)/.test(userAgent) ||
/Android/i.test(userAgent) ||
/Mobile/i.test(userAgent);
},
screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft,
screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.documentElement.clientWidth,
outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : document.documentElement.clientHeight - 22,
targetWidth = mobile() ? null : w,
targetHeight = mobile() ? null : h,
V = screenX < 0 ? window.screen.width + screenX : screenX,
left = parseInt(V + (outerWidth - targetWidth) / 2, 10),
right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10),
features = [];
if (targetWidth !== null) {
features.push('width=' + targetWidth);
}
if (targetHeight !== null) {
features.push('height=' + targetHeight);
}
features.push('left=' + left);
features.push('top=' + right);
features.push('scrollbars=1');
var newWindow = window.open(url, title, features.join(','));
if (window.focus) {
newWindow.focus();
}
return newWindow;
}
I did it! Using <intent-filter>
. Put the following into your manifest file:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>
This works perfectly!
Just try -webkit-flexbox
. it's working for safari.
webkit-flex
safari will not taking.
$(document).ready(function() {
$(".tab").click(function () {
if(!$(this).hasClass('active'))
{
$(".tab.active").removeClass("active");
$(this).addClass("active");
}
});
});
Time package in Golang has some methods that might be worth looking.
func (Time) Format
func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,
Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.
Source (http://golang.org/pkg/time/#Time.Format)
I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)
func ExampleTime_Format() {
// layout shows by example how the reference time should be represented.
const layout = "Jan 2, 2006 at 3:04pm (MST)"
t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
fmt.Println(t.Format(layout))
fmt.Println(t.UTC().Format(layout))
// Output:
// Nov 10, 2009 at 3:00pm (PST)
// Nov 10, 2009 at 11:00pm (UTC)
}
NA is a special value in R, do not mix up the NA value with the "NA" string. Depending on the way the data was imported, your "NA" and "NULL" cells may be of various type (the default behavior is to convert "NA" strings to NA values, and let "NULL" strings as is).
If using read.table() or read.csv(), you should consider the "na.strings" argument to do clean data import, and always work with real R NA values.
An example, working in both cases "NULL" and "NA" cells :
DF <- read.csv("file.csv", na.strings=c("NA", "NULL"))
new_DF <- subset(DF, is.na(DF$Var2))
There are two main uses of AtomicInteger
:
As an atomic counter (incrementAndGet()
, etc) that can be used by many threads concurrently
As a primitive that supports compare-and-swap instruction (compareAndSet()
) to implement non-blocking algorithms.
Here is an example of non-blocking random number generator from Brian Göetz's Java Concurrency In Practice:
public class AtomicPseudoRandom extends PseudoRandom {
private AtomicInteger seed;
AtomicPseudoRandom(int seed) {
this.seed = new AtomicInteger(seed);
}
public int nextInt(int n) {
while (true) {
int s = seed.get();
int nextSeed = calculateNext(s);
if (seed.compareAndSet(s, nextSeed)) {
int remainder = s % n;
return remainder > 0 ? remainder : remainder + n;
}
}
}
...
}
As you can see, it basically works almost the same way as incrementAndGet()
, but performs arbitrary calculation (calculateNext()
) instead of increment (and processes the result before return).
First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :
obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;
Assuming i understand your question.
You can get the selected row using the DataGridView.SelectedRows
Collection. If your DataGridView allows only one selected, have a look at my sample.
DataGridView.SelectedRows Gets the collection of rows selected by the user.
if (dataGridView1.SelectedRows.Count != 0)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
row.Cells["ColumnName"].Value
}
I had the same problem. Tore my hair for hours trying all sorts of solutions. Turned out to be an unclosed a tag.Try validate your HTML code, solution could be an unclosed tag causing issues
you may use this query for selecting top records in oracle. Rakesh B
select * from User_info where id >= (select max(id)-10 from User_info);
Below code split file every 500
@echo off
setlocal ENABLEDELAYEDEXPANSION
REM Edit this value to change the name of the file that needs splitting. Include the extension.
SET BFN=upload.txt
REM Edit this value to change the number of lines per file.
SET LPF=15000
REM Edit this value to change the name of each short file. It will be followed by a number indicating where it is in the list.
SET SFN=SplitFile
REM Do not change beyond this line.
SET SFX=%BFN:~-3%
SET /A LineNum=0
SET /A FileNum=1
For /F "delims==" %%l in (%BFN%) Do (
SET /A LineNum+=1
echo %%l >> %SFN%!FileNum!.%SFX%
if !LineNum! EQU !LPF! (
SET /A LineNum=0
SET /A FileNum+=1
)
)
endlocal
Pause
I was looking for a client-side solution to detect if the internet was down or my server was down. The other solutions I found always seemed to be dependent on a 3rd party script file or image, which to me didn't seem like it would stand the test of time. An external hosted script or image could change in the future and cause the detection code to fail.
I've found a way to detect it by looking for an xhrStatus with a 404 code. In addition, I use JSONP to bypass the CORS restriction. A status code other than 404 shows the internet connection isn't working.
$.ajax({
url: 'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',
dataType: 'jsonp',
timeout: 5000,
error: function(xhr) {
if (xhr.status == 404) {
//internet connection working
}
else {
//internet is down (xhr.status == 0)
}
}
});
According to my understanding to your question, as an example: you had a style at the beginning in style sheet (ex. background-color: red), then using java script you changed it to another style (ex. background-color: green), now you want to reset the style to its original value in style sheet (background-color: red) without mentioning or even knowing its value (ex. element.style.backgroundColor = 'red')...!
If I'm correct, I have a good solution for you which is using another class name for the element:
steps:
if you want to edit or set a new style, get the element by the new class name and edit the style as desired.
I hope this helps. Regards!
Recently I have worked on my sliding menu implementation version. It uses popular J.Feinstein Android library SlidingMenu.
Please check the source code at GitHub:
https://github.com/baruckis/Android-SlidingMenuImplementation
Download app directly to the device to try:
https://play.google.com/store/apps/details?id=com.baruckis.SlidingMenuImplementation
Code should be self-explanatory because of comments. I hope it will be helpful! ;)
these will help you...
Application Controller
class ApplicationController < ActionController::Base
protect_from_forgery
unless Rails.application.config.consider_all_requests_local
rescue_from ActionController::RoutingError, ActionController::UnknownController, ::AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, with: lambda { |exception| render_error 404, exception }
end
private
def render_error(status, exception)
Rails.logger.error status.to_s + " " + exception.message.to_s
Rails.logger.error exception.backtrace.join("\n")
respond_to do |format|
format.html { render template: "errors/error_#{status}",status: status }
format.all { render nothing: true, status: status }
end
end
end
Errors controller
class ErrorsController < ApplicationController
def error_404
@not_found_path = params[:not_found]
end
end
views/errors/error_404.html.haml
.site
.services-page
.error-template
%h1
Oops!
%h2
404 Not Found
.error-details
Sorry, an error has occured, Requested page not found!
You tried to access '#{@not_found_path}', which is not a valid page.
.error-actions
%a.button_simple_orange.btn.btn-primary.btn-lg{href: root_path}
%span.glyphicon.glyphicon-home
Take Me Home
Responsive way to center your button in a div:
<div
style="display: flex;
align-items: center;
justify-content: center;
margin-bottom: 2rem;">
<button type="button" style="height: 10%; width: 20%;">hello</button>
</div>
My favourite answer so far is coloredEcho.
Just to post another option, you can check out this little tool xcol
https://ownyourbits.com/2017/01/23/colorize-your-stdout-with-xcol/
you use it just like grep, and it will colorize its stdin with a different color for each argument, for instance
sudo netstat -putan | xcol httpd sshd dnsmasq pulseaudio conky tor Telegram firefox "[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+" ":[[:digit:]]+" "tcp." "udp." LISTEN ESTABLISHED TIME_WAIT
Note that it accepts any regular expression that sed will accept.
This tool uses the following definitions
#normal=$(tput sgr0) # normal text
normal=$'\e[0m' # (works better sometimes)
bold=$(tput bold) # make colors bold/bright
red="$bold$(tput setaf 1)" # bright red text
green=$(tput setaf 2) # dim green text
fawn=$(tput setaf 3); beige="$fawn" # dark yellow text
yellow="$bold$fawn" # bright yellow text
darkblue=$(tput setaf 4) # dim blue text
blue="$bold$darkblue" # bright blue text
purple=$(tput setaf 5); magenta="$purple" # magenta text
pink="$bold$purple" # bright magenta text
darkcyan=$(tput setaf 6) # dim cyan text
cyan="$bold$darkcyan" # bright cyan text
gray=$(tput setaf 7) # dim white text
darkgray="$bold"$(tput setaf 0) # bold black = dark gray text
white="$bold$gray" # bright white text
I use these variables in my scripts like so
echo "${red}hello ${yellow}this is ${green}coloured${normal}"
401 means "Unauthorized", so there must be something with your credentials.
I think that java URL
does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
PHP 5.2.0 and later
Linux systems
In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option.
Windows
Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.
A simple solution is encapsulate code of button event in a function, and call it when you add TRs too:
var i = 1;
$("#addbutton").click(function() {
$("table tr:first").clone().find("input").each(function() {
$(this).val('').attr({
'id': function(_, id) {return id + i },
'name': function(_, name) { return name + i },
'value': ''
});
}).end().appendTo("table");
i++;
applyRemoveEvent();
});
function applyRemoveEvent(){
$('button.removebutton').on('click',function() {
alert("aa");
$(this).closest( 'tr').remove();
return false;
});
};
applyRemoveEvent();
If the code in your question doesn't work, you probably have not implemented equals(Object)
on the Customer
class appropriately.
Presumably there is some key (let us call it customerId
) that uniquely identifies a customer; e.g.
class Customer {
private String customerId;
...
An appropriate definition of equals(Object)
would look like this:
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Customer)) {
return false;
}
Customer other = (Customer) obj;
return this.customerId.equals(other.customerId);
}
For completeness, you should also implement hashCode
so that two Customer
objects that are equal will return the same hash value. A matching hashCode
for the above definition of equals
would be:
public int hashCode() {
return customerId.hashCode();
}
It is also worth noting that this is not an efficient way to remove duplicates if the list is large. (For a list with N customers, you will need to perform N*(N-1)/2
comparisons in the worst case; i.e. when there are no duplicates.) For a more efficient solution you should use something like a HashSet
to do the duplicate checking.
At last i did it Thanks alot friends, and a special thanks to Mr https://stackoverflow.com/users/87015/salman-a because of his code i was able to solve it properly. finally my code is looking like this as i am using groovy grails i hope this will help somebody there.. Thanks alot
html code looks like this in my gsp page
<input id="populate-dropdown" name="nameofClient" type="text">
<input id="wilhaveid" name="idofclient" type="text">
script Function is like this in my gsp page
<script>
$( "#populate-dropdown").on('input', function() {
$.ajax({
url:'autoCOmp',
data: {inputField: $("#populate-dropdown").val()},
success: function(resp){
$('#populate-dropdown').autocomplete({
source:resp,
select: function (event, ui) {
$("#populate-dropdown").val(ui.item.label);
$("#wilhaveid").val(ui.item.value);
return false;
}
})
}
});
});
</script>
And my controller code is like this
def autoCOmp(){
println(params)
def c = Client.createCriteria()
def results = c.list {
like("nameOfClient", params.inputField+"%")
}
def itemList = []
results.each{
itemList << [value:it.id,label:it.nameOfClient]
}
println(itemList)
render itemList as JSON
}
One more thing i have not set id field hidden because at first i was checking that i am getting the exact id , you can keep it hidden just put type=hidden instead of text for second input item in html
Thanks !
You can use numpy's polyfit. I use the following (you can safely remove the bit about coefficient of determination and error bounds, I just think it looks nice):
#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import csv
with open("example.csv", "r") as f:
data = [row for row in csv.reader(f)]
xd = [float(row[0]) for row in data]
yd = [float(row[1]) for row in data]
# sort the data
reorder = sorted(range(len(xd)), key = lambda ii: xd[ii])
xd = [xd[ii] for ii in reorder]
yd = [yd[ii] for ii in reorder]
# make the scatter plot
plt.scatter(xd, yd, s=30, alpha=0.15, marker='o')
# determine best fit line
par = np.polyfit(xd, yd, 1, full=True)
slope=par[0][0]
intercept=par[0][1]
xl = [min(xd), max(xd)]
yl = [slope*xx + intercept for xx in xl]
# coefficient of determination, plot text
variance = np.var(yd)
residuals = np.var([(slope*xx + intercept - yy) for xx,yy in zip(xd,yd)])
Rsqr = np.round(1-residuals/variance, decimals=2)
plt.text(.9*max(xd)+.1*min(xd),.9*max(yd)+.1*min(yd),'$R^2 = %0.2f$'% Rsqr, fontsize=30)
plt.xlabel("X Description")
plt.ylabel("Y Description")
# error bounds
yerr = [abs(slope*xx + intercept - yy) for xx,yy in zip(xd,yd)]
par = np.polyfit(xd, yerr, 2, full=True)
yerrUpper = [(xx*slope+intercept)+(par[0][0]*xx**2 + par[0][1]*xx + par[0][2]) for xx,yy in zip(xd,yd)]
yerrLower = [(xx*slope+intercept)-(par[0][0]*xx**2 + par[0][1]*xx + par[0][2]) for xx,yy in zip(xd,yd)]
plt.plot(xl, yl, '-r')
plt.plot(xd, yerrLower, '--r')
plt.plot(xd, yerrUpper, '--r')
plt.show()
You can find your created database, named <your-database-name>
in
//data/data/<Your-Application-Package-Name>/databases/<your-database-name>
Pull it out using File explorer and rename it to have .db3 extension to use it in SQLiteExplorer
Use File explorer of DDMS to navigate to emulator directory.
Essentially equivalent to @waitingkuo, but I would use to_datetime
here (it seems a little cleaner, and offers some additional functionality e.g. dayfirst
):
In [11]: df
Out[11]:
a time
0 1 2013-01-01
1 2 2013-01-02
2 3 2013-01-03
In [12]: pd.to_datetime(df['time'])
Out[12]:
0 2013-01-01 00:00:00
1 2013-01-02 00:00:00
2 2013-01-03 00:00:00
Name: time, dtype: datetime64[ns]
In [13]: df['time'] = pd.to_datetime(df['time'])
In [14]: df
Out[14]:
a time
0 1 2013-01-01 00:00:00
1 2 2013-01-02 00:00:00
2 3 2013-01-03 00:00:00
Handling ValueError
s
If you run into a situation where doing
df['time'] = pd.to_datetime(df['time'])
Throws a
ValueError: Unknown string format
That means you have invalid (non-coercible) values. If you are okay with having them converted to pd.NaT
, you can add an errors='coerce'
argument to to_datetime
:
df['time'] = pd.to_datetime(df['time'], errors='coerce')
You'll want to use the clone()
method in order to get a deep copy of the element:
$(function(){
var $button = $('.button').clone();
$('.package').html($button);
});
Full demo: http://jsfiddle.net/3rXjx/
From the jQuery docs:
The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page.
The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).
1 git fetch
from your feature branch (make sure the feature branch you are working on is update to date)
2 git rebase origin/develop
3 if any conflict shall arise, resolve them one by one
4 use git rebase --continue
once all conflicts are dealt with
5 git push --force
In Oracle 12c you can also declare an identity column
CREATE TABLE identity_test_tab (
id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
description VARCHAR2(30)
);
examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.
I've your same requirements on a public API for which I used rails-api.
I've also set header in a before filter. It looks like this:
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
It seems you missed the Access-Control-Request-Method header.
If using Express it's not necessary to use a View Engine at all, use something like this:
<h1>{{ name }} </h1>
This works if you previously set your application to use HTML instead of any View Engine
You could write this extension method:
// Possibly call this "Do"
IEnumerable<T> Apply<T> (this IEnumerable<T> source, Action<T> action)
{
foreach (var e in source)
{
action(e);
yield return e;
}
}
Pros
Allows chaining:
MySequence
.Apply(...)
.Apply(...)
.Apply(...);
Cons
It won't actually do anything until you do something to force iteration. For that reason, it shouldn't be called .ForEach()
. You could write .ToList()
at the end, or you could write this extension method, too:
// possibly call this "Realize"
IEnumerable<T> Done<T> (this IEnumerable<T> source)
{
foreach (var e in source)
{
// do nothing
;
}
return source;
}
This may be too significant a departure from the shipping C# libraries; readers who are not familiar with your extension methods won't know what to make of your code.
This is basic code to find and play an audio file in Swift.
Add your audio file to your Xcode and add the code below.
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer() // declare globally
override func viewDidLoad() {
super.viewDidLoad()
guard let sound = Bundle.main.path(forResource: "audiofilename", ofType: "mp3") else {
print("Error getting the mp3 file from the main bundle.")
return
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
} catch {
print("Audio file error.")
}
audioPlayer.play()
}
@IBAction func notePressed(_ sender: UIButton) { // Button action
audioPlayer.stop()
}
}
The problem is your angular material version, I have the same, and I have resolved this when I have installed the good version of angular material in local.
Hope it solve yours too.
You can access 1 line at a time by for loop
#!/bin/bash -eu
#This script prints contents of /etc/passwd line by line
FILENAME='/etc/passwd'
I=0
for LN in $(cat $FILENAME)
do
echo "Line number $((I++)) --> $LN"
done
Copy the entire content to File (say line.sh ) ; Execute
chmod +x line.sh
./line.sh
In case the formatting needs to be done on Crystal Report side.
Simple way.
Crystal Report Design Window->Right click on the date field->format Field->Customize the date format per your need.
Works effectively.
On Mac remove hidden file: <FLUTTER_HOME>/bin/cache/.upgrade_lock
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>test</title>
</head>
<body>
<table>
<tr>
<td>
<div>content</div>
</td>
</tr>
</table>
</body>
</html>
This document was successfully checked as XHTML 1.0 Transitional!
You could also consider:
RUN apt-get update && apt-get install -y iputils-ping
(as Contango comments: you must first run apt-get update
, to avoid error with missing repository).
See "Replacing ifconfig with ip"
it is most often recommended to move forward with the command that has replaced
ifconfig
. That command isip
, and it does a great job of stepping in for the out-of-dateifconfig
.
But as seen in "Getting a Docker container's IP address from the host", using docker inspect
can be more useful depending on your use case.
As long as have added type="submit" to button you are good.
<form action="">
<input type="text" placeholder="name" required>
<button type="submit">Submit</button>
</form>
Trying my part, simple, one liner, pythonic way using islice. But, may not be optimally efficient.
from itertools import islice
array = range(0, 10)
window_size = 4
map(lambda i: list(islice(array, i, i + window_size)), range(0, len(array) - window_size + 1))
# output = [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9]]
Explanation: Create window by using islice of window_size and iterate this operation using map over all array.
Example query:
DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)
Here fields
are column on which you want to group the duplicate rows.
Try following source code it worked for me
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");
=(B0+4)/($A$0)
$ means keep same (press a few times F4 after typing A4 to flip through combos quick!)
It's compiler dependent. That said, in general using "
prioritizes headers in the current working directory over system headers. <>
usually is used for system headers. From to the specification (Section 6.10.2):
A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the
<
and>
delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"
delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read# include <h-char-sequence> new-line
with the identical contained sequence (including
>
characters, if any) from the original directive.
So on most compilers, using the ""
first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <>
starts the search with system headers.
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
^
is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow
.
If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:
$('#exampleBtn').click(function() {
function();
});
Hey I got something that seems to be doing what you want a do. It involves some dirty copying but works. You can find the working code here
So here is the main html file :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
Iframe = $('#frame1');
Iframe.on('load', function(){
IframeInner = Iframe.contents().find('iframe');
IframeInnerClone = IframeInner.clone();
IframeInnerClone.insertAfter($('#insertIframeAfter')).css({display:'none'});
IframeInnerClone.on('load', function(){
IframeContents = IframeInner.contents();
YourNestedEl = IframeContents.find('div');
$('<div>Yeepi! I can even insert stuff!</div>').insertAfter(YourNestedEl)
});
});
});
</script>
</head>
<body>
<div id="insertIframeAfter">Hello!!!!</div>
<iframe id="frame1" src="Test_Iframe.html">
</iframe>
</body>
</html>
As you can see, once the first Iframe is loaded, I get the second one and clone it. I then reinsert it in the dom, so I can get access to the onload event. Once this one is loaded, I retrieve the content from non-cloned one (must have loaded as well, since they use the same src). You can then do wathever you want with the content.
Here is the Test_Iframe.html file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>Test_Iframe</div>
<iframe src="Test_Iframe2.html">
</iframe>
</body>
</html>
and the Test_Iframe2.html file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>I am the second nested iframe</div>
</body>
</html>
As you mentioned duplicate values . In such case you may use DISTINCT and GROUP BY to find out second highest value
Here is a table
salary
:
GROUP BY
SELECT amount FROM salary
GROUP by amount
ORDER BY amount DESC
LIMIT 1 , 1
DISTINCT
SELECT DISTINCT amount
FROM salary
ORDER BY amount DESC
LIMIT 1 , 1
First portion of LIMIT = starting index
Second portion of LIMIT = how many value
Let's say you have a path with a file in this format:
/dirA/dirB/dirC/filename.file
Now you only want the path which includes four "/". Type
$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-4 -d"/"
and your output will be
/dirA/dirB/dirC
The advantage of using cut is that you can also cut out the uppest directory as well as the file (in this example), so if you type
$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-3 -d"/"
your output would be
/dirA/dirB
Though you can do the same from the other side of the string, it would not make that much sense in this case as typing
$ echo "/dirA/dirB/dirC/filename.file" | cut -f2-4 -d"/"
results in
dirA/dirB/dirC
In some other cases the last case might also be helpful. Mind that there is no "/" at the beginning of the last output.
Yes it can. I checked on Mozilla's page. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
If mysql binlog is enabled you can check the commands ran by user by executing following command in linux console by browsing to mysql binlog directory
mysqlbinlog binlog.000001 > /tmp/statements.sql
enabling
[mysqld]
log = /var/log/mysql/mysql.log
or general log will have an effect on performance of mysql
You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:
sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh
open new terminal and validate environment is clean from old RVM settings (should be no output):
env | grep rvm
if there was output, try to open new terminal, if it does not help then restart your computer.
\curl -L https://get.rvm.io |
bash -s stable --ruby --autolibs=enable --auto-dotfiles
If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.
RawMaterialButton(
onPressed: () {},
constraints: BoxConstraints(),
elevation: 2.0,
fillColor: Colors.white,
child: Icon(
Icons.pause,
size: 35.0,
),
padding: EdgeInsets.all(15.0),
shape: CircleBorder(),
)
note down constraints: BoxConstraints()
, it's for not allowing padding in left.
Happy fluttering!!
In my case got a working solution through Cross-document Messaging (XDM) and Executing Chrome extension onclick instead of page load.
manifest.json
{
"name": "JQuery Light",
"version": "1",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts": [
{
"matches": [
"https://*.google.com/*"
],
"js": [
"jquery-3.3.1.min.js",
"myscript.js"
]
}
],
"background": {
"scripts": [
"background.js"
]
}
}
background.js
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
});
});
myscript.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.message === "clicked_browser_action") {
console.log('Hello world!')
}
}
);
If the Exception is being thrown in that try
block then at worst case scenario Exception
should be catching anything uncaught.
Consider that the first part of the test is throwing the Exception and wrap that in the try
block as well.
In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.
Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression. Let's see an example.
>>> # Defining a lambda function that takes 2 parameters(as integer) and returns their sum
...
>>> lambda num1, num2: num1 + num2
<function <lambda> at 0x1004b5de8>
>>>
>>> # Let's store the returned value in variable & call it(1st way to call)
...
>>> addition = lambda num1, num2: num1 + num2
>>> addition(62, 5)
67
>>> addition(1700, 29)
1729
>>>
>>> # Let's call it in other way(2nd way to call, one line call )
...
>>> (lambda num1, num2: num1 + num2)(120, 1)
121
>>> (lambda num1, num2: num1 + num2)(-68, 2)
-66
>>> (lambda num1, num2: num1 + num2)(-68, 2**3)
-60
>>>
Now let me give an answer of your 2nd question. The 1st answer is also great. This is my own way to explain with another example.
Suppose we have a list of items(integers and strings with numeric contents) as follows,
nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
and I want to sort it using sorted() function, lets see what happens.
>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums)
[1, 3, 4, '-1', '-10', '2', '5', '8']
>>>
It didn't give me what I expected as I wanted like below,
['-10', '-1', 1, '2', 3, 4, '5', '8']
It means we need some strategy(so that sorted could treat our string items as an ints) to achieve this. This is why the key keyword argument is used. Please look at the below one.
>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums, key=int)
['-10', '-1', 1, '2', 3, 4, '5', '8']
>>>
Lets use lambda function as a value of key
>>> names = ["Rishikesh", "aman", "Ajay", "Hemkesh", "sandeep", "Darshan", "Virendra", "Shwetabh"]
>>> names2 = sorted(names)
>>> names2
['Ajay', 'Darshan', 'Hemkesh', 'Rishikesh', 'Shwetabh', 'Virendra', 'aman', 'sandeep']
>>> # But I don't want this o/p(here our intention is to treat 'a' same as 'A')
...
>>> names3 = sorted(names, key=lambda name:name.lower())
>>> names3
['Ajay', 'aman', 'Darshan', 'Hemkesh', 'Rishikesh', 'sandeep', 'Shwetabh', 'Virendra']
>>>
You can define your own function(callable) and provide it as value of key.
Dear programers, I have written the below code for you, just try to understand it and comment your explanation. I would be glad to see your explanation(it's simple).
>>> def validator(item):
... try:
... return int(item)
... except:
... return 0
...
>>> sorted(['gurmit', "0", 5, 2, 1, "front", -2, "great"], key=validator)
[-2, 'gurmit', '0', 'front', 'great', 1, 2, 5]
>>>
I hope it would be useful.
We test our own with our own unit tests and oftentimes a dedicated client app.
Once you've got expandtab on as per the other answers, the extremely convenient way to convert existing files according to your new settings is:
:retab
It will work on the current buffer.
You have to define your exception elsewhere as a new class
public class YourCustomException extends Exception{
//Required inherited methods here
}
Then you can throw and catch YourCustomException as much as you'd like.
Just write:
min-height: xxx;
overflow: hidden;
then div
will automatically take the height of the content.
Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random()
.
Math.random()
Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.
I call this the "Fractional-Unique-ID".
Wrote code to generate 1,000,000 Math.random()
numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):
random_numbers = []
for (i = 0; i < 1000000; i++) {
random_numbers.push(Math.random());
//random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16
}
if (i === 1000000) {
console.log("Before checking duplicate");
console.log(random_numbers.length);
console.log("After checking duplicate");
random_set = new Set(random_numbers); // Set removes duplicates
console.log([...random_set].length); // length is still the same after removing
}
I needed to print important warning about skipped tests exactly when PyTest
muted literally everything.
I didn't want to fail a test to send a signal, so I did a hack as follow:
def test_2_YellAboutBrokenAndMutedTests():
import atexit
def report():
print C_patch.tidy_text("""
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.""")
if sys.stdout != sys.__stdout__:
atexit.register(report)
The atexit
module allows me to print stuff after PyTest
released the output streams. The output looks as follow:
============================= test session starts ==============================
platform linux2 -- Python 2.7.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /media/Storage/henaro/smyth/Alchemist2-git/sources/C_patch, inifile:
collected 15 items
test_C_patch.py .....ssss....s.
===================== 10 passed, 5 skipped in 0.15 seconds =====================
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.
~/.../sources/C_patch$
Message is printed even when PyTest
is in silent mode, and is not printed if you run stuff with py.test -s
, so everything is tested nicely already.
Use DATE_FORMAT
select DATE_FORMAT(date,'%d') from tablename =>Date only
example:
select DATE_FORMAT(`date_column`,'%d') from `database_name`.`table_name`;
Wouldn't occam's razor say to just do this until you need something more complex? It's a bit of a hack, but may suit the needs of someone that wants a quick fix.
.navbar-default .container-fluid{
background-color:#62ADD7; // Change the color
margin: -1px -1px 10px -1px; // Get rid of the border
}
PDFsharp seems to allow merging multiple PDF documents into one.
And the same is also possible with ITextSharp.
No, grep works just fine for this:
grep -rl "filename" [starting point]
grep -rL "not in filename"
I got this error when I tried to install pymssql even though Visual C++ 2015 (14.0) is installed in my system.
I resolved this error by downloading the .whl file of pymssql from here.
Once downloaded, it can be installed by the following command :
pip install python_package.whl
Hope this helps
Everytime I install node.js it needs a reboot and then the path is recognized.
This also works:
db.getCollection('collectionName').find({'arrayName': {$elemMatch:{}}})
you can configure profiles in the bash_profile file using
<profile_name>
aws_access_key_id = <access_key>
aws_secret_access_key = <acces_key_secret>
if you are using multiple profiles. then use:
aws s3 ls --profile <profile_name>
Use Cheerio. It isn't as strict as jsdom and is optimized for scraping. As a bonus, uses the jQuery selectors you already know.
? Familiar syntax: Cheerio implements a subset of core jQuery. Cheerio removes all the DOM inconsistencies and browser cruft from the jQuery library, revealing its truly gorgeous API.
? Blazingly fast: Cheerio works with a very simple, consistent DOM model. As a result parsing, manipulating, and rendering are incredibly efficient. Preliminary end-to-end benchmarks suggest that cheerio is about 8x faster than JSDOM.
? Insanely flexible: Cheerio wraps around @FB55's forgiving htmlparser. Cheerio can parse nearly any HTML or XML document.
Depending on how many dynamic classes you need to add as your project grows it's probably worth checking out the classnames utility by JedWatson on GitHub. It allows you to represent your conditional classes as an object and returns those that evaluate to true.
So as an example from its React documentation:
render () {
var btnClass = classNames({
'btn': true,
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
return <button className={btnClass}>I'm a button!</button>;
}
Since React triggers a re-render when there is a state change, your dynamic class names are handled naturally and kept up to date with the state of your component.
This is just a suggestion, but what I like to do while I'm coding sometimes is to Invert the colors of my Screen. On a Mac it's Ctrl-Cmd-Alt->8 and it inverts the colors.
Haven't personally tried these in Idea10, but it worked on Idea9. http://devnet.jetbrains.net/docs/DOC-1154
All work perfectly :)
NSString *test = @"test";
unichar a;
int index = 5;
@try {
a = [test characterAtIndex:index];
}
@catch (NSException *exception) {
NSLog(@"%@", exception.reason);
NSLog(@"Char at index %d cannot be found", index);
NSLog(@"Max index is: %lu", [test length] - 1);
}
@finally {
NSLog(@"Finally condition");
}
Log:
[__NSCFConstantString characterAtIndex:]: Range or index out of bounds
Char at index 5 cannot be found
Max index is: 3
Finally condition
TextFieldInTableViewCell
import UIKit
protocol TextFieldInTableViewCellDelegate: class {
func textField(editingDidBeginIn cell:TextFieldInTableViewCell)
func textField(editingChangedInTextField newText: String, in cell: TextFieldInTableViewCell)
}
class TextFieldInTableViewCell: UITableViewCell {
private(set) weak var textField: UITextField?
private(set) weak var descriptionLabel: UILabel?
weak var delegate: TextFieldInTableViewCellDelegate?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupSubviews()
}
private func setupSubviews() {
let stackView = UIStackView()
stackView.distribution = .fill
stackView.alignment = .leading
stackView.spacing = 8
contentView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 6).isActive = true
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6).isActive = true
stackView.leftAnchor.constraint(equalTo: leftAnchor, constant: 16).isActive = true
stackView.rightAnchor.constraint(equalTo: rightAnchor, constant: -16).isActive = true
let label = UILabel()
label.text = "Label"
stackView.addArrangedSubview(label)
descriptionLabel = label
let textField = UITextField()
textField.textAlignment = .left
textField.placeholder = "enter text"
textField.setContentHuggingPriority(.fittingSizeLevel, for: .horizontal)
stackView.addArrangedSubview(textField)
textField.addTarget(self, action: #selector(textFieldValueChanged(_:)), for: .editingChanged)
textField.addTarget(self, action: #selector(editingDidBegin), for: .editingDidBegin)
self.textField = textField
stackView.layoutSubviews()
selectionStyle = .none
let gesture = UITapGestureRecognizer(target: self, action: #selector(didSelectCell))
addGestureRecognizer(gesture)
}
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
}
extension TextFieldInTableViewCell {
@objc func didSelectCell() { textField?.becomeFirstResponder() }
@objc func editingDidBegin() { delegate?.textField(editingDidBeginIn: self) }
@objc func textFieldValueChanged(_ sender: UITextField) {
if let text = sender.text { delegate?.textField(editingChangedInTextField: text, in: self) }
}
}
ViewController
import UIKit
class ViewController: UIViewController {
private weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
}
extension ViewController {
func setupTableView() {
let tableView = UITableView(frame: .zero)
tableView.register(TextFieldInTableViewCell.self, forCellReuseIdentifier: "TextFieldInTableViewCell")
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = UITableView.automaticDimension
tableView.tableFooterView = UIView()
self.tableView = tableView
tableView.dataSource = self
let gesture = UITapGestureRecognizer(target: tableView, action: #selector(UITextView.endEditing(_:)))
tableView.addGestureRecognizer(gesture)
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int { return 1 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldInTableViewCell") as! TextFieldInTableViewCell
cell.delegate = self
return cell
}
}
extension ViewController: TextFieldInTableViewCellDelegate {
func textField(editingDidBeginIn cell: TextFieldInTableViewCell) {
if let indexPath = tableView?.indexPath(for: cell) {
print("textfield selected in cell at \(indexPath)")
}
}
func textField(editingChangedInTextField newText: String, in cell: TextFieldInTableViewCell) {
if let indexPath = tableView?.indexPath(for: cell) {
print("updated text in textfield in cell as \(indexPath), value = \"\(newText)\"")
}
}
}
we can directly see the indexes on to the table if we know the index name with below :
select * from all_indexes where index_name= 'your index'
Most importantly you need to mount the drive
net use z: \\yourserver\sharename
Of course, you need to make sure that the account the batch file runs under has permission to access the share. If you are doing this by using a Scheduled Task, you can choose the account by selecting the task, then:
"When running the task, use the following user account:" That's on Windows 7, it might be slightly different on different versions of Windows.
Then run your batch script with the following changes
copy "z:\FolderName" "C:\TEST_BACKUP_FOLDER"
It seems to be the fault of the mainfest Merger tool for gradle.
http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger
Solved it by adding to my manifest tag xmlns:tools="http://schemas.android.com/tools"
Then added tools:replace="android:icon,android:theme"
to the application tag
This tells the merger to use my manifest icon and theme and not of other libraries
Hope it helps thanks
Normally a jdk installation has javac in the environment path variables ... so if you check for javac in the path, that's pretty much a good indicator that you have a jdk installed.
You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.
You will have to convert into a decimal radix, either via BigDecimal
or DecimalFormat
, depending on what you want to do with the value later.
See also my answer to this question for a refutation of the inevitable *100/100 answers.
Adding another solution (Python 3) - Iterating over json files in a directory and on each file iterating over all objects and printing relevant fields.
See comments in the code.
import os,json
data_path = '/path/to/your/json/files'
# 1. Iterate over directory
directory = os.fsencode(data_path)
for file in os.listdir(directory):
filename = os.fsdecode(file)
# 2. Take only json files
if filename.endswith(".json"):
file_full_path=data_path+filename
# 3. Open json file
with open(file_full_path, encoding='utf-8', errors='ignore') as json_data:
data_in_file = json.load(json_data, strict=False)
# 4. Iterate over objects and print relevant fields
for json_object in data_in_file:
print("ttl: %s, desc: %s" % (json_object['title'],json_object['description']) )
The array is being re-indexed when you do a .splice()
, which means you'll skip over an index when one is removed, and your cached .length
is obsolete.
To fix it, you'd either need to decrement i
after a .splice()
, or simply iterate in reverse...
var i = Auction.auctions.length
while (i--) {
...
if (...) {
Auction.auctions.splice(i, 1);
}
}
This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.
Try to check the limits of your SQL database. Maybe you'r exceeding the field limit for this row.
<select name="select_box" multiple>
<option>123</option>
<option>456</option>
<option>789</option>
</select>
To disable the warning while connecting to a database in Java, use the below concept -
autoReconnect=true&useSSL=false
Just need to change connectionURL like :
String connectionURL = jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false
This will disable SSL and also suppress the SSL errors.
Add an onchange event to your input element:
<input type="text" id="fName" value="" onchange="fName_Changed(this)" />
Javascript:
function fName_Changed(fName)
{
fName.style.borderColor = (fName.value != 'correct text') ? "#FF0000"; : fName.style.borderColor="";
}
Much confusion stems from the existence of at least three major libraries named bootstrap-datepicker:
If you're starting a new project - or heck, even if you're taking over an old project using the eyecon version - I recommend that you use eternicode's version, not eyecon's. The original eyecon version is outright inferior in terms of both functionality and documentation, and this is unlikely to change - it has not been updated since March 2013.
You can see most of the capabilities of the eternicode datepicker on the demo page which lets you play with the datepicker's configuration and observe the results. For more detail, see the succinct but comprehensive documentation, which you can probably consume in its entirety in under an hour.
In case you're impatient, though, here's a very short step-by-step guide to the simplest and most common use case for the datepicker.
Put an input
element on your page somewhere, e.g.
<input id="my-date-input">
With jQuery, select your input and call the .datepicker()
method:
jQuery('#my-date-input').datepicker();
Load your page and click on or tab into your input
element. A datepicker will appear:
In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:
Should I use NULL or 0?
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.
Based on W3schools default transition value is: all 0s ease 0s
, which should be the cross-browser compatible way of disabling the transition.
Here is a link: https://www.w3schools.com/cssref/css3_pr_transition.asp
double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);
TimeSpan.TotalMinutes: The total number of minutes represented by this instance.
So, because everyone is posting their solution and none was good for me, here is mine (tested on Chrome & Firefox).
table { height: 1px; } /* Will be ignored, don't worry. */
tr { height: 100%; }
td { height: 100%; }
td > div { height: 100%; }
Fiddle: https://jsfiddle.net/nh6g5fzv/
--
Edit: one thing you might want to note, if you want to apply a padding to the div in the td, you must add box-sizing: border-box;
because of height: 100%
.
It's recommended to set self.title as this is used while pushing child navbars or showing title on tabbars.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// create and customize title view
self.title = NSLocalizedString(@"My Custom Title", @"");
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
titleLabel.text = self.title;
titleLabel.font = [UIFont boldSystemFontOfSize:16];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor whiteColor];
[titleLabel sizeToFit];
self.navigationItem.titleView = titleLabel;
[titleLabel release];
}
}
There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.
Solution for linux and other posix compliant systems:
Here, for Morgan Mattews's code provide kbhit()
functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.
Solution for windows:
For windows, Microsoft offers _kbhit()
Copied over from comment by @sloth
Instead of YourCollection.FirstOrDefault()
, you could use YourCollection.DefaultIfEmpty(YourDefault).First()
for example.
Example:
var viewModel = new CustomerDetailsViewModel
{
MainResidenceAddressSection = (MainResidenceAddressSection)addresses.DefaultIfEmpty(new MainResidenceAddressSection()).FirstOrDefault( o => o is MainResidenceAddressSection),
RiskAddressSection = addresses.DefaultIfEmpty(new RiskAddressSection()).FirstOrDefault(o => !(o is MainResidenceAddressSection)),
};
I also had this problem and it's solved as change line from res/values/styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
both solutions worked
Active Mode—The client issues a PORT command to the server signaling that it will “actively” provide an IP and port number to open the Data Connection back to the client.
Passive Mode—The client issues a PASV command to indicate that it will wait “passively” for the server to supply an IP and port number, after which the client will create a Data Connection to the server.
There are lots of good answers above, but this blog post includes some helpful graphics and gives a pretty solid explanation: https://titanftp.com/2018/08/23/what-is-the-difference-between-active-and-passive-ftp/
Using reduce is clever, but the OP's set method may have issues if the parent keys do not pre-exist in the nested dictionary. Since this is the first SO post I saw for this subject in my google search, I would like to make it slightly better.
The set method in ( Setting a value in a nested python dictionary given a list of indices and value ) seems more robust to missing parental keys. To copy it over:
def nested_set(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
Also, it can be convenient to have a method that traverses the key tree and get all the absolute key paths, for which I have created:
def keysInDict(dataDict, parent=[]):
if not isinstance(dataDict, dict):
return [tuple(parent)]
else:
return reduce(list.__add__,
[keysInDict(v,parent+[k]) for k,v in dataDict.items()], [])
One use of it is to convert the nested tree to a pandas DataFrame, using the following code (assuming that all leafs in the nested dictionary have the same depth).
def dict_to_df(dataDict):
ret = []
for k in keysInDict(dataDict):
v = np.array( getFromDict(dataDict, k), )
v = pd.DataFrame(v)
v.columns = pd.MultiIndex.from_product(list(k) + [v.columns])
ret.append(v)
return reduce(pd.DataFrame.join, ret)
I edited your plunker to include ABOS's solution.
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
Followed by @Andy's answer, you can do following to solve your second question:
In [56]: df.groupby(['col5','col2']).size().reset_index().groupby('col2')[[0]].max()
Out[56]:
0
col2
A 3
B 2
C 1
D 3
Drag the variable from Variables pane to Watch pane and voila!
Use mysqli_fetch_row()
. Try this,
$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$ssfullname = $row['ssfullname'];
$ssemail = $row['ssemail'];
You can read HTML page using 'urllib'.
#python 2.x
import urllib
page = urllib.urlopen("your path ").read()
print page
Having tested several options, I finally solved this by using
contract="IMySOAPWebService"
i.e. without the full namespace in the config. For some reason the full name didn't resolve properly
$command = 'convert -density 300 ';
if(Input::Post('height')!='' && Input::Post('width')!=''){
$command.='-resize '.Input::Post('width').'x'.Input::Post('height').' ';
}
$command.=$svg.' '.$source;
exec($command);
@unlink($svg);
or using : potrace demo :Tool4dev.com
Here are the steps:
To verify if Path is set successfully open terminal again and type adb if adb version and other details are displayed that means path is set properly.
In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:
$.ajax(
'https://foo.bar.com,
{
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: successFunc
}
);
The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:
An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT
Here is a new way to work with SQL views in EF Core: Query Types.
HashSet hs = new HashSet();
hs.addAll(arrayList);
arrayList.clear();
arrayList.addAll(hs);
The web host is not really playing foul. It's not strictly according to the rules - but compared with some some of the amazing inventions intended to prevent spam, its not a particularly bad one.
If you really do want to send mail from '@gmail.com' why not just use the gmail SMTP service? If you can't reconfigure the server where PHP is running, then there are lots of email wrapper tools out there which allow you to specify a custom SMTP relay phpmailer springs to mind.
C.
For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:
# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
Model.where(attributes).first || Model.create(attributes)
end
Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.
(Re)installing the latest JDK (e.g. Oracle's) fixed it for me.
Prior to installing the latest JDK, when I executed the following command in Terminal.app:
keytool -list -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -v
It resulted in:
keytool error: java.io.IOException: Invalid keystore format
java.io.IOException: Invalid keystore format
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:650)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
at java.security.KeyStore.load(KeyStore.java:1445)
at sun.security.tools.keytool.Main.doCommands(Main.java:792)
at sun.security.tools.keytool.Main.run(Main.java:340)
at sun.security.tools.keytool.Main.main(Main.java:333)
But, after installing the latest Oracle JDK and restarting Terminal, executing the following command:
keytool -list -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -v
Results in:
Enter keystore password:
Which indicates that the keytool on path can access the keystore.
You can go to for example C:\Python2.7\Scripts and then run cmd from that path. After that you can run pip2.7 install yourpackage...
That will install package for that version of Python.
Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import
to Tkinter
rather than tkinter
(the difference being the capitalization):
import tkinter as tk
#import Tkinter as tk # for python 2
def create_window():
window = tk.Toplevel(root)
root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()
root.mainloop()
This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.
There is a more simpler way using the mongoose exists function
router.post("/groups/members", async (ctx) => {
const group_name = ctx.request.body.group_membership.group_name;
const member_name = ctx.request.body.group_membership.group_members;
const GroupMembership = GroupModels.GroupsMembers;
console.log("group_name : ", group_name, "member : ", member_name);
try {
if (
(await GroupMembership.exists({
"group_membership.group_name": group_name,
})) === false
) {
console.log("new function");
const newGroupMembership = await GroupMembership.insertMany({
group_membership: [
{ group_name: group_name, group_members: [member_name] },
],
});
await newGroupMembership.save();
} else {
const UpdateGroupMembership = await GroupMembership.updateOne(
{ "group_membership.group_name": group_name },
{ $push: { "group_membership.$.group_members": member_name } },
);
console.log("update function");
await UpdateGroupMembership.save();
}
ctx.response.status = 201;
ctx.response.message = "A member added to group successfully";
} catch (error) {
ctx.body = {
message: "Some validations failed for Group Member Creation",
error: error.message,
};
console.log(error);
ctx.throw(400, error);
}
});
If you want to match starting from the beginning of the word, use:
\b\w{3,}
\b: word boundary
\w: word character
{3,}: three or more times for the word character
you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload
or DOMReady
event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});
The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as
pip3 install hide_code
Visit https://github.com/kirbs-/hide_code/ for more info about this extension.
And also
library(dplyr)
data %>% filter(!v1 %in% c("b", "d", "e"))
or
data %>% filter(v1 != "b" & v1 != "d" & v1 != "e")
or
data %>% filter(v1 != "b", v1 != "d", v1 != "e")
Since the &
operator is implied by the comma.
You have to cd to your master directory and then rails s command will work without problems.
But do not forget bundle-install command when you didn't do it before.
THE ANSWER: The problem was all of the posts for such an issue were related to older kerberos and IIS issues where proxy credentials or AllowNTLM properties were helping. My case was different. What I have discovered after hours of picking worms from the ground was that somewhat IIS installation did not include Negotiate provider under IIS Windows authentication providers list. So I had to add it and move up. My WCF service started to authenticate as expected. Here is the screenshot how it should look if you are using Windows authentication with Anonymous auth OFF.
You need to right click on Windows authentication and choose providers menu item.
Hope this helps to save some time.
I have tried some methods above. However, the experiment by @zbinsd has its limitation. The sparsity of matrix used in the experiment is extremely low while the real sparsity is usually over 90%. In my condition, the sparse is with the shape of (7000, 25000) and the sparsity of 97%. The method 4 is extremely slow and I can't tolerant getting the results. I use the method 6 which is finished in 10 s. Amazingly, I try the method below and it's finished in only 0.247 s.
import sklearn.preprocessing as pp
def cosine_similarities(mat):
col_normed_mat = pp.normalize(mat.tocsc(), axis=0)
return col_normed_mat.T * col_normed_mat
This efficient method is linked by enter link description here
This will do it without painful manipulation or multiple command sequences:
build/%.o: src/%.cpp src/%.o: src/%.cpp %.o: $(CC) -c $< -o $@ build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o $(LD) $^ -o $@
JasperE has explained why "%.o: %.cpp" won't work; this version has one pattern rule (%.o:) with commands and no prereqs, and two pattern rules (build/%.o: and src/%.o:) with prereqs and no commands. (Note that I put in the src/%.o rule to deal with src/ui/flash.o, assuming that wasn't a typo for build/ui/flash.o, so if you don't need it you can leave it out.)
build/test.exe needs build/widgets/apple.o,
build/widgets/apple.o looks like build/%.o, so it needs src/%.cpp (in this case src/widgets/apple.cpp),
build/widgets/apple.o also looks like %.o, so it executes the CC command and uses the prereqs it just found (namely src/widgets/apple.cpp) to build the target (build/widgets/apple.o)
i faced the same problem "Class file has wrong version 52.0, should be 50.0" when running java through ant... all i did was add fork="true" wherever i used the javac task and it worked...
These commands worked for me
sudo npm cache clean --force
sudo npm cache verify
sudo npm i npm@latest -g
For anyone interested in a pure POSIX method:
#!/usr/bin/env sh
string_fetch_last_character() {
length_of_string=${#string}
last_character="$string"
i=1
until [ $i -eq "$length_of_string" ]; do
last_character="${last_character#?}"
i=$(( i + 1 ))
done
printf '%s' "$last_character"
}
string_fetch_last_character "$string"
Write your first unit test
Write a JUnit test -- here's mine:
import org.junit.Assert;
import org.junit.Test;
public class MyFirstTest {
@Test
public void firstTest() {
Assert.assertTrue(true);
}
}
configure project in android studio from eclipse: you have to import eclipse ndk project to android studio without exporting to gradle and it works , also you need to add path of ndk in local.properties ,if shows error then add
sourceSets.main {
jniLibs.srcDir 'src/main/libs'
jni.srcDirs = [] //disable automatic ndk-build callenter code here
}
in build.gradle file then create jni folder and file using terminal and run it will work
Another pure CSS solution
.form{_x000D_
position:relative;_x000D_
display:inline-block;_x000D_
}_x000D_
.form input{_x000D_
margin-top:10px;_x000D_
}_x000D_
.form label{_x000D_
position:absolute;_x000D_
left:0;_x000D_
top:0;_x000D_
opacity:0;_x000D_
transition:all 1s ease;_x000D_
}_x000D_
input:not(:placeholder-shown) + label{_x000D_
top:-10px;_x000D_
opacity:1;_x000D_
}
_x000D_
<div class="form">_x000D_
<input type="text" id="inputFName" placeholder="Firstname">_x000D_
<label class="label" for="inputFName">Firstname</label>_x000D_
</div>_x000D_
<div class="form">_x000D_
<input type="text" id="inputLName" placeholder="Lastname">_x000D_
<label class="label" for="inputLName">Lastname</label>_x000D_
</div>
_x000D_
for speed you can do this
WHERE date(created_at) ='2019-10-21'
A simple call back program. Hope it answers your question.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"
typedef void (*call_back) (S32, S32);
void test_call_back(S32 a, S32 b)
{
printf("In call back function, a:%d \t b:%d \n", a, b);
}
void call_callback_func(call_back back)
{
S32 a = 5;
S32 b = 7;
back(a, b);
}
S32 main(S32 argc, S8 *argv[])
{
S32 ret = SUCCESS;
call_back back;
back = test_call_back;
call_callback_func(back);
return ret;
}
If you can possibly help it, DO NOT USE .scrollHeight.
.scrollHeight does not yield the same kind of results in different browsers in certain circumstances (most prominently while scrolling).
For example:
<div id='outer' style='width:100px; height:350px; overflow-y:hidden;'>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
</div>
If you do
console.log($('#outer').scrollHeight);
you'll get 900px in Chrome, FireFox and Opera. That's great.
But, if you attach a wheelevent / wheel event to #outer, when you scroll it, Chrome will give you a constant value of 900px (correct) but FireFox and Opera will change their values as you scroll down (incorrect).
A very simple way to do this is like so (a bit of a cheat, really). (This example works while dynamically adding content to #outer as well):
$('#outer').css("height", "auto");
var outerContentsHeight = $('#outer').height();
$('#outer').css("height", "350px");
console.log(outerContentsHeight); //Should get 900px in these 3 browsers
The reason I pick these three browsers is because all three can disagree on the value of .scrollHeight in certain circumstances. I ran into this issue making my own scrollpanes. Hope this helps someone.
If you need minimal value for particular column
min(data[,2])
Note: R considers NA
both the minimum and maximum value so if you have NA's in your column, they return: NA
. To remedy, use:
min(data[,2], na.rm=T)
On the contrary, you should always prefer stack allocations, to the extent that as a rule of thumb, you should never have new/delete in your user code.
As you say, when the variable is declared on the stack, its destructor is automatically called when it goes out of scope, which is your main tool for tracking resource lifetime and avoiding leaks.
So in general, every time you need to allocate a resource, whether it's memory (by calling new), file handles, sockets or anything else, wrap it in a class where the constructor acquires the resource, and the destructor releases it. Then you can create an object of that type on the stack, and you're guaranteed that your resource gets freed when it goes out of scope. That way you don't have to track your new/delete pairs everywhere to ensure you avoid memory leaks.
The most common name for this idiom is RAII
Also look into smart pointer classes which are used to wrap the resulting pointers on the rare cases when you do have to allocate something with new outside a dedicated RAII object. You instead pass the pointer to a smart pointer, which then tracks its lifetime, for example by reference counting, and calls the destructor when the last reference goes out of scope. The standard library has std::unique_ptr
for simple scope-based management, and std::shared_ptr
which does reference counting to implement shared ownership.
Many tutorials demonstrate object instantiation using a snippet such as ...
So what you've discovered is that most tutorials suck. ;) Most tutorials teach you lousy C++ practices, including calling new/delete to create variables when it's not necessary, and giving you a hard time tracking lifetime of your allocations.
<form id="myform">
<input type="textbox" id="field"/>
<input type="button" value="submit">
</form>
<script>
$(function () {
$("#field").keyup(function (event) {
if (event.which === 13) {
document.myform.submit();
}
}
});
</script>
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
A stateful app is one that stores information about what has happened or changed since it started running. Any public info about what "mode" it is in, or how many records is has processed, or whatever, makes it stateful.
Stateless apps don't expose any of that information. They give the same response to the same request, function or method call, every time. HTTP is stateless in its raw form - if you do a GET to a particular URL, you get (theoretically) the same response every time. The exception of course is when we start adding statefulness on top, e.g. with ASP.NET web apps :) But if you think of a static website with only HTML files and images, you'll know what I mean.
Another to answer this question available here answered by @nilesh https://stackoverflow.com/a/19934852/2079692
public void setAttributeValue(WebElement elem, String value){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
elem, "value", value
);
}
this takes advantage of selenium findElementBy function where xpath can be used also.
ELXAN@DB1> create table cedvel(id integer,ad varchar2(15)); Table created. ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id); Table altered. ELXAN@DB1> create sequence test_seq start with 1 increment by 1; Sequence created. ELXAN@DB1> create or replace trigger ad_insert before insert on cedvel REFERENCING NEW AS NEW OLD AS OLD for each row begin select test_seq.nextval into :new.id from dual; end; / 2 3 4 5 6 7 8 Trigger created. ELXAN@DB1> insert into cedvel (ad) values ('nese'); 1 row created.
Awesome answers I found here and I also tried this return statement see StatusCode(whatever code you wish)
and it worked!!!
return Ok(new {
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo,
username = user.FullName,
StatusCode = StatusCode(200)
});
You can do the following:
TimeSpan duration = b - a;
There's plenty of built in methods in the timespan class to do what you need, i.e.
duration.TotalSeconds
duration.TotalMinutes
More info can be found here.
Add this in manifest.
<service
android:name=".YourServiceName"
android:enabled="true"
android:exported="false" />
Add a service class.
public class YourServiceName extends Service {
@Override
public void onCreate() {
super.onCreate();
// Timer task makes your service will repeat after every 20 Sec.
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
// Add your code here.
}
});
}
};
//Starts after 20 sec and will repeat on every 20 sec of time interval.
timer.schedule(doAsynchronousTask, 20000,20000); // 20 sec timer
(enter your own time)
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO do something useful
return START_STICKY;
}
}
After loading the SSH private key in Git Extensions, this issue gets resolved.
You can do like this
echo date('Y-m-d H:i:s', strtotime('4 minute'));
echo date('Y-m-d H:i:s', strtotime('6 hour'));
echo date('Y-m-d H:i:s', strtotime('2 day'));
This..
(
(meta_key = 'lat' AND meta_value >= '60.23457047672217')
OR
(meta_key = 'lat' AND meta_value <= '60.23457047672217')
)
is the same as
(
(meta_key = 'lat')
)
Adding it all together (the same applies to the long
filter) you have this impossible WHERE clause which will give no rows because meta_key
cannot be 2 values in one row
WHERE
(meta_key = 'lat' AND meta_key = 'long' )
You need to review your operators to make sure you get the correct logic
Just remove the border and add a background image in css
Example:
$("#form").on('submit', function() {_x000D_
alert($("#submit-icon").val());_x000D_
});
_x000D_
#submit-icon {_x000D_
background-image: url("https://pixabay.com/static/uploads/photo/2016/10/18/21/22/california-1751455__340.jpg"); /* Change url to wanted image */_x000D_
background-size: cover;_x000D_
border: none;_x000D_
width: 32px;_x000D_
height: 32px;_x000D_
cursor: pointer;_x000D_
color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="form">_x000D_
<input type="submit" id="submit-icon" value="test">_x000D_
</form>
_x000D_
You can use property dangerouslySetInnerHTML
, like this
const Component = React.createClass({_x000D_
iframe: function () {_x000D_
return {_x000D_
__html: this.props.iframe_x000D_
}_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
<Component iframe={iframe} />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe>
tag and pass it to new <iframe>
tag, like that
/**_x000D_
* getAttrs_x000D_
* returns all attributes from TAG string_x000D_
* @return Object_x000D_
*/_x000D_
const getAttrs = (iframeTag) => {_x000D_
var doc = document.createElement('div');_x000D_
doc.innerHTML = iframeTag;_x000D_
_x000D_
const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
return [].slice_x000D_
.call(iframe.attributes)_x000D_
.reduce((attrs, element) => {_x000D_
attrs[element.name] = element.value;_x000D_
return attrs;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<iframe {...getAttrs(this.props.iframe) } />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
<Component iframe={iframe} />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
The correct way to close the socket so you can re-open is:
tcpClient.Client.Disconnect(true);
The Boolean parameter indicates if you want to reuse the socket:
I resolved this issue by excluding byte-buddy dependency from springfox
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
I've always solved this using lower:
SELECT * FROM trees WHERE LOWER( trees.title ) LIKE '%elm%'
The following selects all descendant elements and disables them:
$("#dcacl").find("*").prop("disabled", true);
But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:
$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);
To re-enable you just set "disabled" to false.
I want to Disable them at loading the page and then by a click i can enable them
OK, so put the above code in a document ready handler, and setup an appropriate click handler:
$(document).ready(function() {
var $dcac1kids = $("#dcac1").find(":input");
$dcac1kids.prop("disabled",true);
// not sure what you want to click on to re-enable
$("selector for whatever you want to click").one("click",function() {
$dcac1kids.prop("disabled",false);
}
}
I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one()
since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one()
to .click()
if appropriate.
Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .
Copy the file to C:\Python27\Scripts
Run cmd from the above location and type
pip install numpy-1.9.2+mkl-cp27-none-win32.whl
You will hopefully get the below output:
Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2
Hope that works for you.
EDIT 1
Adding @oneleggedmule 's suggestion:
You can also run the following command in the cmd:
pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl
Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.
See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")
Make sure you first check for null and empty and ten converts existing string to upper. Use S.O.P if want to see outputs otherwise boolean like Rabiz did.
public static void main(String[] args)
{
System.out.println("Enter name");
Scanner kb = new Scanner (System.in);
String text = kb.next();
if ( null == text || text.isEmpty())
{
System.out.println("Text empty");
}
else if (text.charAt(0) == (text.toUpperCase().charAt(0)))
{
System.out.println("First letter in word "+ text + " is upper case");
}
}
You can use windows Powershell to execute a query and output it to a text file
Invoke-Sqlcmd -Query "Select * from database" -ServerInstance "Servername\SQL2008" -Database "DbName" > c:\Users\outputFileName.txt
This does not do what you expect:
if var is 'stringone' or 'stringtwo':
dosomething()
It is the same as:
if (var is 'stringone') or 'stringtwo':
dosomething()
Which is always true, since 'stringtwo'
is considered a "true" value.
There are two alternatives:
if var in ('stringone', 'stringtwo'):
dosomething()
Or you can write separate equality tests,
if var == 'stringone' or var == 'stringtwo':
dosomething()
Don't use is
, because is
compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is
unless you really want object identity.
>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True # but could be False
I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
You must set your query base to the DN of the user in question, then set your filter to the DN of the group you're wondering if they're a member of. To see if jdoe is a member of the office group then your query will look something like this:
ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host '(memberof=cn=officegroup,dc=example,dc=local)'
If you want to see ALL the groups he's a member of, just request only the 'memberof' attribute in your search, like this:
ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host **memberof**
Here's an example of using text-overflow:
.text {_x000D_
display: block;_x000D_
width: 100px;_x000D_
overflow: hidden;_x000D_
white-space: nowrap;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<span class="text">Hello world this is a long sentence</span>
_x000D_
Try the Python scp module for Paramiko. It's very easy to use. See the following example:
import paramiko
from scp import SCPClient
def createSSHClient(server, port, user, password):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(server, port, user, password)
return client
ssh = createSSHClient(server, port, user, password)
scp = SCPClient(ssh.get_transport())
Then call scp.get()
or scp.put()
to do SCP operations.
I'm not sure why you think the documentation is vague.
It simply goes through all the parameters one by one, and returns the first that is NOT NULL
.
COALESCE(NULL, NULL, NULL, 1, 2, 3)
=> 1
COALESCE(1, 2, 3, 4, 5, NULL)
=> 1
COALESCE(NULL, NULL, NULL, 3, 2, NULL)
=> 3
COALESCE(6, 5, 4, 3, 2, NULL)
=> 6
COALESCE(NULL, NULL, NULL, NULL, NULL, NULL)
=> NULL
It accepts pretty much any number of parameters, but they should be the same data-type. (If they're not the same data-type, they get implicitly cast to an appropriate data-type using data-type order of precedence.)
It's like ISNULL()
but for multiple parameters, rather than just two.
It's also ANSI-SQL
, where-as ISNULL()
isn't.
While not directly related to Eclipse:
If you're running Windows 7 (and presumably Windows Vista), be sure to disable the file indexing of your workspace folder if your stuff is is in the default place - your home folder. Windows by default indexes everything in you home folder, and it's normally just a waste for your workspace. (Right click the workspace folder in explorer , Properties -> Advanced.)
The accepted answer previously contained new Buffer()
, which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).
The Buffer
constructor is deprecated according to the documentation.
Here is an example of a vulnerability that can result from using it in the ws library.
The code snippets should read:
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
After this answer was written, it has been updated and now matches this.