docker-compose up --force-recreate
is one option, but if you're using it for CI, I would start the build with docker-compose rm -f
to stop and remove the containers and volumes (then follow it with pull and up).
This is what I use:
docker-compose rm -f
docker-compose pull
docker-compose up --build -d
# Run some tests
./tests
docker-compose stop -t 1
The reason containers are recreated is to preserve any data volumes that might be used (and it also happens to make up
a lot faster).
If you're doing CI you don't want that, so just removing everything should get you want you want.
Update: use up --build
which was added in docker-compose
1.7
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1 nvarchar (100) = 'test1'
DECLARE @xTxt2 nvarchar (500) = 'test2'
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2
Encountered this while using SourceTree, fixed it by
Worked like a charm.
I needed to exclude an auditing @Aspect @Component from the app context but only for a few test classes. I ended up using @Profile("audit") on the aspect class; including the profile for normal operations but excluding it (don't put it in @ActiveProfiles) on the specific test classes.
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("delete successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM suppliers";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
SqlDataReader reader = sqlcom.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(reader);
dataGridView1.DataSource = datatable;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Sounds to me like at least one of those tables has defined UserID
as a uniqueidentifier
, not an int
. Did you check the data in each table? What does SELECT TOP 1 UserID FROM
each table yield? An int
or a GUID
?
EDIT
I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership
table in your script, since it's not really one of "your" tables.
If you meant to design your tables around the aspnet_Membership
database, then why are the rest of the columns int
when that table clearly uses a uniqueidentifier
for the UserID
column?
Try wrapping your dates in single quotes, like this:
'15-6-2005'
It should be able to parse the date this way.
Yes, this is possible. As previously noted by multiple users, there seems to be a problem with excel reading the correct Byte Order Mark when the file is encoded in UTF-8. With UTF-16 it does not seem to have a problem, so it is endemic to UTF-8. The solution I use for this is adding the BOM, TWICE. For this I execute the following sed command twice:
sed -I '1s/^/\xef\xbb\xbf/' *.csv
, where the wildcard can be replaced with any file name. However, this leads to a mutation of the sep= at the beginning of the .csv file. The .csv file will then open normally in excel, but with an extra row with "sep=" in the first cell. The "sep=" can also be removed in the source .csv itself, but when opening the file with VBA the delimiter should be specified:
Workbooks.Open(name, Format:=6, Delimiter:=";", Local:=True)
Format 6 is the .csv format. Set Local to true, in case there are dates in the file. If Local is not set to true the dates will be Americanized, which in some cases will corrupt the .csv format.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.
[Edit] Read this answer. It explains why multiline lambda is not a thing.
Simply put, it's unpythonic. From Guido van Rossum's blog post:
I find any solution unacceptable that embeds an indentation-based block in the middle of an expression. Since I find alternative syntax for statement grouping (e.g. braces or begin/end keywords) equally unacceptable, this pretty much makes a multi-line lambda an unsolvable puzzle.
INSERT
INTO first_table f
SELECT *
FROM second_table s
ON DUPLICATE KEY
UPDATE
s.column1 = DO_WHAT_EVER_MUST_BE_DONE_ON_KEY_CLASH(f.column1)
Here's an idea. Imagine an HSV cylinder
Define the upper and lower limits you want for the Brightness and Saturation. This defines a square cross section ring within the space.
Now, scatter N points randomly within this space.
Then apply an iterative repulsion algorithm on them, either for a fixed number of iterations, or until the points stabilise.
Now you should have N points representing N colours that are about as different as possible within the colour space you're interested in.
Hugo
It is just as simple as this.....
//import java.io.FileInputStream;
//import java.io.FileInputStream;
Properties prop = new Properties();
//c:\\myapp\\config.ini is the location of the ini file
//ini file should look like host=localhost
prop.load(new FileInputStream("c:\\myapp\\config.ini"));
String host = prop.getProperty("host");
I couldn't properly follow the other answers, here's more of a dummies guide...
You can do this either way round to go trunk -> branch
or branch -> trunk
. I always first do trunk -> branch
fix any conflicts there and then merge branch -> trunk
.
Use child.setLocation(0, 0)
on the button, and parent.setLayout(null)
. Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...)
and letting the OS position the frame.
//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");
public Control() {
//JFrame layout
this.setLayout(null);
//JPanel layout
pnlButton.setLayout(null);
//Adding to JFrame
pnlButton.add(btnAddFlight);
add(pnlButton);
// postioning
pnlButton.setLocation(0,0);
You have two ways to enable it.
First, you can set the absolute path of the php module file in your httpd.conf file like this:
LoadModule php5_module /path/to/mods-available/libphp5.so
Second, you can link the module file to the mods-enabled directory:
ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so
ALTER TABLE [dbo].[TableName]
ALTER COLUMN ColumnName VARCHAR(Max) NULL
The Navigation Drawer pattern is officially described in the Android documentation!
Check out the following links:
Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.
I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).
Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".
To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.
With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,
One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView
in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.
The G+ app uses a ViewPager
to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.
On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).
You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).
Add a float to dimens.xml:
<item format="float" name="my_dimen" type="dimen">1.2</item>
To reference from XML:
<EditText
android:lineSpacingMultiplier="@dimen/my_dimen"
...
To read this value programmatically you can use ResourcesCompat.getFloat
from androidx.core
Gradle dependency:
implementation("androidx.core:core:${version}")
Usage:
import androidx.core.content.res.ResourcesCompat;
...
float value = ResourcesCompat.getFloat(context.getResources(), R.dimen.my_dimen);
Maybe using Where() before First() can help you, as my problem has been solved in this case.
var documentRow = _dsACL.Documents.Where(o => o.ID == id).FirstOrDefault();
I needed something similar (left, center and right aligned items), but with ability to mark centered items as active. What worked for me was:
http://www.bootply.com/CSI2KcCoEM
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="navbar-left"><a href="#">Left 1</a></li>
<li class="navbar-left"><a href="#">Left 2</a></li>
<li class="active"><a href="#">Center 1</a></li>
<li><a href="#">Center 2</a></li>
<li><a href="#">Center 3</a></li>
<li class="navbar-right"><a href="#">Right 1</a></li>
<li class="navbar-right"><a href="#">Right 2</a></li>
</ul>
</div>
</nav>
CSS:
@media (min-width: 768px) {
.navbar-nav {
width: 100%;
text-align: center;
}
.navbar-nav > li {
float: none;
display: inline-block;
}
.navbar-nav > li.navbar-right {
float: right !important;
}
}
I found this nugget at the link following. It worked perfect for me and only took 5 seconds.
As of VirtualBox 4 they added support for expansion.
VBoxManage modifyhd filename.vdi --resize 46080
That will resize a virtual disk image to 45GB.
https://superuser.com/questions/172651/increasing-disk-space-on-virtualbox
echo "Subject: test" | /usr/sbin/sendmail [email protected]
This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935's answer. So credit goes there.
You mus use nvarchar text too. that's mean you have to simply had a "N" before your massive string and that's it! no limitation anymore
DELARE @SQL NVARCHAR(MAX);
SET @SQL = N'SomeMassiveString > 4000 chars...';
EXEC(@SQL);
GO
A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.
For example, If I do this:
Integer myInteger = null;
int n = myInteger.intValue();
The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.
What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!
Just revisiting the old thread you can debug PHPMailer in depth by adding:
print_r(error_get_last());
this will print out the exact error for you which is causing the default php mail() to break.
Hope it helps somebody.
Here are some blog posts with numerous examples of ways to load assemblies in PowerShell v1, v2 and v3.
The ways include:
v1.0 How To Load .NET Assemblies In A PowerShell Session
v2.0 Using CSharp (C#) code in PowerShell scripts 2.0
v3.0 Using .NET Framework Assemblies in Windows PowerShell
That looks like it might belong in the select statement:
SELECT id, col1, col2, col3, (CASE WHEN table3.col3 IS NULL THEN table2.col3 AS col4 ELSE table3.col3 as col4 END)
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
LEFT OUTER JOIN table3
ON table1.id = table3.id
Lacking a complete example, here is my little test script for getting user input when working with React and TypeScript. Based partially on the other comments and this link https://medium.com/@basarat/strongly-typed-refs-for-react-typescript-9a07419f807#.cdrghertm
/// <reference path="typings/react/react-global.d.ts" />
// Init our code using jquery on document ready
$(function () {
ReactDOM.render(<ServerTime />, document.getElementById("reactTest"));
});
interface IServerTimeProps {
}
interface IServerTimeState {
time: string;
}
interface IServerTimeInputs {
userFormat?: HTMLInputElement;
}
class ServerTime extends React.Component<IServerTimeProps, IServerTimeState> {
inputs: IServerTimeInputs = {};
constructor() {
super();
this.state = { time: "unknown" }
}
render() {
return (
<div>
<div>Server time: { this.state.time }</div>
<input type="text" ref={ a => this.inputs.userFormat = a } defaultValue="s" ></input>
<button onClick={ this._buttonClick.bind(this) }>GetTime</button>
</div>
);
}
// Update state with value from server
_buttonClick(): void {
alert(`Format:${this.inputs.userFormat.value}`);
// This part requires a listening web server to work, but alert shows the user input
jQuery.ajax({
method: "POST",
data: { format: this.inputs.userFormat.value },
url: "/Home/ServerTime",
success: (result) => {
this.setState({ time : result });
}
});
}
}
These two steps worked for me!
Step 1:
git remote set-url origin https://github.com/username/example_repo.git
Step 2:
git push --set-upstream -f origin main
Step 3:
your username and password for github
On step 2, -f
is actually required because of the rebase, quote from this post.
If you propagate the exception by declaring the throws directive in the signature of the current method, then somewhere up the line or call stack a try/catch construct must be used to handle the exception.
I am installing pyfuzzy
but is is not in PyPI; it returns the message: No matching distribution found for pyfuzzy
.
I tried the accepted answer
pip install --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy
But it does not work either and returns the following error:
Ignoring indexes: https://pypi.python.org/simple Collecting pyfuzzy Could not find a version that satisfies the requirement pyfuzzy (from versions: ) No matching distribution found for pyfuzzy
At last , I have found a simple good way there: https://pip.pypa.io/en/latest/reference/pip_install.html
Install a particular source archive file.
$ pip install ./downloads/SomePackage-1.0.4.tar.gz
$ pip install http://my.package.repo/SomePackage-1.0.4.zip
So the following command worked for me:
pip install ../pyfuzzy-0.1.0.tar.gz.
Hope it can help you.
This error was raised because your Controller method name is not same as the View's name.
If you right click on your controller method and select Go To View (Ctrl+M,Ctrl+G), it will either open a View (success) or complain that it couldn't find one (what you're seeing).
return view("viewName")
in the method.For Swift 3
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
//Landscape
}
else if UIDevice.current.orientation.isFlat {
//isFlat
}
else {
//Portrait
}
}
Say your string is:
let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;
You want to split the string by the following delimiters:
You could split the string like this:
let rawElements = str.split(new RegExp('[,;\n]', 'g'));
Finally, you may need to trim the elements in the array:
let elements = rawElements.map(element => element.trim());
try the following to change your array to 1D
a.reshape((1, -1))
You are missing spring-security-web-3.1.X.RELEASE.jar
from your classpath
Hard to believe adding a custom icon is so complicated. I found a similar solution to those posted above, but for me, I could not get the icon to display until I added the viewBox info, which I got directly from opening the SVG in a text editor.
//customIcon.js
import React from "react";
import {ReactComponent as ImportedSVG} from "path/to/myIcon.svg";
import { SvgIcon } from '@material-ui/core';
function CustomIcon() {
return(
<SvgIcon component={ImportedSVG} viewBox="0 0 384 512"/>
)
}
export default CustomIcon;
I also ran into an error with namespaces and had to clean up the SVG before it would work, following advice from this post
Why reindexing? Just add 1 to the index:
foreach ($array as $key => $val) {
echo $key + 1, '<br>';
}
Edit After the question has been clarified: You could use the array_values
to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1.
Better make the google object convert as a javascript readable object first.
Create two functions like below and call it passing google map return object.
function getShortAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.short_name;
});
return address;
}
function getLongAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.long_name;
});
return address;
}
Then user can access names like below.
var addressObj = getLongAddressObject(object);
var country = addressObj.country; //Sri Lanka
All address parts are like below.
administrative_area_level_1: "Western Province"
administrative_area_level_2: "Colombo"
country: "Sri Lanka"
locality: "xxxx xxxxx"
political: "xxxxx"
route: "xxxxx - xxxxx Road"
street_number: "No:00000"
I think all the answers here are relevant however if, like me, you are looking for where Visual Studio takes the template from when it creates a new version of the applicationHost.config then you can look here:
C:\Program Files (x86)\IIS Express\config\templates\PersonalWebServer
This happens a lot if you are often working on multiple branches of the same project and pressing 'debug' in a lot of them. Making an edit here will ensure that edit propagates to any new project/solution folders that get created.
Answer indirectly came from this answer
If you are willing to use SourceTree (which I strongly recommend), you can right click your branch and chose 'Rename'.
it is safe to delete the inetpub it is only a cache.
Got this off an Android forum where I asked the same question. Hope this helps somebody else.
On a terminal emulator on the phone:
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
Then on the cmd prompt, do the adb push
Here's an approach that leaves the default collapse behavior unchanged while allowing a new section of navigation to always remain visible. Its an augmentation of navbar
; navbar-header-menu
is a CSS class I have created and is not part of Bootstrap proper.
Place this in the navbar-header
element after navbar-brand
:
<div class="navbar-header-menu">
<ul class="nav navbar-nav">
<li class="active"><a href="#">I'm always visible</a></li>
</ul>
<form class="navbar-form" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
Add this CSS:
.navbar-header-menu {
float: left;
}
.navbar-header-menu > .navbar-nav {
float: left;
margin: 0;
}
.navbar-header-menu > .navbar-nav > li {
float: left;
}
.navbar-header-menu > .navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
.navbar-header-menu > .navbar-nav .open .dropdown-menu {
position: absolute;
float: left;
width: auto;
margin-top: 0;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0,0,0,.15);
-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
.navbar-header-menu > .navbar-form {
float: left;
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-header-menu > .navbar-form > .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-header-menu > .navbar-left {
float: left;
}
.navbar-header-menu > .navbar-right {
float: right !important;
}
.navbar-header-menu > *.navbar-right:last-child {
margin-right: -15px !important;
}
Check the fiddle: http://jsfiddle.net/L2txunqo/
Caveat: navbar-right
can be used to sort elements visually but is not guaranteed to pull the element to the furthest right portion of the screen. The fiddle demonstrates that behavior with the navbar-form
.
in my case, the error was with www-data user but not with normal user on development. The error was a problem to initialize an x display for this user. So, the problem was resolved running my selenium test without opening a browser window, headless:
opts.set_headless(True)
This program is the bug free and enhanced version of the above MD5 cracker that reads the file containing list of hashed passwords and checks it against hashed word from the English dictionary word list. Hope it is helpful.
I downloaded the English dictionary from the following link https://github.com/dwyl/english-words
# md5cracker.py
# English Dictionary https://github.com/dwyl/english-words
import hashlib, sys
hash_file = 'exercise\hashed.txt'
wordlist = 'data_sets\english_dictionary\words.txt'
try:
hashdocument = open(hash_file,'r')
except IOError:
print('Invalid file.')
sys.exit()
else:
count = 0
for hash in hashdocument:
hash = hash.rstrip('\n')
print(hash)
i = 0
with open(wordlist,'r') as wordlistfile:
for word in wordlistfile:
m = hashlib.md5()
word = word.rstrip('\n')
m.update(word.encode('utf-8'))
word_hash = m.hexdigest()
if word_hash==hash:
print('The word, hash combination is ' + word + ',' + hash)
count += 1
break
i += 1
print('Itiration is ' + str(i))
if count == 0:
print('The hash given does not correspond to any supplied word in the wordlist.')
else:
print('Total passwords identified is: ' + str(count))
sys.exit()
XCode 6.1.1, and multiple apple developer accounts
Another answer for this already fairly comprehensive mix: I came across this issue again today, and this time it was due to my having multiple apple accounts. I needed to first add the 2nd developer account in XCode > Preferences > Accounts > +
Next I needed to actually explicitly enable In-App Purchase in the app (I did not need to do this previously). XCode > (the app window) > Targets > Capabilities > In-App Purchase ON (and at this stage I was given the option to choose the correct certificate)
Note that I had already added the Push enabled certificate by double clicking it in Finder.
You can do the following steps:
First isolate the column (by inserting a blank column before and/or after the column you want to count the unique values if there are any adjacent columns;
Then select the whole column, go to 'Data' > 'Advanced Filter' and check the checkbox 'Unique records only'. This will hide all non-unique records so you can count the unique ones by selecting the whole column.
If you use @JsonManagedReference
, @JsonBackReference
or @JsonIgnore
annotation it ignore some fields and solve Infinite Recursion with Jackson JSON.
But if you use @JsonIdentityInfo
which also avoid the Infinite Recursion and you can get all the fields values, so I suggest that you use @JsonIdentityInfo
annotation.
@JsonIdentityInfo(generator= ObjectIdGenerators.UUIDGenerator.class, property="@id")
Refer this article https://www.toptal.com/javascript/bidirectional-relationship-in-json to get good understanding about @JsonIdentityInfo
annotation.
length
is a property, not a method. You can't call it, hence you don't need parenthesis ()
:
function getlength(number) {
return number.toString().length;
}
UPDATE: As discussed in the comments, the above example won't work for float numbers. To make it working we can either get rid of a period with String(number).replace('.', '').length
, or count the digits with regular expression: String(number).match(/\d/g).length
.
In terms of speed potentially the fastest way to get number of digits in the given number is to do it mathematically. For positive integers there is a wonderful algorithm with log10
:
var length = Math.log(number) * Math.LOG10E + 1 | 0; // for positive integers
For all types of integers (including negatives) there is a brilliant optimised solution from @Mwr247, but be careful with using Math.log10
, as it is not supported by many legacy browsers. So replacing Math.log10(x)
with Math.log(x) * Math.LOG10E
will solve the compatibility problem.
Creating fast mathematical solutions for decimal numbers won't be easy due to well known behaviour of floating point math, so cast-to-string approach will be more easy and fool proof. As mentioned by @streetlogics fast casting can be done with simple number to string concatenation, leading the replace solution to be transformed to:
var length = (number + '').replace('.', '').length; // for floats
You've the following possibilities to solve issue with CERTIFICATE_VERIFY_FAILED
:
--index-url=http://pypi.python.org/simple/
).Use --cert <trusted.pem>
or CA_BUNDLE
variable to specify alternative CA bundle.
E.g. you can go to failing URL from web-browser and import root certificate into your system.
Run python -c "import ssl; print(ssl.get_default_verify_paths())"
to check the current one (validate if exists).
SSL_CERT_DIR
, SSL_CERT_FILE
) which can be used to specify different certificate databasePEP-476.--trusted-host <hostname>
to mark the host as trusted.verify=False
for requests.get
(see: SSL Cert Verification).--proxy <proxy>
to avoid certificate checks.Read more at: TLS/SSL wrapper for socket objects - Verifying certificates.
From the JSON standard:
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
(emphasis mine).
So, no you can't guarantee the order.
JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required. Allowing \/
helps when embedding JSON in a <script>
tag, which doesn't allow </
inside strings, like Seb points out.
Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/"
. (Yuck)
Previous answer doesn't work for me :( But it's OK like that :)
$data = json_decode(
iconv(
mb_detect_encoding($data, mb_detect_order(), true),
'CP1252',
json_encode($data)
)
, true)
Or another typical standard in the industry is to have a Constants.java named class file containing all the constants to be used all over the project.
While we're big fans of Deis (deis.io) and are actively deploying to it, there are other Heroku like PaaS style deployment solutions out there, including:
Longshoreman from the Wayfinder folks:
https://github.com/longshoreman/longshoreman
Decker from the CloudCredo folks, using CloudFoundry:
http://www.cloudcredo.com/decker-docker-cloud-foundry/
As for straight up orchestration, NewRelic's opensource Centurion project seems quite promising:
As I got this case at my own and the answers here didn't help me, my situation was because of I downgraded the targetSdkVersion
in gradle app module file from 24 to 22 for some reason, and apparently the apk doesn't accept another one with downgraded targetSdkVersion
to be installed over it.
So, once I changed it back to 24 the error disappeared and app installed correctly.
First you need to determine the revision ID of the last known commit. You can use HEAD^
or HEAD~{1}
if you know you need to reverse exactly one commit.
git reset --hard <revision_id_of_last_known_good_commit>
git push --force
Below are code snippets to create and delete a cookie. The cookie is set for 1 day.
// 1 Day = 24 Hrs = 24*60*60 = 86400.
By using max-age:
document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";
document.cookie = "cookieName=; max-age=- (any digit); path=/;";
By using expires:
var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
document.cookie = "cookieName=cookieValue; expires=" + expires + 86400) + ";path=/;"
You can run the following command to determine if postgress is running:
$ pg_ctl status
You'll also want to set the PGDATA
environment variable.
Here's what I have in my ~/.bashrc
file for postgres:
export PGDATA='/usr/local/var/postgres'
export PGHOST=localhost
alias start-pg='pg_ctl -l $PGDATA/server.log start'
alias stop-pg='pg_ctl stop -m fast'
alias show-pg-status='pg_ctl status'
alias restart-pg='pg_ctl reload'
To get them to take effect, remember to source it like so:
$ . ~/.bashrc
Now, try it and you should get something like this:
$ show-pg-status
pg_ctl: server is running (PID: 11030)
/usr/local/Cellar/postgresql/9.2.4/bin/postgres
go through the below coding to get the separate group replacement.
new_bib = Regex.Replace(new_bib, @"(?s)(\\bibitem\[[^\]]+\]\{" + pat4 + @"\})[\s\n\v]*([\\\{\}a-zA-Z\.\s\,\;\\\#\\\$\\\%\\\&\*\@\\\!\\\^+\-\\\=\\\~\\\:\\\" + dblqt + @"\\\;\\\`\\\']{20,70})", delegate(Match mts)
{
var fg = mts.Groups[0].Value.ToString();
var fs = mts.Groups[1].Value.ToString();
var fss = mts.Groups[2].Value.ToString();
fss = Regex.Replace(fss, @"[\\\{\}\\\#\\\$\\\%\\\&\*\@\\\!\\\^+\-\\\=\\\~\\\:\\\" + dblqt + @"\\\;\\\`\\\']+", "");
return "<augroup>" + fss + "</augroup>" + fs;
}, RegexOptions.IgnoreCase);
To clarify and update @neo useful answer and the original question. A clean solution consists of installing Pillow, which is an updated version of the Python Imaging Library (PIL). This is done using
pip install pillow
Once Pillow is installed, the standard Matplotlib commands
import matplotlib.pyplot as plt
plt.plot([1, 2])
plt.savefig('image.jpg')
will save the figure into a JPEG file and will not generate a ValueError any more.
Contrary to @amillerrhodes answer, as of Matplotlib 3.1, JPEG files are still not supported. If I remove the Pillow package I still receive a ValueError about an unsupported file type.
export user="your_new_owner"
export dbname="your_db_name"
cat <<EOF | docker run -i --rm --link postgres:postgres postgres sh -c "psql -h \$POSTGRES_PORT_5432_TCP_ADDR -p \$POSTGRES_PORT_5432_TCP_PORT -U postgres -d $dbname" | grep ALTER | docker run -i --rm --link postgres:postgres postgres sh -c "psql -h \$POSTGRES_PORT_5432_TCP_ADDR -p \$POSTGRES_PORT_5432_TCP_PORT -U postgres -d $dbname"
SELECT 'ALTER TABLE '||schemaname||'.'||tablename||' OWNER TO $user;' FROM pg_tables WHERE schemaname = 'public';
SELECT 'ALTER SEQUENCE '||relname||' OWNER TO $user;' FROM pg_class WHERE relkind = 'S';
EOF
class Phone {
public Phone getMsg() {
System.out.println("phone...");
return new Phone();
}
}
class Samsung extends Phone{
@Override
public Samsung getMsg() {
System.out.println("samsung...");
return new Samsung();
}
public static void main(String[] args) {
Phone p=new Samsung();
p.getMsg();
}
}
This will remove all underlines from all links:
a {text-decoration: none; }
If you have specific links that you want to apply this to, give them a class name, like nounderline
and do this:
a.nounderline {text-decoration: none; }
That will apply only to those links and leave all others unaffected.
This code belongs in the <head>
of your document or in a stylesheet:
<head>
<style type="text/css">
a.nounderline {text-decoration: none; }
</style>
</head>
And in the body:
<a href="#" class="nounderline">Link</a>
I found this question because having trouble with configparser.ConfigParser().read(fp)
when opening files with UTF8 BOM header.
For those who are looking for a solution to remove the header so that ConfigPhaser could open the config file instead of reporting an error of:
File contains no section headers
, please open the file like the following:
configparser.ConfigParser().read(config_file_path, encoding="utf-8-sig")
This could save you tons of effort by making the remove of the BOM header of the file unnecessary.
(I know this sounds unrelated, but hopefully this could help people struggling like me.)
Swift 2.0
extension Dictionary {
mutating func unionInPlace(dictionary: Dictionary) {
dictionary.forEach { self.updateValue($1, forKey: $0) }
}
func union(var dictionary: Dictionary) -> Dictionary {
dictionary.unionInPlace(self)
return dictionary
}
}
BEWARE : Order of update columns is critical
GOOD: What I want saves existing Value of Status to PrevStatus
UPDATE Collections SET PrevStatus=Status, Status=44 WHERE ID=1487496;
BAD: Status & PrevStatus both end up as 44
UPDATE Collections SET Status=44, PrevStatus=Status WHERE ID=1487496;
I had a similar problem and had to convert the URL from string to Uri object using:
Uri myUri = new Uri(URLInStringFormat, UriKind.Absolute);
(URLInStringFormat is your URL) Try to connect using the Uri instead of the string as:
WebClient client = new WebClient();
client.OpenRead(myUri);
Components
@Component
meta-data annotation.@View
decorator or templateurl template are mandatory in the component.Directive
@Directive
meta-data annotation.Sources:
http://www.codeandyou.com/2016/01/difference-between-component-and-directive-in-Angular2.html
select * from Tran_LibraryBooksTrans LBT left join
Tran_LibraryIssuedBooks LIB ON case WHEN LBT.IssuedTo='SN' AND
LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when LBT.IssuedTo='SM'
AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 WHEN
LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
ELSE 0 END`enter code here`select * from Tran_LibraryBooksTrans LBT
left join Tran_LibraryIssuedBooks LIB ON case WHEN LBT.IssuedTo='SN'
AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when
LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN
1 ELSE 0 END
Add 'justified' class to 'ul'.
<ul class="nav navbar-nav justified">
CSS:
.justified {
position:absolute;
left:50%;
}
Now, calculate its 'margin-left' in order to align it to center
.
// calculating margin-left to align it to center;
var width = $('.justified').width();
$('.justified').css('margin-left', '-' + (width / 2)+'px');
As you probably all ready know if you use the following line of code, your app will be rejected by Apple
NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];
here is a reference
http://ayeapi.blogspot.com/2009/12/sbformatphonenumber-is-lie.html
you can use the following information instead
NSString *phoneName = [[UIDevice currentDevice] name];
NSString *phoneUniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];
and so on
@property(nonatomic,readonly,retain) NSString *name; // e.g. "My iPhone"
@property(nonatomic,readonly,retain) NSString *model; // e.g. @"iPhone", @"iPod Touch"
@property(nonatomic,readonly,retain) NSString *localizedModel; // localized version of model
@property(nonatomic,readonly,retain) NSString *systemName; // e.g. @"iPhone OS"
@property(nonatomic,readonly,retain) NSString *systemVersion; // e.g. @"2.0"
@property(nonatomic,readonly) UIDeviceOrientation orientation; // return current device orientation
@property(nonatomic,readonly,retain) NSString *uniqueIdentifier; // a string unique to each device based on various hardware info.
Hope this helps!
mapStateToProps()
is a utility which helps your component get updated state(which is updated by some other components),
mapDispatchToProps()
is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)
This line calls the selector secondMethod after 3 seconds:
[self performSelector:@selector(secondMethod) withObject:nil afterDelay:3.0 ];
Use it on your second operation with your desired delay. If you have a lot of code, place it in its own method and call that method with performSelector:
. It wont block the UI like sleep
Edit: If you do not want a second method you could add a category to be able to use blocks with performSelector:
@implementation NSObject (PerformBlockAfterDelay)
- (void)performBlock:(void (^)(void))block
afterDelay:(NSTimeInterval)delay
{
block = [block copy];
[self performSelector:@selector(fireBlockAfterDelay:)
withObject:block
afterDelay:delay];
}
- (void)fireBlockAfterDelay:(void (^)(void))block
{
block();
}
@end
Or perhaps even cleaner:
void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
dispatch_get_current_queue(), block);
}
You've already got the correct answer from Gursel Koca but I believe that there's a good chance that this is not what you really want to do. How about parsing the key-values instead?
import java.util.Enumeration;
import java.util.Hashtable;
class SplitIt {
public static void main(String args[]) {
String person = "name=john age=13 year=2001";
for (String p : person.split("\\s")) {
String[] keyValue = p.split("=");
System.out.println(keyValue[0] + " = " + keyValue[1]);
}
}
}
output:
name = john
age = 13
year = 2001
print "bla: ", $myvar =~ tr{a}{b},"\n";
Just came across the same problem and the null-coalescing operator with SelectSingleNode worked a treat, assigning null with string.Empty
foreach (XmlNode txElement in txElements)
{
var txStatus = txElement.SelectSingleNode(".//ns:TxSts", nsmgr).InnerText ?? string.Empty;
var endToEndId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
var paymentAmount = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).InnerText ?? string.Empty;
var paymentAmountCcy = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).Attributes["Ccy"].Value ?? string.Empty;
var clientId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
var bankSortCode = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
//TODO finish Object creation and Upsert DB
}
If you're already logged into the command line client try this:
mysql> select user();
It will output something similar to this:
+----------------+
| user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.41 sec)
In my example above, I was logged in as root
from localhost
.
To find port number and other interesting settings use this command:
mysql> show variables;
Yes, you can install Postman using these commands:
wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
sudo tar -xzf postman.tar.gz -C /opt
rm postman.tar.gz
sudo ln -s /opt/Postman/Postman /usr/bin/postman
You can also get Postman to show up in the Unity Launcher:
cat > ~/.local/share/applications/postman.desktop <<EOL
[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=postman
Icon=/opt/Postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
EOL
You don't need node.js or any other dependencies with a standard Ubuntu dev install.
See more at our blog post at https://blog.bluematador.com/posts/postman-how-to-install-on-ubuntu-1604/.
EDIT: Changed icon.png location. Latest versions of Postman changed their directory structure slightly.
As the error states - the database is not open - it was previously shut down, and someone left it in the middle of the startup process. They may either be intentional, or unintentional (i.e., it was supposed to be open, but failed to do so).
Assuming that's nothing wrong with the database itself, you could open it with a simple statement:(Since the question is asked specifically in the context of SQLPlus, kindly remember to put a statement terminator(Semicolon) at the end mandatorily, otherwise, it will result in an error.)
ALTER DATABASE OPEN;
The easiest option is to just use the list() command. However, if you don't want to use it or it dose not work for some bazaar reason, you can always use this method.
word = 'foo'
splitWord = []
for letter in word:
splitWord.append(letter)
print(splitWord) #prints ['f', 'o', 'o']
I might also look into adding explicit samples for each controller/action, as well covered here:
i.e. config.SetActualResponseType(typeof(SomeType), "Values", "Get");
If you have multiple headers then you might want to use the following:
curl -X POST --header "Content-Type:application/json" --header "X-Auth:AuthKey" --data @hello.json Your_url
.aspx is a rendered page. If you need a view, use an .aspx page. If all you need is backend functionality but will be staying on the same view, use an .ashx page.
I had c++ codes in my project but i didn't have NDK
installed, installing it solved the problem
Selenium WebDriver Java code:
Download Gecko Driver from https://github.com/mozilla/geckodriver/releases based on your platform. Extract it in a location by your choice. Write the following code:
System.setProperty("webdriver.gecko.driver", "D:/geckodriver-v0.16.1-win64/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.lynda.com/Selenium-tutorials/Mastering-Selenium-Testing-Tools/521207-2.html");
Using the length of the list would be the fastest solution to check if an index exists:
def index_exists(ls, i):
return (0 <= i < len(ls)) or (-len(ls) <= i < 0)
This also tests for negative indices, and most sequence types (Like ranges
and str
s) that have a length.
If you need to access the item at that index afterwards anyways, it is easier to ask forgiveness than permission, and it is also faster and more Pythonic. Use try: except:
.
try:
item = ls[i]
# Do something with item
except IndexError:
# Do something without the item
This would be as opposed to:
if index_exists(ls, i):
item = ls[i]
# Do something with item
else:
# Do something without the item
They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.
If you're experiencing a different behaviour, it's time to change for another DBMS.
You can use Apache Commons CollectionUtils:
if(CollectionUtils.containsAny(list1,list2)) {
// do whatever you want
} else {
// do other thing
}
This assumes that you have properly overloaded the equals functionality for your custom objects.
my config.inc.php file in the phpmyadmin folder. Change username and password to the one you have set for your database.
<?php
/*
* 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 and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'enter_username_here';
$cfg['Servers'][$i]['password'] = 'enter_password_here';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
/*
* End of servers configuration
*/
?>
My way:
private static int hexToDec(String hex) {
return Integer.parseInt(hex, 16);
}
Your userPhotos
array is option-typed, you should retrieve the actual underlying object with !
(if you want an error in case the object isn't there) or ?
(if you want to receive nil
in url):
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
But to preserve safe nil handling, you better use functional approach, for instance, with map
, like this:
let urls = userPhotos?.map{ $0.url }
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
DISPLAY=pygame.display.set_mode((500,400),0,32)
WHITE=(255,255,255)
BLUE=(0,0,255)
DISPLAY.fill(WHITE)
pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
main()
This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect
to go about this, and you add the DISPLAY
constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.
Look up pygame.org for more info
Adapted Paul Dixon's answer to Excel, this works perfectly.
=POWER(2,CEILING.MATH(LOG(A1)/LOG(2)))
You might also consider using the open source SpringSandwich library which lets you directly annotate in your Spring Boot controllers which interceptors to apply, much in the same way you annotate your url routes.
That way, no typo-prone Strings floating around -- SpringSandwich's method and class annotations easily survive refactoring and make it clear what's being applied where. (Disclosure: I'm the author).
You'll need to save as a blob, LONGBLOB datatype in mysql will work.
Ex:
CREATE TABLE 'test'.'pic' (
'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'caption' VARCHAR(45) NOT NULL,
'img' LONGBLOB NOT NULL,
PRIMARY KEY ('idpic')
)
As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.
Typing brew install cmake
as you did installs cmake
. Now you can type cmake
and use it.
If typing cmake
doesn’t work make sure /usr/local/bin
is your PATH
. You can see it with echo $PATH
. If you don’t see /usr/local/bin
in it add the following to your ~/.bashrc
:
export PATH="/usr/local/bin:$PATH"
Then reload your shell session and try again.
(all the above assumes Homebrew is installed in its default location, /usr/local
. If not you’ll have to replace /usr/local
with $(brew --prefix)
in the export
line)
If preg_match
did not find a match, $matches
is an empty array. So you should check if preg_match
found an match before accessing $matches[0]
, for example:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
Best way is to Use a Python Web Frame Work you can choose Django/Flask. I will suggest you to Use Django because it's more powerful. Here is Step by guide to get complete your task :
pip install django
django-admin createproject buttonpython
then you have to create a file name views.py in buttonpython directory.
write below code in views.py:
from django.http import HttpResponse
def sample(request):
#your python script code
output=code output
return HttpResponse(output)
Once done navigate to urls.py and add this stanza
from . import views
path('', include('blog.urls')),
Now go to parent directory and execute manage.py
python manage.py runserver 127.0.0.1:8001
Step by Step Guide in Detail: Run Python script on clicking HTML button
In .Net 2.0 I`m pretty sure about this solution:
public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
List<T> uniques = new List<T>();
foreach (T item in source)
{
if (!uniques.Contains(item)) uniques.Add(item);
}
return uniques;
}
If rownumber() over(...)
is available for you ....
select OrderNO,
PartCode,
Quantity
from (select OrderNO,
PartCode,
Quantity,
row_number() over(partition by OrderNO order by DateEntered desc) as rn
from YourTable) as T
where rn = 1
For Staging Area vs Repository(last commit) comparison use
$git diff --staged
The command compares your staged($ git add fileName
) changes to your last commit. If you want to see what you’ve staged that will go into your next commit, you can use git diff --staged. This command compares your staged changes to your last commit.
For Working vs Staging comparison use
$ git diff
The command compares what is in your working directory with what is in your staging area. It’s important to note that git diff by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. If you’ve staged all of your changes($ git add fileName
), git diff will give you no output.
Also, if you stage a file($ git add fileName
) and then edit it, you can use git diff to see the changes in the file that are staged and the changes that are unstaged.
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
The file default.properties
is by default read only, changing that worked for me.
Camille's solution worked. Turned it into a basic PHP function, which writes up the SQL statement. Hope this helps someone else.
function _bulk_sql_update_query($table, $array)
{
/*
* Example:
INSERT INTO mytable (id, a, b, c)
VALUES (1, 'a1', 'b1', 'c1'),
(2, 'a2', 'b2', 'c2'),
(3, 'a3', 'b3', 'c3'),
(4, 'a4', 'b4', 'c4'),
(5, 'a5', 'b5', 'c5'),
(6, 'a6', 'b6', 'c6')
ON DUPLICATE KEY UPDATE id=VALUES(id),
a=VALUES(a),
b=VALUES(b),
c=VALUES(c);
*/
$sql = "";
$columns = array_keys($array[0]);
$columns_as_string = implode(', ', $columns);
$sql .= "
INSERT INTO $table
(" . $columns_as_string . ")
VALUES ";
$len = count($array);
foreach ($array as $index => $values) {
$sql .= '("';
$sql .= implode('", "', $array[$index]) . "\"";
$sql .= ')';
$sql .= ($index == $len - 1) ? "" : ", \n";
}
$sql .= "\nON DUPLICATE KEY UPDATE \n";
$len = count($columns);
foreach ($columns as $index => $column) {
$sql .= "$column=VALUES($column)";
$sql .= ($index == $len - 1) ? "" : ", \n";
}
$sql .= ";";
return $sql;
}
This solution works like a charm (updated in 2017 to honor that log_format needs to be in the http part of the nginx config):
log_format postdata $request_body;
server {
# (...)
location = /post.php {
access_log /var/log/nginx/postdata.log postdata;
fastcgi_pass php_cgi;
}
}
I think the trick is making nginx believe that you will call a cgi script.
As mentioned by a couple of others, there isn't a way to style an element's parent/s using just CSS but the following works with jQuery:
$("a.active").parents('li').css("property", "value");
Are you using virtualenv
? If yes, deactivate the virtualenv. If you are not using, it is already installed widely (system level). Try to upgrade package.
pip install flake8 --upgrade
try this: (create extension method)
public static List<T> ExecuteQuery<T>(this dbContext db, string query) where T : class, new()
{
using (var command = db.Database.GetDbConnection().CreateCommand())
{
command.CommandText = query;
command.CommandType = CommandType.Text;
db.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
var lst = new List<T>();
var lstColumns = new T().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
while (reader.Read())
{
var newObject = new T();
for (var i = 0; i < reader.FieldCount; i++)
{
var name = reader.GetName(i);
PropertyInfo prop = lstColumns.FirstOrDefault(a => a.Name.ToLower().Equals(name.ToLower()));
if (prop == null)
{
continue;
}
var val = reader.IsDBNull(i) ? null : reader[i];
prop.SetValue(newObject, val, null);
}
lst.Add(newObject);
}
return lst;
}
}
}
Usage:
var db = new dbContext();
string query = @"select ID , Name from People where ... ";
var lst = db.ExecuteQuery<PeopleView>(query);
my model: (not in DbSet
):
public class PeopleView
{
public int ID { get; set; }
public string Name { get; set; }
}
tested in
.netCore 2.2 and 3.0
.
Note: this solution has the slow performance
I ended up finding it through the IntelliSense on the get()
function. So, I'll post it here for anyone who is looking for similar information.
Anyways, the syntax is nearly identical, but slightly different. Instead of using URLSearchParams()
the parameters need to be initialized as HttpParams()
and the property within the get()
function is now called params
instead of search
.
import { HttpClient, HttpParams } from '@angular/common/http';
getLogs(logNamespace): Observable<any> {
// Setup log namespace query parameter
let params = new HttpParams().set('logNamespace', logNamespace);
return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
}
I actually prefer this syntax as its a little more parameter agnostic. I also refactored the code to make it slightly more abbreviated.
getLogs(logNamespace): Observable<any> {
return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, {
params: new HttpParams().set('logNamespace', logNamespace)
})
}
Multiple Parameters
The best way I have found thus far is to define a Params
object with all of the parameters I want to define defined within. As @estus pointed out in the comment below, there are a lot of great answers in This Question as to how to assign multiple parameters.
getLogs(parameters) {
// Initialize Params Object
let params = new HttpParams();
// Begin assigning parameters
params = params.append('firstParameter', parameters.valueOne);
params = params.append('secondParameter', parameters.valueTwo);
// Make the API call using the new parameters.
return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
Multiple Parameters with Conditional Logic
Another thing I often do with multiple parameters is allow the use of multiple parameters without requiring their presence in every call. Using Lodash, it's pretty simple to conditionally add/remove parameters from calls to the API. The exact functions used in Lodash or Underscores, or vanilla JS may vary depending on your application, but I have found that checking for property definition works pretty well. The function below will only pass parameters that have corresponding properties within the parameters variable passed into the function.
getLogs(parameters) {
// Initialize Params Object
let params = new HttpParams();
// Begin assigning parameters
if (!_.isUndefined(parameters)) {
params = _.isUndefined(parameters.valueOne) ? params : params.append('firstParameter', parameters.valueOne);
params = _.isUndefined(parameters.valueTwo) ? params : params.append('secondParameter', parameters.valueTwo);
}
// Make the API call using the new parameters.
return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
public static int reverse(int x) {
int tmp = x;
int oct = 0;
int res = 0;
while (true) {
oct = tmp % 10;
tmp = tmp / 10;
res = (res+oct)*10;
if ((tmp/10) == 0) {
res = res+tmp;
return res;
}
}
}
Note with PrestoDB SQL (from Facebook), there is a shortcut:
https://prestodb.io/docs/current/functions/aggregate.html
count_if(x) ? bigint
Returns the number of TRUE input values. This function is equivalent to count(CASE WHEN x THEN 1 END)
Just create your own template for the type in Views/Shared/EditorTemplates/MyTypeEditor.vbhtml
@ModelType MyType
@ModelType MyType
@Code
Dim name As String = ViewData("ControlId")
If String.IsNullOrEmpty(name) Then
name = "MyTypeEditor"
End If
End Code
' Mark-up for MyType Editor
@Html.TextBox(name, Model, New With {.style = "width:65px;background-color:yellow"})
Invoke editor from your view with the model property:
@Html.EditorFor(Function(m) m.MyTypeProperty, "MyTypeEditor", New {.ControlId = "uniqueId"})
Pardon the VB syntax. That's just how we roll.
You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:
body{
min-width:1000px; /* Suppose you want minimum width of 1000px */
width: auto !important; /* Firefox will set width as auto */
width:1000px; /* As IE6 ignores !important it will set width as 1000px; */
}
Or:
body{
min-width:1000px; // Suppose you want minimum width of 1000px
_width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}
Step 1: Inject the $locationProvider service into the app config's constructor
Step 2: Add code line $locationProvider.html5Mode(true) to the app config's constructor.
Step 3: in the container (landing, master, or layout) page, add html tag such as <base href="/">
inside the tag.
Step 4: remove all '#" for routing config from all anchor tags. For examples, href="#home" becomes href="home"; href="#about" becomes herf="about"; href="#contact" becomes href="contact"
<ul class="nav navbar-nav">
<li><a href="home">Home</a></li>
<li><a href="about">About us</a></li>
<li><a href="contact">Contact us</a></li>
</ul>
A SysOps guy once taught me the Three-Fingered Claw technique:
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try()
your statement and code on.
(based on flying sheep comment).
yell
: print the script name and all arguments to stderr
:
$0
is the path to the script ;$*
are all arguments. >&2
means >
redirect stdout to & pipe 2
. pipe 1
would be stdout
itself. die
does the same as yell
, but exits with a non-0 exit status, which means “fail”. try
uses the ||
(boolean OR
), which only evaluates the right side if the left one failed.
$@
is all arguments again, but different. If you need to read all values from a section in properties file in a simple manner:
Your config.cfg
file layout :
[SECTION_NAME]
key1 = value1
key2 = value2
You code:
import configparser
config = configparser.RawConfigParser()
config.read('path_to_config.cfg file')
details_dict = dict(config.items('SECTION_NAME'))
This will give you a dictionary where keys are same as in config file and their corresponding values.
details_dict
is :
{'key1':'value1', 'key2':'value2'}
Now to get key1's value :
details_dict['key1']
Putting it all in a method which reads sections from config file only once(the first time the method is called during a program run).
def get_config_dict():
if not hasattr(get_config_dict, 'config_dict'):
get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
return get_config_dict.config_dict
Now call the above function and get the required key's value :
config_details = get_config_dict()
key_1_value = config_details['key1']
Generic Multi Section approach:
[SECTION_NAME_1]
key1 = value1
key2 = value2
[SECTION_NAME_2]
key1 = value1
key2 = value2
Extending the approach mentioned above, reading section by section automatically and then accessing by section name followed by key name.
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = collections.defaultdict()
for section in config.sections():
get_config_section.section_dict[section] = dict(config.items(section))
return get_config_section.section_dict
To access:
config_dict = get_config_section()
port = config_dict['DB']['port']
(here 'DB' is a section name in config file and 'port' is a key under section 'DB'.)
Javascript will do the trick here.
function load() {
var file = new XMLHttpRequest();
file.open("GET", "http://remote.tld/random.txt", true);
file.onreadystatechange = function() {
if (file.readyState === 4) { // Makes sure the document is ready to parse
if (file.status === 200) { // Makes sure it's found the file
text = file.responseText;
document.getElementById("div1").innerHTML = text;
}
}
}
}
window.onLoad = load();
In this example, you may show your menu centered.
<div id="main-menu-container">
<div id="main-menu">
//your menu
</div>
</div>
.f-nav{ /* To fix main menu container */
z-index: 9999;
position: fixed;
left: 0;
top: 0;
width: 100%;
}
#main-menu-container {
text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
display: inline-block;
width: 1024px; /* Your menu's width */
}
$("document").ready(function($){
var nav = $('#main-menu-container');
$(window).scroll(function () {
if ($(this).scrollTop() > 125) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
});
Up above, you mention having compiling your as part of your steps to reproduce, but then below you made an edit saying,
"is there a way to see on which distro a shared library was compiled on?"
Whether or not you compiled this on the same distro, and even a different version of the same distro is an important detail, especially for c++ applications.
Linking to c++ libraries, including libstdc++ can have mixed results, as far as I can tell. Here is a related question about recompiling with different versions of c++.
do we need to recompile libraries with c++11?
Basically, if you compiled against c++ on a different distro (and possibly different gcc version), this may be causing your trouble.
I think you have two options:
I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.
I order to change the dialog buttons and background colors, you will need to extend the Dialog theme, eg.:
<style name="MyDialogStyle" parent="android:Theme.Material.Light.Dialog.NoActionBar">
<item name="android:buttonBarButtonStyle">@style/MyButtonsStyle</item>
<item name="android:colorBackground">@color/white</item>
</style>
<style name="MyButtonsStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">@color/light.blue</item>
</style>
After that, you need to pass this custom style to the dialog builder, eg. like this:
AlertDialog.Builder(requireContext(), R.style.MyDialogStyle)
If you want to change the color of the text inside the dialog, you can pass a custom view to this Builder:
AlertDialog.Builder.setView(View)
or
AlertDialog.Builder.setView(@LayoutResource int)
Using ObjectAnimator
private fun slideDown(view: View) {
val height = view.height
ObjectAnimator.ofFloat(view, "translationY", 0.toFloat(), height.toFloat()).apply {
duration = 1000
start()
}
}
private fun slideUp(view: View) {
val height = view.height
ObjectAnimator.ofFloat(view, "translationY", height.toFloat(),0.toFloat()).apply {
duration = 1000
start()
}
}
Try this:
counter=0
while true; do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
break
elif [[ "$counter" -gt 20 ]]; then
echo "Counter limit reached, exit script."
exit 1
else
let counter++
echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
Explanation
break
- if files are present, it will break and allow the script to process the files.[[ "$counter" -gt 20 ]]
- if the counter variable is greater than 20, the script will exit.let counter++
- increments the counter by 1 at each pass.If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
I found a new way to do it without interfaces. You only need to add the below code to the Fragment’s onCreate() method:
//overriding the fragment's oncreate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//calling onBackPressedDispatcher and adding call back
requireActivity().onBackPressedDispatcher.addCallback(this) {
//do stuff here
}
}
The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max
key (as opposed to the dict
key) you can easily extract the highest value and its associated key.
mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)
You should set the timezone to the one of the timezones you want. let set the Indian timezone
// set default timezone
date_default_timezone_set('Asia/Kolkata');
$info = getdate();
$date = $info['mday'];
$month = $info['mon'];
$year = $info['year'];
$hour = $info['hours'];
$min = $info['minutes'];
$sec = $info['seconds'];
$current_date = "$date/$month/$year == $hour:$min:$sec";
I would use Environment.Newline when I wanted to insert a newline for a string, but not to remove all newlines from a string.
Depending on your platform you can have different types of newlines, but even inside the same platform often different types of newlines are used. In particular when dealing with file formats and protocols.
string ReplaceNewlines(string blockOfText, string replaceWith)
{
return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}
Have a look at the HttpURLConnection
class API documentation, especially setInstanceFollowRedirects()
.
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
I found a solution:
print("My message here");
It's compiling because printf
isn't type safe, since it uses variable arguments in the C sense1. printf
has no option for std::string
, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.
The easiest way to fix this, since you're using C++, is printing it normally with std::cout
, since std::string
supports that through operator overloading:
std::cout << "Follow this command: " << myString;
If, for some reason, you need to extract the C-style string, you can use the c_str()
method of std::string
to get a const char *
that is null-terminated. Using your example:
#include <iostream>
#include <string>
#include <stdio.h>
int main()
{
using namespace std;
string myString = "Press ENTER to quit program!";
cout << "Come up and C++ me some time." << endl;
printf("Follow this command: %s", myString.c_str()); //note the use of c_str
cin.get();
return 0;
}
If you want a function that is like printf
, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format
.
[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf
, that means a string with encoded type information like %d
meaning int
. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.
Just for completeness, the following is a Java solution. I am certain the same could be done in C# as well. It avoids having to specify the type anywhere in code - instead, you specify it in the strings you are trying to parse.
The problem is that there isn't any way to know which enumeration the String might match - so the answer is to solve that problem.
Instead of accepting just the string value, accept a String that has both the enumeration and the value in the form "enumeration.value". Working code is below - requires Java 1.8 or later. This would also make the XML more precise as in you would see something like color="Color.red" instead of just color="red".
You would call the acceptEnumeratedValue() method with a string containing the enum name dot value name.
The method returns the formal enumerated value.
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class EnumFromString {
enum NumberEnum {One, Two, Three};
enum LetterEnum {A, B, C};
Map<String, Function<String, ? extends Enum>> enumsByName = new HashMap<>();
public static void main(String[] args) {
EnumFromString efs = new EnumFromString();
System.out.print("\nFirst string is NumberEnum.Two - enum is " + efs.acceptEnumeratedValue("NumberEnum.Two").name());
System.out.print("\nSecond string is LetterEnum.B - enum is " + efs.acceptEnumeratedValue("LetterEnum.B").name());
}
public EnumFromString() {
enumsByName.put("NumberEnum", s -> {return NumberEnum.valueOf(s);});
enumsByName.put("LetterEnum", s -> {return LetterEnum.valueOf(s);});
}
public Enum acceptEnumeratedValue(String enumDotValue) {
int pos = enumDotValue.indexOf(".");
String enumName = enumDotValue.substring(0, pos);
String value = enumDotValue.substring(pos + 1);
Enum enumeratedValue = enumsByName.get(enumName).apply(value);
return enumeratedValue;
}
}
Below command is working on ubuntu 16.04, I am not sure it is working or not other Linux platforms.
Export SQL file:
$ mysqldump -u [user_name] -p [database_name] > [database_name.sql]
Example : mysqldump -u root -p max_development > max_development.sql
Import SQL file:
$ mysqldump -u [user_name] -p [database_name] < [file_name.sql]
Example: mysqldump -u root -p max_production < max_development.sql
Note SQL file should exist same directory
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
I found a case (overflow div > table > tr > td) in which scrolling to the relative position of the tr does not work. Instead, I had to scroll the overflow container (div) using scrollTop to <tr>.offset().top - <table>.offset().top
. Eg:
$('#container').scrollTop( $('#tr').offset().top - $('#td').offset().top )
Try this
String mess = getResources().getString(R.string.mess_1);
UPDATE
String string = getString(R.string.hello);
You can use either getString(int)
or getText(int)
to retrieve a string. getText(int)
will retain any rich text styling applied to the string.
Reference: https://developer.android.com/guide/topics/resources/string-resource.html
I just wanted to post a demo using calc() for setting rows/height, since no one did.
body {_x000D_
/* page default */_x000D_
font-size: 15px;_x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
/* demo related */_x000D_
width: 300px;_x000D_
margin-bottom: 1em;_x000D_
display: block;_x000D_
_x000D_
/* rows related */_x000D_
font-size: inherit;_x000D_
line-height: inherit;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows); */_x000D_
height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.
I created this script to solve the problem of the class img-responsive bootstrap3, and in my case this solved!
$(document).ready(function() {
if ($.browser.msie) {
var pic_real_width, pic_real_height;
var images = $(".img-responsive");
images.each(function(){
var img = $(this);
$("<img/>")
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width;
pic_stretch_width = $(img).width();
if(pic_stretch_width > pic_real_width)
{
$(img).width(pic_real_width);
}
});
});
}
});
if one wants to use .post() then this will set headers for all future request made with jquery
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
then make your .post() calls as normal.
As other answers pointed out in a more complicated way already, you did already create a list of lists! It's just the odd output of R that confuses (everybody?). Try this:
> str(list_all)
List of 2
$ :List of 2
..$ : num 1
..$ : num 2
$ :List of 2
..$ : chr "a"
..$ : chr "b"
And the most simple construction would be this:
> str(list(list(1, 2), list("a", "b")))
List of 2
$ :List of 2
..$ : num 1
..$ : num 2
$ :List of 2
..$ : chr "a"
..$ : chr "b"
nginx or G-WAN
http://nbonvin.wordpress.com/2011/03/24/serving-small-static-files-which-server-to-use/
If you think all those prototype definitions, array creations, and join operations are overkill, just use a single line code where you need it. String S repeating N times:
for (var i = 0, result = ''; i < N; i++) result += S;
I don't know if VB.net in VS 2008 is any different, but none of the above worked for me. Double-clicking My Project in Solution Explorer brings up the window seen below. Select Application on the left, then browse for your icon using the combobox. After you build, it should show up on your exe file.
<bean id="mockDaoFactory" name="dao" class="com.package.test.MocksFactory">
<property name="type" value="com.package.Dao" />
</bean>
this ^ works perfectly well if declared first/early in the XML file. Mockito 1.9.0/Spring 3.0.5
Add-ons:If you want for eg: /users as application base for router and /public as base for assets use
$ ng build -prod --base-href /users --deploy-url /public
Subclass UILabel and override drawTextInRect:
like this:
- (void)drawTextInRect:(CGRect)rect
{
UIEdgeInsets insets = {0, 10, 0, 0};
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
Maybe this may help you as well. I was having some trouble getting my head wrapped around how socket.io worked, so I tried to boil an example down as much as I could.
I adapted this example from the example posted here: http://socket.io/get-started/chat/
First, start in an empty directory, and create a very simple file called package.json Place the following in it.
{
"dependencies": {}
}
Next, on the command line, use npm to install the dependencies we need for this example
$ npm install --save express socket.io
This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.
$ cat package.json
{
"dependencies": {
"express": "~4.9.8",
"socket.io": "~1.1.0"
}
}
Create a file called server.js This will obviously be our server run by node. Place the following code into it:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
//for testing, we're just going to send data to the client every second
setInterval( function() {
/*
our message we want to send to the client: in this case it's just a random
number that we generate on the server
*/
var msg = Math.random();
io.emit('message', msg);
console.log (msg);
}, 1000);
Create the last file called index.html and place the following code into it.
<html>
<head></head>
<body>
<div id="message"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(msg){
console.log(msg);
document.getElementById("message").innerHTML = msg;
});
</script>
</body>
</html>
You can now test this very simple example and see some output similar to the following:
$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653
If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.
If I understand your question correctly, you're asking if you can call multiple constructors in C++?
If that's what you're looking for, then no - that is not possible.
You certainly can have multiple constructors, each with unique argument signatures, and then call the one you want when you instantiate a new object.
You can even have one constructor with defaulted arguments on the end.
But you may not have multiple constructors, and then call each of them separately.
Use "
That should work.
Usually, we want to divide our vector into a number of intervals. In this case, you can use a function where (a) is a vector and (b) is the number of intervals. (Let's suppose you want 4 intervals)
a <- 1:10
b <- 4
FunctionIntervalM <- function(a,b) {
seq(from=min(a), to = max(a), by = (max(a)-min(a))/b)
}
FunctionIntervalM(a,b)
# 1.00 3.25 5.50 7.75 10.00
Therefore you have 4 intervals:
1.00 - 3.25
3.25 - 5.50
5.50 - 7.75
7.75 - 10.00
You can also use a cut function
cut(a, 4)
# (0.991,3.25] (0.991,3.25] (0.991,3.25] (3.25,5.5] (3.25,5.5] (5.5,7.75]
# (5.5,7.75] (7.75,10] (7.75,10] (7.75,10]
#Levels: (0.991,3.25] (3.25,5.5] (5.5,7.75] (7.75,10]
foreach my $arg (@ARGV) {
print $arg, "\n";
}
will print each argument.
Look at this code, it can help you to get out of the loop fast!
foreach (var name in parent.names)
{
if (name.lastname == null)
{
Violated = true;
this.message = "lastname reqd";
break;
}
else if (name.firstname == null)
{
Violated = true;
this.message = "firstname reqd";
break;
}
}
If dealing with numbers that are either one or two digits:
'0'+str(number)[-2:]
or '0{0}'.format(number)[-2:]
One more method worth to mention here:
SQLCMD -S SEVERNAME -E -Q "SELECT COLUMN FROM TABLE" -s "," -o "c:\test.csv"
NOTE: I don't see any network admin let you run powershell scripts
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
For windows - just go to Mongodb folder (ex : C:\ProgramFiles\MongoDB\Server\3.4\bin) and open cmd in the folder and type "mongod.exe --dbpath c:\data\db"
if c:\data\db folder doesn't exist then create it by yourself and run above command again.
All should work fine by now.))
or :
public static IDictionary<TKey, TValue> Merge<TKey, TValue>( IDictionary<TKey, TValue> x, IDictionary<TKey, TValue> y)
{
return x
.Except(x.Join(y, z => z.Key, z => z.Key, (a, b) => a))
.Concat(y)
.ToDictionary(z => z.Key, z => z.Value);
}
the result is a union where for duplicate entries "y" wins.
So I did some speed comparisons to get the fastest way. List comprehensions are indeed very fast. The only way to get close is to avoid bytecode getting exectuded during construction of the list. My first attempt was the following method, which would appear to be faster in principle:
l = [[]]
for _ in range(n): l.extend(map(list,l))
(produces a list of length 2**n, of course) This construction is twice as slow as the list comprehension, according to timeit, for both short and long (a million) lists.
My second attempt was to use starmap to call the list constructor for me, There is one construction, which appears to run the list constructor at top speed, but still is slower, but only by a tiny amount:
from itertools import starmap
l = list(starmap(list,[()]*(1<<n)))
Interesting enough the execution time suggests that it is the final list call that is makes the starmap solution slow, since its execution time is almost exactly equal to the speed of:
l = list([] for _ in range(1<<n))
My third attempt came when I realized that list(()) also produces a list, so I tried the apperently simple:
l = list(map(list, [()]*(1<<n)))
but this was slower than the starmap call.
Conclusion: for the speed maniacs: Do use the list comprehension. Only call functions, if you have to. Use builtins.
Stop your server before you start to clean.
Stopping a server
You can stop the server from the Servers view.
To stop the server:
If for some reason the server fails to stop, you can terminate the process as follows:
a. Switch to the Debug perspective.
b. In the Process view, select the server process that you want to stop.
c. Click the Terminate icon in the toolbar.
Note: When terminating a server, the server process will end and the server will not go through the normal routine of stopping, for example calling the destroy() method on a servlet.
Source: Eclipse Help
If you want everything in your post to be as $Variables you can use something like this:
foreach($_POST as $key => $value) {
eval("$" . $key . " = " . $value");
}
The sad state of "record separators" or "line terminators" is a legacy of the dark ages of computing.
Now, we take it for granted that anything we want to represent is in some way structured data and conforms to various abstractions that define lines, files, protocols, messages, markup, whatever.
But once upon a time this wasn't exactly true. Applications built-in control characters and device-specific processing. The brain-dead systems that required both CR and LF simply had no abstraction for record separators or line terminators. The CR was necessary in order to get the teletype or video display to return to column one and the LF (today, NL, same code) was necessary to get it to advance to the next line. I guess the idea of doing something other than dumping the raw data to the device was too complex.
Unix and Mac actually specified an abstraction for the line end, imagine that. Sadly, they specified different ones. (Unix, ahem, came first.) And naturally, they used a control code that was already "close" to S.O.P.
Since almost all of our operating software today is a descendent of Unix, Mac, or MS operating SW, we are stuck with the line ending confusion.
I usually put these lines at the beginning of my stored procedure, and then at the end.
It is an "exists" check for #temp tables.
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
begin
drop table #MyCoolTempTable
end
Full Example:
CREATE PROCEDURE [dbo].[uspTempTableSuperSafeExample]
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyCoolTempTable
END
CREATE TABLE #MyCoolTempTable (
MyCoolTempTableKey INT IDENTITY(1,1),
MyValue VARCHAR(128)
)
INSERT INTO #MyCoolTempTable (MyValue)
SELECT LEFT(@@VERSION, 128)
UNION ALL SELECT TOP 10 LEFT(name, 128) from sysobjects
SELECT MyCoolTempTableKey, MyValue FROM #MyCoolTempTable
IF OBJECT_ID('tempdb..#MyCoolTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyCoolTempTable
END
SET NOCOUNT OFF;
END
GO
Just to mention a simple one-line concatenation as it can be useful sometimes.
# for bash
v=" guga "$'\n'" puga "
# Just for an example.
v2="bar "$'\n'" foo "$'\n'"$v"
# Let's simplify the previous version of $v2.
n=$'\n'
v3="bar ${n} foo ${n}$v"
echo "$v3"
You'll get something like this
bar foo guga puga
All leading and ending white spaces will be preserved right for
echo "$v3" > filename
You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.
var elem = document.getElementById('the-span');_x000D_
_x000D_
var typeId = elem.getAttribute('data-typeId');_x000D_
var type = elem.getAttribute('data-type');_x000D_
var points = elem.getAttribute('data-points');_x000D_
var important = elem.getAttribute('data-important');_x000D_
_x000D_
console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`_x000D_
);
_x000D_
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
_x000D_
cell.separatorInset = UIEdgeInsetsMake(0.0, cell.bounds.size.width, 0.0, -cell.bounds.size.width)
works well in iOS 10.2
The problem you're having is that you're passing incompatible formats from a formatted java.util.Date to construct an instance of java.sql.Date
, which don't behave in the same way when using valueOf()
since they use different formats.
I also can see that you're aiming to persist hours and minutes, and I think that you'd better change the data type to java.sql.Timestamp
, which supports hours and minutes, along with changing your database field to DATETIME or similar (depending on your database vendor).
Anyways, if you want to change from java.util.Date to java.sql.Date
, I suggest to use
java.util.Date date = Calendar.getInstance().getTime();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
// ... more code here
prs.setDate(sqlDate);
Use config.to_prepare to load you monkey patches/extensions for every request in development mode.
config.to_prepare do |action_dispatcher|
# More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
Rails.logger.info "\n--- Loading extensions for #{self.class} "
Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
Rails.logger.info "Loading extension(s): #{entry}"
require_dependency "#{entry}"
end
Rails.logger.info "--- Loaded extensions for #{self.class}\n"
end
check properties->java build path -> libraries. there should be no errors, in my case there was errors in the maven. once I put the required jar in the maven repo, it worked fine
I don't like adding yet another answer, but the Google maps API v.3 has spherical geometry (and more). After converting your WGS84 to decimal degrees you can do this:
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry" type="text/javascript"></script>
distance = google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(fromLat, fromLng),
new google.maps.LatLng(toLat, toLng));
No word about how accurate Google's calculations are or even what model is used (though it does say "spherical" rather than "geoid". By the way, the "straight line" distance will obviously be different from the distance if one travels on the surface of the earth which is what everyone seems to be presuming.
Try using file to view the encoding details (reference):
cd directory/of/interest
file *
It produces useful output like this:
$ file *
CR6Series_stats resaved.dat: ASCII text, with very long lines, with CRLF line terminators
CR6Series_stats utf8.dat: UTF-8 Unicode (with BOM) text, with very long lines, with CRLF line terminators
CR6Series_stats.dat: ASCII text, with very long lines, with CRLF line terminators
readme.md: ASCII text, with CRLF line terminators
Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:
echo '<p>' . $unit1 . "</p>\n";
PS: One clarification, single quotes strings do accept two escape sequences:
\'
when you want to use single quote inside single quoted strings\\
when you want to use backslash literallyschtasks /create /sc onlogon /tn MyProgram /rl highest /tr "exeFullPath"
This behaves as expected. The URLEncoder
implements the HTML Specifications for how to encode URLs in HTML forms.
From the javadocs:
This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.
and from the HTML Specification:
application/x-www-form-urlencoded
Forms submitted with this content type must be encoded as follows:
- Control names and values are escaped. Space characters are replaced by `+'
You will have to replace it, e.g.:
System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));
If you want to test for a specific error type, use a combination of try, catch and raise:
#-- test for TypeError
try:
myList.append_number("a")
assert False
except TypeError: pass
except: assert False
var getKeyByDinner = function(obj, dinner) {
var returnKey = -1;
$.each(obj, function(key, info) {
if (info.dinner == dinner) {
returnKey = key;
return false;
};
});
return returnKey;
}
So long as -1
isn't ever a valid key.
faster and shorter :
// nl is the nodelist
var a=[], l=nl.length>>>0;
for( ; l--; a[l]=nl[l] );
The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.
Create it at the following location <your home folder>/.m2/settings.xml
e.g. C:\Users\YourUserName\.m2\settings.xml
on Windows or /home/YourUserName/.m2/settings.xml
on Linux
Here's an empty skeleton you can use:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies/>
<profiles/>
<activeProfiles/>
</settings>
If you use Eclipse to edit it, it will give you auto-completion when editing it.
And here's the Maven settings.xml Reference page
Look at the exception:
No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency
This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:
UserDaoImpl
with @Component
or @Repository
, and let the component scan do the work for you, exactly as you have done with UserService
.UserBoImpl
.Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.
When you say str
, you should be careful what you mean:
do you mean the variable str
?
or do you mean the object referenced by str
?
In your StringBuffer
example you are not altering the value of str
, and in your String
example you are not altering the state of the String
object.
The most poignant way to experience the difference would be something like this:
static void change(String in) {
in = in + " changed";
}
static void change(StringBuffer in) {
in.append(" changed");
}
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("value");
String str = "value";
change(sb);
change(str);
System.out.println("StringBuffer: "+sb);
System.out.println("String: "+str);
}
Log in to MySQL console with root user:
root@9532f0da1a2a:/# mysql -u root -pPASSWORD
and change the Authentication Plugin with the password there:
mysql> ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';
Query OK, 0 rows affected (0.08 sec)
You can read more info about the Preferred Authentication Plugin on the MySQL 8.0 Reference Manual
It is working perfectly in a dockerized environment:
docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -p 3306:3306 -d mysql:latest
docker exec -it mysql bash
mysql -u root -pPASSWORD
ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';
exit
exit
docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest
So you can now log in to phpMyAdmin on http://localhost:8080 with root / PASSWORD
mysql/mysql-server
If you are using mysql/mysql-server docker image
But remember, it is just a 'quick and dirty' solution in the development environment. It is not wise to change the MySQL Preferred Authentication Plugin.
docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest
docker exec -it mysql mysql -u root -pPASSWORD -e "ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';"
docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest
Updated solution at 10/04/2018
Change the MySQL default authentication plugin by uncommenting the default_authentication_plugin=mysql_native_password
setting in /etc/my.cnf
use at your own risk
docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest
docker exec -it mysql sed -i -e 's/# default-authentication-plugin=mysql_native_password/default-authentication-plugin=mysql_native_password/g' /etc/my.cnf
docker stop mysql; docker start mysql
docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest
Updated workaround at 01/30/2019
docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest
docker exec -it mysql sed -i -e 's/# default-authentication-plugin=mysql_native_password/default-authentication-plugin=mysql_native_password/g' /etc/my.cnf
docker exec -it mysql mysql -u root -pPASSWORD -e "ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';"
docker stop mysql; docker start mysql
docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest
Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:
@echo off
setlocal enabledelayedexpansion
set myvar=the list:
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%
Also consider the following restriction (MSDN):
The maximum individual environment variable size is 8192bytes.
Why nobody wrote this simple way of converting JSON string in List ?
List<Object> list = Arrays.asList(new GsonBuilder().create().fromJson(jsonString, Object[].class));
CTRL+D? http://www.scribd.com/doc/7580088/SQL-Developer-Hot-Keys
If that doesn't work, you might be able to set up an Accelerator: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b31695/intro.htm#sthref208
Android Developer has the right answer, but the provided source code is pretty verbose and doesn't actually implement the pattern described in the diagram.
Here is a better template:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- stuff to scroll -->
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<!-- footer -->
</FrameLayout>
</RelativeLayout>
</ScrollView>
Its up to you to decide what views you use for the "scrolling" and "footer" parts. Also know that you probably have to set the ScrollView
s
fillViewPort .
One option would be VistaDB. They allow databases (or even tables) to be password protected (and optionally encrypted).
Code behind solution
private void Button1_Click(object sender, RoutedEventArgs e)
{
System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
myStringBuilder.Append("Orange").AppendLine();
myStringBuilder.Append("").AppendLine();
myStringBuilder.Append("Apple").AppendLine();
myStringBuilder.Append("Banana").AppendLine();
myStringBuilder.Append("").AppendLine();
myStringBuilder.Append("Plum").AppendLine();
TextBox1.Text = myStringBuilder.ToString();
}
One of the way to do this is you can use ResponseEntity as a return object.
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
if(everything_fine)
return new ResponseEntity<>(RestModel, HttpStatus.OK);
else
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
I won't refer too your example as it is quite simple for a general answer (for example it doesn't contain templated functions ,which force you to implement them on the header) , what I follow as a rule of thumb is the pimpl idiom
It has quite some benefits as you get faster compilation times and the syntactic sugar :
class->member
instead of class.member
The only drawback is the extra pointer you pay.
You can prepare your data and pass it to the real column
utility.
Let's assume you have printed data to file /tmp/filename.txt with the tab as a delimeter. Then you can columnize it like this:
import subprocess
result = subprocess.run("cat /tmp/filename.txt | column -N \"col_1,col_2,col_3\" -t -s'\t' -R 2,3", shell=True, stdout=subprocess.PIPE)
print(result.stdout.decode("utf-8"))
As you can see, you can use features of column utility, such as right aligning.
Use the CSS3 Viewport-percentage feature.
Viewport-Percentage Explanation
Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Styles</title>_x000D_
_x000D_
<style>_x000D_
@media screen and (min-width: 480px) {_x000D_
body {_x000D_
background-color: skyblue;_x000D_
width: 90vw;_x000D_
height: 90vh;_x000D_
border: groove black;_x000D_
}_x000D_
_x000D_
div#main {_x000D_
font-size: 3vw;_x000D_
}_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div id="main">_x000D_
Viewport-Percentage Test_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
You can install vim/vi for windows and set windows PATH variable and open it in command line.
Calligraphy works pretty well, but it is not suitable for me, since it does not support different weights (bold, italic, etc) for a font-family.
So I tried Fontain, which allows you to define custom Views and apply them custom font families.
in order to use Fontain, you should add the following to your app module build.gradle:
compile 'com.scopely:fontain:1.0.0'
Then, instead of using regular TextView, you should use FontTextView
Example of FontTextView with uppercase and bold content:
<com.scopely.fontain.views.FontTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/black"
android:textColor="@android:color/white"
android:textSize="11dp"
android:gravity="center"
android:id="@+id/tv1"
app:font_family="myCustomFont"
app:caps_mode="characters"
app:font_weight="BOLD"/>
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
This will get you the most expensive car for the user:
SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
However, this statement makes me think that you want all of the cars prices sorted, descending:
So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?
So you could try this:
SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC
To run in Windows, copy this *.bat file to each directory you wish to use and run the ipython notebook by executing the batch file. This assumes you have ipython installed in windows.
set "var=%cd%"
cd var
ipython notebook
In Windows 7, 8 or 8.1, in Devices Manager:
In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.
this is because your project has been linked to a git-hub repository, and the file having question mark on it, is not been added yet. if you want to remove this sign you will have to add this file to git-hub repository.
For me I had to put the whole interval in single quotes not just the value of the interval.
select id,
title,
created_at + interval '1 day' * claim_window as deadline from projects
Instead of
select id,
title,
created_at + interval '1' day * claim_window as deadline from projects
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
As said before, VBA does not support Multithreading.
But you don't need to use C# or vbScript to start other VBA worker threads.
I use VBA to create VBA worker threads.
First copy the makro workbook for every thread you want to start.
Then you can start new Excel Instances (running in another Thread) simply by creating an instance of Excel.Application (to avoid errors i have to set the new application to visible).
To actually run some task in another thread i can then start a makro in the other application with parameters form the master workbook.
To return to the master workbook thread without waiting i simply use Application.OnTime in the worker thread (where i need it).
As semaphore i simply use a collection that is shared with all threads. For callbacks pass the master workbook to the worker thread. There the runMakroInOtherInstance Function can be reused to start a callback.
'Create new thread and return reference to workbook of worker thread
Public Function openNewInstance(ByVal fileName As String, Optional ByVal openVisible As Boolean = True) As Workbook
Dim newApp As New Excel.Application
ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & fileName
If openVisible Then newApp.Visible = True
Set openNewInstance = newApp.Workbooks.Open(ThisWorkbook.Path & "\" & fileName, False, False)
End Function
'Start macro in other instance and wait for return (OnTime used in target macro)
Public Sub runMakroInOtherInstance(ByRef otherWkb As Workbook, ByVal strMakro As String, ParamArray var() As Variant)
Dim makroName As String
makroName = "'" & otherWkb.Name & "'!" & strMakro
Select Case UBound(var)
Case -1:
otherWkb.Application.Run makroName
Case 0:
otherWkb.Application.Run makroName, var(0)
Case 1:
otherWkb.Application.Run makroName, var(0), var(1)
Case 2:
otherWkb.Application.Run makroName, var(0), var(1), var(2)
Case 3:
otherWkb.Application.Run makroName, var(0), var(1), var(2), var(3)
Case 4:
otherWkb.Application.Run makroName, var(0), var(1), var(2), var(3), var(4)
Case 5:
otherWkb.Application.Run makroName, var(0), var(1), var(2), var(3), var(4), var(5)
End Select
End Sub
Public Sub SYNCH_OR_WAIT()
On Error Resume Next
While masterBlocked.Count > 0
DoEvents
Wend
masterBlocked.Add "BLOCKED", ThisWorkbook.FullName
End Sub
Public Sub SYNCH_RELEASE()
On Error Resume Next
masterBlocked.Remove ThisWorkbook.FullName
End Sub
Sub runTaskParallel()
...
Dim controllerWkb As Workbook
Set controllerWkb = openNewInstance("controller.xlsm")
runMakroInOtherInstance controllerWkb, "CONTROLLER_LIST_FILES", ThisWorkbook, rootFold, masterBlocked
...
End Sub
Edit your package.json. Change:
"gulp-sass": "^2.3.2"
to
"gulp-sass": "3.0.0"
Delete the node_modules folder and run npm install
again.
Source: https://github.com/codecombat/codecombat/issues/4430#issuecomment-348927771
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.
Using _blank
will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).
Since we now have inline javascript snippets I might as well add an interactive example of pre and pos increment. It's not C++ but the concept stays the same.
let A = 1;_x000D_
let B = 1;_x000D_
_x000D_
console.log('A++ === 2', A++ === 2);_x000D_
console.log('++B === 2', ++B === 2);
_x000D_
If your request contains an object like this:
{
"year": 1900,
"month": 1,
"day": 20
}
Then you can use:
data class DateObject(
val day: Int,
val month: Int,
val year: Int
)
class LocalDateConverter : StdConverter<DateObject, LocalDate>() {
override fun convert(value: DateObject): LocalDate {
return value.run { LocalDate.of(year, month, day) }
}
}
Above the field:
@JsonDeserialize(converter = LocalDateConverter::class)
val dateOfBirth: LocalDate
The code is in Kotlin but this would work for Java too of course.
Basically, no. That is an http header, so it is reasonable to cast to HttpWebRequest
and set the .Referer
(as you indicate in the question):
HttpWebRequest req = ...
req.Referer = "your url";
Take a look at the very recently released SSHD, which is based on the Apache MINA project.