I am using the new EF & Identity Core and I have the same issue, with the addition that I've got this error:
The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked.
With the new DI model I added the constructor's Controller the context to the DB.
I tried to see what are the conflict with _conext.ChangeTracker.Entries()
and adding AsNoTracking()
to my calls without success.
I only need to change the state of my object (in this case Identity)
_context.Entry(user).State = EntityState.Modified;
var result = await _userManager.UpdateAsync(user);
And worked without create another store or object and mapping.
I hope someone else is useful my two cents.
Here is a concise breadth-first iterative solution, which I prefer to recursion:
const findCar = function(car) {
const carSearch = [cars];
while(carSearch.length) {
let item = carSearch.shift();
if (item.label === car) return true;
carSearch.push(...item.subs);
}
return false;
}
Alternative answer, you can use this JDBC URL directly in your datasource configuration:
jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull
Edit:
Datetimes with all-zero components (0000-00-00 ...) — These values can not be represented reliably in Java. Connector/J 3.0.x always converted them to NULL when being read from a ResultSet.
Connector/J 3.1 throws an exception by default when these values are encountered as this is the most correct behavior according to the JDBC and SQL standards. This behavior can be modified using the zeroDateTimeBehavior configuration property. The allowable values are:
- exception (the default), which throws an SQLException with an SQLState of S1009.
- convertToNull, which returns NULL instead of the date.
- round, which rounds the date to the nearest closest value which is 0001-01-01.
Update: Alexander reported a bug affecting mysql-connector-5.1.15 on that feature. See CHANGELOGS on the official website.
Code:
str = "http://localhost/with spaces and spaces"
encoded = URI::encode(str)
puts encoded
Result:
http://localhost/with%20spaces%20and%20spaces
If you have more than one button, then you can do the following.
<div class="center-block" style="max-width:400px">
<a href="#" class="btn btn-success">Accept</a>
<a href="#" class="btn btn-danger"> Reject</a>
</div>
This is how i do it.
<?php echo 'rgba('.rand(0,255).', '.rand(0,255).', '.rand(0,255).', 0.73)'; ?>
It's been many functions, macros and objects since I posted this question. The way I handled it, which is mentioned in one of the answers here, is by creating a string function that handles the errors that get generate by the vlookup function, and returns either nothing or the vlookup result if any.
Function fsVlookup(ByVal pSearch As Range, ByVal pMatrix As Range, ByVal pMatColNum As Integer) As String
Dim s As String
On Error Resume Next
s = Application.WorksheetFunction.VLookup(pSearch, pMatrix, pMatColNum, False)
If IsError(s) Then
fsVlookup = ""
Else
fsVlookup = s
End If
End Function
One could argue about the position of the error handling or by shortening this code, but it works in all cases for me, and as they say, "if it ain't broke, don't try and fix it".
Use this simple code for generate med-strong password 12 length
$password_string = '!@#$%*&abcdefghijklmnpqrstuwxyzABCDEFGHJKLMNPQRSTUWXYZ23456789';
$password = substr(str_shuffle($password_string), 0, 12);
CAST both fields to datatype DATE and you can use a minus:
(CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
Test case:
SELECT (CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
FROM
generate_series('2014-01-01'::timestamp, '2014-02-01'::timestamp, interval '1 hour') g(joindate);
Result: 31
Or create a function datediff():
CREATE OR REPLACE FUNCTION datediff(timestamp, timestamp)
RETURNS int
LANGUAGE sql
AS
$$
SELECT CAST($1 AS date) - CAST($2 AS date) as DateDifference
$$;
console.log(_x000D_
_x000D_
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")_x000D_
_x000D_
)
_x000D_
FormHelper::select(string $fieldName, array $options,
array $attributes)
$attributes['value']
to set which value should be selected default
<?php echo $this->Form->select('status', $list, array(
'empty' => false,
'value' => 1)
); ?>
here is the automatic spin and rotating zoom effect using css3
#obj1{
float:right;
width: 96px;
height: 100px;
-webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
animation: mymove 20s infinite;
animation-delay:2s;
background-image:url("obj1.png");
transform: scale(1.5);
-moz-transform: scale(1.5);
-webkit-transform: scale(1.5);
-o-transform: scale(1.5);
-ms-transform: scale(1.5); /* IE 9 */
margin-bottom: 70px;
}
#obj2{
float:right;
width: 96px;
height: 100px;
-webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
animation: mymove 20s infinite;
animation-delay:2s;
background-image:url("obj2.png");
transform: scale(1.5);
-moz-transform: scale(1.5);
-webkit-transform: scale(1.5);
-o-transform: scale(1.5);
-ms-transform: scale(1.5); /* IE 9 */
margin-bottom: 70px;
}
#obj6{
float:right;
width: 96px;
height: 100px;
-webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
animation: mymove 20s infinite;
animation-delay:2s;
background-image:url("obj6.png");
transform: scale(1.5);
-moz-transform: scale(1.5);
-webkit-transform: scale(1.5);
-o-transform: scale(1.5);
-ms-transform: scale(1.5); /* IE 9 */
margin-bottom: 70px;
}
/* Standard syntax */
@keyframes mymove {
50% {transform: rotate(30deg);
}
<div style="width:100px; float:right; ">
<div id="obj2"></div><br /><br /><br />
<div id="obj6"></div><br /><br /><br />
<div id="obj1"></div><br /><br /><br />
</div>
Here is the demo
I changed the memory limit from .htaccess and this problem got resolved.
I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:
php_value memory_limit 512M
After scan was over, I removed this line to make the size as it was before.
If I remember from your previous questions, you're binding to a DataTable. Try this:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable sourceData = (DataTable)GridView1.DataSource;
sourceData.Rows[e.RowIndex].Delete();
GridVie1.DataSource = sourceData;
GridView1.DataBind();
}
Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.
If you're looking for a quick solution to load images over HTTPS then the free reverse proxy service at https://images.weserv.nl/ may interest you. It was exactly what I was looking for.
If you're looking for a paid solution, I have previously used Cloudinary.com which also works well but is too expensive solely for this task, in my opinion.
Follow these steps :
Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder. Refer the screenshot :
<content>(?:[^\n]*(\n+))+</content>
When we open a modal it accept size as a paramenter:
Possible values for it size: sm, md, lg
$scope.openModal = function (size) {
var modal = $modal.open({
size: size,
templateUrl: "/app/user/welcome.html",
......
});
}
HTML:
<button type="button"
class="btn btn-default"
ng-click="openModal('sm')">Small Modal</button>
<button type="button"
class="btn btn-default"
ng-click="openModal('md')">Medium Modal</button>
<button type="button"
class="btn btn-default"
ng-click="openModal('lg')">Large Modal</button>
If you want any specific size, add style on model HTML:
<style>.modal-dialog {width: 500px;} </style>
Webkit is an HTML rendering engine used by Chrome and Safari.
It supports a number of custom CSS properties that are prefixed by -webkit-
.
In Windows nslookup
the command is
ls -d somedomain.com > outfile.txt
which stores the subdomain list in outfile.txt
few domains these days allow this
I am using following in SSRS 2005
=Format(Globals!ExecutionTime,"MM-dd-yyyy" & " ")
& CStr(Hour(Globals!ExecutionTime)) & ":"
& CStr(Minute(Globals!ExecutionTime))
Or
=Format(Globals!ExecutionTime,"MM-dd-yyyy" & " ")
& Right("00" & CStr(Hour(Globals!ExecutionTime)), 2)
& ":"
& Right("00" & CStr(Minute(Globals!ExecutionTime)), 2)
Based on comment:
=Format(CDate(Globals!ExecutionTime), "MM-dd-yyyy hh:mm.ss")
OR
=Format(CDate(Globals!ExecutionTime), "MM-dd-yyyy HH:mm.ss")
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
The open-source Angara.Table library allows to load CSV into typed columns, so you can get the arrays from the columns. Each column can be indexed both by name or index. See http://predictionmachines.github.io/Angara.Table/saveload.html.
The library follows RFC4180 for CSV; it enables type inference and multiline strings.
Example:
using System.Collections.Immutable;
using Angara.Data;
using Angara.Data.DelimitedFile;
...
ReadSettings settings = new ReadSettings(Delimiter.Semicolon, false, true, null, null);
Table table = Table.Load("data.csv", settings);
ImmutableArray<double> a = table["double-column-name"].Rows.AsReal;
for(int i = 0; i < a.Length; i++)
{
Console.WriteLine("{0}: {1}", i, a[i]);
}
You can see a column type using the type Column, e.g.
Column c = table["double-column-name"];
Console.WriteLine("Column {0} is double: {1}", c.Name, c.Rows.IsRealColumn);
Since the library is focused on F#, you might need to add a reference to the FSharp.Core 4.4 assembly; click 'Add Reference' on the project and choose FSharp.Core 4.4 under "Assemblies" -> "Extensions".
In my case finish()
executed immediately after a dialog has shown.
Create a new file startCmdLine.bat in your directory and put this line in it
call cmd
That is it. Now double click on the .bat file. It works for me.
You can replace call with start, it will also work.
And,
I suggest you to learn about system configuration.
How to Show All Categories on System Configuration Field?
Here I solved with a good example. It working. You can check and learn the flow of code.
There are other too many examples also that you should learn.
SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))
How about this:
string test = "01-12-12";
try{
DateTime dateTime = DateTime.Parse(test);
test = dateTime.ToString("dd/yyyy");
}
catch (FormatException exc)
{
MessageBox.Show(exc.Message);
}
Where test will be equal to "12/2012"
Hope it helps!
Please read HERE.
You'll have to turn to Flash, Java or Silverlight. In the case of Silverlight, you'll be looking at Isolated Storage. That will get you write to files in your own playground on the users disk. It won't let you write outside of your playground though.
try something like
background: url(bgimage.jpg) no-repeat;
background-size: 100%;
Simple ready2use snippet, working perfectly for me
static void waitForPageLoad(WebDriver wdriver) {
WebDriverWait wait = new WebDriverWait(wdriver, 60);
Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver input) {
return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
}
};
wait.until(pageLoaded);
}
$('#cloneDiv').click(function(){
// get the last DIV which ID starts with ^= "klon"
var $div = $('div[id^="klon"]:last');
// Read the Number from that DIV's ID (i.e: 3 from "klon3")
// And increment that number by 1
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
var $klon = $div.clone().prop('id', 'klon'+num );
// Finally insert $klon wherever you want
$div.after( $klon.text('klon'+num) );
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
You might be using C:/[your-php-directory]/php.exe in Handler mapping of IIS just change it C:/[your-php-directory]/php-cgi.exe.
In CSS you can use the color string currentColor
inside a link to eg make the border the same color as your default link color:
.example {
border: 1px solid currentColor;
}
Actually, a third is preferred:
ArrayList<Object> array = new ArrayList<Object>();
array.add(Integer.valueOf(3));
array.add("ss");
This avoids autoboxing (Integer.valueOf(3)
versus 3
) and doesn't create an unnecessary String object.
Eclipse complains when you don't use type arguments with a generic type like ArrayList, because you are using something called a raw type, which is discouraged. If a class is generic (that is, it has type parameters), then you should always use type arguments with that class.
Autoboxing, on the other hand, is a personal preference. Some people are okay with it, and some not. I don't like it, and I turn on the warning for autoboxing/autounboxing.
It wasn't working because your image was too big - there are restrictions on the image dimensions. In Firefox, for example, the size limit is 128x128px. See this page for more details.
Additionally, you also have to add in auto
.
jsFiddle demo here - note that's an actual image, and not a default cursor.
.test {_x000D_
background:gray;_x000D_
width:200px;_x000D_
height:200px;_x000D_
cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif), auto;_x000D_
}
_x000D_
<div class="test">TEST</div>
_x000D_
Create a new Item and go to the last you'll find option to copy from existing, just write your current job name and you will have clone of that project to work with.
<c:if test="${ansokanInfo.pSystem eq 'NAT'}">
TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])
try this:
=(RIGHT(E9;3))+(MID(E9;7;2)*1000)+(MID(E9;5;2)*3600000)+(LEFT(E9;2)*216000000)
Maybe you need to change semi-colon by coma...
You can do it with css first-letter! eg I wanted it for the Menu:
a {display:inline-block; text-transorm:uppercase;}
a::first-letter {font-size:50px;}
It only runs with block elements - therefore the inline-block!
I think you are creating a document that looks like this:
<mycatch>
....
</mycatch>
<mycatch>
....
</mycatch>
This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in
<mydocument>
<mycatch>
....
</mycatch>
<mycatch>
....
</mycatch>
....
</mydocument>
Since pip 20.1b1, which was released on 21 April 2020 and "added pip cache
command for inspecting/managing pip’s wheel cache", it is possible to issue this command:
pip cache purge
The reference guide is here:
https://pip.pypa.io/en/stable/reference/pip_cache/
The corresponding pull request is here.
In SQL SERVER it is BIT
, though it allows NULL
to be stored
ALTER TABLE person add [AdminApproved] BIT default 'FALSE';
Also there are other mistakes in your query
When you alter a table to add column no need to mention column
keyword in alter
statement
For adding default constraint no need to use SET
keyword
Default value for a BIT
column can be ('TRUE' or '1')
/ ('FALSE' or 0)
. TRUE
or FALSE
needs to mentioned as string
not as Identifier
As a general architectural point, I usually advise against letting dependencies on a particular serialization format bleed out beyond your storage/networking layer; thus, I'd first recommend that you consider testing equality between your own application objects rather than their JSON manifestations.
Having said that, I'm currently a big fan of Jackson which my quick read of their ObjectNode.equals() implementation suggests does the set membership comparison that you want:
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o.getClass() != getClass()) {
return false;
}
ObjectNode other = (ObjectNode) o;
if (other.size() != size()) {
return false;
}
if (_children != null) {
for (Map.Entry<String, JsonNode> en : _children.entrySet()) {
String key = en.getKey();
JsonNode value = en.getValue();
JsonNode otherValue = other.get(key);
if (otherValue == null || !otherValue.equals(value)) {
return false;
}
}
}
return true;
}
Are you sure you're not confusing Oracle database with Oracle SQL Developer?
The database itself has no date format, the date comes out of the database in raw form. It's up to the client software to render it, and SQL Developer does use YYYY-MM-DD as its default format, which is next to useless, I agree.
edit: As was commented below, SQL Developer can be reconfigured to display DATE values properly, it just has bad defaults.
From http://www.coderanch.com/t/587493/vc/Debugging-Eclipse-Source
"When running in debug mode, right click on the running thread (in threads tab) and select Edit Source Lookup. At this point, you should be able to add the necessary project/jar which contains your source code."
I added my current project in this way, and it solved my problem
This issue occurs because of the Gradle version changes, since your application uses old version of gradle, you need to update to new version.
This changes needs to be done in build.gradle file, have look at this link http://www.feelzdroid.com/2015/11/android-plugin-too-old-update-recent-version.html. to know how to update the gradle and detailed steps are provided. there.
Thans
In my case, I has having problems removing and reinstalling SaltStack.
After running:
ls -lah /usr/local/Cellar/salt/
I noticed that the group owner was "staff". (BTW, I'm running macOS Mojave version 10.14.3.) The staff group could be related to my workplace configuration, but I don't really know. Regardless, I preserved the group to prevent myself from breaking anything further.
I then ran:
sudo chown -R "$USER":staff /usr/local/Cellar/salt/
After that, I was successfully able to remove it with this command (not as root):
brew uninstall --force salt
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@color/orange"/>
</shape>
</item>
<item
android:top="2dp"
android:bottom="2dp"
android:left="2dp"
android:right="2dp">
<shape android:shape="oval">
<solid android:color="@color/white"/>
</shape>
</item>
<item
android:drawable="@drawable/messages" //here messages is my image name, please give here your image name.
android:bottom="15dp"
android:left="15dp"
android:right="15dp"
android:top="15dp"/>
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/merchant_circle" /> // here merchant_circle will be your first .xml file name
Configure your package.json file
"test": "jest --coverage",
Now run:
yarn test
All the test will start running and you will get the report.
When define some member variable outside any member method, the variable can be either static or non-static depending on how the variable is expressed.
For example:
#!/usr/bin/python
class A:
var=1
def printvar(self):
print "self.var is %d" % self.var
print "A.var is %d" % A.var
a = A()
a.var = 2
a.printvar()
A.var = 3
a.printvar()
The results are
self.var is 2
A.var is 1
self.var is 2
A.var is 3
Always : If you always want vertical scrollbar, use overflow-y: scroll;
<div style="overflow-y: scroll;">
......
</div>
When needed: If you only want vertical scrollbar when needed, use overflow-y: auto;
(You need to specify a height in this case)
<div style="overflow-y: auto; height:150px; ">
....
</div>
mysqli_error()
As in:
$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);
Trigger error is better than die because you can use it for development AND production, it's the permanent solution.
It's not compiling that's hurting me here, it's the typing. I could disable all the smart features and be back to notepad++ like TomTsagk suggested in a comment. For today I need more cores and RAM.
Playing devil's advocate I'd argue that typing shouldn't require a 16Gb PC octacore PC. Liked Sajan Rana's advice but things are so slow here it felt mostly a placebo.
To be fair I am using 1.4RC1, which is just short of being in the stable branch. Turning the internet off helped a little. The new feature of simultaneous Design (Preview) and Text views working with XML layouts is very helpful.
No, it is ridiculous. Never leave the stable channel.
I always prefer to read input using nextLine()
and then parse the string.
Using next()
will only return what comes before the delimiter (defaults to whitespace). nextLine()
automatically moves the scanner down after returning the current line.
A useful tool for parsing data from nextLine()
would be str.split("\\s+")
.
String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces
For more information regarding the Scanner class or String class refer to the following links.
Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.
The hidden
attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden
property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:
https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden
Using these standards can make it easier for disabled people to use the web.
If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:
alias df-gb='df -BG'
So if you type:
df-gb
into a terminal, you'll get your intended output of the disk usage in GB.
EDIT: or even use just df -h
to get it in a standard, human readable format.
Get list commit
git log --oneline
For example, Stable commit has hash: 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git reset --hard 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git push -ff origin master
I know this is an old question, but I recently ran into this same issue. It ended up being a Proguard problem (when I set minifyEnabled
to false
it stopped happening.)
To stop it, with proguard enabled, I added the following to my proguard rules file, thanks to a solution I found elsewhere (after discovering that the problem was proguard)
-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.** { *; }
Not sure if they're necessary, but I also added these lines:
-keep class com.google.** { *; }
-keep interface com.google.** { *; }
The following php snippets would return the text between html tags/elements.
regex : "/tagname(.*)endtag/" will return text between tags.
i.e.
$regex="/[start_tag_name](.*)[/end_tag_name]/";
$content="[start_tag_name]SOME TEXT[/end_tag_name]";
preg_replace($regex,$content);
It will return "SOME TEXT".
If none of your routes contain closures, but you are still getting this error, please check
routes/api.php
Laravel has a default auth api route in the above file.
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
which can be commented or replaced with a call to controller method if required.
Take a clone of a remote repository and run git branch -a
(to show all the branches git knows about). It will probably look something like this:
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
Here, master
is a branch in the local repository. remotes/origin/master
is a branch named master
on the remote named origin
. You can refer to this as either origin/master
, as in:
git diff origin/master..master
You can also refer to it as remotes/origin/master
:
git diff remotes/origin/master..master
These are just two different ways of referring to the same thing (incidentally, both of these commands mean "show me the changes between the remote master
branch and my master
branch).
remotes/origin/HEAD
is the default branch
for the remote named origin
. This lets you simply say origin
instead of origin/master
.
Using event.target.reset()
only works for uncontrolled components, which is not recommended. For controlled components you would do something like this:
import React, { Component } from 'react'
class MyForm extends Component {
initialState = { name: '' }
state = this.initialState
handleFormReset = () => {
this.setState(() => this.initialState)
}
render() {
return (
<form onReset={this.handleFormReset}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
placeholder="Enter name"
name="name"
value={name}
onChange={this.handleInputOnChange}
/>
</div>
<div>
<input
type="submit"
value="Submit"
/>
<input
type="reset"
value="Reset"
/>
</div>
</form>
)
}
}
ContactAdd.propTypes = {}
export default MyForm
The cause is the difference between how a Windows-based based OS and a Unix based OS store the end-of-line markers.
Windows based operating systems, thanks to their DOS heritage, store an end-of-line as a pair of characters - 0x0D0A
(carriage return + line feed). Unix-based operating systems just use 0x0A
(a line feed). The ^M
you're seeing is a visual representation of 0x0D
(a carriage return).
dos2unix will help with this. You probably also need to adjust the source of the scripts to be 'Unix-friendly'.
There are several ways to do it, through settings or by deleting the cache.
Deleting the cache is the most versatile method. First, locate it:
On XP, it was located here:
C:\Documents and Settings\%USER%\Application Data\Subversion\auth\svn.simple\
On Vista, it was located here:
C:\Users\%USER%\AppData\Roaming\Subversion\auth\svn.simple\
Then look in those files with Notepad, and delete the one with your credentials.
Had the same problem. This worked for me -
$('selector').once().click(function() {});
Hope this helps someone.
I have always been a fan of WinMerge which is an open source project. You can plug it into Visual Studio fairly easily.
will show you how to do this
You have to convert the int into a string:
"abc" + str(9)
Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.Exampleslazy=true (default)Address child of User class can be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.
I had this issue today, and for me the problem was that I had allocated too much memory:
-Xmx1024M -XX:MaxPermSize=1024m
Once I reduced the PermGen space, everything worked fine:
-Xmx1024M -XX:MaxPermSize=512m
I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
It turns out that writing a performant scaler is not trivial. I did it once for an open source project: ImageScaler.
In principle 'java.awt.Image#getScaledInstance(int, int, int)' would do the job as well, but there is a nasty bug with this - refer to my link for details.
Using generics (as in the above answers) is your best bet here. I've just double checked and:
test.put("test", arraylistone);
ArrayList current = new ArrayList();
current = (ArrayList) test.get("test");
will work as well, through I wouldn't recommend it as the generics ensure that only the correct data is added, rather than trying to do the handling at retrieval time.
Ideally, the Python script you want to run will be set up with code like this near the end:
def main(arg1, arg2, etc):
# do whatever the script does
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2], sys.argv[3])
In other words, if the module is called from the command line, it parses the command line options and then calls another function, main()
, to do the actual work. (The actual arguments will vary, and the parsing may be more involved.)
If you want to call such a script from another Python script, however, you can simply import
it and call modulename.main()
directly, rather than going through the operating system.
os.system
will work, but it is the roundabout (read "slow") way to do it, as you are starting a whole new Python interpreter process each time for no raisin.
The -H 'Cache-Control: no-cache'
argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.
curl "http://www.example.com?foo123"
You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s
, which will return the seconds since epoch.
curl "http://www.example.com?$(date +%s)"
Use either the <button>
element or use an <input type="button"/>
.
I've used the following in the DIV that needs to be resized:
overflow: hidden;
height: 1%;
Had the same issue, found that the template component tags worked with <app-[component-name]></app-[component-name]>
. So, if your component is called mycomponent.component.ts
:
@Component({
selector: 'my-app',
template: `
<h1>Hello {{name}}</h1>
<h4>Something</h4>
<app-mycomponent></app-mycomponent>
`,
Just Add in AndroidManifest.xml
<activity android:name=".HomeActivity" android:windowSoftInputMode="stateHidden">
</activity>
task :build => [:some_other_tasks] do
build
end
task :build_all do
[:debug, :release].each { |t| build t }
end
def build(type = :debug)
# ...
end
rake
's idioms, here are your possibilities, compiled from past answers:This always executes the task, but it doesn't execute its dependencies:
Rake::Task["build"].execute
This one executes the dependencies, but it only executes the task if it has not already been invoked:
Rake::Task["build"].invoke
This first resets the task's already_invoked state, allowing the task to then be executed again, dependencies and all:
Rake::Task["build"].reenable
Rake::Task["build"].invoke
Note that dependencies already invoked are not automatically re-executed unless they are re-enabled. In Rake >= 10.3.2, you can use the following to re-enable those as well:
Rake::Task["build"].all_prerequisite_tasks.each(&:reenable)
You're trying to create a tuple, but you're just parenthesizing a string :)
Add an extra ',':
dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,)) # <- note extra ','
processThread.start()
Or use brackets to make a list:
dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved]) # <- 1 element list
processThread.start()
If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)
The *self.__args
turns your string into a list of characters, passing them to the processLine
function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.
Use a concrete list type, e.g. ArrayList
instead of just List
.
Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));
You have to be clear on what you mean by "JSON".
Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]
. This one happens to be an array. If you want to add a new element to the array, just push
it, as in
var arr = [{a: 1}];
arr.push({b: 2});
< [{a: 1}, {b: 2}]
The word JSON may also be used to refer to a string which is encoded in JSON format:
var json = '[{"a": 1}]';
Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse
:
var obj = JSON.parse(json);
Now you can manipulate the object any way you want, including push
as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify
:
var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'
JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse
it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify
, and use another ajax call to send the data to the server for storage or other manipulation.
You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.
Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?
My answer below doesn't solve the question but it relates to.
If someone is using enum
instead of a class model, like this example:
public enum Counter
{
[Display(Name = "Number 1")]
No1 = 1,
[Display(Name = "Number 2")]
No2 = 2,
[Display(Name = "Number 3")]
No3 = 3
}
And a property to get the value when submiting:
public int No { get; set; }
In the razor page, you can use Html.GetEnumSelectList<Counter>()
to get the enum properties.
<select asp-for="No" asp-items="@Html.GetEnumSelectList<Counter>()"></select>
It generates the following HTML:
<select id="No" name="No">
<option value="1">Number 1</option>
<option value="2">Number 2</option>
<option value="3">Number 3</option>
</select>
Use form-inline
.
It only works on screen resolutions greater than 768px though. To test the snippet below make sure to click the "Expand snippet" link to get a wider viewing area.
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
<form class="form-inline">_x000D_
<input type="text" class="form-control"/>-<input type="text" class="form-control"/>_x000D_
</form>
_x000D_
Reference: https://getbootstrap.com/docs/3.3/css/#forms-inline
You can do this in many ways before clicking on add items:
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid")));// instead of id u can use cssSelector or xpath of ur element.
or
wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));
You can also wait like this. If you want to wait until invisible of previous page element:
wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));
Here is the link where you can find all the Selenium WebDriver APIs that can be used for wait
and its documentation.
$url = 'http://legis.senado.leg.br/dadosabertos/materia/tramitando';
$xml = file_get_contents("xml->{$url}");
$xml = simplexml_load_file($url);
You can try the below:
function formatAMPM() {
var date = new Date();
var currDate = date.getDate();
var hours = date.getHours();
var dayName = getDayName(date.getDay());
var minutes = date.getMinutes();
var monthName = getMonthName(date.getMonth());
var year = date.getFullYear();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
alert(strTime);
}
function getMonthName(month) {
var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return ar[month];
}
function getDayName(day) {
var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
return ar1[day];
}
EDIT: Refer here for a working demo.
Or, if you need to access the element that has that property and it does not use an id, you could go this route:
$("img").each(function () {
if ($(this).css("float") == "left") { $(this).addClass("left"); }
if ($(this).css("float") == "right") { $(this).addClass("right"); }
})
It really depends on what you're trying to accomplish. If you have no else clause then if(!doSomething())
seems fine. However, if you have
if(!doSomething()) {
...
}
else {
// do something else
}
I'd probably reverse that logic to remove the !
operator and make the if
clause slightly more clear.
The data received in your serialPort1_DataReceived
method is coming from another thread context than the UI thread, and that's the reason you see this error.
To remedy this, you will have to use a dispatcher as descibed in the MSDN article:
How to: Make Thread-Safe Calls to Windows Forms Controls
So instead of setting the text property directly in the serialport1_DataReceived
method, use this pattern:
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
So in your case:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
txt += serialPort1.ReadExisting().ToString();
SetText(txt.ToString());
}
Just to elaborate on the etymology of the command name rev-parse
, Git consistently uses the term rev
in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list
for example prints a list of 40-char commit hashes for a branch or whatever.
In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash
. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.
I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)
Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.
The problem here is that the length of your array is undefined, and this confuses VBA if the array is explicitly defined as a string. Variants, however, seem to be able to resize as needed (because they hog a bunch of memory, and people generally avoid them for a bunch of reasons).
The following code works just fine, but it's a bit manual compared to some of the other languages out there:
Dim SomeArray(3) As String
SomeArray(0) = "Zero"
SomeArray(1) = "One"
SomeArray(2) = "Two"
SomeArray(3) = "Three"
You need to change the seed.
int main() {
srand(time(NULL));
cout << (rand() % 101);
return 0;
}
the srand
seeding thing is true also for a c
language code.
See also: http://xkcd.com/221/
Same issue I'm getting in my MYSQL while running sql script Please look into below image.. Error code 1206: The number of locks exceeds the lock table size Picture
This is Mysql configuration issue so I made some changes in my.ini
and It's working on my system & issue resolved.
We need to make some changes in my.ini
which is available on following Path:- C:\ProgramData\MySQL\MySQL Server 5.7\my.ini
and please update following changes in my.ini
config file fields:-
key_buffer_size=64M
read_buffer_size=64M
read_rnd_buffer_size=128M
innodb_log_buffer_size=10M
innodb_buffer_pool_size=256M
query_cache_type=2
max_allowed_packet=16M
After all above changes please restart the MYSQL Service. Please refer the image:- Microsoft MYSQL Service Picture
If you are using Spring Framework with application.yml
and having trouble to make the test find the SQL file on the INIT
property, you can use the classpath:
notation.
For example, if you have a init.sql
SQL file on the src/test/resources
, just use:
url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM 'classpath:init.sql';DB_CLOSE_DELAY=-1;
The cleaner way in my opinion is to first export to .py as aforementioned:
pyuic4 foo.ui > foo.py
And then use it inside your code (e.g main.py
), like:
from foo import Ui_MyWindow
class MyWindow(QtGui.QDialog):
def __init__(self):
super(MyWindow, self).__init__()
self.ui = Ui_MyWindow()
self.ui.setupUi(self)
# go on setting up your handlers like:
# self.ui.okButton.clicked.connect(function_name)
# etc...
def main():
app = QtGui.QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
This way gives the ability to other people who don't use qt-designer to read the code, and also keeps your functionality code outside foo.py
that could be overwritten by designer. You just reference ui
through MyWindow
class as seen above.
In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).
I removed " at the end of the connection string and it worked
Instead of
App=EntityFramework"
Used
App=EntityFramework;
<add name="DefaultConnection" connectionString="data source=(local);initial catalog=NamSdb;persist security info=True;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.SqlClient" />
Note : In connectionString Do not include :
|x| Metadata info : "metadata=res://*/"
|x| Encoded Quotes : """
The cleanest solution is probably to specify your divs as exact children.
Try changing this:
div.rounded div div {
background: url('bl.gif') no-repeat bottom left;
}
To this:
div.rounded > div > div {
background: url('bl.gif') no-repeat bottom left;
}
Pure javascript can do!
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
Depending on your content and space, you can use floats or inline display:
<table style="display: inline-block;">
<table style="float: left;">
Check it out here: http://jsfiddle.net/SM769/
Documentation
display
on MDN - https://developer.mozilla.org/en/CSS:displayfloat
on MDN - https://developer.mozilla.org/en/CSS/floatI wrote this javascript script and included it in the header (before anything loads). It seems to work. If the page was loaded more than one hour ago or the situation is undefined it will reload everything from server. The time of one hour = 3600000 milliseconds can be changed in the following line: if(alter > 3600000)
With regards, Birke
<script type="text/javascript">
//<![CDATA[
function zeit()
{
if(document.cookie)
{
a = document.cookie;
cookiewert = "";
while(a.length > 0)
{
cookiename = a.substring(0,a.indexOf('='));
if(cookiename == "zeitstempel")
{
cookiewert = a.substring(a.indexOf('=')+1,a.indexOf(';'));
break;
}
a = a.substring(a.indexOf(cookiewert)+cookiewert.length+1,a.length);
}
if(cookiewert.length > 0)
{
alter = new Date().getTime() - cookiewert;
if(alter > 3600000)
{
document.cookie = "zeitstempel=" + new Date().getTime() + ";";
location.reload(true);
}
else
{
return;
}
}
else
{
document.cookie = "zeitstempel=" + new Date().getTime() + ";";
location.reload(true);
}
}
else
{
document.cookie = "zeitstempel=" + new Date().getTime() + ";";
location.reload(true);
}
}
zeit();
//]]>
</script>
I think the answer depends on which features of stored procedures you need to use.
Stored procedures returning a result set can be run using Query
; stored procedures which don't return a result set can be run using Execute
- in both cases (using EXEC <procname>
) as the SQL command (plus input parameters as necessary). See the documentation for more details.
As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT
parameters; you could add this, or alternatively construct a more complex Query
command which declared TSQL variables, executed the SP collecting OUTPUT
parameters into the local variables and finallyreturned them in a result set:
DECLARE @output int
EXEC <some stored proc> @i = @output OUTPUT
SELECT @output AS output1
Another option would be to add engine='python'
to the command pandas.read_csv(filename, sep='\t', engine='python')
I had a problem with mime types and where making tests for few file types. It looks like each browser sends it's variation of a mime type for a specific file. I was trying to upload mp3 and zip files with open source php class, that what I have found:
So if you need several file types to upload, you better make some tests so that every browser could upload a file and pass mime type check.
The definition on Wikipedia reads:
Hence,
sign = lambda x: -1 if x < 0 else (1 if x > 0 else (0 if x == 0 else NaN))
Which for all intents and purposes may be simplified to:
sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)
This function definition executes fast and yields guaranteed correct results for 0, 0.0, -0.0, -4 and 5 (see comments to other incorrect answers).
Note that zero (0) is neither positive nor negative.
Here are some notes: The real alphanumeric string is like "0a0a0a0b0c0d"
and not like "000000"
or "qwertyuio"
.
All the answers I read here, returned true
in both cases. This is not right.
If I want to check if my "00000"
string is alphanumeric, my intuition is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9]
.
On the other hand, if I wanted to check my "abcdefg"
string, my intuition
is still FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z]
.
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789"
(only numeric), "qwertyuiop"
(only alpha) and "0a1b2c3d4f4g"
(alphanumeric) returns TRUE
as alphanumeric. Same regex /^[a-z0-9]+$/i
way.
The reason why the regex does not work is as simple as obvious. The syntax []
indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true
.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguously
processes an alphanumeric string. I called it like PHP relative function ctype_alnum
(edit 2020-02-18: Where, however, this checks OR and not AND).
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; // I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true) {
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): // check if A-Z or a-z
isAlpha = true;
break;
default:
// not 0-9, not A-Z or a-z
return false; // stop function with false result, no more checks
}
}
return isNumeric && isAlpha; // return the loop results, if both are true, the string is certainly alphanumeric
}
And here is a demo:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
loop1:
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
$("#input").on("keyup", function(){
if ($(this).val().length === 0) {$("#results").html(""); return false};
var isAlphaNumeric = ctype_alnum ($(this).val());
$("#results").html(
(isAlphaNumeric) ? 'Yes' : 'No'
)
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input">
<div> is Alphanumeric?
<span id="results"></span>
</div>
_x000D_
This is an implementation of Michael Martin-Smucker's method in JavaScript.
Always open in binary mode, in this case
file = open("Fruits.obj",'rb')
From the bottom of the ?mutate_each
(at least in dplyr 0.5) it looks like that function, as in @docendo discimus's answer, will be deprecated and replaced with more flexible alternatives mutate_if
, mutate_all
, and mutate_at
. The one most similar to what @hadley mentions in his comment is probably using mutate_at
. Note the order of the arguments is reversed, compared to mutate_each
, and vars()
uses select()
like semantics, which I interpret to mean the ?select_helpers
functions.
dat %>% mutate_at(vars(starts_with("fac")),funs(factor)) %>%
mutate_at(vars(starts_with("dbl")),funs(as.numeric))
But mutate_at
can take column numbers instead of a vars()
argument, and after reading through this page, and looking at the alternatives, I ended up using mutate_at
but with grep
to capture many different kinds of column names at once (unless you always have such obvious column names!)
dat %>% mutate_at(grep("^(fac|fctr|fckr)",colnames(.)),funs(factor)) %>%
mutate_at(grep("^(dbl|num|qty)",colnames(.)),funs(as.numeric))
I was pretty excited about figuring out mutate_at
+ grep
, because now one line can work on lots of columns.
EDIT - now I see matches()
in among the select_helpers, which handles regex, so now I like this.
dat %>% mutate_at(vars(matches("fac|fctr|fckr")),funs(factor)) %>%
mutate_at(vars(matches("dbl|num|qty")),funs(as.numeric))
Another generally-related comment - if you have all your date columns with matchable names, and consistent formats, this is powerful. In my case, this turns all my YYYYMMDD columns, which were read as numbers, into dates.
mutate_at(vars(matches("_DT$")),funs(as.Date(as.character(.),format="%Y%m%d")))
Not only can it implement any conceivable O(x) value short of infinity, the time taken is provably correct (if you can wait that long).
for who one in laravel 5 or greater in blade:
{{ $table->appends(['id' => $something ])->links() }}
you can get the passed item with
$passed_item=$request->id;
test it with
dd($passed_item);
you must get $something value
Here's how can do it on Windows:
"""
Display series of numbers in infinite loop
Listen to key "s" to stop
Only works on Windows because listening to keys
is platform dependent
"""
# msvcrt is a windows specific native module
import msvcrt
import time
# asks whether a key has been acquired
def kbfunc():
#this is boolean for whether the keyboard has bene hit
x = msvcrt.kbhit()
if x:
#getch acquires the character encoded in binary ASCII
ret = msvcrt.getch()
else:
ret = False
return ret
#begin the counter
number = 1
#infinite loop
while True:
#acquire the keyboard hit if exists
x = kbfunc()
#if we got a keyboard hit
if x != False and x.decode() == 's':
#we got the key!
#because x is a binary, we need to decode to string
#use the decode() which is part of the binary object
#by default, decodes via utf8
#concatenation auto adds a space in between
print ("STOPPING, KEY:", x.decode())
#break loop
break
else:
#prints the number
print (number)
#increment, there's no ++ in python
number += 1
#wait half a second
time.sleep(0.5)
If you only want the mean of the weight
column, select the column (which is a Series) and call .mean()
:
In [479]: df
Out[479]:
ID birthyear weight
0 619040 1962 0.123123
1 600161 1963 0.981742
2 25602033 1963 1.312312
3 624870 1987 0.942120
In [480]: df["weight"].mean()
Out[480]: 0.83982437500000007
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
ssh user@machine python < script.py - arg1 arg2
Because cat |
is usually not necessary
I had the same problem even after installing JDK 1.7. I corrected it by adding the bin directory to my PATH. So I went to
computer>properties>advanced>environment variables
and then added
C:\Program Files\Java\jdk1.7.0_55\bin;
then I followed these instructions
http://clean-clouds.com/2012/12/06/how-to-install-and-add-jre7-in-eclipse/
select *
from sys.configurations
where name = 'clr enabled'
Easy way: use the following CDN:
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-material-icons/0.5.0/angular-material-icons.min.js"></script>
Inject ngMdIcons to your angularjs application:
angular.module('demoapp', ['ngMdIcons']);
Use ng-md-icon directive in your html, specifying fill-color through css:
<ng-md-icon icon="..." style="fill: ..." size="..."></ng-md-icon>
Checkboxes are posting value 'on' if and only if the checkbox is checked. Insted of catching checkbox value you can use hidden inputs
JS:
var chk = $('input[type="checkbox"]');
chk.each(function(){
var v = $(this).attr('checked') == 'checked'?1:0;
$(this).after('<input type="hidden" name="'+$(this).attr('rel')+'" value="'+v+'" />');
});
chk.change(function(){
var v = $(this).is(':checked')?1:0;
$(this).next('input[type="hidden"]').val(v);
});
HTML:
<label>Active</label><input rel="active" type="checkbox" />
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
You'd normally use java.net.URLConnection
to fire HTTP requests. You'd also normally use multipart/form-data
encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data
request body. The specification is in more detail described in RFC2388.
Here's a kickoff example:
String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}
// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200
This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.
The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.
// Replace invalid characters with empty strings.
Regex.Replace(inputString, @"[^\w\.@-]", "");
The regular expression pattern [^\w.@-] matches any character that is not a word character, a period, an @ symbol, or a hyphen. A word character is any letter, decimal digit, or punctuation connector such as an underscore. Any character that matches this pattern is replaced by String.Empty, which is the string defined by the replacement pattern. To allow additional characters in user input, add those characters to the character class in the regular expression pattern. For example, the regular expression pattern [^\w.@-\%] also allows a percentage symbol and a backslash in an input string.
Regex.Replace(inputString, @"[!@#$%_]", "");
Refer this too :
Removing Invalid Characters from XML Name Tag - RegEx C#
Here is a function to remove the characters from a specified XML string:
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace XMLUtils
{
class Standards
{
/// <summary>
/// Strips non-printable ascii characters
/// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
/// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
/// </summary>
/// <param name="content">contents</param>
/// <param name="XMLVersion">XML Specification to use. Can be 1.0 or 1.1</param>
private void StripIllegalXMLChars(string tmpContents, string XMLVersion)
{
string pattern = String.Empty;
switch (XMLVersion)
{
case "1.0":
pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])";
break;
case "1.1":
pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])";
break;
default:
throw new Exception("Error: Invalid XML Version!");
}
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
if (regex.IsMatch(tmpContents))
{
tmpContents = regex.Replace(tmpContents, String.Empty);
}
tmpContents = string.Empty;
}
}
}
try
$("#btnId").click(function(e){
e.preventDefault();
//show loading gif
$.ajax({
...
success:function(data){
//remove gif
},
error:function(){//remove gif}
});
});
EDIT: after reading the comments
in case you decide against ajax
$("#btnId").click(function(e){
e.preventDefault();
//show loading gif
$(this).closest('form').submit();
});
Someone linked me this: What is the best way to move an element that's on the top to the bottom in Responsive design.
The solution in that worked perfectly. Though it doesn’t support old IE, that doesn’t matter for me, since I’m using responsive design for mobile. And it works for most mobile browsers.
Basically, I had this:
@media (max-width: 30em) {
.container {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-orient: vertical;
-moz-box-orient: vertical;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
/* optional */
-webkit-box-align: start;
-moz-box-align: start;
-ms-flex-align: start;
-webkit-align-items: flex-start;
align-items: flex-start;
}
.container .first_div {
-webkit-box-ordinal-group: 2;
-moz-box-ordinal-group: 2;
-ms-flex-order: 2;
-webkit-order: 2;
order: 2;
}
.container .second_div {
-webkit-box-ordinal-group: 1;
-moz-box-ordinal-group: 1;
-ms-flex-order: 1;
-webkit-order: 1;
order: 1;
}
}
This worked better than floats for me, because I needed them stacked on top of each other and I had about five different divs that I had to swap around the position of.
This is a String
extension written in Swift to return a HTML string as NSAttributedString
.
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
return html
}
}
To use,
label.attributedText = "<b>Hello</b> \u{2022} babe".htmlAttributedString()
In the above, I have purposely added a unicode \u2022 to show that it renders unicode correctly.
A trivial: The default encoding that NSAttributedString
uses is NSUTF16StringEncoding
(not UTF8!).
I'm going to put in a vote for np.vectorize. It allows you to just shoot over x number of columns and not deal with the dataframe in the function, so it's great for functions you don't control or doing something like sending 2 columns and a constant into a function (i.e. col_1, col_2, 'foo').
import numpy as np
import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
def get_sublist(sta,end):
return mylist[sta:end+1]
#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below
df.loc[:,'col_3'] = np.vectorize(get_sublist, otypes=["O"]) (df['col_1'], df['col_2'])
df
ID col_1 col_2 col_3
0 1 0 1 [a, b]
1 2 2 4 [c, d, e]
2 3 3 5 [d, e, f]
Appending a single scalar could be done a bit easier as already shown (and also without converting to float) by expanding the scalar to a python-list-type:
import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
x = 10
b = np.hstack ((a, [[x]] * len (a) ))
returns b
as:
array([[ 1, 3, 4, 10],
[ 1, 2, 3, 10],
[ 1, 2, 1, 10]])
Appending a row could be done by:
c = np.vstack ((a, [x] * len (a[0]) ))
returns c
as:
array([[ 1, 3, 4],
[ 1, 2, 3],
[ 1, 2, 1],
[10, 10, 10]])
\r used for carriage return. (ASCII value is 13) \n used for new line. (ASCII value is 10)
For people who have narrowed down the issue to the COMMENT ON
statements (as per various answers below) and who have superuser access to the source database from which the dump file is created, the simplest solution might be to prevent the comments from being included to the dump file in the first place, by removing them from the source database being dumped...
COMMENT ON EXTENSION postgis IS NULL;
COMMENT ON EXTENSION plpgsql IS NULL;
COMMENT ON SCHEMA public IS NULL;
Future dumps then won't include the COMMENT ON
statements.
def reverse(text):
reversed = ''
for i in range(len(text)-1, -1, -1):
reversed += text[i]
return reversed
print("reverse({}): {}".format("abcd", reverse("abcd")))
If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all
(or delete_all
) in the seed.db file to clean out a table before your MyModel.create!(...)
statements load the data. Then, you can redo the db:seed
operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)
There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...
screen -x
^A
*
, select the one to disconnect, press d
Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)
Note:
PREFIX
is usually^A
=ctrl+a
Note: the display may also be called:
- "user front-end" (in
at
command manual in screen)- "client" (tmux vocabulary where this functionality is
detach-client
)- "terminal" (as we call the window in our user interface) /depending on
1. Reattach a session: screen -x
-x
attach to a not detached screen session without detaching it
2. List displays of this session: PREFIX
*
It is the default key binding for: PREFIX
:displays
.
Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).
term-type size user interface window Perms
---------- ------- ---------- ----------------- ---------- -----
screen 240x60 you@/dev/pts/2 nb 0(zsh) rwx
screen 78x40 you@/dev/pts/0 nb 0(zsh) rwx
Using arrows ?
?
, select the targeted display, press d
If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.
Press ENTER
to quit the listing.
Optionally: in order to make the content fit your screen, reflow: PREFIX
F
(uppercase F)
Excerpt from man page of screen:
displays
Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:
mouseclick
Move to the selected line. Available when "mousetrack" is set to on.space
Refresh the listd
Detach that displayD
Power detach that displayC-g
,enter
, orescape
Exit the list
They are extension methods. Welcome to a whole new fluent world. :)
There are only two good ones: Doctrine and Propel. We favor Doctrine, and it works well with Symfony. However if you're looking for database support besides the main ones you'll have to write your own code.
I think, bwawok's answer is wrong at some point:
if you do
git reset --soft c14809fa
It will make your local files changed to be like they were then, but leave your history etc. the same.
According to manual: git-reset, "git reset --soft"...
does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.
So it will "remove" newer commits from the branch. This means, after looking at your old code, you cannot go to the newest commit in this branch again, easily. So it does the opposide as described by bwawok: Local files are not changed (they look exactly as before "git reset --soft"), but the history is modified (branch is truncated after the specified commit).
The command for bwawok's answer might be:
git checkout <commit>
You can use this to peek at old revision: How did my code look yesterday?
(I know, I should put this in comments to this answer, but stackoverflow does not allow me to do so! My reputation is too low.)
When I had this problem was beacuse my directory had non ASCII characteres. Try changing it
Make sure Virtualization is enabled in your bios.
I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.
After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.
If the requirement is to reference the global object (JavaScript) in your HTML code, you can try this. [Don't use any quotes (' or ") around the variable]
Fiddle reference.
JavaScript:
var result = {name: 'hello'};
function gotoNode(name) {
alert(name);
}
HTML:
<input value="Hello" type="button" onClick="gotoNode(result.name)" />?
Either you initialize the variable to something
char retChar = 'x';
or you leave it automatically initialized, which is
char retChar = '\0';
an ascii 0, the same as
char retChar = (char) 0;
What can one initialize char values to?
Sounds undecided between automatic initialisation, which means, you have no influence, or explicit initialisation. But you cannot change the default.
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
To some extent, this is going to vary by the "flavour" of RegEx you're using. The following is based on .NET RegEx, which uses \b
for word boundaries. In the last example, it also uses negative lookaround (?<!)
and (?!)
as well as non-capturing parentheses (?:)
Basically, though, if the terms always contain at least one uppercase letter followed by at least one number, you can use
\b[A-Z]+[0-9]+\b
For all-uppercase and numbers (total must be 2 or more):
\b[A-Z0-9]{2,}\b
For all-uppercase and numbers, but starting with at least one letter:
\b[A-Z][A-Z0-9]+\b
The granddaddy, to return items that have any combination of uppercase letters and numbers, but which are not single letters at the beginning of a line and which are not part of a line that is all uppercase:
(?:(?<!^)[A-Z]\b|(?<!^[A-Z0-9 ]*)\b[A-Z0-9]+\b(?![A-Z0-9 ]$))
breakdown:
The regex starts with (?:
. The ?:
signifies that -- although what follows is in parentheses, I'm not interested in capturing the result. This is called "non-capturing parentheses." Here, I'm using the paretheses because I'm using alternation (see below).
Inside the non-capturing parens, I have two separate clauses separated by the pipe symbol |
. This is alternation -- like an "or". The regex can match the first expression or the second. The two cases here are "is this the first word of the line" or "everything else," because we have the special requirement of excluding one-letter words at the beginning of the line.
Now, let's look at each expression in the alternation.
The first expression is: (?<!^)[A-Z]\b
. The main clause here is [A-Z]\b
, which is any one capital letter followed by a word boundary, which could be punctuation, whitespace, linebreak, etc. The part before that is (?<!^)
, which is a "negative lookbehind." This is a zero-width assertion, which means it doesn't "consume" characters as part of a match -- not really important to understand that here. The syntax for negative lookbehind in .NET is (?<!x)
, where x is the expression that must not exist before our main clause. Here that expression is simply ^
, or start-of-line, so this side of the alternation translates as "any word consisting of a single, uppercase letter that is not at the beginning of the line."
Okay, so we're matching one-letter, uppercase words that are not at the beginning of the line. We still need to match words consisting of all numbers and uppercase letters.
That is handled by a relatively small portion of the second expression in the alternation: \b[A-Z0-9]+\b
. The \b
s represent word boundaries, and the [A-Z0-9]+
matches one or more numbers and capital letters together.
The rest of the expression consists of other lookarounds. (?<!^[A-Z0-9 ]*)
is another negative lookbehind, where the expression is ^[A-Z0-9 ]*
. This means what precedes must not be all capital letters and numbers.
The second lookaround is (?![A-Z0-9 ]$)
, which is a negative lookahead. This means what follows must not be all capital letters and numbers.
So, altogether, we are capturing words of all capital letters and numbers, and excluding one-letter, uppercase characters from the start of the line and everything from lines that are all uppercase.
There is at least one weakness here in that the lookarounds in the second alternation expression act independently, so a sentence like "A P1 should connect to the J9" will match J9, but not P1, because everything before P1 is capitalized.
It is possible to get around this issue, but it would almost triple the length of the regex. Trying to do so much in a single regex is seldom, if ever, justfied. You'll be better off breaking up the work either into multiple regexes or a combination of regex and standard string processing commands in your programming language of choice.
Using recursion combined with the square root rule from here, checks whether a number is prime or not:
function isPrime(num){
// An integer is prime if it is not divisible by any prime less than or equal to its square root
var squareRoot = parseInt(Math.sqrt(num));
var primeCountUp = function(divisor){
if(divisor > squareRoot) {
// got to a point where the divisor is greater than
// the square root, therefore it is prime
return true;
}
else if(num % divisor === 0) {
// found a result that divides evenly, NOT prime
return false;
}
else {
// keep counting
return primeCountUp(++divisor);
}
};
// start @ 2 because everything is divisible by 1
return primeCountUp(2);
}
DECLARE @Database NVARCHAR(255)
DECLARE @Table NVARCHAR(255)
DECLARE @cmd NVARCHAR(1000)
DECLARE DatabaseCursor CURSOR READ_ONLY FOR
SELECT name FROM master.sys.databases
WHERE name NOT IN ('master','msdb','tempdb','model','distribution') -- databases to exclude
--WHERE name IN ('DB1', 'DB2') -- use this to select specific databases and comment out line above
AND state = 0 -- database is online
AND is_in_standby = 0 -- database is not read only for log shipping
ORDER BY 1
OPEN DatabaseCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd = 'DECLARE TableCursor CURSOR READ_ONLY FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +
table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''
-- create table cursor
EXEC (@cmd)
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @Table
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD'
--PRINT @cmd -- uncomment if you want to see commands
EXEC (@cmd)
END TRY
BEGIN CATCH
PRINT '---'
PRINT @cmd
PRINT ERROR_MESSAGE()
PRINT '---'
END CATCH
FETCH NEXT FROM TableCursor INTO @Table
END
CLOSE TableCursor
DEALLOCATE TableCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
Actually there is an operator for that in PostgreSQL:
SELECT *
FROM table
WHERE lower(value) ~~ ANY('{%foo%,%bar%,%baz%}');
I had the same problem, but setting windowSoftInputMode
did not help, and I did not want to change the upper view to have isScrollContainer="false"
because I wanted it to scroll.
My solution was to define the top location of the navigation tools instead of the bottom. I'm using Titanium, so I'm not sure exactly how this would translate to android. Defining the top location of the navigation tools view prevented the soft keyboard from pushing it up, and instead covered the nav controls like I wanted.
you can use unlink in the folder where you have created your symlink
Adam has already suggested database profiles.
You could check the SQLNET.ORA file. There's an EXPIRE_TIME parameter but this is for detecting lost connections, rather than terminating existing ones.
Given it happens overnight, it sounds more like an idle timeout, which could be down to a firewall between the app server and database server. Setting the EXPIRE_TIME may stop that happening (as there'll be check every 10 minutes to check the client is alive).
Or possibly the database is being shutdown and restarted and that is killing the connections.
Alternatively, you should be able to configure tomcat with a validationQuery so that it will automatically restart the connection without a tomcat restart
the emptyList method has this signature:
public static final <T> List<T> emptyList()
That <T>
before the word List means that it infers the value of the generic parameter T from the type of variable the result is assigned to. So in this case:
List<String> stringList = Collections.emptyList();
The return value is then referenced explicitly by a variable of type List<String>
, so the compiler can figure it out. In this case:
setList(Collections.emptyList());
There's no explicit return variable for the compiler to use to figure out the generic type, so it defaults to Object
.
Here is what I find works
form name
Use a default select option
, for example...
<option value="-1" selected>Please Select</option>
So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.
This input
<input type="submit">
should be
<input name="Submit" type="submit" value="Submit">
whenever I use a form that fails, it is a failure due to the difference in calling the button name submit
and name as Submit
.
You should also set your enctype attribute for your form as forms fail on my web host if it's not set.
delete from employee where rowid in (select rowid from (select rowid, name_count from (select rowid, count(emp_name) as name_count from employee group by emp_id, emp_name) where name_count>1))
This is a specific issue for Windows Vista, 7, 8 (and presumably newer).
User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.
This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.
XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.
All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.
I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.
I found this on google, tested in Excel 2003 & it works for me:
=IF(COUNTIF(A1,"* *"),RIGHT(A1,LEN(A1)-LOOKUP(LEN(A1),FIND(" ",A1,ROW(INDEX($A:$A,1,1):INDEX($A:$A,LEN(A1),1))))),A1)
[edit] I don't have enough rep to comment, so this seems the best place...BradC's answer also doesn't work with trailing spaces or empty cells...
[2nd edit] actually, it doesn't work for single words either...
Andrey Tarasevich provides the following explanation:
[Minor changes to formatting made. Parenthetical annotations added in square brackets []
].
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
Consider the following code sketch:
if (<condition>) foo(a); else bar(a);
where
foo
andbar
are ordinary functions. Now imagine that you'd like to replace functionfoo
with a macro of the above nature [namedCALL_FUNCS
]:if (<condition>) CALL_FUNCS(a); else bar(a);
Now, if your macro is defined in accordance with the second approach (just
{
and}
) the code will no longer compile, because the 'true' branch ofif
is now represented by a compound statement. And when you put a;
after this compound statement, you finished the wholeif
statement, thus orphaning theelse
branch (hence the compilation error).One way to correct this problem is to remember not to put
;
after macro "invocations":if (<condition>) CALL_FUNCS(a) else bar(a);
This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:
#define CALL_FUNCS(x) \ do { \ func1(x); \ func2(x); \ func3(x); \ } while (0)
Now this code:
if (<condition>) CALL_FUNCS(a); else bar(a);
will compile without any problems.
However, note the small but important difference between my definition of
CALL_FUNCS
and the first version in your message. I didn't put a;
after} while (0)
. Putting a;
at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.I don't know why the author of the code you quoted in your original message put this
;
afterwhile (0)
. In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final;
into the macro (for the reasons that I explained above).
For structuring an app, this is one of the best guides that I've found:
Note that the structure recommended by Google is different than what you'll find in a lot of seed projects, but for large apps it's a lot saner.
Google also has a style guide that makes sense to use only if you also use Closure.
...this answer is incomplete, but I hope that the limited information above will be helpful to someone.
I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.
example:
linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));
see definition: http://man7.org/linux/man-pages/man7/socket.7.html
SO_LINGER
Sets or gets the SO_LINGER option. The argument is a linger
structure.
struct linger {
int l_onoff; /* linger active */
int l_linger; /* how many seconds to linger for */
};
When enabled, a close(2) or shutdown(2) will not return until
all queued messages for the socket have been successfully sent
or the linger timeout has been reached. Otherwise, the call
returns immediately and the closing is done in the background.
When the socket is closed as part of exit(2), it always
lingers in the background.
More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required
You don't need the assignment, list.append(x)
will always append x
to a
and therefore there's no need te redefine a
.
a = []
for i in range(5):
a.append(i)
print(a)
is all you need. This works because list
s are mutable.
Also see the docs on data structures.
// This was my example that I used to automatically resize every inserted photo to 100 by 50 pixel and image format to jpeg hope this helps too
if($result){
$maxDimW = 100;
$maxDimH = 50;
list($width, $height, $type, $attr) = getimagesize( $_FILES['photo']['tmp_name'] );
if ( $width > $maxDimW || $height > $maxDimH ) {
$target_filename = $_FILES['photo']['tmp_name'];
$fn = $_FILES['photo']['tmp_name'];
$size = getimagesize( $fn );
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = $maxDimW;
$height = $maxDimH/$ratio;
} else {
$width = $maxDimW*$ratio;
$height = $maxDimH;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor( $width, $height );
imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );
imagejpeg($dst, $target_filename); // adjust format as needed
}
move_uploaded_file($_FILES['pdf']['tmp_name'],"pdf/".$_FILES['pdf']['name']);
If you are working with Spyder, use CTRL + . (DOT) and you will restart the kernel, also you will stop the program.
Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter. Should look like this when you're done:
Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//your stuff here.
}
});
as above, but qualitatively:
private - least access, best encapsulation
protected - some access, moderate encapsulation
public - full access, no encapsulation
the less access you provide the fewer implementation details leak out of your objects. less of this sort of leakage means more flexibility (aka "looser coupling") in terms of changing how an object is implemented without breaking clients of the object. this is a truly fundamental thing to understand.
You can use the bind function to set the context of this
within a function.
function myFunc() {
console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"
Try this:
catch (Throwable t) {
logger.error("any message" + t);
StackTraceElement[] s = t.getStackTrace();
for(StackTraceElement e : s){
logger.error("\tat " + e);
}
}
self.view.backgroundColor = UIColor.redColor()
In Swift 3:
self.view.backgroundColor = UIColor.red
redsquare's solution is the right answer.
But as an IN-THEORY solution you can write a function which is selecting the elements classed by .visibilityCheck
(not all visible elements) and check their visibility
property value; if true
then do something.
Afterward, the function should be performed periodically using the setInterval()
function. You can stop the timer using the clearInterval()
upon successful call-out.
Here's an example:
function foo() {
$('.visibilityCheck').each(function() {
if ($(this).is(':visible')){
// do something
}
});
}
window.setInterval(foo, 100);
You can also perform some performance improvements on it, however, the solution is basically absurd to be used in action. So...
On my Arch Linux install, gems were installed to the ~/.gem/ruby/2.6.0/bin
directory if installed as user, or /root/.gem/ruby/2.6.0/bin
if installed via sudo
. Just append the appropriate one to your $PATH
environment variable:
export PATH=$PATH:/home/your_username/.gem/ruby/2.6.0/bin
You just use dangerouslySetInnerHTML method of React
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
Or you can implement more with this easy way: Render the HTML raw in React app
chmod u+x program_name
. Then execute it.
If that does not work, copy the program from the USB device to a native volume on the system. Then chmod u+x program_name
on the local copy and execute that.
Unix and Unix-like systems generally will not execute a program unless it is marked with permission to execute. The way you copied the file from one system to another (or mounted an external volume) may have turned off execute permission (as a safety feature). The command chmod u+x name
adds permission for the user that owns the file to execute it.
That command only changes the permissions associated with the file; it does not change the security controls associated with the entire volume. If it is security controls on the volume that are interfering with execution (for example, a noexec
option may be specified for a volume in the Unix fstab
file, which says not to allow execute permission for files on the volume), then you can remount the volume with options to allow execution. However, copying the file to a local volume may be a quicker and easier solution.
Just catch your exception and do proper exception handling:
if (cost !=null && !"".equals(cost) ){
try {
Integer intCost = Integer.parseInt(cost);
List<Book> books = bookService . findBooksCheaperThan(intCost);
} catch (NumberFormatException e) {
System.out.println("This is not a number");
System.out.println(e.getMessage());
}
}
These are few things which will help you in understanding everything... using iloc
In iloc, [initial row:ending row, initial column:ending column]
case 1: if you want only last column --- df.iloc[:,-1] & df.iloc[:,-1:]
this means that you want only the last column...
case 2: if you want all columns and all rows except the last column --- df.iloc[:,:-1]
this means that you want all columns and all rows except the last column...
case 3: if you want only last row --- df.iloc[-1:,:] & df.iloc[-1,:]
this means that you want only the last row...
case 4: if you want all columns and all rows except the last row --- df.iloc[:-1,:]
this means that you want all columns and all rows except the last column...
case 5: if you want all columns and all rows except the last row and last column --- df.iloc[:-1,:-1]
this means that you want all columns and all rows except the last column and last row...
The PDB file is a Visual Studio specific file that has the debugging symbols for your project. You can ignore those messages, unless you're hoping to step into the code for those dlls with the debugger (which is doubtful, as those are system dlls). In other words, you can and should ignore them, as you won't have the PDB files for any of those dlls (by default at least, it turns out you can actually obtain them when debugging via the Microsoft Symbol Server). All it means is that when you set a breakpoint and are stepping through the code, you won't be able to step into any of those dlls (which you wouldn't want to do anyways).
Just for completeness, here's the official PDB description from MSDN:
A program database (PDB) file holds debugging and project state information that allows incremental linking of a Debug configuration of your program. A PDB file is created when you compile a C/C++ program with /ZI or /Zi
Also for future reference, if you want to have PDB files for your own code, you would would have to build your project with either the /ZI or /Zi options enabled (you can set them via project properties --> C/C++ --> General, then set the field for "Debug Information Format"). Not relevant to your situation, but I figured it might be useful in the future
>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]
Works - Add Spacing To Table
#options table {
border-spacing: 8px;
}
you can see this also in sockets ...
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("hello");
This is an expansion to totem's answer. It does basically the same thing but the property matching is based on the serialized json object, not reflect the .net object. This is important if you're using [JsonProperty], using the CamelCasePropertyNamesContractResolver, or doing anything else that will cause the json to not match the .net object.
Usage is simple:
[KnownType(typeof(B))]
public class A
{
public string Name { get; set; }
}
public class B : A
{
public string LastName { get; set; }
}
Converter code:
/// <summary>
/// Use KnownType Attribute to match a divierd class based on the class given to the serilaizer
/// Selected class will be the first class to match all properties in the json object.
/// </summary>
public class KnownTypeConverter : JsonConverter {
public override bool CanConvert( Type objectType ) {
return System.Attribute.GetCustomAttributes( objectType ).Any( v => v is KnownTypeAttribute );
}
public override bool CanWrite {
get { return false; }
}
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ) {
// Load JObject from stream
JObject jObject = JObject.Load( reader );
// Create target object based on JObject
System.Attribute[ ] attrs = System.Attribute.GetCustomAttributes( objectType ); // Reflection.
// check known types for a match.
foreach( var attr in attrs.OfType<KnownTypeAttribute>( ) ) {
object target = Activator.CreateInstance( attr.Type );
JObject jTest;
using( var writer = new StringWriter( ) ) {
using( var jsonWriter = new JsonTextWriter( writer ) ) {
serializer.Serialize( jsonWriter, target );
string json = writer.ToString( );
jTest = JObject.Parse( json );
}
}
var jO = this.GetKeys( jObject ).Select( k => k.Key ).ToList( );
var jT = this.GetKeys( jTest ).Select( k => k.Key ).ToList( );
if( jO.Count == jT.Count && jO.Intersect( jT ).Count( ) == jO.Count ) {
serializer.Populate( jObject.CreateReader( ), target );
return target;
}
}
throw new SerializationException( string.Format( "Could not convert base class {0}", objectType ) );
}
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ) {
throw new NotImplementedException( );
}
private IEnumerable<KeyValuePair<string, JToken>> GetKeys( JObject obj ) {
var list = new List<KeyValuePair<string, JToken>>( );
foreach( var t in obj ) {
list.Add( t );
}
return list;
}
}
The following link gives information on launching the app (if installed) directly from browser. Otherwise it directly opens up the app in play store so that user can seamlessly download.
You can use np.logaddexp
(which implements the idea in @gg349's answer):
In [33]: d = np.array([[1089, 1093]])
In [34]: e = np.array([[1000, 4443]])
In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
In [36]: log_res
Out[36]: -266.99999385580668
In [37]: res = exp(log_res)
In [38]: res
Out[38]: 1.1050349147204485e-116
Or you can use scipy.special.logsumexp
:
In [52]: from scipy.special import logsumexp
In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
In [54]: res
Out[54]: 1.1050349147204485e-116
A shorter alternative to the first solution given by Russ Cam would be:
$('#mySelect').val('');
This assumes you want to retain the list, but make it so that no option is selected.
If you wish to select a particular default value, just pass that value instead of an empty string.
$('#mySelect').val('someDefaultValue');
or to do it by the index of the option, you could do:
$('#mySelect option:eq(0)').attr('selected','selected'); // Select first option
set /a countfiles-=%countfiles%
This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:
set /a countfiles-=1
I'm not sure if the for loop will work, better try something like this:
:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
if you're goal is to reset EVERYTHING then @Björn's answer should be your goal but applied as:
* {
padding: initial;
}
if this is loaded after your original reset.css should have the same weight and will rely on each browser's default padding as initial value.
Considering that an include statment in php at the most basic level takes the code from a file and pastes it into where you called it and the fact that the manual on include states the following:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
These things make me think that there is a diffrent problem alltogether. Also Option number 3 will never work because you're not redirecting to second.php
you're just including it and option number 2 is just a weird work around. The most basic example of the include statment in php is:
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
Considering that option number one is the closest to this example (even though more complicated then it should be) and it's not working, its making me think that you made a mistake in the include statement (the wrong path relative to the root or a similar issue).
Use o parameter of pgsql command.
-o, --output=FILENAME send query results to file (or |pipe)
psql -d DatabaseName -U UserName -c "SELECT * FROM TABLE" -o /root/Desktop/file.txt
Swift 5
Since UITableViewRowAction was deprecated in iOS 13.0 so you can use UISwipeActionsConfiguration
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (contextualAction, view, boolValue) in
self.deleteData(at: indexPath)
}
let editAction = UIContextualAction(style: .normal, title: "Edit") { (contextualAction, view, boolValue) in
self.editData(at: indexPath)
}
editAction.backgroundColor = .purple
let swipeActions = UISwipeActionsConfiguration(actions: [deleteAction,editAction])
return swipeActions
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func deleteData(at indexPath: IndexPath) {
print(indexPath.row)
}
func editData(at indexPath: IndexPath) {
print(indexPath.row)
}
Set android:windowSoftInputMode="adjustPan" in your manifest file, and it will work as you expect.
Insted of
drawer.setDrawerListener(toggle);
You can use
drawer.addDrawerListener(toggle);
You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).
Try something like this in your main
routine:
import sys, traceback
def main():
try:
do main program stuff here
....
except KeyboardInterrupt:
print "Shutdown requested...exiting"
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
if __name__ == "__main__":
main()
Using the answer of Andoma, this is what I'm doing
You can create a Struct or a Class like this one
struct Date
{
public static double GetTime(DateTime dateTime)
{
return dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
}
public static DateTime DateTimeParse(double milliseconds)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds).ToLocalTime();
}
}
And you can use this in your code as following
DateTime dateTime = DateTime.Now;
double total = Date.GetTime(dateTime);
dateTime = Date.DateTimeParse(total);
I hope this help you
UPDATE 21/11/2012 @ALL : I have updated the example so that it works better and takes into accounts remarks from Chris Jacob and FB Best practices, have a look of working example here
Hi So as promised here is my answer using only javascript :
The content of the BODY of the page :
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR APP ID',
status : true,
cookie : true,
xfbml : true
});
</script>
<div id="container_notlike">
YOU DONT LIKE
</div>
<div id="container_like">
YOU LIKE
</div>
The CSS :
body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}
#container_notlike, #container_like {
display:none
}
And finally the javascript :
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
});
So what what does it do ?
First it logins to FB (if you already have the USER ID, and you are sure your user is already logged in facebook, you can bypass the login stuff and replace response.session.uid
with YOUR_USER_ID (from your rails app for example)
After that it makes a FQL query on the page_fan
table, and the meaning is that if the user is a fan of the page, it returns the user id and otherwise it returns an empty array, after that and depending on the results its show a div or the other.
Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/
It's using the coca-cola page as an example, try it go and like/unlike the coca cola page and run it again ...
Finally some related docs :
Don't hesitate if you have any question ..
Cheers
UPDATE 2
As stated by somebody, jQuery is required for the javascript version to work BUT you could easily remove it (it's only used for the document.ready and show/hide).
For the document.ready, you could wrap your code in a function and use body onload="your_function"
or something more complicated like here : Javascript - How to detect if document has loaded (IE 7/Firefox 3) so that we replace document ready.
And for the show and hide stuff you could use something like : document.getElementById("container_like").style.display = "none" or "block"
and for more reliable cross browser techniques see here : http://www.webmasterworld.com/forum91/441.htm
But jQuery is so easy :)
UPDATE
Relatively to the comment I posted here below here is some ruby code to decode the "signed_request" that facebook POST to your CANVAS URL when it fetches it for display inside facebook.
In your action controller :
decoded_request = Canvas.parse_signed_request(params[:signed_request])
And then its a matter of checking the decoded request and display one page or another .. (Not sure about this one, I'm not comfortable with ruby)
decoded_request['page']['liked']
And here is the related Canvas Class (from fbgraph ruby library) :
class Canvas
class << self
def parse_signed_request(secret_id,request)
encoded_sig, payload = request.split('.', 2)
sig = ""
urldecode64(encoded_sig).each_byte { |b|
sig << "%02x" % b
}
data = JSON.parse(urldecode64(payload))
if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
raise "Bad signature algorithm: %s" % data['algorithm']
end
expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
if expected_sig != sig
raise "Bad signature"
end
data
end
private
def urldecode64(str)
encoded_str = str.gsub('-','+').gsub('_','/')
encoded_str += '=' while !(encoded_str.size % 4).zero?
Base64.decode64(encoded_str)
end
end
end
You asked how to escape an Apostrophe character (')
in SQL Server. All the answers above do an excellent job of explaining that.
However, depending on the situation, the Right single quotation mark character (’)
might be appropriate.
(No escape characters needed)
-- Direct insert
INSERT INTO Table1 (Column1) VALUES ('John’s')
• Apostrophe (U+0027)
• Right single quotation mark (U+2019)
You need to escape the backslash \
:
println yourString.replace("\\", "/")
You need to run the script like this:
groovy helloworld.groovy
In case you need to check against any amount of whitespace, not just single space, you can do this:
To strip string of extra white space (also condences whitespace in the middle to one space):
trimmed=`echo -- $original`
The --
ensures that if $original
contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put ""
around $original
, or the spaces will not get removed.
After that you can just check if $trimmed
is empty.
[ -z "$trimmed" ] && echo "empty!"
public string CreatePassword(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
This has a good benefit of being able to choose from a list of available characters for the generated password (e.g. digits only, only uppercase or only lowercase etc.)
If you're trying to get access to a file, try the openFileOutput()
and openFileInput()
methods as described here. They automatically open input/output streams to the specified file in internal memory. This allows you to bypass the directory and File
objects altogether which is a pretty clean solution.
Simple example to achieve the below:
ApplicationDbContext forumDB = new ApplicationDbContext();
MonitorDbContext monitor = new MonitorDbContext();
Just scope the properties in the main context: (used to create and maintain the DB) Note: Just use protected: (Entity is not exposed here)
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("QAForum", throwIfV1Schema: false)
{
}
protected DbSet<Diagnostic> Diagnostics { get; set; }
public DbSet<Forum> Forums { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Thread> Threads { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
MonitorContext: Expose separate Entity here
public class MonitorDbContext: DbContext
{
public MonitorDbContext()
: base("QAForum")
{
}
public DbSet<Diagnostic> Diagnostics { get; set; }
// add more here
}
Diagnostics Model:
public class Diagnostic
{
[Key]
public Guid DiagnosticID { get; set; }
public string ApplicationName { get; set; }
public DateTime DiagnosticTime { get; set; }
public string Data { get; set; }
}
If you like you could mark all entities as protected inside the main ApplicationDbContext, then create additional contexts as needed for each separation of schemas.
They all use the same connection string, however they use separate connections, so do not cross transactions and be aware of locking issues. Generally your designing separation so this shouldn't happen anyway.