As defer attribute works only with scripts tag with src. Found a way to mimic defer for inline scripts. Use DOMContentLoaded event.
<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
// Your inline scripts which uses methods from external-scripts.
});
</script>
This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded.
if (isset($_POST['Register']))
{
$ErrorArrays = array (); //Empty array for input errors
$Input_Username = $_POST['Username'];
$Input_Password = $_POST['Password'];
$Input_Confirm = $_POST['ConfirmPass'];
$Input_Email = $_POST['Email'];
if (empty($Input_Username))
{
$ErrorArrays[] = "Username Is Empty";
}
if (empty($Input_Password))
{
$ErrorArrays[] = "Password Is Empty";
}
if ($Input_Password !== $Input_Confirm)
{
$ErrorArrays[] = "Passwords Do Not Match!";
}
if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
{
$ErrorArrays[] = "Incorrect Email Formatting";
}
if (count($ErrorArrays) == 0)
{
// No Errors
}
else
{
foreach ($ErrorArrays AS $Errors)
{
echo "<font color='red'><b>".$Errors."</font></b><br>";
}
}
}
?>
<form method="POST">
Username: <input type='text' name='Username'> <br>
Password: <input type='password' name='Password'><br>
Confirm Password: <input type='password' name='ConfirmPass'><br>
Email: <input type='text' name='Email'> <br><br>
<input type='submit' name='Register' value='Register'>
</form>
This is a very basic PHP Form validation. This could be put in a try
block, but for basic reference, I see this fit following our conversation in the comment box.
What this script will do, is process each of the post elements, and act accordingly, for example:
if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
{
$ErrorArrays[] = "Incorrect Email Formatting";
}
This will check:
if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.
Further down the script, you will see:
if (count($ErrorArrays) == 0)
{
// No Errors
}
else
{
foreach ($ErrorArrays AS $Errors)
{
echo "<font color='red'><b>".$Errors."</font></b><br>";
}
}
Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.
Remember, this is a reference based on our conversation in the comment box, and should be used as such.
Now that most people use Kotlin instead of Java, here is the code in Kotlin for converting a bitmap into a base64 string.
import java.io.ByteArrayOutputStream
private fun encodeImage(bm: Bitmap): String? {
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}
If you get this error:
Cannot load 32-bit plugin, XMLTools.dll is not compatible with the current version of Notepad++
Here you can find a working version for Windows 10 x64: Xml Tools 2.4.9.2 Unicode
Note: It's the only version I've found working on Windows 10 Professional x64.
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {_x000D_
display:flex;_x000D_
_x000D_
align-items:flex-start;_x000D_
align-content:flex-start;_x000D_
}_x000D_
_x000D_
#a > div {_x000D_
_x000D_
background-color:red;_x000D_
padding:5px;_x000D_
margin:2px;_x000D_
}_x000D_
#a > #c {_x000D_
align-self:stretch;_x000D_
}
_x000D_
<div id="a">_x000D_
_x000D_
<div id="b">left</div>_x000D_
<div id="c">middle</div>_x000D_
<div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
_x000D_
</div>
_x000D_
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards
If you have a type like: Object[] | string[]
and what to do something conditionally based on what type it is - you can use this type guarding:
function isStringArray(value: any): value is string[] {
if (value instanceof Array) {
value.forEach(function(item) { // maybe only check first value?
if (typeof item !== 'string') {
return false
}
})
return true
}
return false
}
function join<T>(value: string[] | T[]) {
if (isStringArray(value)) {
return value.join(',') // value is string[] here
} else {
return value.map((x) => x.toString()).join(',') // value is T[] here
}
}
There is an issue with an empty array being typed as string[]
, but that might be okay
Only checked
and checked="checked"
are valid. Your other options depend on error recovery in browsers.
checked="yes"
and checked="true"
are particularly bad as they imply that checked="no"
and checked="false"
will set the default state to be unchecked … which they will not.
I had the same problem because .htaccess
has incorrect settings:
RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css)$ index.php
I solved this by modifying the file:
RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css|eot|svg|ttf|woff|woff2|map)$ index.php
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
Add atribute in xml:
<android.support.design.widget.TabLayout
....
app:tabBackground="@drawable/tab_color_selector"
...
/>
And create in drawable folder, tab_color_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
<item android:drawable="@color/tab_background_unselected"/>
</selector>
Try this solution. It works fine.
try{
String url = textBox1.Text;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(sr);
var aTags = doc.DocumentNode.SelectNodes("//a");
int counter = 1;
if (aTags != null)
{
foreach (var aTag in aTags)
{
richTextBox1.Text += aTag.InnerHtml + "\n" ;
counter++;
}
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Failed to retrieve related keywords." + ex);
}
Save your sorting order in a ViewState.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression,string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
Why you don't want to use existing sorting functionality? You can always customize it.
Sorting Data in a GridView Web Server Control at MSDN
Here is an example with customization:
You have the field in a string, so you'll need to convert it to datetime
order by CONVERT(datetime, EventDate ) desc
SELECT DECODE(REGEXP_COUNT(:value,'\d'),LENGTH(:value),'Y','N') AS is_numeric FROM dual;
There are many ways but this one works perfect for me.
You need to use the doubleValue()
method to get the double value from a BigDecimal object.
BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
If you want to run a script to a database:
mysql -u user -p data_base_name_here < db.sql
Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:
RGB
:
To shade:
newR = currentR * (1 - shade_factor)
newG = currentG * (1 - shade_factor)
newB = currentB * (1 - shade_factor)
To tint:
newR = currentR + (255 - currentR) * tint_factor
newG = currentG + (255 - currentG) * tint_factor
newB = currentB + (255 - currentB) * tint_factor
More generally, the color resulting in layering a color RGB(currentR,currentG,currentB)
with a color RGBA(aR,aG,aB,alpha)
is:
newR = currentR + (aR - currentR) * alpha
newG = currentG + (aG - currentG) * alpha
newB = currentB + (aB - currentB) * alpha
where (aR,aG,aB) = black = (0,0,0)
for shading, and (aR,aG,aB) = white = (255,255,255)
for tinting
HSV
or HSB
:
Value
/ Brightness
or increase the Saturation
Saturation
or increase the Value
/ Brightness
HSL
:
Lightness
Lightness
There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB
and want to use the HSV
model to shade for example, you can just convert to HSV
, do the shading and convert back to RGB
. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :
RGB
has the advantage of being really simple to implement, but:
HSV
or HSB
is kind of complex because you need to play with two parameters to get what you want (Saturation
& Value
/ Brightness
)HSL
is the best from my point of view:
50%
means an unaltered Hue>50%
means the Hue is lighter (tint)<50%
means the Hue is darker (shade)Lightness
part)You can just concat the values using +
<a ng-click="$navigate.go('#/path/' + obj.val1 + '/' + obj.val2)">{{obj.val1}}, {{obj.val2}}</a>
I am sure the code you posted is a simplified example, if your path building is more complex I would recommend extracting out a function (or service) that would build your urls so you can effectively write unit test.
if you compile in C change
for (int i=0;i<10;i++) { ..
to
int i;
for (i=0;i<10;i++) { ..
You can also compile with the C99 switch set. Put -std=c99 in the compilation line:
gcc -std=c99 foo.c -o foo
REF: http://cplusplus.syntaxerrors.info/index.php?title='for'_loop_initial_declaration_used_outside_C99_mode
You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:
fun_mean <- function(x){
return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}
ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)
Align to the center, using display: inline-block
and text-align: center
.
.outerdiv_x000D_
{_x000D_
height:100px;_x000D_
width:500px;_x000D_
background: red;_x000D_
margin: 0 auto;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
height:40px;_x000D_
width: 100px;_x000D_
margin: 2px;_x000D_
box-sizing: border-box;_x000D_
background: green;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
<div class="innerdiv"></div>_x000D_
<div class="innerdiv"></div>_x000D_
</div>
_x000D_
Align to the center using display: flex
and justify-content: center
.outerdiv_x000D_
{_x000D_
height:100px;_x000D_
width:500px;_x000D_
background: red;_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
height:40px;_x000D_
width: 100px;_x000D_
margin: 2px;_x000D_
box-sizing: border-box;_x000D_
background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
<div class="innerdiv"></div>_x000D_
<div class="innerdiv"></div>_x000D_
</div>
_x000D_
Align to the center vertically and horizontally using display: flex
, justify-content: center
and align-items:center
.
.outerdiv_x000D_
{_x000D_
height:100px;_x000D_
width:500px;_x000D_
background: red;_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
justify-content: center;_x000D_
align-items:center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
height:40px;_x000D_
width: 100px;_x000D_
margin: 2px;_x000D_
box-sizing: border-box;_x000D_
background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
<div class="innerdiv"></div>_x000D_
<div class="innerdiv"></div>_x000D_
</div>
_x000D_
Remembering that the mean can also by obtained using a linear model, regressing the variable against a single intercept, you can use also the lm(x~1)
function for this!
Advantages are:
confint()
car::linear.hypothesis()
sandwich
## generate data
x <- rnorm(1000)
## estimate reg
reg <- lm(x~1)
coef(summary(reg))[,"Std. Error"]
#> [1] 0.03237811
## conpare with simple formula
all.equal(sd(x)/sqrt(length(x)),
coef(summary(reg))[,"Std. Error"])
#> [1] TRUE
## extract confidence interval
confint(reg)
#> 2.5 % 97.5 %
#> (Intercept) -0.06457031 0.0625035
Created on 2020-10-06 by the reprex package (v0.3.0)
.NET Core 5.0 does not have FromSql
instead it has FromSqlRaw
All below worked for me. Account
class here is Entity in C# with exact same table and column names as in the database.
App configuration class as below
class AppConfiguration
{
public AppConfiguration()
{
var configBuilder = new ConfigurationBuilder();
var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
configBuilder.AddJsonFile(path, false);
var root = configBuilder.Build();
var appSetting = root.GetSection("ConnectionStrings:DefaultConnection");
sqlConnectionString = appSetting.Value;
}
public string sqlConnectionString { get; set; }
}
DbContext class:
public class DatabaseContext : DbContext
{
public class OptionsBuild
{
public OptionsBuild()
{
setting = new AppConfiguration();
opsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
opsBuilder.UseSqlServer(setting.sqlConnectionString);
dbOptions = opsBuilder.Options;
}
public DbContextOptionsBuilder<DatabaseContext> opsBuilder { get; set; }
public DbContextOptions<DatabaseContext> dbOptions { get; set; }
private AppConfiguration setting { get; set; }
}
public static OptionsBuild ops = new OptionsBuild();
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
//disable initializer
// Database.SetInitializer<DatabaseContext>(null);
}
public DbSet<Account> Account { get; set; }
}
This code should be in your data access layer:
List<Account> accounts = new List<Account>();
var context = new DatabaseContext(DatabaseContext.ops.dbOptions);
accounts = await context.Account.ToListAsync(); //direct select from a table
var param = new SqlParameter("@FirstName", "Bill");
accounts = await context.Account.FromSqlRaw<Account>("exec Proc_Account_Select",
param).ToListAsync(); //procedure call with parameter
accounts = context.Account.FromSqlRaw("SELECT * FROM dbo.Account").ToList(); //raw query
The obj
directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin
directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.
You can change the actual directories used for both purposes within the project settings, if you like.
$().ready(function(){_x000D_
_x000D_
$('div.alert').delay(1500);_x000D_
$('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
for those like me who are looking to send objects other than primitives, since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.
It depends on how efficient you need things to be. Simply iterating over the list looking for the element which satisfies a certain condition is O(n), but so is ArrayList.Contains if you could implement the Equals method. If you're not doing this in loops or inner loops this approach is probably just fine.
If you really need very efficient look-up speeds at all cost, you'll need to do two things:
Of course, building this HashSet still has a O(n) cost. You are only going to gain anything if the cost of building the HashSet is negligible compared to the total cost of all the contains() checks that you need to do. Trying to build a list without duplicates is such a case.
I am both a web developer and a former employee of one of the companies you mentioned. I completely understand where you're coming from. Verifying addresses seems like a simple problem to tackle, but it's very much an iceberg. I suppose one workaround to the legal constraints of the Google or Yahoo! Maps APIs is to request your users verify their addresses on a map. If I were in your shoes, though, I wouldn't go that route.
The reason address verification services are so expensive is that they require licenses and ongoing relationships with grumpy, bureaucratic postal authorities (including the Royal Mail). Unfortunately, postal authorities are the best (and often the only) sources of data against which to verify addresses, so there really isn't any other way to go about it. The bottom line is you need to weigh the cost of bad addresses (usually a question of mail volume) against the cost of the software to verify them. Irish postal data is even more rubbish than Irish postal formats (which frequently omit building numbers), so there's little you can do about those addresses.
Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex
on the row container and at least making sure your middle container on the row has a flex-grow
value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow
properties applied, middle container only needs 1 for flex-grow
).
Here's a pic of what I was trying to do and sample code for how I solved it.
.row {
background: lightgray;
height: 30px;
width: 100%;
display: flex;
align-items:flex-end;
margin-top:5px;
}
.left {
background:lightblue;
}
.separator{
flex-grow:1;
border-bottom:dotted 2px black;
}
.right {
background:coral;
}
_x000D_
<div class="row">
<div class="left">Left</div>
<div class="separator"></div>
<div class="right">Right With Text</div>
</div>
<div class="row">
<div class="left">Left With More Text</div>
<div class="separator"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">Left With Text</div>
<div class="separator"></div>
<div class="right">Right With More Text</div>
</div>
_x000D_
You can use argv npm module (install it by running npm install argv --save) for getting params in your webpack.config.js file and as for production you use -p flag "build": "webpack -p", you can add condition in webpack.config.js file like below
plugins: [
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': argv.p ? JSON.stringify('production') : JSON.stringify('development')
}
})
]
And thats it.
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
System.out.println(s);
}
Another reason of the above error is corrupted jar file. I got the same error but for Junit when running unit tests. Removing jar and downloading it again fixed the issue.
1-Create Your icon in Photoshop Or Coreldraw by size 256*256
note that use PNG file format if you want to have a transparent icon
2-Upload Your icon in https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
3-Set your setting on this site
4-Download the zip file automatically created by the webpage by clicking on download button
5-Extract the zip file and copy res folder to you project library
note that res folder contain all size icon
6-finally you need to set the manifest to use icon
<application android:icon="@drawable/your_icon" >
....
</application>
I add an answer because I think a one line solution is always good!
Atop of your myRscript.R
file, add the following line:
eval(parse(text=paste(commandArgs(trailingOnly = TRUE), collapse=";")))
Then submit your script with something like:
R CMD BATCH [options] '--args arguments you want to supply' myRscript.R &
For example:
R CMD BATCH --vanilla '--args N=1 l=list(a=2, b="test") name="aname"' myscript.R &
Then:
> ls()
[1] "N" "l" "name"
As you said, Safari sends Cache-Control: max-age=0
on reload. Express (or more specifically, Express's dependency, node-fresh) considers the cache stale when Cache-Control: no-cache
headers are received, but it doesn't do the same for Cache-Control: max-age=0
. From what I can tell, it probably should. But I'm not an expert on caching.
The fix is to change (what is currently) line 37 of node-fresh/index.js
from
if (cc && cc.indexOf('no-cache') !== -1) return false;
to
if (cc && (cc.indexOf('no-cache') !== -1 ||
cc.indexOf('max-age=0') !== -1)) return false;
I forked node-fresh and express to include this fix in my project's package.json
via npm
, you could do the same. Here are my forks, for example:
https://github.com/stratusdata/node-fresh https://github.com/stratusdata/express#safari-reload-fix
The safari-reload-fix branch is based on the 3.4.7 tag.
I got this error going from Gradle 3.5.3 to 5.4.1 (Android Studio prompted and I clicked "Upgrade".)
Gradle proceeded to upgrade but yielded some errors such as:
ONFIGURE SUCCESSFUL in 1m 27s
ERROR: The Android Gradle plugin supports only Crashlytics Gradle plugin version 1.25.4 and higher.
The following dependencies do not satisfy the required version:
root project 'Android%20App' -> io.fabric.tools:gradle:1.25.1
Update plugins
Affected Modules: app
INFO: API 'variant.getExternalNativeBuildTasks()' is obsolete and has been replaced with 'variant.getExternalNativeBuildProviders()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variant.getExternalNativeBuildTasks(), use -Pandroid.debug.obsoleteApi=true on the command line to display more information.
Affected Modules: app
INFO: The specified Android SDK Build Tools version (27.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '27.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
Install Build Tools 28.0.3, update version in build file and sync project
Affected Modules: app
The thing that fixed it was opening Settings --> Appearance & Behavior --> System Settings --> Android SDK and I then selected some recent versions of Android SDK like 8, 9, and 10. (I had only had 5.1, 6.0, and Android N Preview installed.)
Once that's installed, I had to modify my build.gradle file for my Module: app
Then I clicked the "Sync Project with Gradle Files" button on the toolbar. The Sync output window offered an option to "Update Plugins" and once I clicked through that everything seemed to work. For good measure I again clicked "Sync Project with Gradle Files" followed by Build --> Clean Project, and finally I was able to run my project again.
Can be done via slicing too
package main
import "fmt"
func main() {
fmt.Print("HELLO"[1:2])
}
NOTE: This solution only works for ASCII characters.
The answer to your problem is easy: replace the current Fragment
with the new Fragment
and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity
really defeats the whole purpose to use fragments anyway...very counter productive.
@Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
http://developer.android.com/guide/components/fragments.html#Transactions
You can use <br />
for Line Breaks, and
for white space.
string s = "First line <br /> Second line";
Output:
First line
Second line
For more info refer to this: Line break in Label
It just means that the server cannot find your image.
Remember The image path must be relative to the CSS file location
Check the path and if the image file exist.
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
None of the top-voted answers worked for me, except when I unchecked "Use detected ADB location" as mentioned above by @???. Fortunately, in my case though, the message didn't show up, even when I turned it back on. In other words, the problem might be resolved by restarting "Use detected ADB location" :)
Declare a variable in component.ts and initialize it to some value
buttonDisabled: boolean;
ngOnInit() {
this.buttonDisabled = false;
}
Now in .html or in the template, you can put following code:
<button disabled="{{buttonDisabled}}"> Click Me </button>
Now you can enable/disable button by changing value of buttonDisabled
variable.
you can achive it with group join
var result = (from c in Customers
join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
Select new { customer = c, orderItems = g});
c is Customer and g is the customers order items.
1) Get py2exe from here, according to your Python version.
2) Make a file called "setup.py" in the same folder as the script you want to convert, having the following code:
from distutils.core import setup import py2exe setup(console=['myscript.py']) #change 'myscript' to your script
3) Go to command prompt, navigate to that folder, and type:
python setup.py py2exe
4) It will generate a "dist" folder in the same folder as the script. This folder contains the .exe file.
Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:
.order_by(model.Entry.amount.desc())
This is handy since it avoids an import
, and you can use it on other places such as in a relation definition, etc.
For more information, you can refer this
To JUST LET EMAIL APPS to resolve your intent you need to specify ACTION_SENDTO as Action and mailto as Data.
private void sendEmail(){
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:" + "[email protected]"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My email's subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "My email's body");
try {
startActivity(Intent.createChooser(emailIntent, "Send email using..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Activity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
}
}
1]We can save xsl as .csv file
2] Got to MongoDB bin pathon cmd - > cd D:\Arkay\soft\MongoDB\bin
3] Run below command
> mongoimport.exe -d dbname -c collectionname --type csv --file "D:\Arkay\test.csv" --headerline
4] Verify on Mongo side using below coomand.
>db.collectioname.find().pretty().limit(1)
I'm on XP and this allowed Git Bash to communicate w/ Github (after much frustration):
c:\cygwin\bin\cyg*
(~50 files) to c:\Program Files\Git\bin\
c:\cygwin\bin\ssh.exe
to c:\Program Files\Git\bin\
(overwriting)Create the file c:\Documents and Settings\<username>\.ssh\config
containing:
Host github.com
User git
Hostname github.com
PreferredAuthentications publickey
IdentityFile "/cygdrive/c/Documents and Settings/<username>/.ssh/id_rsa"
(optional) Use ssh -v git@github
to see the connection debugged.
Background: The general problem is a combination of these two:
If you are connecting to the server from Windows, the Putty version of scp ("pscp") lets you pass the password with the -pw
parameter.
I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.
This can be another solution if jquery is loaded in iframe.html.
$('#iframe')[0].contentWindow.$("html").html()
You need to add a pseudo-hostname to the CALLBACK_URL 'app://' doesn't make sense as a URL and cannot be parsed.
Restoring a Database from Backup
sql-server-->connect to instance-->Databases-->right-click on databases-->Restore
DataBase..-->Device-->Add-->choose the path_filename(.bak)-->click OK
Unfortunately if you're looking to apply UIPopoverController
in iOS9, you'll get a deprecated class warning. Instead you need to set your desired view's UIModalPresentationPopover
property to achieve the same result.
Popover
In a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the passthroughViews property of the associated UIPopoverPresentationController object, which you can get from the popoverPresentationController property.
In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.
Available in iOS 8.0 and later.
Reference: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621355-modalpresentationstyle
In order to make your code work without having to return the slice from Test, you can pass a pointer like this:
package main
import (
"fmt"
)
var a = make([]int, 7, 8)
func Test(slice *[]int) {
*slice = append(*slice, 100)
fmt.Println(*slice)
}
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(&a)
fmt.Println(a)
}
I used the url as above: http://translate.google.com/translate_tts?tl=en&q=Hello%20World
And requested with python library..however I'm getting HTTP 403 FORBIDDEN
In the end I had to mock the User-Agent
header with the browser's one to succeed.
/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
g.setColor(Color.RED);
g.fillOval(50,50,20,20);
}
g.fillOval(x-axis,y-axis,width,height);
Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.
write.csv(Data_output, "output.csv", row.names = F, quote = F)
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();
It may have been covered elsewhere but simply changing the encoding line of the XML source to 'utf-16' allows the XML to be inserted into a SQL Server 'xml'data type.
using (DataSetTableAdapters.SQSTableAdapter tbl_SQS = new DataSetTableAdapters.SQSTableAdapter())
{
try
{
bodyXML = @"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><test></test>";
bodyXMLutf16 = bodyXML.Replace("UTF-8", "UTF-16");
tbl_SQS.Insert(messageID, receiptHandle, md5OfBody, bodyXMLutf16, sourceType);
}
catch (System.Data.SqlClient.SqlException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
The result is all of the XML text is inserted into the 'xml' data type field but the 'header' line is removed. What you see in the resulting record is just
<test></test>
Using the serialization method described in the "Answered" entry is a way of including the original header in the target field but the result is that the remaining XML text is enclosed in an XML <string></string>
tag.
The table adapter in the code is a class automatically built using the Visual Studio 2013 "Add New Data Source: wizard. The five parameters to the Insert method map to fields in a SQL Server table.
This method checks if a String contains a special character (based on your definition).
/**
* Returns true if s contains any character other than
* letters, numbers, or spaces. Returns false otherwise.
*/
public boolean containsSpecialCharacter(String s) {
return (s == null) ? false : s.matches("[^A-Za-z0-9 ]");
}
You can use the same logic to count special characters in a string like this:
/**
* Counts the number of special characters in s.
*/
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
return 0;
}
int theCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
theCount++;
}
}
return theCount;
}
Another approach is to put all the special chars in a String and use String.contains:
/**
* Counts the number of special characters in s.
*/
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
return 0;
}
int theCount = 0;
String specialChars = "/*!@#$%^&*()\"{}_[]|\\?/<>,.";
for (int i = 0; i < s.length(); i++) {
if (specialChars.contains(s.substring(i, 1))) {
theCount++;
}
}
return theCount;
}
NOTE: You must escape the backslash and "
character with a backslashes.
The above are examples of how to approach this problem in general.
For your exact problem as stated in the question, the answer by @LanguagesNamedAfterCoffee is the most efficient approach.
This code should work for you
$("#intro").owlCarousel ({
slideSpeed : 800,
autoPlay: 6000,
items : 1,
stopOnHover : true,
itemsDesktop : [1199,1],
itemsDesktopSmall : [979,1],
itemsTablet : [768,1],
});
If you don't need the seeding capability just use Math.random()
and build helper functions around it (eg. randRange(start, end)
).
I'm not sure what RNG you're using, but it's best to know and document it so you're aware of its characteristics and limitations.
Like Starkii said, Mersenne Twister is a good PRNG, but it isn't easy to implement. If you want to do it yourself try implementing a LCG - it's very easy, has decent randomness qualities (not as good as Mersenne Twister), and you can use some of the popular constants.
EDIT: consider the great options at this answer for short seedable RNG implementations, including an LCG option.
function RNG(seed) {_x000D_
// LCG using GCC's constants_x000D_
this.m = 0x80000000; // 2**31;_x000D_
this.a = 1103515245;_x000D_
this.c = 12345;_x000D_
_x000D_
this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));_x000D_
}_x000D_
RNG.prototype.nextInt = function() {_x000D_
this.state = (this.a * this.state + this.c) % this.m;_x000D_
return this.state;_x000D_
}_x000D_
RNG.prototype.nextFloat = function() {_x000D_
// returns in range [0,1]_x000D_
return this.nextInt() / (this.m - 1);_x000D_
}_x000D_
RNG.prototype.nextRange = function(start, end) {_x000D_
// returns in range [start, end): including start, excluding end_x000D_
// can't modulu nextInt because of weak randomness in lower bits_x000D_
var rangeSize = end - start;_x000D_
var randomUnder1 = this.nextInt() / this.m;_x000D_
return start + Math.floor(randomUnder1 * rangeSize);_x000D_
}_x000D_
RNG.prototype.choice = function(array) {_x000D_
return array[this.nextRange(0, array.length)];_x000D_
}_x000D_
_x000D_
var rng = new RNG(20);_x000D_
for (var i = 0; i < 10; i++)_x000D_
console.log(rng.nextRange(10, 50));_x000D_
_x000D_
var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];_x000D_
for (var i = 0; i < 10; i++)_x000D_
console.log(rng.choice(digits));
_x000D_
You really need to post a more complete example, so we can see what you're trying to do. From what you have posted, here's what I can see. First, there is no built-in round()
method. You need to either call Math.round(n)
, or statically import Math.round
, and then call it like you have.
I use:
jps
Depending on your installation a running Zookeeper would look like
HQuorumPeer
or sth. with zookeeper in it's name.
Node is complaining because there is no function called define
, which your code tries to call on its very first line.
define
comes from AMD, which is not used in standard node development.
It is possible that the developer you got your project from used some kind of trickery to use AMD in node. You should ask this person what special steps are necessary to run the code.
The most modern answer, taken from Valloric's comment above:
git mv old/submod new/submod
git status
.)git commit
and you're good to go!Done!
$scope.rtGo = function(){
$window.sessionStorage.removeItem('message');
$window.sessionStorage.removeItem('status');
}
zip, sort by the second column, return the first column.
zip(*sorted(zip(X,Y), key=operator.itemgetter(1)))[0]
Since the desired page will be called from a different domain you need to return jsonp instead of a json.
$.get("http://theSource", {callback : "?" }, "jsonp", function(data) {
$('#summary').text(data.result);
});
If the service is running via brew, you can stop it using the following command:
brew services stop mongodb
try
date.innerHTML= date.innerHTML.replace(/^(..)\//,'<span>$1</span></br>')
_x000D_
<div id="date">23/05/2013</div>
_x000D_
Handler answer in Kotlin :
1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :
fun delayFunction(function: ()-> Unit, delay: Long) {
Handler().postDelayed(function, delay)
}
2 - Then call it anywhere you needed it :
delayFunction({ myDelayedFunction() }, 300)
Age old thread, but there are new ways to run an equivalent isset()
.
Two new syntax allow us to vastly simplify the use of isset()
functionality:
Please read the docs and mind the browser compatibility.
See below for explanation. Note I use StandardJS syntax
// IMPORTANT pass a function to our isset() that returns the value we're
// trying to test(ES6 arrow function)
isset(() => some) // false
// Defining objects
let some = { nested: { value: 'hello' } }
// More tests that never throw an error
isset(() => some) // true
isset(() => some.nested) // true
isset(() => some.nested.value) // true
isset(() => some.nested.deeper.value) // false
// Less compact but still viable except when trying to use `this` context
isset(function () { return some.nested.deeper.value }) // false
/**
* Checks to see if a value is set.
*
* @param {Function} accessor Function that returns our value
* @returns {Boolean} Value is not undefined or null
*/
function isset (accessor) {
try {
// Note we're seeing if the returned value of our function is not
// undefined or null
return accessor() !== undefined && accessor() !== null
} catch (e) {
// And we're able to catch the Error it would normally throw for
// referencing a property of undefined
return false
}
}
Note that in PHP you can reference any variable at any depth - even trying to
access a non-array as an array will return a simple true
or false
:
// Referencing an undeclared variable
isset($some); // false
$some = 'hello';
// Declared but has no depth(not an array)
isset($some); // true
isset($some['nested']); // false
$some = ['nested' => 'hello'];
// Declared as an array but not with the depth we're testing for
isset($some['nested']); // true
isset($some['nested']['deeper']); // false
In JavaScript, we don't have that freedom, we'll always get an error if we do
the same because JS is immediately attempting to access the value of deeper
before we can wrap it in our isset()
function so...
// Common pitfall answer(ES6 arrow function)
const isset = (ref) => typeof ref !== 'undefined'
// Same as above
function isset (ref) { return typeof ref !== 'undefined' }
// Referencing an undeclared variable will throw an error, so no luck here
isset(some) // Error: some is not defined
// Defining a simple object with no properties - so we aren't defining
// the property `nested`
let some = {}
// Simple checking if we have a declared variable
isset(some) // true
// Now trying to see if we have a top level property, still valid
isset(some.nested) // false
// But here is where things fall apart: trying to access a deep property
// of a complex object; it will throw an error
isset(some.nested.deeper) // Error: Cannot read property 'deeper' of undefined
// ^^^^^^ undefined
More failing alternatives:
// Any way we attempt to access the `deeper` property of `nested` will
// throw an error
some.nested.deeper.hasOwnProperty('value') // Error
// ^^^^^^ undefined
Object.hasOwnProperty.call(some.nested.deeper, 'value') // Error
// ^^^^^^ undefined
// Same goes for typeof
typeof some.nested.deeper !== 'undefined' // Error
// ^^^^^^ undefined
And some working alternatives that can get redundant fast:
// Wrap everything in try...catch
try {
if (isset(some.nested.deeper)) {
// ...
}
} catch (e) {}
try {
if (typeof some.nested.deeper !== 'undefined') {
// ...
}
} catch (e) {}
// Or by chaining all of the isset which can get long
isset(some) && isset(some.nested) && isset(some.nested.deeper) // false
// ^^^^^^ returns false so the next isset() is never run
All of the other answers - though most are viable...
isset()
isset(some, 'nested.deeper.value')
eval()
which works but I personally avoidI think I covered a lot of it. There are some points I make in my answer that I don't touch upon because they - although relevant - are not part of the question(e.g. short circuiting). If need be, though, I can update my answer with links to some of the more technical aspects based on demand.
I spent waaay to much time on this so hopefully it helps people out.
Thank-you for reading!
Use typeof
or instanceof
:
const assert = require('assert');
function myFunction(Date myDate, String myString)
{
assert( typeof(myString) === 'string', 'Error message about incorrect arg type');
assert( myDate instanceof Date, 'Error message about incorrect arg type');
}
Special thanks to the answer here for more-or-less the same question.
For me, all I needed was setlocale(LC_ALL, "en_US.UTF-8");
Then, I could use even raw wchar_t
characters.
this.contentList.nativeElement.scrollTo({left: 0 , top: this.contentList.nativeElement.scrollHeight, behavior: 'smooth'});
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
Not the best way, but at lease does not need external tools (except grep, which is standard on *nix boxes anyway)
sqlite3 database.db3 .dump | grep '^INSERT INTO "tablename"'
but you do need to do this command for each table you are looking for though.
Note that this does not include schema.
NewScores is an alias to Scores table - it looks like you can combine the queries as follows:
SELECT
ROW_NUMBER() OVER( ORDER BY NETT) AS Rank,
Name,
FlagImg,
Nett,
Rounds
FROM (
SELECT
Members.FirstName + ' ' + Members.LastName AS Name,
CASE
WHEN MenuCountry.ImgURL IS NULL THEN
'~/images/flags/ismygolf.png'
ELSE
MenuCountry.ImgURL
END AS FlagImg,
AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett,
COUNT(Score.ScoreID) AS Rounds
FROM
Members
INNER JOIN
Score NewScores
ON Members.MemberID = NewScores.MemberID
LEFT OUTER JOIN MenuCountry
ON Members.Country = MenuCountry.ID
WHERE
Members.Status = 1
AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
GROUP BY
Members.FirstName + ' ' + Members.LastName,
MenuCountry.ImgURL
) AS Dertbl
ORDER BY;
<%@ page import="com.example.Status" %>
1. ${dp.status eq Title.VALID.getStatus()}
2. ${dp.status eq Title.VALID}
3. ${dp.status eq Title.VALID.toString()}
If you want to avoid the null value use IsNull(Column, 1)
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm()
method returns false
.
Swamibebop's solution works, but by taking advantage of table.*
syntax, we can avoid repeating the column names of the inner select
and get a simpler/shorter result:
SELECT @r := @r+1 ,
z.*
FROM(/* your original select statement goes in here */)z,
(SELECT @r:=0)y;
So that will give you:
SELECT @r := @r+1 ,
z.*
FROM(
SELECT itemID,
count(*) AS ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC
)z,
(SELECT @r:=0)y;
USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up
sudo systemctl enable postgresql
DISABLE exists as well ofc
Some DOC: freedesktop man systemctl
The best way is to use:
$("#yourid option:selected").text();
Depending on the requirement, you could also use this way:
var v = $("#yourid").val();
$("#yourid option[value="+v+"]").text()
A not well known feature of numpy is to use r_
. This is a simple way to build up arrays quickly:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.r_[a[None,:],b[None,:]]
print(c)
#[[1 2 3]
# [4 5 6]]
The purpose of a[None,:]
is to add an axis to array a
.
if the string is mutable, then you can transform it in place using this form:
[string replaceOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, string.length)];
this is also useful if you would like the result to be a mutable instance of an input string:
NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, string.length)];
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
Simple explanation is : STATE is local state of component for example colour = "blue" or animation=true etc . Use this.setState to change state of component. PROPS is how components talk to each other (send data from parent to child) and make components reusable .
as a workaround just add this line incase you have custom action/toolbars
this.setTitle("");
in your Activity
Just in case anyone wants yet another solution:
Hope it helps someone.
-Ev
You can use merge to combine two dataframes into one:
import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')
where on specifies field name that exists in both dataframes to join on, and how
defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y')
. if you wanted to do something like star_restaurant_id
and star_restaurant_review
, you can do:
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))
The parameters are explained in detail in this link.
Press Ctrl + KM and then type in (or click) the language you want.
Alternatively, to access it from the command palette, look for "Change Language Mode" as seen below:
Is the following acceptable:
$('#myTableRow').remove();
Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79
.
Locking a file is usually a platform-specific operation, so you may need to allow for the possibility of running on different operating systems. For example:
import os
def my_lock(f):
if os.name == "posix":
# Unix or OS X specific locking here
elif os.name == "nt":
# Windows specific locking here
else:
print "Unknown operating system, lock unavailable"
http://css-tricks.com/perfect-full-page-background-image/
//HTML
<img src="images/bg.jpg" id="bg" alt="">
//CSS
#bg {
position: fixed;
top: 0;
left: 0;
/* Preserve aspet ratio */
min-width: 100%;
min-height: 100%;
}
OR
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px) { /* Specific to this particular image */
img.bg {
left: 50%;
margin-left: -512px; /* 50% */
}
}
OR
//HTML
<img src="images/bg.jpg" id="bg" alt="">
//CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
//jQuery
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
Hibernate Criteria API (not plain SQL though, but very powerful and in active development):
List sales = session.createCriteria(Sale.class)
.add(Expression.ge("date",startDate);
.add(Expression.le("date",endDate);
.addOrder( Order.asc("date") )
.setFirstResult(0)
.setMaxResults(10)
.list();
Of course, the problem is all about getting your height back. But how can you do that if you don't know the height ahead of time? Well, if you know what aspect ratio you want to give the container (and keep it responsive), you can get your height back by adding padding to another child of the container, expressed as a percentage.
You can even add a dummy div
to the container and set something like padding-top: 56.25%
to give the dummy element a height that is a proportion of the container's width. This will push out the container and give it an aspect ratio, in this case 16:9 (56.25%).
Padding and margin use the percentage of the width, that's really the trick here.
You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:
input[type="range"] {_x000D_
position: absolute;_x000D_
top: 40%;_x000D_
transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
or the 3d transform equivalent:
input[type="range"] {
transform: rotateZ(270deg);
}
You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.
You Just need to subtract one day from today's date. In Python datetime.timedelta
object lets you create specific spans of time as a timedelta
object.
datetime.timedelta(1)
gives you the duration of "one day" and is subtractable from a datetime
object. After you subtracted the objects you can use datetime.strftime
in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime
function, you can also directly use strftime
method of datetime
objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
def yesterday(string=False):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime('%Y-%m-%d')
return yesterday
Using jQuery you can do this:
var str = '<td>1</td><td>2</td>';
$('#__TABLE__').replaceWith(str);
Or in pure javascript:
var str = '<td>1</td><td>2</td>';
var tdElement = document.getElementById('__TABLE__');
var trElement = tdElement.parentNode;
trElement.removeChild(tdElement);
trElement.innerHTML = str + trElement.innerHTML;
First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.
Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:
Consider following query.
Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A
You can use lateral in this condition.
Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
Select B.Column1,B.Column2,B.Fk1 from B Limit 1
) x ON X.Fk1 = A.PK
In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.
There are more usages for lateral or cross apply but this is most common one I found.
It's not that different in bash
.
workdone=0
while : ; do
...
if [ "$workdone" -ne 0 ]; then
break
fi
done
:
is the no-op command; its exit status is always 0, so the loop runs until workdone
is given a non-zero value.
There are many ways you could set and test the value of workdone
in order to exit the loop; the one I show above should work in any POSIX-compatible shell.
CENTERING THE WINDOW IN PYTHON Tkinter This is the most easiest thing in tkinter because all we must know is the dimension of the window as well as the dimensions of the computer screen. I come up with the following code which can help someone somehow and i did add some comments so that they can follow up.
code
# create a window first
root = Tk()
# define window dimensions width and height
window_width = 800
window_height = 500
# get the screen size of your computer [width and height using the root object as foolows]
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# Get the window position from the top dynamically as well as position from left or right as follows
position_top = int(screen_height/2 -window_height/2)
position_right = int(screen_width / 2 - window_width/2)
# this is the line that will center your window
root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')
# initialise the window
root.mainloop(0)
I had a similar problem, needed to trim trailing zeros from numbers like xx0000,x00000,xxx000
I used:
select LEFT(code,LEN(code)+1 - PATINDEX('%[1-Z]%',REVERSE(code))) from Tablename
Code is the name of the field with the number to be trimmed. Hope this helps someone else.
At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:
IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END
Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.
If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.
IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE clockDate = '08/10/2012' AND userName = 'test'
END
As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.
An excellent explanation can be found here: Generate script in SQL Server Management Studio
Courtesy Ali Issa Here's what you have to do:
If you want to create a script that just generates the tables (no data) you can skip the advanced part of the instructions!
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.
<body>
"button" value="Add Students" onclick="window.location.href='Students.html';">
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';">
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
</body>
There are a few situations where you might prefer the first one to (slightly) improve performance, for example on some JVMs without a JIT compiler.
Out of that kind of very specific context, you should use the first one.
Run:
go mod init yellow
Then create a file yellow.go
:
package yellow
func Mix(s string) string {
return s + "Yellow"
}
Then create a file orange/orange.go
:
package main
import "yellow"
func main() {
s := yellow.Mix("Red")
println(s)
}
Then build:
go build
Use these sizes 57x57, 72x72, 114x114, 144x144 then do this in the head of your document:
<link rel="apple-touch-icon" href="apple-touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-iphone4.png" />
This will look good on all apple devices. ;)
This one without maps:
public class Main {
public static void main(String[] args) {
int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
System.out.println(getMostPopularElement(a));
}
private static int getMostPopularElement(int[] a) {
int maxElementIndex = getArrayMaximumElementIndex(a);
int[] b = new int[a[maxElementIndex] + 1]
for (int i = 0; i < a.length; i++) {
++b[a[i]];
}
return getArrayMaximumElementIndex(b);
}
private static int getArrayMaximumElementIndex(int[] a) {
int maxElementIndex = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[maxElementIndex]) {
maxElementIndex = i;
}
}
return maxElementIndex;
}
}
You only have to change some code if your array can have elements which are < 0
.
And this algorithm is useful when your array items are not big numbers.
As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.
That's right. Remember that you're writing the condition in terms of what you want to keep, not in terms of what you want to drop. For df1
:
df1 = df[(df.a != -1) & (df.b != -1)]
You're saying "keep the rows in which df.a
isn't -1 and df.b
isn't -1", which is the same as dropping every row in which at least one value is -1.
For df2
:
df2 = df[(df.a != -1) | (df.b != -1)]
You're saying "keep the rows in which either df.a
or df.b
is not -1", which is the same as dropping rows where both values are -1.
PS: chained access like df['a'][1] = -1
can get you into trouble. It's better to get into the habit of using .loc
and .iloc
.
With WinForms you can use the ErrorProvider in conjunction with the Validating
event to handle the validation of user input. The Validating
event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx
Note:
=""
is a blank cell) without a need to use data
twice. The solution for goolge-spreadhseet: =ARRAYFORMULA(SUM(IFERROR(IF(data="",0,1),1)))
. For excel ={SUM(IFERROR(IF(data="",0,1),1))}
should work (press Ctrl+Shift+Enter in the formula).I came across this post as I had the same issue then I thought why mess about with css, adjusting values and hitting refresh when you can easily adjust the opacity in Photoshop? Copy the image, paste it as a new layer then move the opacity slider.
I ended up with cleaning the project file (csproj) and the applicationhost.config (iis express) with all entries regarding iis express configuration. After that, it worked.
I think you are looking for $evalAsync http://docs.angularjs.org/api/ng.$rootScope.Scope#$evalAsync
Use the constructor for appending material to the file:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
So to append to a file say "abc.txt" use
FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
In case you just need the existence of it you could also throw it off the screen with display: fixed; right: -1000px;
. It is useful when you need an input for copying to clipboard. :)
Using XAML:
If you know the other assembly
structure and want the resources
in c# code, then use below code:
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
foreach (var item in dictionary.Values)
{
//operations
}
Output: If we want to use ResourceDictionary
RD1.xaml
of Project WpfControlLibrary1
into StackOverflowApp
project.
Structure of Projects:
Code Output:
PS: All ResourceDictionary
Files should have Build Action
as 'Resource
' or 'Page
'.
Using C#:
If anyone wants the solution in purely c# code then see my this solution.
ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused
When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.
The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.
Do you really need to do that programmatically?
Just considering the title: You could use a ShapeDrawable as android:background…
For example, let's define res/drawable/my_custom_background.xml
as:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="2dp"
android:topRightRadius="0dp"
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp" />
<stroke
android:width="1dp"
android:color="@android:color/white" />
</shape>
and define android:background="@drawable/my_custom_background".
I've not tested but it should work.
Update:
I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border"
android:padding="10dip" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
[... more TextView ...]
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
</LinearLayout>
and a res/drawable/border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="5dip"
android:color="@android:color/white" />
</shape>
Reported to work on a gingerbread device. Note that you'll need to relate android:padding
of the LinearLayout to the android:width
shape/stroke's value. Please, do not use @android:color/white
in your final application but rather a project defined color.
You could apply android:background="@drawable/border" android:padding="10dip"
to each of the LinearLayout from your provided sample.
As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…
Your problem resides clearly in the use of getBorder.set{Width,Height}(100);
. Why do you do that in an onClick method?
I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.
To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…
I know it's a bit old but I ran in the same problem today. I wanted to install eclipse on my vm with xubuntu. Because I've had problems with the latest eclipse version 2019-06 I tried with Oxygen. So I went to eclipse.org and downloaded oxygen. When running oxygen, the problem with merketplace not reachable occurs. So I downloaded the eclipse installer not immediatly the oxygen. After that I can use eclipse as expectet ( all versions)
If you are looking for a better way to handle SQLException, there are a couple things you could do. First, Spring.NET does something similar to what you are looking for (I think). Here is a link to what they are doing:
http://springframework.net/docs/1.2.0/reference/html/dao.html
Also, instead of looking at the message, you could check the error code (sqlEx.Number
). That would seem to be a better way of identifying which error occurred. The only problem is that the error number returned might be different for each database provider. If you plan to switch providers, you will be back to handling it the way you are or creating an abstraction layer that translates this information for you.
Here is an example of a guy who used the error code and a config file to translate and localize user-friendly error messages:
Camel sends messages from A to B:
Why a whole framework for this? Well, what if you have:
ftp
, http
, jms
, etc.)So now you need:
Camel gives you the above (and more) out of the box:
with a cool DSL language for you to define the what and how:
new DefaultCamelContext().addRoutes(new RouteBuilder() {
public void configure() {
from("jms:incomingMessages")
.choice() // start router rules
.when(header("CamelFileName")
.endsWith(".xml"))
.to("jms:xmlMessages")
.when(header("CamelFileName")
.endsWith(".csv"))
.to("ftp:csvMessages");
}
See also this and this and Camel in Action (as others have said, an excellent book!)
Bash alternative (for Bash scripting):
psql -h localhost -U postgres -tc \
"SELECT 1 FROM pg_user WHERE usename = 'my_user'" \
| grep -q 1 \
|| psql -h localhost -U postgres \
-c "CREATE ROLE my_user LOGIN PASSWORD 'my_password';"
(isn't the answer for the question! it is only for those who may be useful)
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
Only if you want to destroy previous session :
<?php
if(!isset($_SESSION))
{
session_start();
}
else
{
session_destroy();
session_start();
}
?>
or you can use
unset($_SESSION['variable_session _data'])
to destroy a particular session variable.
Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.
In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
//your operations on file
} else {
String name = item.getFieldName();
String value = item.getString();
//you operations on paramters
}
}
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
Right now you're setting the innerHTML to an entire div element; you want to set it to just the innerHTML. Also, I think you want MyDiv2.innerHTML = MyDiv 1 .innerHTML. Also, I think the argument to document.getElementById
is case sensitive. You were passing Div2
when you wanted DIV2
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Also, this code will run before your DOM is ready. You can either put this script at the bottom of your body like paislee said, or put it in your body's onload function
<body onload="loadFunction()">
and then
function loadFunction(){
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
}
Take a look at the write.csv
or the write.table
functions. You just have to supply the file name the user selects to the file
parameter, and the dataframe to the x
parameter:
write.csv(x=df, file="myFileName")
Here is an easy way to do so using HTMLBuilder
myTextView.setText(new HtmlBuilder().
open(HtmlBuilder.Type.BOLD).
append("Some bold text ").
close(HtmlBuilder.Type.BOLD).
open(HtmlBuilder.Type.ITALIC).
append("Some italic text").
close(HtmlBuilder.Type.ITALIC).
build()
);
Result:
Some bold text Some italic text
from flask import request
@app.route('/data')
def data():
# here we want to get the value of user (i.e. ?user=some-value)
user = request.args.get('user')
I've found this way to create dataframe by raw without matrix.
With automatic column name
df<-data.frame(
t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
,row.names = NULL,stringsAsFactors = FALSE
)
With column name
df<-setNames(
data.frame(
t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
,row.names = NULL,stringsAsFactors = FALSE
),
c("col1","col2","col3")
)
Doing some Codecademy challenges I resolved this like:
def digit_sum(n):
digits = []
nstr = str(n)
for x in nstr:
digits.append(int(x))
return sum(digits)
Open your project build.gradle file and add below line under dependencies module.
dependencies {
compile 'com.google.android.gms:play-services:7.0.0'
}
The below will be add Google Analytics and Maps if you don't want to integrate full library
dependencies {
compile 'com.google.android.gms:play-services-analytics:7.0.0'
compile 'com.google.android.gms:play-services-maps:7.0.0'
}
Here is a generic wrapper which can be used to convert a binary function to multi-parameters function. The benefit of this solution is that it is very generic and can be applied to any binary functions. You just need to do it once and then you can apply it any where.
To demo the idea, I use simple recursion to implement. It can be of course implemented with more elegant way that benefits from R's good support for functional paradigm.
fold_left <- function(f) {
return(function(...) {
args <- list(...)
return(function(...){
iter <- function(result,rest) {
if (length(rest) == 0) {
return(result)
} else {
return(iter(f(result, rest[[1]], ...), rest[-1]))
}
}
return(iter(args[[1]], args[-1]))
})
})}
Then you can simply wrap any binary functions with it and call with positional parameters (usually data.frames) in the first parentheses and named parameters in the second parentheses (such as by =
or suffix =
). If no named parameters, leave second parentheses empty.
merge_all <- fold_left(merge)
merge_all(df1, df2, df3, df4, df5)(by.x = c("var1", "var2"), by.y = c("var1", "var2"))
left_join_all <- fold_left(left_join)
left_join_all(df1, df2, df3, df4, df5)(c("var1", "var2"))
left_join_all(df1, df2, df3, df4, df5)()
UPDATE mytbl
SET a = ABS(a)
where a < 0
All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.
For example:
private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
return;
MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());
}
JAPICC, sample usage:
japi-compliance-checker OLD.jar NEW.jar
Sample reports for log4j: http://abi-laboratory.pro/java/tracker/timeline/log4j/
PkgDiff, sample usage:
pkgdiff OLD.jar NEW.jar
See sample report for args4j.
Clirr, sample usage:
java -jar clirr-core-0.6-uber.jar -o OLD.jar -n NEW.jar
if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-
repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();
try like this
Some of you might find this useful. Just copy paste it to your page and you will get a sequence in which events are fired in the Chrome console (Ctrl + Shift + I).
$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});
You are not going see unload in the console as it is fired when the page is being unloaded (when you move away from the page). Use it like this:
$(window).unload(function () { debugger; console.log("window unloaded");});
And you will see what I mean.
You can use GCD (in the example with a 10 second delay):
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
I had a similar problem -- no matter what I did I couldn't get the tabsize to stick at 2, even though it is in my user settings -- that ended up being due to the EditorConfig extension. It looks for a .editorconfig
file in your current working directory and, if it doesn't find one (or the one it finds doesn't specify root=true
), it will continue looking at parent directories until it finds one.
Turns out I had a .editorconfig
in a parent directory of the dir I put all my new code projects in, and it specified a tabSize of 4. Deleting that file fixed my issue.
a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']
I can think of a one liner like this to run
ping -c 1 127.0.0.1 &> /dev/null && echo success || echo fail
Replace 127.0.0.1 with IP or hostname, replace echo commands with what needs to be done in either case.
Code above will succeed, maybe try with an IP or hostname you know that is not accessible.
Like this:
ping -c 1 google.com &> /dev/null && echo success || echo fail
and this
ping -c 1 lolcatz.ninja &> /dev/null && echo success || echo fail
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
Why not use a combination of the CSS and backend? Use:
style='text-transform:uppercase'
on the TextBox, and in your codebehind use:
Textbox.Value.ToUpper();
You can also easily change your regex on the validator to use lowercase and uppercase letters. That's probably the easier solution than forcing uppercase on them.
Finally I got a way to to solve this issue by server side as it's more like an issue with AngularJs itself I am using 1.5 Angularjs and I got same issue on reload the page.
But after adding below code in my server.js
file it is save my day but it's not a proper solution or not a good way .
app.use(function(req, res, next){
var d = res.status(404);
if(d){
res.sendfile('index.html');
}
});
You could set the @Input
on the setter directly, as described below:
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.
I know this is old but my order is as follows:
in order of public, protected, private, internal, abstract
I also like to write out properties like this (instead of the shorthand approach)
// Some where in the fields section
private int someVariable;
// I also refrain from
// declaring variables outside of the constructor
// and some where in the properties section I do
public int SomeVariable
{
get { return someVariable; }
set { someVariable = value; }
}
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
def avg(l):
"""uses floating-point division."""
return sum(l) / float(len(l))
l1 = [3,5,14,2,5,36,4,3]
l2 = [0,0,0]
print(avg(l1)) # 9.0
print(avg(l2)) # 0.0
It is now possible with the HTML5 webapp manifest. See below.
Original answer:
You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.
You can detect the device orientation with CSS3 media queries like this:
@media screen and (orientation:portrait) {
// CSS applied when the device is in portrait mode
}
@media screen and (orientation:landscape) {
// CSS applied when the device is in landscape mode
}
Or by binding a JavaScript orientation change event like this:
document.addEventListener("orientationchange", function(event){
switch(window.orientation)
{
case -90: case 90:
/* Device is in landscape mode */
break;
default:
/* Device is in portrait mode */
}
});
Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.
As explained on html5rocks.com, you can now force the orientation mode using a manifest.json
file.
You need to include those line into the json file:
{
"display": "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
"orientation": "landscape", /* Could be "landscape" or "portrait" */
...
}
And you need to include the manifest into your html file like this:
<link rel="manifest" href="manifest.json">
Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.
Problem solved with data-container="body" and z-index
1->
<div class="button btn-align"
data-container="body"
data-toggle="popover"
data-placement="top"
title="Top"
data-trigger="hover"
data-title-backcolor="#fff"
data-content="A top aligned popover is a really boring thing in the real
life.">Top</div>
2->
.ggpopover.in {
z-index: 9999 !important;
}
You can do this with the scp
command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp
to allow references to other systems:
scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file
Copy something from this machine to some other machine:
scp /path/to/local/file username@hostname:/path/to/remote/file
Copy something from another machine to this machine:
scp username@hostname:/path/to/remote/file /path/to/local/file
Copy with a port number specified:
scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file
To add to @luke-west 's excellent answer:
OLD.xcworkspace
to NEW.xcworkspace
.Podfile
from the project navigator. You should see a target
clause with the OLD name. Change it to NEW.OLD.podspec
file.rm -rf Pods/
pod install
.Build Phases
tab.Link Binary With Libraries
, look for libPods-OLD.a
and delete
it.this also works, and prolly is more readable than the echo version:
printf "`date` User `whoami` started the script.\r\n" >> output.log
mysql> CREATE USER 'name'@'%' IDENTIFIED BY 'passWord'; Query OK, 0 rows affected (0.00 sec)
mysql> GRANT ALL PRIVILEGES ON . TO 'name'@'%'; Query OK, 0 rows affected (0.00 sec)
mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)
mysql>
hope this helps someone...
Alternatively you could read you csv with header=None
and then add it with df.columns
:
Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]
using SimpleDateFormat or DateFormat class through
for e.g.
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}
os.path.split(os.path.abspath(mydir))[0]
A much simpler alternative is to get the information from the connection object itself. For example:
IDbConnection connection = new SqlConnection(connectionString);
var dbName = connection.Database;
Similarly you can get the server name as well from the connection object.
DbConnection connection = new SqlConnection(connectionString);
var server = connection.DataSource;
How about a pure CSS solution without being (that) hacky?
.page {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
right: 0;_x000D_
left: 0;_x000D_
background-color: #121519;_x000D_
color: whitesmoke;_x000D_
}_x000D_
_x000D_
.controls {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.arrow {_x000D_
cursor: pointer;_x000D_
transition: filter 0.3s ease 0.3s;_x000D_
}_x000D_
_x000D_
.arrow:active {_x000D_
filter: drop-shadow(0 0 0 steelblue);_x000D_
transition: filter 0s;_x000D_
}
_x000D_
<body class="page">_x000D_
<div class="controls">_x000D_
<div class="arrow">_x000D_
<img src="https://i.imgur.com/JGUoNfS.png" />_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
@TylerH has a great response but its a pretty complex solution. I have a solution for those of you that just want a simple "onclick" effect with pure css without a bunch of extra elements.
We will simply use css transitions. You could probably do similar with animations.
The trick is to change the delay for the transition so that it will last when the user clicks.
.arrowDownContainer:active,
.arrowDownContainer.clicked {
filter: drop-shadow(0px 0px 0px steelblue);
transition: filter 0s;
}
Here I add the "clicked" class as well so that javascript can also provide the effect if it needs to. I use 0px drop-shadow filter because it will highlight the given transparent graphic blue this way for my case.
I have a filter at 0s here so that it wont take effect. When the effect is released I can then add the transition with a delay so that it will provide a nice "clicked" effect.
.arrowDownContainer {
cursor: pointer;
position: absolute;
bottom: 0px;
top: 490px;
left: 108px;
height: 222px;
width: 495px;
z-index: 3;
transition: filter 0.3s ease 0.3s;
}
This allows me to set it up so that when the user clicks the button, it highlights blue then fades out slowly (you could, of course, use other effects as well).
While you are limited here in the sense that the animation to highlight is instant, it does still provide the desired effect. You could likely use this trick with animation to produce a smoother overall transition.
tchester said :
(2) Create a login for the non-sysadmin user that has public access to the master database
I went to my user's database list (server/security/connections/my user name/properties/user mapping, and wanted to check the box for master database. I got an error message telling that the user already exists in the master database. Went to master database, dropped the user, went back to "user mapping" and checked the box for master. Check the "public" box below.
After that, you need to re-issue the grant execute on xp_cmdshell to "my user name"
Yves
I think what you want is this:
last_list=[]
if p.last_name != None and p.last_name != "":
last_list.append(p.last_name)
print last_list
Your current if statement:
if p.last_name == None or p.last_name == "":
pass
Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.
Also, it looks like your statement pan_list.append(p.last)
is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.
The easiest way is to simply use the
stmt.setString(position, xml);
methods (for "small" strings which can be easily kept in Java memory), or
try {
java.sql.Clob clob =
oracle.sql.CLOB.createTemporary(
connection, false, oracle.sql.CLOB.DURATION_SESSION);
clob.setString(1, xml);
stmt.setClob(position, clob);
stmt.execute();
}
// Important!
finally {
clob.free();
}
I was having the same issue. It was due to a typo in an attribute in one of my XML file. Anyways, Android Studio did not specify the source of the error in the first run. But when I did a
Build -> Clean Project
and then ran the app again it showed me the exact line in the XML code where the typo was.
UPDATE 12/11/2019: Material Components Library
With the Material Components and Androidx libraries you can use:
the android:background
attribute in the layout:
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
apply the default style: style="@style/Widget.MaterialComponents.Toolbar.Primary"
or customize the style inheriting from it:
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
style="@style/Widget.MaterialComponents.Toolbar.Primary"
override the default color using the android:theme
attribute:
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="@style/MyThemeOverlay_Toolbar"
with:
<style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
<item name="android:textColorPrimary">....</item>
<item name="colorPrimary">@color/.....
<item name="colorOnPrimary">@color/....</item>
</style>
OLD: Support libraries:
You can use a app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
theme as suggested in other answers, but you can also use a solution like this:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
style="@style/HeaderBar"
app:theme="@style/ActionBarThemeOverlay"
app:popupTheme="@style/ActionBarPopupThemeOverlay"/>
And you can have the full control of your ui elements with these styles:
<style name="ActionBarThemeOverlay" parent="">
<item name="android:textColorPrimary">#fff</item>
<item name="colorControlNormal">#fff</item>
<item name="colorControlHighlight">#3fff</item>
</style>
<style name="HeaderBar">
<item name="android:background">?colorPrimary</item>
</style>
<style name="ActionBarPopupThemeOverlay" parent="ThemeOverlay.AppCompat.Light" >
<item name="android:background">@android:color/white</item>
<item name="android:textColor">#000</item>
</style>
In my case, I was using Nginx in front of my application with the following configuration:
location / {
proxy_pass http://localhost:8080/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
add_header Content-Security-Policy 'upgrade-insecure-requests';
}
so in my application I get the real user ip like so:
String clientIP = request.getHeader("X-Real-IP");
My preference is to utilize the inline
attribute. This will cause the icon to correctly scale with the size of the button.
<button mat-button>
<mat-icon inline=true>local_movies</mat-icon>
Movies
</button>
<!-- Link button -->
<a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>
I add this to my styles.css
to:
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
vertical-align: top;
font-size: 1.25em;
}
All p
tags with class some_class
which are direct children of a div
tag.
In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.
Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.
# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]
# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]
# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
You're mapping this JSON
{
"id": 2,
"socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
"type": "getDashboard",
"data": {
"workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
},
"reply": true
}
that contains an element named data
that has a JSON object as its value. You are trying to deserialize the element named workstationUuid
from that JSON object into this setter.
@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {
This won't work directly because Jackson sees a JSON_OBJECT, not a String.
Try creating a class Data
public class Data { // the name doesn't matter
@JsonProperty("workstationUuid")
private String workstationUuid;
// getter and setter
}
the switch up your method
@JsonProperty("data")
public void setWorkstation(Data data) {
// use getter to retrieve it
Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431
So if you want to validate if your date string (let's call it datestr
) is in the correct format, it is best to parse it with date
and ask date
to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.
if [[ "$datestr" == $(date -d "$datestr" "+%Y%m%d" 2>/dev/null) ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
Necroing this question but there's an explanation that no-one seems to have considered.
STATISTICS - Statistics are not available or misleading
If all of the following are true:
Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.
As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
Demo: https://ideone.com/rMF2XA
Note that any of the quoting mechanisms -- \____HERE
or "____HERE"
or '____HERE'
-- will disable all variable interpolation, and turn the here-document into a piece of literal text.
A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
:
You can use:
File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO
If you have an enumerable and not an array, you can use:
File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq
An alternative is to call the pip
module by using python2.7, as below:
python2.7 -m pip <commands>
For example, you could run python2.7 -m pip install <package>
to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.
In case the pip module has not yet been installed for this version of python, you can run the following:
python2.7 -m ensurepip
Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo
). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.
Or far simpler than dealing with Spannable
s manually, since you didn't say that you want the background highlighted, just the text:
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
Here's an extension method for converting a Bitmap to BitmapImage.
public static BitmapImage ToBitmapImage(this Bitmap bitmap)
{
using (var memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
}
Use the CSS display values of table and table-cell:
HTML
<html>
<body>
<div class="valign bottom">
<div>
<div>my bottom aligned div 1</div>
<div>my bottom aligned div 2</div>
<div>my bottom aligned div 3</div>
</div>
</div>
</body>
</html>
CSS
html,body {
width: 100%;
height: 100%;
}
.valign {
display: table;
width: 100%;
height: 100%;
}
.valign > div {
display: table-cell;
width: 100%;
height: 100%;
}
.valign.bottom > div {
vertical-align: bottom;
}
I've created a JSBin demo here: http://jsbin.com/INOnAkuF/2/edit
The demo also has an example how to vertically center align using the same technique.
You're not running a module -- you're running subroutines/functions that happen to be stored in modules.
If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).
Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:
SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
FROM MyTable;
That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.
Subroutines (i.e., code that returns no value) are not callable from within SQL statements.
The common way is the format()
function:
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
It works fine with a multi-line format string:
>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.
You can also pass a dictionary with variables:
>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
The closest thing to what you asked (in terms of syntax) are template strings. For example:
>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
I should add though that the format()
function is more common because it's readily available and it does not require an import line.
patrick dw's answer is right on.
For kicks and giggles I thought I would post a simple way to return an array of all the IDs.
var arrayOfIds = $.map($(".myClassName"), function(n, i){
return n.id;
});
alert(arrayOfIds);
Two ways:
If your class has a no-arg constructor, you can get a Class
object using Class.forName()
and use the newInstance()
method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).
For example:
Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.newInstance();
An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor
object and call a newInstance()
method on this object:
Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);
Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:
You don't define the vector, url
, before trying to subset it. url
is also a function in the base package, so url[i]
is attempting to subset that function... which doesn't make sense.
You probably defined url
in your prior R session, but forgot to copy that code to your script.
I had a problem like this before, it was the gradle.properties file doesn't exist, only the gradle.properties.txt , so i went to my project folder and i copied & pasted the gradle.properties.txt file but without .txt extension then it finally worked.
The worse language I've ever seen come from the tool praat, which is a good audio analysis tool. It does a pretty good job until you use the script language. sigh bad memories.
string = selected("Strings")
Nothing special here, you assign to the variable string the result of the selected function. Not really scary... yet.
Create Strings as file list... liste 'path$'/'type$'
As you can see, the function name start at "Create" and finish with the "...". The command "Create Strings as file list" is the text displayed on a button or a menu (I'm to scared to check) on praat. This command take 2 parameters liste and an expression. I'm going to look deeper in the expression 'path$'/'type$'
Hmm. Yep. No spaces. If spaces were introduced, it would be separate arguments. As you can imagine, parenthesis don't work. At this point of the description I would like to point out the suffix of the variable names. I won't develop it in this paragraph, I'm just teasing.
noliftt = Get number of strings
windowname$ = left$(line$,length(line$)-4)
So, what's going on there? It's now time to look at the convention and types of expression, so here we got :
for i from 1 to 4
Select... time time
bandwidth'i'$ = Get bandwidth... i
forhertz'i'$ = Get formant... i
endfor
We got i which is a number and... (no it's not a function)
bandwidth'i'$
What it does is create string variables : bandwidth1$
, bandwidth2$
, bandwidth3$
, bandwidth4$
and give them values. As you can expect, you can't create two dimensional array this way, you must do something like that :
band2D__'i'__'j'$
outline$ = "'time'@F'i':'forhertznum'Hz,'bandnum'Hz, 'spec''newline$'"
outline$ >> 'outfile$'
Strings are weirdly (at least) handled in the language. the '' is used to call the value of a variable inside the global "" string. This is weird. It goes against all the convention built into many languages from bash to PHP passing by the powershell. And look, it even got redirection. Don't be fooled, it doesn't work like in your beloved shell. No you have to get the variable value with the ''
I'm going to put the final touch to this wonderderderfulful presentation by talking to you about the execution model. So as in every procedural languages you got instruction executed from top to bottom, there is the variables and the praat GUI. That is you code everything on the praat gui, you invoke commands written on menu/buttons.
The main window of praat contain a list of items which can be :
To Spectrogram... 0.005 5000 0.002 20 Gaussian
" is like that because it follows this layout:
Needless to say, my nightmares are filled with praat scripts dancing around me and shouting "DEBUG MEEEE!!".
More information at the praat site, under the well-named section "easy programmable scripting language"
The message is clear: you have a repeated column in the mapping. That means you mapped the same database column twice. And indeed, you have:
@Column(nullable=false)
private Long customerId;
and also:
@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer")
private Customer customer;
(and the same goes for productId
/product
).
You shouldn't reference other entities by their ID, but by a direct reference to the entity. Remove the customerId
field, it's useless. And do the same for productId
. If you want the customer ID of a sale, you just need to do this:
sale.getCustomer().getId()