This will get the version of the GTK+ libraries for GTK+ 2 and GTK+ 3.
dpkg -l | egrep "libgtk(2.0-0|-3-0)"
As major versions are parallel installable, you may have both on your system, which is my case, so the above command returns this on my Ubuntu Trusty system:
ii libgtk-3-0:amd64 3.10.8-0ubuntu1.6 amd64 GTK+ graphical user interface library
ii libgtk2.0-0:amd64 2.24.23-0ubuntu1.4 amd64 GTK+ graphical user interface library
This means I have GTK+ 2.24.23 and 3.10.8 installed.
If what you want is the version of the development files, use pkg-config --modversion gtk+-3.0
for example for GTK+ 3. To extend that to the different major versions of GTK+, with some sed magic, this gives:
pkg-config --list-all | sed -ne 's/\(gtk+-[0-9]*.0\).*/\1/p' | xargs pkg-config --modversion
I didn't see an answer that's clean and suitable for production-ready software, so here it goes:
/*
* Get current error_reporting value,
* so that we don't lose preferences set in php.ini and .htaccess
* and accidently reenable message types disabled in those.
*
* If you want to disable e.g. E_STRICT on a global level,
* use php.ini (or .htaccess for folder-level)
*/
$old_error_reporting = error_reporting();
/*
* Disable E_STRICT on top of current error_reporting.
*
* Note: do NOT use ^ for disabling error message types,
* as ^ will re-ENABLE the message type if it happens to be disabled already!
*/
error_reporting($old_error_reporting & ~E_STRICT);
// code that should not emit E_STRICT messages goes here
/*
* Optional, depending on if/what code comes after.
* Restore old settings.
*/
error_reporting($old_error_reporting);
You most certainly have a databases tab in sql developer (all versions I've used in the past have this). Maybe check again? Perhaps, you're looking in the wrong location.
On a mac, the preferences is under "Oracle SQL Developer" (top left) -> Preferences -> Database -> Advanced -> section called Tnsnames Directory is where you specify the file.
On windows (going from memory so might have to search if this isn't correct) Tools -> Preferences -> Database -> Advanced -> section called Tnsnames Directory is where you specify the file.
See this image
There's more then one way to do this with DateTime which was introduced in PHP 5.2. Unlike using strtotime()
this will account for daylight savings time and leap year.
$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.3
$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.4
echo (new DateTime('2013-01-29'))->add(new DateInterval('P1D'))->format('Y-m-d H:i:s');
// Available in PHP 5.5
$start = new DateTimeImmutable('2013-01-29');
$datetime = $start->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
make change in changes in /opt/lampp/phpmyadmin/config.inc.php
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* phpMyAdmin sample configuration, you can use it as base for
* manual configuration. For easier setup you can use setup/
*
* All directives are explained in documentation in the doc/ folder
* or at <http://docs.phpmyadmin.net/>.
*
* @package PhpMyAdmin
*/
/**
* This is needed for cookie based authentication to encrypt password in
* cookie
*/
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */
/**
* Servers configuration
*/
$i = 0;
/**
* First server
*/
$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
/* Server parameters */
//$cfg['Servers'][$i]['host'] = 'localhost';
//$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
/**
* phpMyAdmin configuration storage settings.
*/
/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controlport'] = '';
$cfg['Servers'][1]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][1]['controluser'] = 'pma';
$cfg['Servers'][1]['controlpass'] = '';
$cfg['Servers'][1]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][1]['relation'] = 'pma_relation';
$cfg['Servers'][1]['userconfig'] = 'pma_userconfig';
$cfg['Servers'][1]['table_info'] = 'pma_table_info';
$cfg['Servers'][1]['column_info'] = 'pma_column_info';
$cfg['Servers'][1]['history'] = 'pma_history';
$cfg['Servers'][1]['recent'] = 'pma_recent';
$cfg['Servers'][1]['table_uiprefs'] = 'pma_table_uiprefs';
$cfg['Servers'][1]['tracking'] = 'pma_tracking';
$cfg['Servers'][1]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][1]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][1]['designer_coords'] = 'pma_designer_coords';
// $cfg['Servers'][$i]['favorite'] = 'pma__favorite';
// $cfg['Servers'][$i]['users'] = 'pma__users';
// $cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
// $cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
// $cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
// $cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
// $cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
// $cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
/* Contrib / Swekey authentication */
// $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';
/**
* End of servers configuration
*/
/**
* Directories for saving/loading files from server
*/
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
/**
* Whether to display icons or text or both icons and text in table row
* action segment. Value can be either of 'icons', 'text' or 'both'.
* default = 'both'
*/
//$cfg['RowActionType'] = 'icons';
/**
* Defines whether a user should be displayed a "show all (records)"
* button in browse mode or not.
* default = false
*/
//$cfg['ShowAll'] = true;
/**
* Number of rows displayed when browsing a result set. If the result
* set contains more rows, "Previous" and "Next".
* Possible values: 25, 50, 100, 250, 500
* default = 25
*/
//$cfg['MaxRows'] = 50;
/**
* Disallow editing of binary fields
* valid values are:
* false allow editing
* 'blob' allow editing except for BLOB fields
* 'noblob' disallow editing except for BLOB fields
* 'all' disallow editing
* default = 'blob'
*/
//$cfg['ProtectBinary'] = false;
/**
* Default language to use, if not browser-defined or user-defined
* (you find all languages in the locale folder)
* uncomment the desired line:
* default = 'en'
*/
//$cfg['DefaultLang'] = 'en';
//$cfg['DefaultLang'] = 'de';
/**
* How many columns should be used for table display of a database?
* (a value larger than 1 results in some information being hidden)
* default = 1
*/
//$cfg['PropertiesNumColumns'] = 2;
/**
* Set to true if you want DB-based query history.If false, this utilizes
* JS-routines to display query history (lost by window close)
*
* This requires configuration storage enabled, see above.
* default = false
*/
//$cfg['QueryHistoryDB'] = true;
/**
* When using DB-based query history, how many entries should be kept?
* default = 25
*/
//$cfg['QueryHistoryMax'] = 100;
/**
* Whether or not to query the user before sending the error report to
* the phpMyAdmin team when a JavaScript error occurs
*
* Available options
* ('ask' | 'always' | 'never')
* default = 'ask'
*/
//$cfg['SendErrorReports'] = 'always';
/**
* You can find more configuration options in the documentation
* in the doc/ folder or at <http://docs.phpmyadmin.net/>.
*/
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
CREATE DEFINER=`yourfunctionname`@`%` FUNCTION `money`(
`betrag` DECIMAL(10,2)
)
RETURNS varchar(128) CHARSET latin1
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
return(
select replace(format(cast(betrag as char),2),',',"'") as betrag
)
will creating a MySql-Function with this Code:
select replace(format(cast(amount as char),2),',',"'") as amount_formated
To produce a list of methods put the name of the method in a list without the usual parenthesis. Remove the name and attach the parenthesis and that calls the method.
def methodA():
print("@ MethodA")
def methodB():
print("@ methodB")
a = []
a.append(methodA)
a.append(methodB)
for item in a:
item()
For finding objects which are meaningfully equal, you need to override equals
and hashcode
methods for the class. You can find a good tutorial here.
http://www.thejavageek.com/2013/06/28/significance-of-equals-and-hashcode/
I am not sure if you are trying to create a remote branch from a local branch or vice versa, so I've outlined both scenarios as well as provided information on merging the remote and local branches.
Creating a remote called "github":
git remote add github git://github.com/jdoe/coolapp.git
git fetch github
List all remote branches:
git branch -r
github/gh-pages
github/master
github/next
github/pu
Create a new local branch (test) from a github's remote branch (pu):
git branch test github/pu
git checkout test
Merge changes from github's remote branch (pu) with local branch (test):
git fetch github
git checkout test
git merge github/pu
Update github's remote branch (pu) from a local branch (test):
git push github test:pu
Creating a new branch on a remote uses the same syntax as updating a remote branch. For example, create new remote branch (beta) on github from local branch (test):
git push github test:beta
Delete remote branch (pu) from github:
git push github :pu
save the file on your disk and then use the following as URL:
file://your_path/your_file.wsdl
I have edited one of the previous post. Now, it is way more simple and it works perfectly.
<input style="position: absolute;left:-9999px;" type="radio" name="emotion" id="sad" />
<label for="sad"><img src="red.gif" style="display: inline-block;cursor: pointer;padding: 3px;" alt="I'm sad" /></label>
<input style="position: absolute;left:-9999px;" type="radio" name="emotion" id="happy" />
<label for="happy"><img src="blue.gif" style="display: inline-block;cursor: pointer;padding: 3px;" alt="I'm happy" /></label>
str="abcdef"
str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">
Hope it helps. :)
I have found a way to resize the buffer size without influencing the window size. It works thanks to a flaw in how batch works but it gets the job done.
mode 648 78 >nul 2>nul
How does it work? There is a syntax error in this command, it should be "mode 648, 78". Because of how batch works, the buffer size will first be resized to 648 and then the window resize will come but it will never finish, because of the syntax error. Voila, buffer size is adjusted and the window size stays the same. This produces an ugly error so to get rid of it just add the ">nul 2>nul" and you're done.
Yet another way:
:'<,'>g/^/norm I//
/^/
is just a dummy pattern to match every line. norm
lets you run the normal-mode commands that follow. I//
says to enter insert-mode while jumping the cursor to the beginning of the line, then insert the following text (two slashes).
:g
is often handy for doing something complex on multiple lines, where you may want to jump between multiple modes, delete or add lines, move the cursor around, run a bunch of macros, etc. And you can tell it to operate only on lines that match a pattern.
/* ENDLESS ROTATE */_x000D_
.rotate{_x000D_
animation: rotate 1.5s linear infinite; _x000D_
}_x000D_
@keyframes rotate{_x000D_
to{ transform: rotate(360deg); }_x000D_
}_x000D_
_x000D_
_x000D_
/* SPINNER JUST FOR DEMO */_x000D_
.spinner{_x000D_
display:inline-block; width: 50px; height: 50px;_x000D_
border-radius: 50%;_x000D_
box-shadow: inset -2px 0 0 2px #0bf;_x000D_
}
_x000D_
<span class="spinner rotate"></span>
_x000D_
There is already a Twig extension that lets you call PHP functions form your Twig templates like:
Hi, I am unique: {{ uniqid() }}.
And {{ floor(7.7) }} is floor of 7.7.
See official extension repository.
Just iterate and add:
for(Map.Entry e : a.entrySet())
if(!b.containsKey(e.getKey())
b.put(e.getKey(), e.getValue());
Edit to add:
If you can make changes to a, you can also do:
a.putAll(b)
and a will have exactly what you need. (all the entries in b
and all the entries in a
that aren't in b
)
For completeness, Pandas also has a period_range
function for timestamps that are out of bounds:
import pandas as pd
pd.period_range(start='1/1/1626', end='1/08/1627', freq='D')
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.
require_once('../web/a.php');
If this is not working for anyone, following is the good Idea to include file anywhere in the project.
require_once dirname(__FILE__)."/../../includes/enter.php";
This code will get the file from 2 directory outside of the current directory.
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
Try sgrep. It's not clear exactly what you are trying to do, but I surely would not attempt writing an XML parser in bash.
var fs = require("fs");
function readFileLineByLine(filename, processline) {
var stream = fs.createReadStream(filename);
var s = "";
stream.on("data", function(data) {
s += data.toString('utf8');
var lines = s.split("\n");
for (var i = 0; i < lines.length - 1; i++)
processline(lines[i]);
s = lines[lines.length - 1];
});
stream.on("end",function() {
var lines = s.split("\n");
for (var i = 0; i < lines.length; i++)
processline(lines[i]);
});
}
var linenumber = 0;
readFileLineByLine(filename, function(line) {
console.log(++linenumber + " -- " + line);
});
To merge a local directory into a directory within an image, do this. It will not delete files already present within the image. It will only add files that are present locally, overwriting the files in the image if a file of the same name already exists.
COPY ./files/. /files/
You can delete documents from type with following query:
POST /index/type/_delete_by_query
{
"query" : {
"match_all" : {}
}
}
I tested this query in Kibana and Elastic 5.5.2
String input = "0101";
BigInteger x = new BigInteger ( input , 2 );
String output = x.toString(2);
Another way to do it is to start a local HTTP server on your directory. On Ubuntu and MacOs with Python installed, it's a one-liner.
Go to the directory containing your web files, and :
python -m SimpleHTTPServer
Then connect to http://localhost:8000/index.html with any web browser to test your page.
There is a case I often use. I have a IdUtil
class with static methods to work with objects implementing a very simple Identifiable
interface:
public interface Identifiable<K> {
K getId();
}
public abstract class IdUtil {
public static <T extends Enum<T> & Identifiable<S>, S> T get(Class<T> type, S id) {
for (T t : type.getEnumConstants()) {
if (Util.equals(t.getId(), id)) {
return t;
}
}
return null;
}
public static <T extends Enum<T> & Identifiable<S>, S extends Comparable<? super S>> List<T> getLower(T en) {
List<T> list = new ArrayList<>();
for (T t : en.getDeclaringClass().getEnumConstants()) {
if (t.getId().compareTo(en.getId()) < 0) {
list.add(t);
}
}
return list;
}
}
If I create an Identifiable
enum
:
public enum MyEnum implements Identifiable<Integer> {
FIRST(1), SECOND(2);
private int id;
private MyEnum(int id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Then I can get it by its id
this way:
MyEnum e = IdUtil.get(MyEnum.class, 1);
I use to throw an exception in the base class.
protected abstractMethod() {
throw new Error("abstractMethod not implemented");
}
Then you have to implement in the sub-class. The cons is that there is no build error, but run-time. The pros is that you can call this method from the super class, assuming that it will work :)
HTH!
Milton
I have Alt+←/→ working: open Preferences » Settings » Keyboard, set the entry for option cursor left to send string to shell: \033b, and set option cursor right to send string to shell: \033f. You can also use this for other Control key combinations.
public static void Main(string[] args)
{
string json = @" {
""children"": [
{
""url"": ""foo.pdf"",
""expanded"": false,
""label"": ""E14288-Passive-40085-2014_09_26.pdf"",
""last_modified"": ""2014-09-28T11:19:49.000Z"",
""type"": 1,
""size"": 60929
}
]
}";
var result = JsonConvert.DeserializeObject<ChildrenRootObject>(json);
DataTable tbl = DataTableFromObject(result.children);
}
public static DataTable DataTableFromObject<T>(IList<T> list)
{
DataTable tbl = new DataTable();
tbl.TableName = typeof(T).Name;
var propertyInfos = typeof(T).GetProperties();
List<string> columnNames = new List<string>();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
tbl.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
columnNames.Add(propertyInfo.Name);
}
foreach(var item in list)
{
DataRow row = tbl.NewRow();
foreach (var name in columnNames)
{
row[name] = item.GetType().GetProperty(name).GetValue(item, null);
}
tbl.Rows.Add(row);
}
return tbl;
}
public class Child
{
public string url { get; set; }
public bool expanded { get; set; }
public string label { get; set; }
public DateTime last_modified { get; set; }
public int type { get; set; }
public int size { get; set; }
}
public class ChildrenRootObject
{
public List<Child> children { get; set; }
}
Good point that view is appeared if it's already in window hierarchy stack. thus we can extend our classes for this functionality.
extension UIViewController {
var isViewAppeared: Bool { viewIfLoaded?.isAppeared == true }
}
extension UIView {
var isAppeared: Bool { window != nil }
}
There was recently a node module that was made that solves this problem so you don't have to create another component.
https://github.com/Ajackster/react-native-global-props
https://www.npmjs.com/package/react-native-global-props
The documentation states that in your highest order component, import the setCustomText
function like so.
import { setCustomText } from 'react-native-global-props';
Then, create the custom styling/props you want for the react-native Text
component. In your case, you'd like fontFamily to work on every Text
component.
const customTextProps = {
style: {
fontFamily: yourFont
}
}
Call the setCustomText
function and pass your props/styles into the function.
setCustomText(customTextProps);
And then all react-native Text
components will have your declared fontFamily along with any other props/styles you provide.
In my case I had all of the proper references in my project. I found that by building the solution the nuget packages were automatically restored.
I think I've figured it out:
a = [3, 2, 4, 6, 3, 8]
a.delete(3)
#=> 3
a
#=> [2, 4, 6, 8]
following Anton's solution, come up with this ViewHolder
which holds/handles/delegates different type of layouts.
But not sure if the replacing new layout would work when the recycling view's ViewHolder
is not type of the data roll in.
So basically,
onCreateViewHolder(ViewGroup parent, int viewType)
is only called when new view layout is needed;
getItemViewType(int position)
will be called for the viewType
;
onBindViewHolder(ViewHolder holder, int position)
is always called when recycling the view (new data is brought in and try to display with that ViewHolder
).
So when onBindViewHolder
is called it needs to put in the right view layout and update the ViewHolder
.
Is the way correct to replacing the view layout for that ViewHolder
to be brought in, or any problem?
Appreciate any comment!
public int getItemViewType(int position) {
TypedData data = mDataSource.get(position);
return data.type;
}
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
return ViewHolder.makeViewHolder(parent, viewType);
}
public void onBindViewHolder(ViewHolder holder,
int position) {
TypedData data = mDataSource.get(position);
holder.updateData(data);
}
///
public static class ViewHolder extends
RecyclerView.ViewHolder {
ViewGroup mParentViewGroup;
View mCurrentViewThisViewHolderIsFor;
int mDataType;
public TypeOneViewHolder mTypeOneViewHolder;
public TypeTwoViewHolder mTypeTwoViewHolder;
static ViewHolder makeViewHolder(ViewGroup vwGrp,
int dataType) {
View v = getLayoutView(vwGrp, dataType);
return new ViewHolder(vwGrp, v, viewType);
}
static View getLayoutView(ViewGroup vwGrp,
int dataType) {
int layoutId = getLayoutId(dataType);
return LayoutInflater.from(vwGrp.getContext())
.inflate(layoutId, null);
}
static int getLayoutId(int dataType) {
if (dataType == TYPE_ONE) {
return R.layout.type_one_layout;
} else if (dataType == TYPE_TWO) {
return R.layout.type_two_layout;
}
}
public ViewHolder(ViewGroup vwGrp, View v,
int dataType) {
super(v);
mDataType = dataType;
mParentViewGroup = vwGrp;
mCurrentViewThisViewHolderIsFor = v;
if (data.type == TYPE_ONE) {
mTypeOneViewHolder = new TypeOneViewHolder(v);
} else if (data.type == TYPE_TWO) {
mTypeTwoViewHolder = new TypeTwoViewHolder(v);
}
}
public void updateData(TypeData data) {
mDataType = data.type;
if (data.type == TYPE_ONE) {
mTypeTwoViewHolder = null;
if (mTypeOneViewHolder == null) {
View newView = getLayoutView(mParentViewGroup,
data.type);
/**
* how to replace new view with
the view in the parent
view container ???
*/
replaceView(mCurrentViewThisViewHolderIsFor,
newView);
mCurrentViewThisViewHolderIsFor = newView;
mTypeOneViewHolder =
new TypeOneViewHolder(newView);
}
mTypeOneViewHolder.updateDataTypeOne(data);
} else if (data.type == TYPE_TWO){
mTypeOneViewHolder = null;
if (mTypeTwoViewHolder == null) {
View newView = getLayoutView(mParentViewGroup,
data.type);
/**
* how to replace new view with
the view in the parent view
container ???
*/
replaceView(mCurrentViewThisViewHolderIsFor,
newView);
mCurrentViewThisViewHolderIsFor = newView;
mTypeTwoViewHolder =
new TypeTwoViewHolder(newView);
}
mTypeTwoViewHolder.updateDataTypeOne(data);
}
}
}
public static void replaceView(View currentView,
View newView) {
ViewGroup parent = (ViewGroup)currentView.getParent();
if(parent == null) {
return;
}
final int index = parent.indexOfChild(currentView);
parent.removeView(currentView);
parent.addView(newView, index);
}
Edit: ViewHolder has member mItemViewType to hold the view
Edit: looks like in onBindViewHolder(ViewHolder holder, int position) the ViewHolder passed in has been picked up (or created) by looked at getItemViewType(int position) to make sure it is a match, so may not need to worry there that ViewHolder's type does not match the data[position]'s type. Does anyone knows more how the ViewHolder in the onBindViewHolder() is picked up?
Edit: Looks like The recycle ViewHolder
is picked by type, so no warrior there.
Edit: http://wiresareobsolete.com/2014/09/building-a-recyclerview-layoutmanager-part-1/ answers this question.
It gets the recycle ViewHolder
like:
holder = getRecycledViewPool().getRecycledView(mAdapter.getItemViewType(offsetPosition));
or create new one if not find recycle ViewHolder
of right type.
public ViewHolder getRecycledView(int viewType) {
final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
if (scrapHeap != null && !scrapHeap.isEmpty()) {
final int index = scrapHeap.size() - 1;
final ViewHolder scrap = scrapHeap.get(index);
scrapHeap.remove(index);
return scrap;
}
return null;
}
View getViewForPosition(int position, boolean dryRun) {
......
if (holder == null) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount());
}
final int type = mAdapter.getItemViewType(offsetPosition);
// 2) Find from scrap via stable ids, if exists
if (mAdapter.hasStableIds()) {
holder = getScrapViewForId(mAdapter.getItemId(offsetPosition), type, dryRun);
if (holder != null) {
// update position
holder.mPosition = offsetPosition;
fromScrap = true;
}
}
if (holder == null && mViewCacheExtension != null) {
// We are NOT sending the offsetPosition because LayoutManager does not
// know it.
final View view = mViewCacheExtension
.getViewForPositionAndType(this, position, type);
if (view != null) {
holder = getChildViewHolder(view);
if (holder == null) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view which does not have a ViewHolder");
} else if (holder.shouldIgnore()) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view that is ignored. You must call stopIgnoring before"
+ " returning this view.");
}
}
}
if (holder == null) { // fallback to recycler
// try recycler.
// Head to the shared pool.
if (DEBUG) {
Log.d(TAG, "getViewForPosition(" + position + ") fetching from shared "
+ "pool");
}
holder = getRecycledViewPool()
.getRecycledView(mAdapter.getItemViewType(offsetPosition));
if (holder != null) {
holder.resetInternal();
if (FORCE_INVALIDATE_DISPLAY_LIST) {
invalidateDisplayListInt(holder);
}
}
}
if (holder == null) {
holder = mAdapter.createViewHolder(RecyclerView.this,
mAdapter.getItemViewType(offsetPosition));
if (DEBUG) {
Log.d(TAG, "getViewForPosition created new ViewHolder");
}
}
}
boolean bound = false;
if (mState.isPreLayout() && holder.isBound()) {
// do not update unless we absolutely have to.
holder.mPreLayoutPosition = position;
} else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {
if (DEBUG && holder.isRemoved()) {
throw new IllegalStateException("Removed holder should be bound and it should"
+ " come here only in pre-layout. Holder: " + holder);
}
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
mAdapter.bindViewHolder(holder, offsetPosition);
attachAccessibilityDelegate(holder.itemView);
bound = true;
if (mState.isPreLayout()) {
holder.mPreLayoutPosition = position;
}
}
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
final LayoutParams rvLayoutParams;
if (lp == null) {
rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
holder.itemView.setLayoutParams(rvLayoutParams);
} else if (!checkLayoutParams(lp)) {
rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
holder.itemView.setLayoutParams(rvLayoutParams);
} else {
rvLayoutParams = (LayoutParams) lp;
}
rvLayoutParams.mViewHolder = holder;
rvLayoutParams.mPendingInvalidate = fromScrap && bound;
return holder.itemView;
}
I use a utility that I wrote in C called autotab
. It analyzes the first few thousand lines of a file which you load and determines values for the Vim parameters shiftwidth
, tabstop
and expandtab
.
This is compiled using, for instance, gcc -O autotab.c -o autotab
. Instructions for integrating with Vim are in the comment header at the top.
Autotab is fairly clever, but can get confused from time to time, in particular by that have been inconsistently maintained using different indentation styles.
If a file evidently uses tabs, or a combination of tabs and spaces, for indentation, Autotab will figure out what tab size is being used by considering factors like alignment of internal elements across successive lines, such as comments.
It works for a variety of programming languages, and is forgiving for "out of band" elements which do not obey indentation increments, such as C preprocessing directives, C statement labels, not to mention the obvious blank lines.
This did the trick for me
public static void main(String[] args) {
String text = "abcdefghijklmnopqrstuvwxyz";
for (int i = (text.length() - 1); i >= 0; i--) {
System.out.print(text.charAt(i));
}
}
<?php if (date("H") < "12" && date("H")>"6") { ?>
src="<?php bloginfo('template_url'); ?>/images/img/morning.gif"
<?php } elseif (date("H") > "12" && date("H")<"17") { ?>
src="<?php bloginfo('template_url'); ?>/images/img/noon.gif"
<?php } elseif (date("H") > "17" && date("H")<"21") { ?>
src="<?php bloginfo('template_url'); ?>/images/img/evening.gif"
<?php } elseif (date("H") > "21" && date("H")<"24") { ?>
src="<?php bloginfo('template_url'); ?>/images/img/night.gif"
<?php }else { ?>
src="<?php bloginfo('template_url'); ?>/images/img/mid_night.gif"
<?php } ?>
You can get column type of DataTable with DataType attribute of datatable column like below:
var type = dt.Columns[0].DataType
dt : DataTable object.
0 : DataTable column index.
Hope It Helps
Ty :)
val() returns the value of the <select>
element, i.e. the value
attribute of the selected <option>
element.
Since you actually want the inner text of the selected <option>
element, you should match that element and use text() instead:
var nationality = $("#dancerCountry option:selected").text();
See This question
Your logic in reading
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
is slightly flawed.
If is
applies then ==
will be True, but it does NOT apply in reverse. ==
may yield True while is
yields False.
Be carefull that the page does not contain any empty component which has "required" attribute as "true" before your selectOneMenu component running.
If you use a component such as
<p:inputText label="Nm:" id="id_name" value="#{ myHelper.name}" required="true"/>
then,
<p:selectOneMenu .....></p:selectOneMenu>
and forget to fill the required component, ajax listener of selectoneMenu cannot be executed.
"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.
Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).
Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.
You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:
In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.
All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.
There is no mistake in your bash script. But you are executing it with sh which has a less extensive syntax ;)
So, run bash ./choose.sh
instead :)
I think one reason is that some people feel that the most important part of whether a language will be accepted is how good the language is. Unfortunately, things are rarely so simple. For example, I would argue that the biggest factor behind Python's acceptance isn't the language itself (although that is pretty important). The biggest reason why Python is so popular is its huge standard library and the even bigger community of 3rd party libraries.
Languages like Clojure or F# may be the exception to the rule on this considering that they're built upon the JVM/CLR. As a result, I don't have an answer for them.
protected void Page_Load(object sender, EventArgs e)
{
// prevent user from making operation twice
btnSave.Attributes.Add("onclick",
"this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");
// ... etc.
}
Try this:
<ul id="luke_should_be_here">
{{people.1.name}}
</ul>
If you don't have information_schema:
mysql -e "show full processlist" | cut -f1 | sed -e 's/^/kill /' | sed -e 's/$/;/' ; > /tmp/kill.txt
mysql> . /tmp/kill.txt
Suggest
>>> print vars.__doc__
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
In otherwords, it essentially just wraps __dict__
By far the best option nowadays would be using a maven container as a builder tool. A mvn.sh
script like this would be enough:
#!/bin/bash
docker run --rm -ti \
-v $(pwd):/opt/app \
-w /opt/app \
-e TERM=xterm \
-v $HOME/.m2:/root/.m2 \
maven mvn "$@"
Try to put stateHidden on as your activity windowSoftInputMode
value
http://developer.android.com/reference/android/R.attr.html#windowSoftInputMode
For example for your Activity:
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
You can also set LD_RUN_PATH to /usr/local/lib in your user environment when you compile pycurl in the first place. This will embed /usr/local/lib in the RPATH attribute of the C extension module .so so that it automatically knows where to find the library at run time without having to have LD_LIBRARY_PATH set at run time.
other than the fact that String implements CharSequence and that String is a sequence of character.
Several things happen in your code:
CharSequence obj = "hello";
That creates a String
literal, "hello"
, which is a String
object. Being a String
, which implements CharSequence
, it is also a CharSequence
. (you can read this post about coding to interface for example).
The next line:
String str = "hello";
is a little more complex. String
literals in Java are held in a pool (interned) so the "hello"
on this line is the same object (identity) as the "hello"
on the first line. Therefore, this line only assigns the same String
literal to str
.
At this point, both obj
and str
are references to the String
literal "hello"
and are therefore equals
, ==
and they are both a String
and a CharSequence
.
I suggest you test this code, showing in action what I just wrote:
public static void main(String[] args) {
CharSequence obj = "hello";
String str = "hello";
System.out.println("Type of obj: " + obj.getClass().getSimpleName());
System.out.println("Type of str: " + str.getClass().getSimpleName());
System.out.println("Value of obj: " + obj);
System.out.println("Value of str: " + str);
System.out.println("Is obj a String? " + (obj instanceof String));
System.out.println("Is obj a CharSequence? " + (obj instanceof CharSequence));
System.out.println("Is str a String? " + (str instanceof String));
System.out.println("Is str a CharSequence? " + (str instanceof CharSequence));
System.out.println("Is \"hello\" a String? " + ("hello" instanceof String));
System.out.println("Is \"hello\" a CharSequence? " + ("hello" instanceof CharSequence));
System.out.println("str.equals(obj)? " + str.equals(obj));
System.out.println("(str == obj)? " + (str == obj));
}
Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.
Basic usage:
> df = data.frame(
+ id=1:3, foo=c('a|b','b|c','c|d'),
+ bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
id foo bar test.1 test.2
1 1 a|b p|q a b
2 2 b|c r|s b c
3 3 c|d s|t c d
Multiple columns:
> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
id foo bar X1 X2 X1.1 X2.1
1 1 a|b p|q a b p q
2 2 b|c r|s b c r s
3 3 c|d s|t c d s t
Better naming of multiple split columns:
> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l},
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
id foo bar foo.1 foo.2 bar.1 bar.2
1 1 a|b p|q a b p q
2 2 b|c r|s b c r s
3 3 c|d s|t c d s t
This is because of the combination of two things:
tsconfig
not having any files
section. From http://www.typescriptlang.org/docs/handbook/tsconfig-json.html
If no "files" property is present in a tsconfig.json, the compiler defaults to including all files in the containing directory and subdirectories. When a "files" property is specified, only those files are included.
Including typescript
as an npm dependency : node_modules/typescript/
This means that all of typescript
gets included .... there is an implicitly included lib.d.ts
in your project anyways (http://basarat.gitbook.io/typescript/content/docs/types/lib.d.ts.html) and its conflicting with the one that ships with the NPM version of typescript.
Either list files
or include
explicitly https://basarat.gitbook.io/typescript/docs/project/files.html
You can also return all the information about the Foreign Keys
by adapating @LittleSweetSeas answer:
SELECT
OBJECT_NAME(f.parent_object_id) ConsTable,
OBJECT_NAME (f.referenced_object_id) refTable,
COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM
sys.foreign_keys AS f
INNER JOIN
sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN
sys.tables t
ON t.OBJECT_ID = fc.referenced_object_id
order by
ConsTable
You can use
docker history IMAGE_ID
to see how the image size is ditributed between its various sub-components.
The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)
So, listening to popstate
event and sending a popstate
event when using history.pushState()
should be enough to take action on href
change:
window.addEventListener('popstate', listener);
const pushUrl = (href) => {
history.pushState({}, '', href);
window.dispatchEvent(new Event('popstate'));
};
Container(
height: 50,
// margin: EdgeInsets.only(top: 20),
decoration: BoxDecoration(
color: Colors.tealAccent,
borderRadius: BorderRadius.circular(32)),
child: TextFormField(
cursorColor: Colors.black,
// keyboardType: TextInputType.,
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 17),
hintText: 'Search your trips',
suffixIcon: Icon(Icons.search),
border: InputBorder.none,
contentPadding: EdgeInsets.all(18),
),
),
),
The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
I think you need WaitHandler.WaitAll. Here is an example:
public static void Main(string[] args)
{
int numOfThreads = 10;
WaitHandle[] waitHandles = new WaitHandle[numOfThreads];
for (int i = 0; i < numOfThreads; i++)
{
var j = i;
// Or you can use AutoResetEvent/ManualResetEvent
var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
var thread = new Thread(() =>
{
Thread.Sleep(j * 1000);
Console.WriteLine("Thread{0} exits", j);
handle.Set();
});
waitHandles[j] = handle;
thread.Start();
}
WaitHandle.WaitAll(waitHandles);
Console.WriteLine("Main thread exits");
Console.Read();
}
FCL has a few more convenient functions.
(1) Task.WaitAll, as well as its overloads, when you want to do some tasks in parallel (and with no return values).
var tasks = new[]
{
Task.Factory.StartNew(() => DoSomething1()),
Task.Factory.StartNew(() => DoSomething2()),
Task.Factory.StartNew(() => DoSomething3())
};
Task.WaitAll(tasks);
(2) Task.WhenAll when you want to do some tasks with return values. It performs the operations and puts the results in an array. It's thread-safe, and you don't need to using a thread-safe container and implement the add operation yourself.
var tasks = new[]
{
Task.Factory.StartNew(() => GetSomething1()),
Task.Factory.StartNew(() => GetSomething2()),
Task.Factory.StartNew(() => GetSomething3())
};
var things = Task.WhenAll(tasks);
Had a similar problem and was getting the following errors depending on what app I used and if we bypassed the firewall / load balancer or not:
HTTPS handshake to [blah] (for #136) failed. System.IO.IOException Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host
and
ReadResponse() failed: The server did not return a complete response for this request. Server returned 0 bytes.
The problem turned out to be that the SSL Server Certificate got missed and wasn't installed on a couple servers.
You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>
.
Also make sure you change your id
#rotate
to a class since you have multiple.
$(document).ready(function() {_x000D_
$('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
border-collapse: collapse;_x000D_
border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
/* FF3.5+ */_x000D_
-moz-transform: rotate(-90.0deg);_x000D_
/* Opera 10.5 */_x000D_
-o-transform: rotate(-90.0deg);_x000D_
/* Saf3.1+, Chrome */_x000D_
-webkit-transform: rotate(-90.0deg);_x000D_
/* IE6,IE7 */_x000D_
filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
/* IE8 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
/* Standard */_x000D_
transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>10kg</div>_x000D_
</td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>20kg</div>_x000D_
</td>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>30kg</div>_x000D_
</td>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
JavaScript
The equivalent to the above in pure JavaScript is as follows:
window.addEventListener('load', function () {
var rotates = document.getElementsByClassName('rotate');
for (var i = 0; i < rotates.length; i++) {
rotates[i].style.height = rotates[i].offsetWidth + 'px';
}
});
This function will clone remote repo into local repo dir, after merging all commits will be saved, git log
will be show the original commits and proper paths:
function git-add-repo
{
repo="$1"
dir="$(echo "$2" | sed 's/\/$//')"
path="$(pwd)"
tmp="$(mktemp -d)"
remote="$(echo "$tmp" | sed 's/\///g'| sed 's/\./_/g')"
git clone "$repo" "$tmp"
cd "$tmp"
git filter-branch --index-filter '
git ls-files -s |
sed "s,\t,&'"$dir"'/," |
GIT_INDEX_FILE="$GIT_INDEX_FILE.new" git update-index --index-info &&
mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"
' HEAD
cd "$path"
git remote add -f "$remote" "file://$tmp/.git"
git pull "$remote/master"
git merge --allow-unrelated-histories -m "Merge repo $repo into master" --edit "$remote/master"
git remote remove "$remote"
rm -rf "$tmp"
}
How to use:
cd current/package
git-add-repo https://github.com/example/example dir/to/save
If make a little changes you can even move files/dirs of merged repo into different paths, for example:
repo="https://github.com/example/example"
path="$(pwd)"
tmp="$(mktemp -d)"
remote="$(echo "$tmp" | sed 's/\///g' | sed 's/\./_/g')"
git clone "$repo" "$tmp"
cd "$tmp"
GIT_ADD_STORED=""
function git-mv-store
{
from="$(echo "$1" | sed 's/\./\\./')"
to="$(echo "$2" | sed 's/\./\\./')"
GIT_ADD_STORED+='s,\t'"$from"',\t'"$to"',;'
}
# NOTICE! This paths used for example! Use yours instead!
git-mv-store 'public/index.php' 'public/admin.php'
git-mv-store 'public/data' 'public/x/_data'
git-mv-store 'public/.htaccess' '.htaccess'
git-mv-store 'core/config' 'config/config'
git-mv-store 'core/defines.php' 'defines/defines.php'
git-mv-store 'README.md' 'doc/README.md'
git-mv-store '.gitignore' 'unneeded/.gitignore'
git filter-branch --index-filter '
git ls-files -s |
sed "'"$GIT_ADD_STORED"'" |
GIT_INDEX_FILE="$GIT_INDEX_FILE.new" git update-index --index-info &&
mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"
' HEAD
GIT_ADD_STORED=""
cd "$path"
git remote add -f "$remote" "file://$tmp/.git"
git pull "$remote/master"
git merge --allow-unrelated-histories -m "Merge repo $repo into master" --edit "$remote/master"
git remote remove "$remote"
rm -rf "$tmp"
Notices
Paths replaces via sed
, so make sure it moved in proper paths after merging.
The --allow-unrelated-histories
parameter only exists since git >= 2.9.
Using management studio the procedure can be done as follows
You'll need to specify the WITH REPLACE option to overwrite the existing adventure_second database with a backup taken from a different database.
Click option menu and tick Overwrite the existing database(With replace)
For OS X my connection.xml files are in
/Users/<username>/.sqldeveloper/system<sqldeveloper_version>/o.jdeveloper.db.connection.<oracle_version?>/
This is my benchmark results
test 4,267,740 ops/sec ±1.32% (60 runs sampled)
exec 3,649,719 ops/sec ±2.51% (60 runs sampled)
match 3,623,125 ops/sec ±1.85% (62 runs sampled)
indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)
test method is faster than the match method, but the fastest method is the indexOf
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
There is another (faster?) way to find where your app data is without Terminal:
If you are using other version control software, it may be in conflict. In my case, uninstalling Plastic SCM restored Tortoise SVN icons.
this should work.
TextView t2 = (TextView) findViewById(R.id.text2);
t2.setMovementMethod(LinkMovementMethod.getInstance());
and
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/txtCredits"
android:id="@+id/text2"
android:layout_centerInParent="true"
android:layout_marginTop="20dp"></TextView>
By using typed arrays, you can store arrays of these types:
For example:
?var array = new Uint8Array(100);
array[42] = 10;
alert(array[42]);?
See it in action here.
Reference to HEAD is not necessary.
git checkout -- file.js
is sufficient
__main__.py
file for?When creating a Python module, it is common to make the module execute some functionality (usually contained in a main
function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:
if __name__ == '__main__':
# execute only if run as the entry point into the program
main()
You can get the same semantics for a Python package with __main__.py
, which might have the following structure:
.
+-- demo
+-- __init__.py
+-- __main__.py
To see this, paste the below into a Python 3 shell:
from pathlib import Path
demo = Path.cwd() / 'demo'
demo.mkdir()
(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')
def main():
print('main() executed')
""")
(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')
from demo import main
main()
""")
We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py
(but not the main
function):
>>> import demo
demo/__init__.py executed
When we use the package as the entry point to the program, we perform the code in the __main__.py
, which imports the __init__.py
first:
$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed
You can derive this from the documentation. The documentation says:
__main__
— Top-level script environment
'__main__'
is the name of the scope in which top-level code executes. A module’s__name__
is set equal to'__main__'
when read from standard input, a script, or from an interactive prompt.A module can discover whether or not it is running in the main scope by checking its own
__name__
, which allows a common idiom for conditionally executing code in a module when it is run as a script or withpython -m
but not when it is imported:if __name__ == '__main__': # execute only if run as a script main()
For a package, the same effect can be achieved by including a
__main__.py
module, the contents of which will be executed when the module is run with-m
.
You can also zip up this directory, including the __main__.py
, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:
from pathlib import Path
demo = Path.cwd() / 'demo2'
demo.mkdir()
(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')
def main():
print('main() executed')
""")
(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')
from __init__ import main
main()
""")
Note the subtle change - we are importing main
from __init__
instead of demo2
- this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m
flag.
Particularly relevant to the question - zipapp
causes the zipped directory to execute the __main__.py
by default - and it is executed first, before __init__.py
:
$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed
Note again, this zipped directory is not a package - you cannot import it either.
The aggregate root is a complex name for a simple idea.
Well designed class diagram encapsulates its internals. Point through which you access this structure is called aggregate root
.
Internals of your solution may be very complicated, but users of this hierarchy will just use root.doSomethingWhichHasBusinessMeaning()
.
Check this simple class hierarchy
How do you want to ride your car? Chose better API
Option A (it just somehow works):
car.ride();
Option B (user has access to class inernals):
if(car.getTires().getUsageLevel()< Car.ACCEPTABLE_TIRE_USAGE)
for (Wheel w: car:getWheels()){
w.spin();
}
}
If you think that option A is better then congratulations. You get the main reason behind aggregate root
.
Aggregate root encapsulates multiple classes. you can manipulate the whole hierarchy only through the main object.
In general this is a very subtle issue and not trivial whatsoever. I encourage you to read mysqlperformanceblog.com and High Performance MySQL. I really think there is no general answer for this.
I'm working on a project which has a MySQL database with almost 1TB of data. The most important scalability factor is RAM. If the indexes of your tables fit into memory and your queries are highly optimized, you can serve a reasonable amount of requests with a average machine.
The number of records do matter, depending of how your tables look like. It's a difference to have a lot of varchar fields or only a couple of ints or longs.
The physical size of the database matters as well: think of backups, for instance. Depending on your engine, your physical db files on grow, but don't shrink, for instance with innodb. So deleting a lot of rows, doesn't help to shrink your physical files.
There's a lot to this issues and as in a lot of cases the devil is in the details.
I had the same problem. Go to Project Properties -> Deployment Assemplbly and add jstl jar
VARCHAR(MAX)
is big enough to accommodate TEXT
field. TEXT
, NTEXT
and IMAGE
data types of SQL Server 2000 will be deprecated in future version of SQL Server, SQL Server 2005 provides backward compatibility to data types but it is recommended to use new data types which are VARCHAR(MAX)
, NVARCHAR(MAX)
and VARBINARY(MAX)
.
I just used the @misir-jafarov and is working now with :
here is my code :
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
jQuery('.art-img img').each(function(){
var t = jQuery(this),
s = 'url(' + t.attr('src') + ')',
p = t.parent(),
d = jQuery('<div></div>');
p.append(d);
d.css({
'height' : t.parent().css('height'),
'background-size' : 'cover',
'background-repeat' : 'no-repeat',
'background-position' : '50% 20%',
'background-image' : s
});
t.hide();
});
}
Hope it helps.
Use the System.getenv(String)
method, passing the name of the variable to read.
This worked for me in Xamarin.iOS / Monotouch. Change the keyboard button to Next, pass the control to the next UITextField and hide the keyboard after the last UITextField.
private void SetShouldReturnDelegates(IEnumerable<UIView> subViewsToScout )
{
foreach (var item in subViewsToScout.Where(item => item.GetType() == typeof (UITextField)))
{
(item as UITextField).ReturnKeyType = UIReturnKeyType.Next;
(item as UITextField).ShouldReturn += (textField) =>
{
nint nextTag = textField.Tag + 1;
var nextResponder = textField.Superview.ViewWithTag(nextTag);
if (null != nextResponder)
nextResponder.BecomeFirstResponder();
else
textField.Superview.EndEditing(true);
//You could also use textField.ResignFirstResponder();
return false; // We do not want UITextField to insert line-breaks.
};
}
}
Inside the ViewDidLoad you'll have:
If your TextFields haven't a Tag set it now:
txtField1.Tag = 0;
txtField2.Tag = 1;
txtField3.Tag = 2;
//...
and just the call
SetShouldReturnDelegates(yourViewWithTxtFields.Subviews.ToList());
//If you are not sure of which view contains your fields you can also call it in a safer way:
SetShouldReturnDelegates(txtField1.Superview.Subviews.ToList());
//You can also reuse the same method with different containerViews in case your UITextField are under different views.
There are many different sytles/conventions that people use when coding C++. For example, some people prefer separating words using capitals (myVar or MyVar), or using underscores (my_var). Typically, variables that use underscores are in all lowercase (from my experience).
There is also a coding style called hungarian, which I believe is used by microsoft. I personally believe that it is a waste of time, but it may prove useful. This is were variable names are given short prefixes such as i, or f to hint the variables type. For example: int iVarname, char* strVarname.
It is accepted that you end a struct/class name with _t, to differentiate it from a variable name. E.g.:
class cat_t {
...
};
cat_t myCat;
It is also generally accepted to add a affix to indicate pointers, such as pVariable or variable_p.
In all, there really isn't any single standard, but many. The choices you make about naming your variables doesn't matter, so long as it is understandable, and above all, consistent. Consistency, consistency, CONSISTENCY! (try typing that thrice!)
And if all else fails, google it.
Based on Tom Gullen´s answer.
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var loop = new Date(start);
while(loop <= end){
alert(loop);
var newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
Your select
doesn't have an ID, only a name. You'll need to modify your selector:
$("#pizza").on("click", function(){
$("select[name='pizza_kind']").prop("disabled", !this.checked);
});
A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.
Then, in your HTML code, in head section, put:
<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">
The port is usually fixed, for DNS it's 53.
When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:
string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();
You could argue that I abuse the framework, but it works.
Static members are universal members. They can be accessed from anywhere.
I'm not sure this solution is under the spec but I think I can share for others.
Contains entity classes only. No META-INF/persistence.xml
.
Depends on my-entities
. Contains EJBs only.
Depends on my-services
. Contains resource classes and META-INF/persistence.xml
.
<jar-file/>
element in my-resources
as the version-postfixed artifact name of a transient dependency?<jar-file/>
element's value and the actual transient dependency's one?I put a property and a dependency in my-resources/pom.xml
.
<properties>
<my-entities.version>x.y.z-SNAPSHOT</my-entities.version>
</properties>
<dependencies>
<dependency>
<!-- this is actually a transitive dependency -->
<groupId>...</groupId>
<artifactId>my-entities</artifactId>
<version>${my-entities.version}</version>
<scope>compile</scope> <!-- other values won't work -->
</dependency>
<dependency>
<groupId>...</groupId>
<artifactId>my-services</artifactId>
<version>some.very.sepecific</version>
<scope>compile</scope>
</dependency>
<dependencies>
Now get the persistence.xml
ready for being filtered
<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
<persistence-unit name="myPU" transaction-type="JTA">
...
<jar-file>lib/my-entities-${my-entities.version}.jar</jar-file>
...
</persistence-unit>
</persistence>
With the dependencyConvergence
rule, we can assure that the my-entities
' version is same in both direct and transitive.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version>
<executions>
<execution>
<id>enforce</id>
<configuration>
<rules>
<dependencyConvergence/>
</rules>
</configuration>
<goals>
<goal>enforce</goal>
</goals>
</execution>
</executions>
</plugin>
A new array is created and the contents of the old one are copied over. That's all you know at the API level. Quoting from the docs (my emphasis):
Each
ArrayList
instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
In terms of how it actually happens with a specific implementation of ArrayList
(such as Sun's), in their case you can see the gory details in the source. But of course, relying on the details of a specific implementation isn't usually a good idea...
syntax:
git reflog --date=local | grep checkout: | grep ${current_branch} | tail -1
example:
git reflog --date=local | grep checkout: | grep dev-2.19.0 | tail -1
result:
cc7a3a8ec HEAD@{Wed Apr 29 14:58:50 2020}: checkout: moving from dev-2.18.0 to dev-2.19.0
curl probably does have some options for showing more information but for things like this I always use openssl s_client
With the -debug
option this gives lots of useful information
Maybe I should add that this also works with non HTTP connections. So if you are doing "https", try the curl commands suggested below. If you aren't or want a second option openssl s_client
might be good
Ahem, because 22 is the port number for ssh and has been for ages?
SupressFinalize
tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:
Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
In general, most any Dispose()
method should be able to call GC.SupressFinalize()
, because it should clean up everything that would be cleaned up in the finalizer.
SupressFinalize
is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()
/finalizer should work properly with or without a call to GC.SupressFinalize()
.
he does an integer divide, which means 3 / 4 = 0. cast one of the brackets to float
(float)(a.y - b.y) / (a.x - b.x);
I hope below solution will work for you all as I was having the same problem with my websites...
For : $json = json_decode(file_get_contents('http://...'));
Replace with below query
$Details= unserialize(file_get_contents('http://......'));
It also happens when the view returned by onCreateView() isn't the view that was inflated.
Example:
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.text_view);
textView.setText("Some text.");
return textView;
Fix:
return rootView;
Instead of:
return textView; // or whatever you returned
You might like the function GetInfoFromClosedFile()
Edit: Since the above link does not seem to work anymore, I am adding alternate link 1 and alternate link 2 + code:
Private Function GetInfoFromClosedFile(ByVal wbPath As String, _
wbName As String, wsName As String, cellRef As String) As Variant
Dim arg As String
GetInfoFromClosedFile = ""
If Right(wbPath, 1) <> "" Then wbPath = wbPath & ""
If Dir(wbPath & "" & wbName) = "" Then Exit Function
arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)
On Error Resume Next
GetInfoFromClosedFile = ExecuteExcel4Macro(arg)
End Function
Use css calc()
Super simple and awesome.
input {
width: -moz-calc(100% - 15px);
width: -webkit-calc(100% - 15px);
width: calc(100% - 15px);
}?
As seen here: Div width 100% minus fixed amount of pixels
By webvitaly (https://stackoverflow.com/users/713523/webvitaly)
Original source: http://web-profile.com.ua/css/dev/css-width-100prc-minus-100px/
Just copied this over here, because I almost missed it in the other thread.
This XPath is specific to the code snippet you've provided. To select <child>
with id as #grand
you can write //child[@id='#grand']
.
To get age //child[@id='#grand']/@age
Hope this helps
This operation is a complement, not a negation.
Consider that ~0 = -1, and work from there.
The algorithm for negation is, "complement, increment".
Did you know? There is also "one's complement" where the inverse numbers are symmetrical, and it has both a 0 and a -0.
Try this.
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
ELSE 'UNKNOWN FRUIT'
END AS FRUIT
FROM FRUIT_TABLE;
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
i have a data access library which works with both .net core and .net framework.
the trick was in .net core projects to keep the connection strings in a xml file named "app.config" (also for web projects), and mark it as 'copy to output directory',
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="conn1" connectionString="...." providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
ConfigurationManager.ConnectionStrings - will read the connection string.
var conn1 = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;
Your code is correct. Kindly mark small correction.
#rightcolumn {
width: 750px;
background-color: #777;
display: block;
**float: left;(wrong)**
**float: right; (corrected)**
border: 1px solid white;
}
This is Pythons way do show you unicode encoded strings. But i think you should be able to print the string on the screen or write it into a new file without any problems.
>>> test = u"I don\u2018t like this"
>>> test
u'I don\u2018t like this'
>>> print test
I don‘t like this
The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.
<input type="text" value="3" class="field left" readonly>
You could see in https://www.w3schools.com/tags/att_input_readonly.asp
The method to set "readonly":
$("input").attr("readonly", true)
to cancel "readonly"(work in jQuery):
$("input").attr("readonly", false)
Here's an approach using the URL() interface:
new URL(location.pathname, location.href).href
Extending Piotr's answer, if you also need a way to figure what to put in requirements.in
, you can first use pip-chill
to find the minimal set of required packages you have. By combining these tools, you can show the dependency reason why each package is installed. The full cycle looks like this:
$ python3 -m venv venv
$ . venv/bin/activate
(venv)$ pip install --upgrade pip
(venv)$ pip install pip-tools pip-chill
(venv)$ pip-chill --no-version > requirements.in
(venv)$ pip-compile requirements.in
(venv)$ pip-sync
Try the following:
create these folders under storage/framework:
sessions
views
cache
Now it should work
To me, the following is more readable (thus preferable) way to do it:
git reset HEAD~1
Instead of 1
, there could be any number of commits you want to unstage.
There is no existing Swap-method, so you have to create one yourself. Of course you can linqify it, but that has to be done with one (unwritten?) rules in mind: LINQ-operations do not change the input parameters!
In the other "linqify" answers, the (input) list is modified and returned, but this action brakes that rule. If would be weird if you have a list with unsorted items, do a LINQ "OrderBy"-operation and than discover that the input list is also sorted (just like the result). This is not allowed to happen!
So... how do we do this?
My first thought was just to restore the collection after it was finished iterating. But this is a dirty solution, so do not use it:
static public IEnumerable<T> Swap1<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// Swap the items.
T temp = source[index1];
source[index1] = source[index2];
source[index2] = temp;
// Return the items in the new order.
foreach (T item in source)
yield return item;
// Restore the collection.
source[index2] = source[index1];
source[index1] = temp;
}
This solution is dirty because it does modify the input list, even if it restores it to the original state. This could cause several problems:
There is a better (and shorter) solution: just make a copy of the original list. (This also makes it possible to use an IEnumerable as a parameter, instead of an IList):
static public IEnumerable<T> Swap2<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// If nothing needs to be swapped, just return the original collection.
if (index1 == index2)
return source;
// Make a copy.
List<T> copy = source.ToList();
// Swap the items.
T temp = copy[index1];
copy[index1] = copy[index2];
copy[index2] = temp;
// Return the copy with the swapped items.
return copy;
}
One disadvantage of this solution is that it copies the entire list which will consume memory and that makes the solution rather slow.
You might consider the following solution:
static public IEnumerable<T> Swap3<T>(this IList<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.
using (IEnumerator<T> e = source.GetEnumerator())
{
// Iterate to the first index.
for (int i = 0; i < index1; i++)
yield return source[i];
// Return the item at the second index.
yield return source[index2];
if (index1 != index2)
{
// Return the items between the first and second index.
for (int i = index1 + 1; i < index2; i++)
yield return source[i];
// Return the item at the first index.
yield return source[index1];
}
// Return the remaining items.
for (int i = index2 + 1; i < source.Count; i++)
yield return source[i];
}
}
And if you want to input parameter to be IEnumerable:
static public IEnumerable<T> Swap4<T>(this IEnumerable<T> source, int index1, int index2)
{
// Parameter checking is skipped in this example.
// It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.
using(IEnumerator<T> e = source.GetEnumerator())
{
// Iterate to the first index.
for(int i = 0; i < index1; i++)
{
if (!e.MoveNext())
yield break;
yield return e.Current;
}
if (index1 != index2)
{
// Remember the item at the first position.
if (!e.MoveNext())
yield break;
T rememberedItem = e.Current;
// Store the items between the first and second index in a temporary list.
List<T> subset = new List<T>(index2 - index1 - 1);
for (int i = index1 + 1; i < index2; i++)
{
if (!e.MoveNext())
break;
subset.Add(e.Current);
}
// Return the item at the second index.
if (e.MoveNext())
yield return e.Current;
// Return the items in the subset.
foreach (T item in subset)
yield return item;
// Return the first (remembered) item.
yield return rememberedItem;
}
// Return the remaining items in the list.
while (e.MoveNext())
yield return e.Current;
}
}
Swap4 also makes a copy of (a subset of) the source. So worst case scenario, it is as slow and memory consuming as function Swap2.
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
For easy tasks I often simply do it like:
var undef;
// Fails on undefined variables
if (query !== undef) {
// variable is defined
} else {
// else do this
}
Or if you simply want to check for a nulled value too..
var undef;
// Fails on undefined variables
// And even fails on null values
if (query != undef) {
// variable is defined and not null
} else {
// else do this
}
You have mixed 2 standard.
The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";
The function http_build_query($filedata)
is only for "Content-Type: application/x-www-form-urlencoded", or none.
This is a subjective opinion, but I think a text editor shouldn't do everything and the kitchen sink. I prefer lightweight flexible and powerful (in their specialized fields) editors. Although being mostly a Windows user, I like the Unix philosophy of having lot of specialized tools that you can pipe together (like the UnxUtils) rather than a monster doing everything, but not necessarily as you would like it!
Find in files is on the border of these extra features, but useful when you can double-click on a found line to open the file at the right line. Note that initially, in SciTE it was just a Tools call to grep or equivalent!
FTP is very close to off topic, although it can be seen as an extended open/save dialog.
Replace in files is too much IMO: it is dangerous (you can mess lot of files at once) if you have no preview, etc. I would rather use a specialized tool I chose, perhaps among those in Multi line search and replace tool.
To answer the question, looking at N++, I see a Run menu where you can launch any tool, with assignment of a name and shortcut key. I see also Plugins > NppExec, which seems able to launch stuff like sed (not tried it).
You can use the built-in forEach
function for arrays.
Like this:
//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
element.product_desc = element.product_desc.substring(0,10);
});
Your version wasn't wrong though. It should look more like this:
for(let i=0; i<data.products.length; i++){
console.log(data.products[i].product_desc); //use i instead of 0
}
==
and .Equals
are both dependent upon the behavior defined in the actual type and the actual type at the call site. Both are just methods / operators which can be overridden on any type and given any behavior the author so desires. In my experience, I find it's common for people to implement .Equals
on an object but neglect to implement operator ==
. This means that .Equals
will actually measure the equality of the values while ==
will measure whether or not they are the same reference.
When I'm working with a new type whose definition is in flux or writing generic algorithms, I find the best practice is the following
Object.ReferenceEquals
directly (not needed in the generic case)EqualityComparer<T>.Default
In some cases when I feel the usage of ==
is ambiguous I will explicitly use Object.Reference
equals in the code to remove the ambiguity.
Eric Lippert recently did a blog post on the subject of why there are 2 methods of equality in the CLR. It's worth the read
There's a function empty()
ready for you in std::string:
std::string a;
if(a.empty())
{
//do stuff. You will enter this block if the string is declared like this
}
or
std::string a;
if(!a.empty())
{
//You will not enter this block now
}
a = "42";
if(!a.empty())
{
//And now you will enter this block.
}
For input
elements, this answer works for me.
I implemented it on a custom input component in Angular 4, but I think it could be implemented with pure JS.
HTML
<input type="text" [(ngModel)]="value" (ondragenter)="disableEvent($event)"
(dragover)="disableEvent($event)" (ondrop)="disableEvent($event)"/>
Component definition (JS):
export class CustomInputComponent {
//component construction and attribute definitions
disableEvent(event) {
event.preventDefault();
return false;
}
}
If body contains a io.StringIO, you have to do like below:
object.get()['Body'].getvalue()
Declaring a two dimensional ArrayList:
ArrayList<ArrayList<String>> rows = new ArrayList<String>();
Or
ArrayList<ArrayList<String>> rows = new ArrayList<>();
Or
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
All the above are valid declarations for a two dimensional ArrayList!
Now, Declaring a one dimensional ArrayList:
ArrayList<String> row = new ArrayList<>();
Inserting values in the two dimensional ArrayList:
for(int i=0; i<5; i++){
ArrayList<String> row = new ArrayList<>();
for(int j=0; j<5; j++){
row.add("Add values here");
}
rows.add(row);
}
fetching the values from the two dimensional ArrayList:
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
System.out.print(rows.get(i).get(j)+" ");
}
System.out.println("");
}
Improvement to @madprops answer - solution as a django management command:
import MySQLdb
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
host = settings.DATABASES['default']['HOST']
password = settings.DATABASES['default']['PASSWORD']
user = settings.DATABASES['default']['USER']
dbname = settings.DATABASES['default']['NAME']
db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
cursor = db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)
sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(f'Changing table "{row[0]}"...')
sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
cursor.execute(sql)
db.close()
Hope this helps anybody but me :)
>>> def contains(string, char):
... for i in xrange(len(string) - 1, -1, -1):
... if string[i] == char:
... return i
... raise ValueError("could not find %r in %r" % (char, string))
...
>>> contains('bababa', 'k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in contains
ValueError: could not find 'k' in 'bababa'
>>> contains('bababa', 'a')
5
>>> contains('bababa', 'b')
4
>>> contains('xbababa', 'x')
0
>>>
There is actually a pure javascript way to accomplish this without using setTimeout
or requestAnimationFrame
or jQuery.
In short, find the element in the scrollView that you want to scroll to, and use scrollIntoView
.
el.scrollIntoView({behavior:"smooth"});
Here is a plunkr.
For those who want to use JavaMail with Kotlin in 2020:
implementation 'com.sun.mail:android-mail:1.6.5'
implementation 'com.sun.mail:android-activation:1.6.5'
implementation "org.bouncycastle:bcmail-jdk15on:1.65"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7"
BouncyCastle is for security reasons.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
object Config {
const val EMAIL_FROM = "[email protected]"
const val PASS_FROM = "Your_Sender_Password"
const val EMAIL_TO = "[email protected]"
}
object Mailer {
init {
Security.addProvider(BouncyCastleProvider())
}
private fun props(): Properties = Properties().also {
// Smtp server
it["mail.smtp.host"] = "smtp.gmail.com"
// Change when necessary
it["mail.smtp.auth"] = "true"
it["mail.smtp.port"] = "465"
// Easy and fast way to enable ssl in JavaMail
it["mail.smtp.ssl.enable"] = true
}
// Dont ever use "getDefaultInstance" like other examples do!
private fun session(emailFrom: String, emailPass: String): Session = Session.getInstance(props(), object : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(emailFrom, emailPass)
}
})
private fun builtMessage(firstName: String, surName: String): String {
return """
<b>Name:</b> $firstName <br/>
<b>Surname:</b> $surName <br/>
""".trimIndent()
}
private fun builtSubject(issue: String, firstName: String, surName: String):String {
return """
$issue | $firstName, $surName
""".trimIndent()
}
private fun sendMessageTo(emailFrom: String, session: Session, message: String, subject: String) {
try {
MimeMessage(session).let { mime ->
mime.setFrom(InternetAddress(emailFrom))
// Adding receiver
mime.addRecipient(Message.RecipientType.TO, InternetAddress(Config.EMAIL_TO))
// Adding subject
mime.subject = subject
// Adding message
mime.setText(message)
// Set Content of Message to Html if needed
mime.setContent(message, "text/html")
// send mail
Transport.send(mime)
}
} catch (e: MessagingException) {
Log.e("","") // Or use timber, it really doesn't matter
}
}
fun sendMail(firstName: String, surName: String) {
// Open a session
val session = session(Config.EMAIL_FROM, Config.PASSWORD_FROM)
// Create a message
val message = builtMessage(firstName, surName)
// Create subject
val subject = builtSubject(firstName, surName)
// Send Email
CoroutineScope(Dispatchers.IO).launch { sendMessageTo(Config.EMAIL_FROM, session, message, subject) }
}
I prefer to just return a null, and rely on the caller to handle it appropriately. The (for lack of a better word) exception is if I am absolutely 'certain' this method will return an object. In that case a failure is an exceptional should and should throw.
If the time is 11:03, then the accepted answer will print 11:3.
You could zero-pad the minutes:
"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)
Or go another way and use tdate.time()
and only take the hour/minute part:
str(tdate.time())[0:5]
What worked for me on an Amazon EC2 server was:
sudo service mysqld restart
If you are using the push_back there is no call for the string constructor. Otherwise it will create a string object via casting, then it will add the character in this string to the other string. Too much trouble for a tiny character ;)
Since Node v11.0.0 fs promises are available natively without promisify
:
const fs = require('fs').promises;
async function loadMonoCounter() {
const data = await fs.readFile("monolitic.txt", "binary");
return new Buffer(data);
}
You can overcome this error in two simple ways
First way
using namespace std;
include <string>
// then you can use string class the normal way
Second way
// after including the class string in your cpp file as follows
include <string>
/*Now when you are using a string class you have to put **std::** before you write
string as follows*/
std::string name; // a string declaration
When using NOT IN, you should also consider NOT EXISTS, which handles the null cases silently. See also PostgreSQL Wiki
SELECT mac, creation_date
FROM logs lo
WHERE logs_type_id=11
AND NOT EXISTS (
SELECT *
FROM consols nx
WHERE nx.mac = lo.mac
);
according the documentation, this should do it...
RESET QUERY CACHE
From the command run:
sudo docker build -t myrepo/redis
there are no "arguments" passed to the docker build
command, only a single flag -t
and a value for that flag. After docker parses all of the flags for the command, there should be one argument left when you're running a build.
That argument is the build context. The standard command includes a trailing dot for the context:
sudo docker build -t myrepo/redis .
Every docker build sends a directory to the build server. Docker is a client/server application, and the build runs on the server which isn't necessarily where the docker command is run. Docker uses the build context as the source for files used in COPY
and ADD
steps. When you are in the current directory to run the build, you would pass a .
for the context, aka the current directory. You could pass a completely different directory, even a git repo, and docker will perform the build using that as the context, e.g.:
docker build -t sudobmitch/base:alpine --target alpine-base \
'https://github.com/sudo-bmitch/docker-base.git#main'
For more details on these options to the build command, see the docker build documentation.
If you are including the value for the build context (typically the .
) and still see this error message, you have likely passed more than one argument. Typically this is from failing to parse a flag, or passing a string with spaces without quotes. Possible causes for docker to see more than one argument include:
Missing quotes around a path or argument with spaces (take note using variables that may have spaces in them)
Incorrect dashes in the command: make sure to type these manually rather than copy and pasting
Incorrect quotes: smart quotes don't work on the command line, type them manually rather than copy and pasting.
Whitespace that isn't white space, or that doesn't appear to be a space.
Most all of these come from either a typo or copy and pasting from a source that modified the text to look pretty, breaking it for using as a command.
The easiest way I have to debug this, run the command without any other flags:
docker build .
Once that works, add flags back in until you get the error, and then you'll know what flag is broken and needs the quotes to be fixed/added or dashes corrected, etc.
I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.
You can try
$('#id1 p').each(function() {
var text = $(this).text();
$(this).text(text.replace('dog', 'doll'));
});
You could use instead .html()
and/or further sophisticate the .replace()
call according to your needs
Maybe
if (inventory.contains("bread") && !inventory.contains("water"))
Or
if (inventory.contains("bread")) {
if (!inventory.contains("water")) {
// do something here
}
}
[EDITED] It's seems you earlier have redefined "list", using it as a variable name, like this:
list = set([1,2,3,4]) # oops
#...
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)
And you'l get
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'set' object is not callable
I think it's worth answering the generic question "R - test if string contains string" here.
For that, use the grep function.
# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
Example:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Without curly braces PHP would try to find a variable named $numberth
, that doesn't exist!
I have the same issue as you, after trying all the clean, update and install and there was still missing artifacts. Problem for me is that profiles are not being applied. Check in your .m2/settings.xml and look for <activeProfile>
. Go back to your project, right click under properties -> maven and enter your Active Maven Profiles. All the missing artifacts were resolved.
Suppose you simply don't know the size of the data.frame in advance. It can well be a few rows, or a few millions. You need to have some sort of container, that grows dynamically. Taking in consideration my experience and all related answers in SO I come with 4 distinct solutions:
rbindlist
to the data.frame
Use data.table
's fast set
operation and couple it with manually doubling the table when needed.
Use RSQLite
and append to the table held in memory.
data.frame
's own ability to grow and use custom environment (which has reference semantics) to store the data.frame so it will not be copied on return.
Here is a test of all the methods for both small and large number of appended rows. Each method has 3 functions associated with it:
create(first_element)
that returns the appropriate backing object with first_element
put in.
append(object, element)
that appends the element
to the end of the table (represented by object
).
access(object)
gets the data.frame
with all the inserted elements.
rbindlist
to the data.frameThat is quite easy and straight-forward:
create.1<-function(elems)
{
return(as.data.table(elems))
}
append.1<-function(dt, elems)
{
return(rbindlist(list(dt, elems),use.names = TRUE))
}
access.1<-function(dt)
{
return(dt)
}
data.table::set
+ manually doubling the table when needed.I will store the true length of the table in a rowcount
attribute.
create.2<-function(elems)
{
return(as.data.table(elems))
}
append.2<-function(dt, elems)
{
n<-attr(dt, 'rowcount')
if (is.null(n))
n<-nrow(dt)
if (n==nrow(dt))
{
tmp<-elems[1]
tmp[[1]]<-rep(NA,n)
dt<-rbindlist(list(dt, tmp), fill=TRUE, use.names=TRUE)
setattr(dt,'rowcount', n)
}
pos<-as.integer(match(names(elems), colnames(dt)))
for (j in seq_along(pos))
{
set(dt, i=as.integer(n+1), pos[[j]], elems[[j]])
}
setattr(dt,'rowcount',n+1)
return(dt)
}
access.2<-function(elems)
{
n<-attr(elems, 'rowcount')
return(as.data.table(elems[1:n,]))
}
RSQLite
solutionThis is basically copy&paste of Karsten W. answer on similar thread.
create.3<-function(elems)
{
con <- RSQLite::dbConnect(RSQLite::SQLite(), ":memory:")
RSQLite::dbWriteTable(con, 't', as.data.frame(elems))
return(con)
}
append.3<-function(con, elems)
{
RSQLite::dbWriteTable(con, 't', as.data.frame(elems), append=TRUE)
return(con)
}
access.3<-function(con)
{
return(RSQLite::dbReadTable(con, "t", row.names=NULL))
}
data.frame
's own row-appending + custom environment.create.4<-function(elems)
{
env<-new.env()
env$dt<-as.data.frame(elems)
return(env)
}
append.4<-function(env, elems)
{
env$dt[nrow(env$dt)+1,]<-elems
return(env)
}
access.4<-function(env)
{
return(env$dt)
}
For convenience I will use one test function to cover them all with indirect calling. (I checked: using do.call
instead of calling the functions directly doesn't makes the code run measurable longer).
test<-function(id, n=1000)
{
n<-n-1
el<-list(a=1,b=2,c=3,d=4)
o<-do.call(paste0('create.',id),list(el))
s<-paste0('append.',id)
for (i in 1:n)
{
o<-do.call(s,list(o,el))
}
return(do.call(paste0('access.', id), list(o)))
}
Let's see the performance for n=10 insertions.
I also added a 'placebo' functions (with suffix 0
) that don't perform anything - just to measure the overhead of the test setup.
r<-microbenchmark(test(0,n=10), test(1,n=10),test(2,n=10),test(3,n=10), test(4,n=10))
autoplot(r)
For 1E5 rows (measurements done on Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz):
nr function time
4 data.frame 228.251
3 sqlite 133.716
2 data.table 3.059
1 rbindlist 169.998
0 placebo 0.202
It looks like the SQLite-based sulution, although regains some speed on large data, is nowhere near data.table + manual exponential growth. The difference is almost two orders of magnitude!
If you know that you will append rather small number of rows (n<=100), go ahead and use the simplest possible solution: just assign the rows to the data.frame using bracket notation and ignore the fact that the data.frame is not pre-populated.
For everything else use data.table::set
and grow the data.table exponentially (e.g. using my code).
remove(int index) method of arraylist removes the element at the specified position(index) in the list. After removing arraylist items shifts any subsequent elements to the left.
Means if a arraylist contains {20,15,30,40}
I have called the method: arraylist.remove(1)
then the data 15 will be deleted and 30 & 40 these two items will be left shifted by 1.
For this reason you have to delete higher index item of arraylist first.
So..for your given situation..the code will be..
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");
int i[] = {1,3,5};
for (int j = i.length-1; j >= 0; j--) {
list.remove(i[j]);
}
Single Threaded Event Loop Model Processing Steps:
Clients Send request to Web Server.
Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.
Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”.
Node JS Web Server internally has a Component, known as “Event Loop”. Why it got this name is that it uses indefinite loop to receive requests and process them.
Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model.
Event Loop checks any Client Request is placed in Event Queue. If not then wait for incoming requests for indefinitely.
If yes, then pick up one Client Request from Event Queue
That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop
very nicely explained by @Rambabu Posa for more explanation go throw this Link
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
Here is a function that will flatten an object or array. Use this only if you are sure your keys are unique. If you have keys with the same name they will be overwritten. You will need to place this in a class and replace "Functions" with the name of your class. Enjoy...
function flatten($array, $preserve_keys=1, &$out = array(), $isobject=0) {
# Flatten a multidimensional array to one dimension, optionally preserving keys.
#
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion
# $isobject - is internally set in order to remember if we're using an object or array
if(is_array($array) || $isobject==1)
foreach($array as $key => $child)
if(is_array($child))
$out = Functions::flatten($child, $preserve_keys, $out, 1); // replace "Functions" with the name of your class
elseif($preserve_keys + is_string($key) > 1)
$out[$key] = $child;
else
$out[] = $child;
if(is_object($array) || $isobject==2)
if(!is_object($out)){$out = new stdClass();}
foreach($array as $key => $child)
if(is_object($child))
$out = Functions::flatten($child, $preserve_keys, $out, 2); // replace "Functions" with the name of your class
elseif($preserve_keys + is_string($key) > 1)
$out->$key = $child;
else
$out = $child;
return $out;
}
I found this post to contain the simplest answer. Merely do:
git checkout <branch from which you want files> <file paths>
Pulling .gitignore file from branchB into current branch:
git checkout branchB .gitignore
See the post for more information.
Try using FIND_IN_SET() function of MySql e.g.
SET @c = 'xxx,yyy,zzz';
SELECT * from countries
WHERE FIND_IN_SET(countryname,@c);
Note: You don't have to SET variable in StoredProcedure if you are passing parameter with CSV values.
It seems that most of the answers missed the original question.
Is there a standard sign function (signum, sgn) in C/C++?
Not in the standard library, however there is copysign
which can be used almost the same way via copysign(1.0, arg)
and there is a true sign function in boost
, which might as well be part of the standard.
#include <boost/math/special_functions/sign.hpp>
//Returns 1 if x > 0, -1 if x < 0, and 0 if x is zero.
template <class T>
inline int sign (const T& z);
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
i think doing some like this.
void printchar(char c, int n){
int i;
for(i=0;i<n;i++)
print("%c",c);
}
printchar("*",10);
Set the following system properties, this will enabled xml logging. You can set it in java or configuration file.
static{
System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", "999999");
}
console logs:
INFO: Outbound Message
---------------------------
ID: 1
Address: http://localhost:7001/arm-war/castService
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: xml
--------------------------------------
INFO: Inbound Message
----------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml; charset=UTF-8
Headers: {content-type=[text/xml; charset=UTF-8], Date=[Fri, 20 Jan 2017 11:30:48 GMT], transfer-encoding=[chunked]}
Payload: xml
--------------------------------------
Filezilla just released a Pro version of their FTP client. It connects to S3 buckets in a streamlined FTP like experience. I use it myself (no affiliation whatsoever) and it works great.
I'd add, that you can also use this to call multiple emits or methods or both together by separating with ; semicolon
@click="method1(); $emit('emit1'); $emit('emit2');"
You can use BIGINT as follows:
CREATE TABLE user_reg (
user_id INT NOT NULL AUTO_INCREMENT,
identifier INT,
phone_number CHAR(11) NOT NULL,
verified TINYINT UNSIGNED NOT NULL,
reg_time BIGINT,
last_active_time BIGINT,
PRIMARY KEY (user_id),
INDEX (phone_number, user_id, identifier)
);
The simplest solution that worked for me was to put a height constraint on the textView in the Storyboard, then connect the textView and height constraint to the code:
@IBOutlet var myAwesomeTextView: UITextView!
@IBOutlet var myAwesomeTextViewHeight: NSLayoutConstraint!
Then after setting the text and paragraph styles, add this in viewDidAppear:
self.myAwesomeTextViewHeight.constant = self.myAwesomeTextView.contentSize.height
Some notes:
Try .replace(/ /g,"_");
Edit: or .split(' ').join('_')
if you have an aversion to REs
Edit: John Resig said:
If you're searching and replacing through a string with a static search and a static replace it's faster to perform the action with .split("match").join("replace") - which seems counter-intuitive but it manages to work that way in most modern browsers. (There are changes going in place to grossly improve the performance of .replace(/match/g, "replace") in the next version of Firefox - so the previous statement won't be the case for long.)
You can see here http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx
See the remarks and example section there.
This is fixed in npm 7. See npm/cli#PR169
If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:
NET USE z: \server\c$\folder1\folder2
NET USE y: \server\d$
Note that you can map drive-to-drive or drill down and map to sub-folder.
Something like this:
select *
from User U1
where time_stamp = (
select max(time_stamp)
from User
where username = U1.username)
should do it.
I like Fernandes' answer even though you ask for the obj twice.
This should also do (more or less the same as Martin's A).
id obj;
if ((obj=[dict objectForKey:@"blah"])) {
// use obj
} else {
// Do something else like creating the obj and add the kv pair to the dict
}
Martin's and this answer both work on iPad2 iOS 5.0.1 9A405
This is your code: http://jsfiddle.net/WSFnX/
Using display: table-cell
is fine, provided that you're aware that it won't work in IE6/7. Other than that, it's safe: Is there a disadvantage of using `display:table-cell`on divs?
To fix the space at the bottom, add vertical-align: bottom
to the actual img
s:
Removing the space between the images boils down to this: bikeshedding CSS3 property alternative?
So, here's a demo with the whitespace removed in your HTML: http://jsfiddle.net/WSFnX/4/
- file:
path: /etc/some_directory
state: directory
mode: 0755
owner: someone
group: somegroup
That's the way you can actually also set the permissions, the owner and the group. The last three parameters are not obligatory.
ip addr show | grep -E '^\s*inet' | grep -m1 global | awk '{ print $2 }' | sed 's|/.*||'
One more cause for this:
If the routes are overridden with the same URI (Unknowingly), it causes this error:
Eg:
Route::get('dashboard', ['uses' => 'SomeController@index', 'as' => 'my.dashboard']);
Route::get('dashboard/', ['uses' => 'SomeController@dashboard', 'as' => 'my.home_dashboard']);
In this case route 'my.dashboard' is invalidate as the both routes has same URI ('dashboard', 'dashboard/')
Solution: You should change the URI for either one
Eg:
Route::get('dashboard', ['uses' => 'SomeController@index', 'as' => 'my.dashboard']);
Route::get('home-dashboard', ['uses' => 'SomeController@dashboard', 'as' => 'my.home_dashboard']);
// See the URI changed for this 'home-dashboard'
Hope it helps some once.
Actually it is rather easy. Just think for the optimal way. I beleive the optimal way is:
for (int i=0; i<list.size(); i++) {
Level obj = list.get(i);
//Here execute yr code that may add / or may not add new element(s)
//...
i=list.indexOf(obj);
}
The following example works perfectly in the most logical case - when you dont need to iterate the added new elements before the iteration element. About the added elements after the iteration element - there you might want not to iterate them either. In this case you should simply add/or extend yr object with a flag that will mark them not to iterate them.
str.matches(regex)
behaves like Pattern.matches(regex, str)
which attempts to match the entire input sequence against the pattern and returns
true
if, and only if, the entire input sequence matches this matcher's pattern
Whereas matcher.find()
attempts to find the next subsequence of the input sequence that matches the pattern and returns
true
if, and only if, a subsequence of the input sequence matches this matcher's pattern
Thus the problem is with the regex. Try the following.
String test = "User Comments: This is \t a\ta \ntest\n\n message \n";
String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find()); //true
String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2)); //true
Thus in short, the (\\W)*(\\S)*
portion in your first regex matches an empty string as *
means zero or more occurrences and the real matched string is User Comments:
and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W
matches a non word character, ie [^a-zA-Z0-9_]
and the first character is T
, a word character.
i just do :
set /p input= yes or no
if %input%==yes echo you clicked yes
if %input%==no echo you clicked no
pause
Prefixing the statement with an exclamation mark will let you know whether the array is not empty. So in your case -
a = [1,2,3]
!a.empty?
=> true
In Python 3, I find pathlib is the easiest way to do this. Request's response.content marries up nicely with pathlib's write_bytes.
from pathlib import Path
import requests
filename = Path('metadata.pdf')
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
filename.write_bytes(response.content)
I was getting the same error Requires: container-selinux >= 2.9 on amazon ec2 instance(Rhel7)
I tried to add extra package rmp repo by executing
sudo yum-config-manager --enable rhui-REGION-rhel-server-extras
but it works.
followed steps from https://installdocker.blogspot.com/ and I was able to install docker.
Here are 3 examples:
$(document).on('click', 'ul li a', function (e) {_x000D_
e.preventDefault();_x000D_
_x000D_
var example1 = $(this).parents('ul:first').attr('id');_x000D_
$('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
$('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
_x000D_
var example3 = $(this).closest('ul').attr('id');_x000D_
$('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
<li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
<h1>Results:</h1>_x000D_
</div>
_x000D_
Let me know whether it was helpful.
I solved this problem with conda
and pip
.
Firstly, I run:
conda uninstall qt and conda uninstall matplotlib and conda uninstall PyQt5
After that, I opened the cmd and run this code that
pip uninstall qt , pip uninstall matplotlib , pip uninstall PyQt5
Lastly, You should install matplotlib
in pip by this code that pip install matplotlib
You can use zip
:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
... print x, y
...
1 a
2 b
3 c
I'm giving this example because this actually work for my use case.
I was trying to use the AWS Rekognition API. The API returns a BoundingBox object:
BoundingBox boundingBox = faceDetail.getBoundingBox();
The code below uses it to crop the image:
import com.amazonaws.services.rekognition.model.BoundingBox;
private BufferedImage cropImage(BufferedImage image, BoundingBox box) {
Rectangle goal = new Rectangle(Math.round(box.getLeft()* image.getWidth()),Math.round(box.getTop()* image.getHeight()),Math.round(box.getWidth() * image.getWidth()), Math.round(box.getHeight() * image.getHeight()));
Rectangle clip = goal.intersection(new Rectangle(image.getWidth(), image.getHeight()));
BufferedImage clippedImg = image.getSubimage(clip.x, clip.y , clip.width, clip.height);
return clippedImg;
}
REST is a software design pattern typically used for web applications. In layman's terms this means that it is a commonly used idea used in many different projects. It stands for REpresentational State Transfer. The basic idea of REST is treating objects on the server-side (as in rows in a database table) as resources than can be created or destroyed.
The most basic way of thinking about REST is as a way of formatting the URLs of your web applications. For example, if your resource was called "posts", then:
/posts
Would be how a user would access ALL the posts, for displaying.
/posts/:id
Would be how a user would access and view an individual post, retrieved based on their unique id.
/posts/new
Would be how you would display a form for creating a new post.
Sending a POST request to /users
would be how you would actually create a new post on the database level.
Sending a PUT request to /users/:id
would be how you would update the attributes of a given post, again identified by a unique id.
Sending a DELETE request to /users/:id
would be how you would delete a given post, again identified by a unique id.
As I understand it, the REST pattern was mainly popularized (for web apps) by the Ruby on Rails framework, which puts a big emphasis on RESTful routes. I could be wrong about that though.
I may not be the most qualified to talk about it, but this is how I've learned it (specifically for Rails development).
When someone refers to a "REST api," generally what they mean is an api that uses RESTful urls for retrieving data.
The semantics of setTimeout are roughly the same as in a web browser: the timeout arg is a minimum number of ms to wait before executing, not a guarantee. Furthermore, passing 0, a non-number, or a negative number, will cause it to wait a minimum number of ms. In Node, this is 1ms, but in browsers it can be as much as 50ms.
The reason for this is that there is no preemption of JavaScript by JavaScript. Consider this example:
setTimeout(function () {
console.log('boo')
}, 100)
var end = Date.now() + 5000
while (Date.now() < end) ;
console.log('imma let you finish but blocking the event loop is the best bug of all TIME')
The flow here is:
If this was not the case, then you could have one bit of JavaScript "interrupt" another. We'd have to set up mutexes and semaphors and such, to prevent code like this from being extremely hard to reason about:
var a = 100;
setTimeout(function () {
a = 0;
}, 0);
var b = a; // 100 or 0?
The single-threadedness of Node's JavaScript execution makes it much simpler to work with than most other styles of concurrency. Of course, the trade-off is that it's possible for a badly-behaved part of the program to block the whole thing with an infinite loop.
Is this a better demon to battle than the complexity of preemption? That depends.
According to Apple, generally disabling ATS will lead to app rejection, unless you have a good reason to do so. Even then, you should add exceptions for domains that you can access safely.
Apple has an excellent tool that tells you exactly what settings to use: In Terminal, enter
/usr/bin/nscurl --ats-diagnostics --verbose https://www.example.com/whatever
and nscurl will check whether this request fails, and then try a variety of settings and tell you exactly which one passes, and what to do. For example, for some third-party URL that I visit, this command told me that this dictionary passes:
{
NSExceptionDomains = {
"www.example.com" = {
NSExceptionRequiresForwardSecrecy = false;
};
};
}
To distinguish between your own sites and third-party sites that are out of your control, use, for example, the key NSThirdPartyExceptionRequiresForwardSecrecy.
double[,]
is a 2d array (matrix) while double[][]
is an array of arrays (jagged arrays) and the syntax is:
double[][] ServicePoint = new double[10][];
@JigarJoshi it's the good answer, and of course also @Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date
.
One possibility is to use apache-commons-lang. You can do it using DateUtils
as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang
dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang
it's a good choice. There is also convenient methods to addYears
,addMonths
,addWeeks
and so on, take a look at the api here.
Another possibility is to take advantage of new LocalDate
from Java 8 using minusDays(long days)
method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
(int) add: (int) numberOne plus: (int) numberTwo ;
(returnType) functionPrimaryName : (returnTypeOfArgumentOne) argumentName functionSecondaryNa
me:
(returnTypeOfSecontArgument) secondArgumentName ;
as in other languages we use following syntax
void add(int one, int second)
but way of assigning arguments in OBJ_c
is different as described above
Use.
<?php $con = mysqli_connect('localhost', 'username', 'password', 'database'); ?>
In PHP 7. You probably have PHP 7 in XAMPP. You now have two option: MySQLi and PDO.
I had the same problem and I fixed it with:
<div id="container" style="width: 100%; height: 100%; position:absolute"></div>
The chart fits perfect to the browser even if I resize it. You can change the percentage according to your needs.
in the Gradle 5.1.1 version on mac ive changed how the task names got retrieved, i althought tried to get build flavour / type from build but was to lazy to split the task name:
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def value = 0
def runTasks = gradle.getStartParameter().getTaskRequests().toString()
if (runTasks.contains('assemble') || runTasks.contains('assembleRelease') || runTasks.contains('aR')) {
value = 1
}
def versionMajor = 1
def versionMinor = 0
def versionPatch = versionProps['VERSION_PATCH'].toInteger() + value
def versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
def versionNumber = versionProps['VERSION_NUMBER'].toInteger() + value
versionProps['VERSION_PATCH'] = versionPatch.toString()
versionProps['VERSION_BUILD'] = versionBuild.toString()
versionProps['VERSION_NUMBER'] = versionNumber.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
applicationId "de.evomotion.ms10"
minSdkVersion 21
targetSdkVersion 28
versionCode versionNumber
versionName "${versionMajor}.${versionMinor}.${versionPatch} (${versionBuild})"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
signingConfig signingConfigs.debug
}
} else {
throw new GradleException("Could not read version.properties!")
}
code is from @just_user this one
If you have the Windows SDK installed on your machine, you'll find the "Fusion Log Viewer" under Microsoft SDK\Tools (just type "Fusion" in the start menu on Vista or Windows 7/8). Launch it, click the Settings button, and select "Log bind failure" or "Log all binds".
If these buttons are disabled, go back to the start menu, right-click the Log Viewer, and select "Run as Administrator".
The problem was actually in the version Android Studio 1.3
updated from the canary channel. I updated my studio
to 1.3 and got the same error but reverting back to studio 1.2.1
made my project run fine.
In phpMyAdmin, click the table, and then click the Import tab at the top of the page.
Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:
Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto
Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.
Now click the Go button, and it should run successfully.
or_()
function can be useful in case of unknown number of OR query components.
For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_()
function we must do something like this:
query = Book.query
if filter.title and filter.author:
query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
query = query.filter(Book.author.ilike(filter.author))
With or_()
function it can be rewritten to:
query = Book.query
not_null_filters = []
if filter.title:
not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
not_null_filters.append(Book.author.ilike(filter.author))
if len(not_null_filters) > 0:
query = query.filter(or_(*not_null_filters))
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
getSupportFragmentManager().beginTransaction().detach(fragment).attach(fragment).commit();
this will only work if u use FragmentManager
to initialize the fragment. If u have it as a <fragment ... />
in XML, it won't call the onCreateView
again. Wasted my 30 minutes to figure this out.
puts 'abcdefg'.start_with?('abc') #=> true
[edit] This is something I didn't know before this question: start_with
takes multiple arguments.
'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
The correct answer is as @JaKu pointed out. Tomcat is confining the access to localhost to make it secure. This is as it should be. Port forwarding to tomcat is the correct thing to do, preferably under something secure like SSH.
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);
/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
I see a lot of good answers here, but none that directly address the lack of a StringStream class in C#. So I have written one of my own...
public class StringStream : Stream
{
private readonly MemoryStream _memory;
public StringStream(string text)
{
_memory = new MemoryStream(Encoding.UTF8.GetBytes(text));
}
public StringStream()
{
_memory = new MemoryStream();
}
public StringStream(int capacity)
{
_memory = new MemoryStream(capacity);
}
public override void Flush()
{
_memory.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _memory.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _memory.Seek(offset, origin);
}
public override void SetLength(long value)
{
_memory.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
_memory.Write(buffer, offset, count);
return;
}
public override bool CanRead => _memory.CanRead;
public override bool CanSeek => _memory.CanSeek;
public override bool CanWrite => _memory.CanWrite;
public override long Length => _memory.Length;
public override long Position
{
get => _memory.Position;
set => _memory.Position = value;
}
public override string ToString()
{
return System.Text.Encoding.UTF8.GetString(_memory.GetBuffer(), 0, (int) _memory.Length);
}
public override int ReadByte()
{
return _memory.ReadByte();
}
public override void WriteByte(byte value)
{
_memory.WriteByte(value);
}
}
An example of its use...
string s0 =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\r\n" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud\r\n" +
"exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\r\n" +
"in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint\r\n" +
"occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\r\n";
StringStream ss0 = new StringStream(s0);
StringStream ss1 = new StringStream();
int line = 1;
Console.WriteLine("Contents of input stream: ");
Console.WriteLine();
using (StreamReader reader = new StreamReader(ss0))
{
using (StreamWriter writer = new StreamWriter(ss1))
{
while (!reader.EndOfStream)
{
string s = reader.ReadLine();
Console.WriteLine("Line " + line++ + ": " + s);
writer.WriteLine(s);
}
}
}
Console.WriteLine();
Console.WriteLine("Contents of output stream: ");
Console.WriteLine();
Console.Write(ss1.ToString());