For a case like this, always use RelativeLayouts. A LinearLayout is not intended for such a usage.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/db1_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Place your layout here -->
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:orientation="horizontal"
android:paddingLeft="20dp"
android:paddingRight="20dp" >
<Button
android:id="@+id/setup_macroSavebtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Save" />
<Button
android:id="@+id/setup_macroCancelbtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel" />
</LinearLayout>
</RelativeLayout>
You can't update with a number greater than 1 for datatype number(2,2)
is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1
. i.e. 0.12, 0.95 etc.
Please check NUMBER DATATYPE in NUMBER Datatype.
Try this:
CASE WHEN table3.col3 IS NULL THEN table2.col3 ELSE table3.col3 END as col4
The as col4
should go at the end of the CASE the statement. Also note that you're missing the END
too.
Another probably more simple option would be:
IIf([table3.col3] Is Null,[table2.col3],[table3.col3])
Just to clarify, MS Access does not support COALESCE. If it would that would be the best way to go.
Edit after radical question change:
To turn the query into SQL Server then you can use COALESCE (so it was technically answered before too):
SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID,
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
COALESCE(dbo.EU_Admin3.EUID, dbo.EU_Admin2.EUID)
FROM dbo.AdminID
BTW, your CASE statement was missing a ,
before the field. That's why it didn't work.
<table border="1px;" width="100%">
<tr align="center">
<td>Product</td>
<td>quantity</td>
<td>Price</td>
<td>Totall</td>
</tr>
<tr align="center">
<td>Item-1</td>
<td>Item-1</td>
<td>
<table border="1px;" width="100%">
<tr align="center">
<td>Name1</td>
<td>Price1</td>
</tr>
<tr align="center">
<td>Name2</td>
<td>Price2</td>
</tr>
<tr align="center">
<td>Name3</td>
<td>Price3</td>
</tr>
<tr>
<td>Name4</td>
<td>Price4</td>
</tr>
</table>
</td>
<td>Item-1</td>
</tr>
<tr align="center">
<td>Item-2</td>
<td>Item-2</td>
<td>Item-2</td>
<td>Item-2</td>
</tr>
<tr align="center">
<td>Item-3</td>
<td>Item-3</td>
<td>Item-3</td>
<td>Item-3</td>
</tr>
</table>
_x000D_
To hide the horizontal scrollbar, we can just select the scrollbar of the required div and set it to display: none;
One thing to note is that this will only work for WebKit-based browsers (like Chrome) as there is no such option available for Mozilla.
In order to select the scrollbar, use ::-webkit-scrollbar
So the final code will be like this:
div::-webkit-scrollbar {
display: none;
}
Also, you can use -o
or --offline
in the mvn command line which will put maven in "offline mode" so it won't check for updates. You'll get some warning about not being able to get dependencies not already in your local repo, but no big deal.
"pull-right" class may not be the right way because in uses "float: right" instead of text-align.
Checking the bootstrap 3 css file i found "text-right" class on line 457. This class should be the right way to align the text to the right.
Some code:
<div class="row">
<div class="col-xs-12">
<div class="text-right">
<button type="button" class="btn btn-default">Default</button>
</div>
</div>
</div>
This solution worked for me:
#php -i | grep php.ini
also will work too!
I had the same problem, caused by a clash between the graphicx
package and an inclusion of the epsfig
package that survived the ages...
Please check that there is no inclusion of epsfig
, it is deprecated.
I was facing this problem and the solution was to restart my modem (router). I could get connection for my app to internet after that.
I think the library I am using is not managing connections properly because it happeend just few times.
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex @Bergi mentioned just the string version for new RegExp constructor
I had the same issue when I copy-pasted
the command. Instead, when I typed-in the entire command, it worked!
Good Luck...
Funny you mention that, I did a blog post on this very subject.
See Oracle vs MySQL vs SQL Server: Aggregation vs Joins
Short answer: you have to test it and individual databases vary a lot.
If you just want to check string equality, use the == operator. Determining whether two strings are equal is simpler than finding an ordering (which is what compare() gives,) so it might be better performance-wise in your case to use the equality operator.
Longer answer: The API provides a method to check for string equality and a method to check string ordering. You want string equality, so use the equality operator (so that your expectations and those of the library implementors align.) If performance is important then you might like to test both methods and find the fastest.
Somebody posted quite a few form fields to your page. The new default max introduced by the recent security update is 1000.
Try adding the following setting in your web.config's <appsettings>
block. in this block you are maximizing the MaxHttpCollection values this will override the defaults set by .net Framework. you can change the value accordingly as per your form needs
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="2001" />
</appSettings>
For more information please read this post. For more insight into the security patch by microsoft you can read this Knowledge base article
One can also use RLIKE
as below
SELECT * FROM artists WHERE name RLIKE '^[abc]';
with open('target.txt','w') as out:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print("I'm going to write these to the file.")
out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
Those seem to be MySQL data types.
According to the documentation they take:
tinyint
= 1 bytesmallint
= 2 bytesmediumint
= 3 bytesint
= 4 bytesbigint
= 8 bytesAnd, naturally, accept increasingly larger ranges of numbers.
An interesting example is you can continuously see a counter/stop-watch running in separate thread. Also showing GPS-Location. While main activity User Interface Thread is already there.
Excerpt:
try {
cnt++; scnt++;
now=System.currentTimeMillis();
r=rand.nextInt(6); r++;
loc=lm.getLastKnownLocation(best);
if(loc!=null) {
lat=loc.getLatitude();
lng=loc.getLongitude();
}
Thread.sleep(100);
handler.sendMessage(handler.obtainMessage());
} catch (InterruptedException e) {
Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
}
To look at code see here:
You are not returning a response object from your view my_form_post
. The function ends with implicit return None
, which Flask does not like.
Make the function my_form_post
return an explicit response, for example
return 'OK'
at the end of the function.
The git solution for such scenarios is setting SKIP-WORKTREE BIT. Run only the following command:
git update-index --skip-worktree .classpath .gitignore
It is used when you want git to ignore changes of files that are already managed by git and exist on the index. This is a common use case for config files.
Running git rm --cached
doesn't work for the scenario mentioned in the question. If I simplify the question, it says:
How to have
.classpath
and.project
on the repo while each one can change it locally and git ignores this change?
As I commented under the accepted answer, the drawback of git rm --cached
is that it causes a change in the index, so you need to commit the change and then push it to the remote repository. As a result, .classpath
and .project
won't be available on the repo while the PO wants them to be there so anyone that clones the repo for the first time, they can use it.
Based on git documentaion:
Skip-worktree bit can be defined in one (long) sentence: When reading an entry, if it is marked as skip-worktree, then Git pretends its working directory version is up to date and read the index version instead. Although this bit looks similar to assume-unchanged bit, its goal is different from assume-unchanged bit’s. Skip-worktree also takes precedence over assume-unchanged bit when both are set.
More details is available here.
strncpy
combats buffer overflow by requiring you to put a length in it. strcpy
depends on a trailing \0
, which may not always occur.
Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n
characters, where n
is the third argument.
The n
functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy
.
The problem is because you haven't set JAVA_HOME in Mac properly. In order to do that, you should do set it like this:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home
In my case my JDK installation is jdk1.8.0_40, make sure you type yours.
Then you can use maven commands.
Regards!
php.ini probably needs to read:
extension=ext\php_sqlsrv_53_nts.dll
Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P
Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents<? phpinfo(); ?>
and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)
They're handy if your columns have the same names as SQL keywords, or have spaces in them.
Example:
create table test ( id int, user varchar(20) )
Oh no! Incorrect syntax near the keyword 'user'. But this:
create table test ( id int, [user] varchar(20) )
Works fine.
For one line!
Try using for wmic OS Get localdatetime^|find "."
in for /f
without tokens
and/or delims
, this works in any language / region and also, no user settings interfere with the layout of the output.
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo=month: !_date:~4,2!&echo= day: !_date:~6,2!"
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo=month: !_date:~4,2!&echo= day: !_date:~6,2!"
Results:
year: 2019
month: 06
day: 12
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo= month: !_date:~4,2!&echo= day: !_date:~6,2!&echo= hour: !_date:~8,2!&echo=minute: !_date:~10,2!"
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo= month: !_date:~4,2!&echo= day: !_date:~6,2!&echo= hour: !_date:~8,2!&echo=minute: !_date:~10,2!"
Results:
year: 2020
month: 05
day: 16
hour: 00
minute: 46
Either read it in with 'scan', or just do as.vector() on the matrix. You might want to transpose the matrix first if you want it by rows or columns.
> m=matrix(1:12,3,4)
> m
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> as.vector(m)
[1] 1 2 3 4 5 6 7 8 9 10 11 12
> as.vector(t(m))
[1] 1 4 7 10 2 5 8 11 3 6 9 12
Open a windows command line. Switch directories to C:\Windows\Microsoft.Net\Framework\v4.0.xxxx
where the x's are the build number. Type aspnet_regiis -ir
and hit enter. This should register .Net v4.0 and create the application pools by default. If it doesn't, you will need to create them manually by right-clicking the Application Pools
folder in IIS and choosing Add Application Pool
.
Edit: As a reference, please refer to the section of the linked document referring to the -i argument.
Microsoft is releasing the "Microsoft Edge WebView2" WPF control that will get us a great, free option for embedding Chromium across Windows 10, Windows 8.1, or Windows 7. It is available via Nuget as the package Microsoft.Web.WebView2
.
Turn if off:
You can use error_reporting();
or put an @ in front of your fileopen().
Was looking for a solution to this problem today. None of the above answers seemed to satisfy. I wanted a solution that could be a one liner, no conditional logic and nothing that had to be wrapped in a function.
Here's what I came up with, seems to work really well:
hostname="http://www.example.com:1234" hostname.split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.') // gives "example.com"
May look complicated at first glance, but it works pretty simply; the key is using 'slice(-n)' in a couple of places where the good part has to be pulled from the end of the split array (and [0] to get from the front of the split array).
Each of these tests return "example.com":
"http://example.com".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.') "http://example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.') "http://www.example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.') "http://foo.www.example.com:1234".split("//").slice(-1)[0].split(":")[0].split('.').slice(-2).join('.')
this is a more simpler solution.
@ECHO OFF
set name=%date%
echo %name%
mkdir %name%
In CoffeeScript:
#directive
app.directive('select2', ->
templateUrl: 'partials/select.html'
restrict: 'E'
transclude: 1
replace: 1
scope:
options: '='
model: '='
link: (scope, el, atr)->
el.bind 'change', ->
console.log this.value
scope.model = parseInt(this.value)
console.log scope
scope.$apply()
)
<!-- HTML partial -->
<select>
<option ng-repeat='o in options'
value='{{$index}}' ng-bind='o'></option>
</select>
<!-- HTML usage -->
<select2 options='mnuOffline' model='offlinePage.toggle' ></select2>
<!-- Conclusion -->
<p>Sometimes it's much easier to create your own directive...</p>
For the original issue, I would request you to apply below logic:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPostRequest = new HttpPost();
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
Since C++11, you can copy arrays directly with std::array
:
std::array<int,4> A = {10,20,30,40};
std::array<int,4> B = A; //copy array A into array B
Here is the documentation about std::array
This method orderBy
does not change the input array,
you have to assign the result to your array :
var chars = this.state.characters;
chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'
this.setState({characters: chars})
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
Until I get a better option, this is the most "bootstrappy" answer I can work out:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/
I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less
file:
in _layout.cshtml master page
body-content
containernavbar-fixed-bottom
on the footer<hr/>
before the footer (as now redundant)Relevant page HTML:
<div class="container-fluid body-content">
@RenderBody()
</div>
<footer class="navbar-fixed-bottom">
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
In Site.less
HTML
and BODY
heights to 100%BODY
overflow
to hidden
body-content
div position
to absolute
body-content
div top
to @navbar-height
instead of hard-wiring valuebody-content
div bottom
to 30px
.body-content
div left
and right
to 0body-content
div overflow-y
to auto
Site.less
html {
height: 100%;
body {
height: 100%;
overflow: hidden;
.container-fluid.body-content {
position: absolute;
top: @navbar-height;
bottom: 30px;
right: 0;
left: 0;
overflow-y: auto;
}
}
}
The remaining problem is there seems to be no defining variable for the footer height
in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.
With library(lubridate)
, numeric representations of date and time saved as the number of seconds since
1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime()
:
lubridate::as_datetime(1352068320)
[1] "2012-11-04 22:32:00 UTC"
autopep8 -i script.py
Use autopep8
autopep8
automagically formats Python code to conform to the PEP 8
nullstyle
guide. It uses the pep8
utility to determine what parts of the
nullcode
needs to be formatted. autopep8
is capable of fixing most of the
nullformatting
issues that can be reported by pep8
.
pip install autopep8
autopep8 script.py # print only
autopep8 -i script.py # write file
If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.
In Typescript use the For Each like below.
selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
{
for (var childObj in obj )
{
value.checked = parentChecked;
}
}
}
You have one DateFormat
, but you need two: one for the input, and another for the output.
You've got one for the output, but I don't see anything that would match your input. When you give the input string to the output format, it's no surprise that you see that exception.
DateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS-Z");
See this related thread. Basically, os.environ
is found on import, and os.getenv
is a wrapper to os.environ.get
, at least in CPython.
EDIT: To respond to a comment, in CPython, os.getenv
is basically a shortcut to os.environ.get
; since os.environ
is loaded at import of os
, and only then, the same holds for
os.getenv
.
var result = input.match(/\d+/g).join([])
For versions below 12c, the plain answer is NO, at least not in the manner it is being done is SQL Server.
You can print the results, you can insert the results into tables, you can return the results as cursors from within function/procedure or return a row set from function -
but you cannot execute SELECT statement, without doing something with the results.
begin
select 1+1
select 2+2
select 3+3
end
/* 3 result sets returned */
SQL> begin
2 select 1+1 from dual;
3 end;
4 /
select * from dual;
*
ERROR at line 2:
ORA-06550: line 2, column 1:
PLS-00428: an INTO clause is expected in this SELECT statement
just change your ImageView height and width to wrap_content and use
exampleImage.setScaleType(ImageView.ScaleType.FIT_XY);
in your code.
If you'd like to know how to sort a linked list without using standard Java libraries, I'd suggest looking at different algorithms yourself. Examples here show how to implement an insertion sort, another StackOverflow post shows a merge sort, and ehow even gives some examples on how to create a custom compare function in case you want to further customize your sort.
The issue is that the original axiosTest()
function isn't returning the promise. Here's an extended explanation for clarity:
function axiosTest() {
// create a promise for the axios request
const promise = axios.get(url)
// using .then, create a new promise which extracts the data
const dataPromise = promise.then((response) => response.data)
// return it
return dataPromise
}
// now we can use that data from the outside!
axiosTest()
.then(data => {
response.json({ message: 'Request received!', data })
})
.catch(err => console.log(err))
The function can be written more succinctly:
function axiosTest() {
return axios.get(url).then(response => response.data)
}
Or with async/await:
async function axiosTest() {
const response = await axios.get(url)
return response.data
}
For a very simple but not efficient or scalable solution, you can just use the built in django serve
view. This is excellent for quick prototypes or one-off work, but as has been mentioned throughout this question, you should use something like apache or nginx in production.
from django.views.static import serve
filepath = '/some/path/to/local/file.txt'
return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
Files "LICENSE.txt" and "NOTICE.txt" are case sensitive. So for SPring android library I had to add
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/notice.txt'
}
}
For the sake of completeness: the previous answers tell how to set the upstream branch, but not how to see it.
There are a few ways to do this:
git branch -vv
shows that info for all branches. (formatted in blue in most terminals)
cat .git/config
shows this also.
For reference:
We encountered this issue on a Tomcat running from a jre directory that was (almost fully) removed after an automatic jre update, so that the running jre could no longer find jre.../lib/security/cacerts because it no longer existed.
Restarting Tomcat (after changing the configuration to run from the different jre location) fixed the problem.
When none of the if
test in number_translator()
evaluate to true, the function returns None
. The error message is the consequence of that.
Whenever you see an error that include 'NoneType'
that means that you have an operand or an object that is None
when you were expecting something else.
To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.
let maxDate = new Date(8640000000000000);_x000D_
let minDate = new Date(-8640000000000000);_x000D_
_x000D_
console.log(new Date(maxDate.getTime()).toString());_x000D_
console.log(new Date(maxDate.getTime() - 1).toString());_x000D_
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date_x000D_
_x000D_
console.log(new Date(minDate.getTime()).toString());_x000D_
console.log(new Date(minDate.getTime() + 1).toString());_x000D_
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
_x000D_
function bindAllEvents (el) {
for (const key in el) {
if (key.slice(0, 2) === 'on') {
el.addEventListener(key.slice(2), e => console.log(e.type));
}
}
}
bindAllEvents($('.yourElement'))
This uses a bit of ES6 for prettiness, but can easily be translated for legacy browsers as well. In the function attached to the event listeners, it's currently just logging out what kind of event occurred but this is where you could print out additional information, or using a switch case on the e.type
, you could only print information on specific events
I struggled with the same question since i had submit button in the middle of the from which redirected submit to another page, like so:
<button type="submit" onclick="this.form.action = '#another_page'">More</button>
When user pressed enter key, this button was clicked instead of another submit button.
So i did some primitive tests by creating a from with multiple submit buttons and different visibility options and onclick event alerting which button was clicked: https://jsfiddle.net/aqfy51om/1/
Browsers and OS'es i used for testing:
WINDOWS
OSX
Most of these browsers clicked very first button despite the visibility options applied exept IE and Safari which clicked the third button, which is "visible" inside "hidden" container:
<div style="width: 0; height: 0; overflow: hidden;">
<button type="submit" class="btn btn-default" onclick="alert('Hidden submit button #3 was clicked');">Hidden submit button #3</button>
</div>
So my suggestion, which i'm going to use myself, is:
If you form has multiple submit buttons with different meaning, then include submit button with default action at the beginning of the form which is either:
style="width: 0; height: 0; overflow: hidden;"
EDIT
Another option might be to offset the button(still at the beginning of the from) style="position: absolute; left: -9999px; top: -9999px;"
, just tried it in IE - worked , but i have no idea what else it can screw up, for example printing..
For what it's worth, it appears your intent is to use the incoming HTTP request to form another HTTP request. Sort of like a gateway. There is an excellent module django-revproxy that accomplishes exactly this.
The source is a pretty good reference on how to accomplish what you are trying to do.
A boolean is not an integer; 1
and 0
are not boolean values in Java. You'll need to convert them explicitly:
boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));
std::string a = "Hello ";
a += "World";
There are many problems in your query.
This is a modified version of your code
string connetionString = null;
string sql = null;
// All the info required to reach your db. See connectionstrings.com
connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// Prepare a proper parameterized query
sql = "insert into Main ([Firt Name], [Last Name]) values(@first,@last)";
// Create the connection (and be sure to dispose it at the end)
using(SqlConnection cnn = new SqlConnection(connetionString))
{
try
{
// Open the connection to the database.
// This is the first critical step in the process.
// If we cannot reach the db then we have connectivity problems
cnn.Open();
// Prepare the command to be executed on the db
using(SqlCommand cmd = new SqlCommand(sql, cnn))
{
// Create and set the parameters values
cmd.Parameters.Add("@first", SqlDbType.NVarChar).Value = textbox2.text;
cmd.Parameters.Add("@last", SqlDbType.NVarChar).Value = textbox3.text;
// Let's ask the db to execute the query
int rowsAdded = cmd.ExecuteNonQuery();
if(rowsAdded > 0)
MessageBox.Show ("Row inserted!!" + );
else
// Well this should never really happen
MessageBox.Show ("No row inserted");
}
}
catch(Exception ex)
{
// We should log the error somewhere,
// for this example let's just show a message
MessageBox.Show("ERROR:" + ex.Message);
}
}
using
statement to be sure that the connection
will be closed and resources released Apart from this, there are other potential problems. What if the user doesn't input anything in the textbox controls? Do you have done any checking on this before trying to insert? As I have said the fields names contain spaces and this will cause inconveniences in your code. Try to change those field names.
This code assumes that your database columns are of type NVARCHAR, if not, then use the appropriate SqlDbType enum value.
Please plan to switch to a more recent version of NET Framework as soon as possible. The 1.1 is really obsolete now.
And, about AddWithValue problems, this article explain why we should avoid it. Can we stop using AddWithValue() already?
I have recently released a tiny library for doing just that with tests in mind. Maven dependency is:
<dependency>
<groupId>me.alexpanov</groupId>
<artifactId>free-port-finder</artifactId>
<version>1.0</version>
</dependency>
Once installed, free port numbers can be obtained via:
int port = FreePortFinder.findFreeLocalPort();
Another way to do this is to have a struct of pointers with the ,omitempty
tag. If the pointers are nil, the fields won't be Marshalled.
This method will not require additional reflection or inefficient use of maps.
Same example as jorelli using this method: http://play.golang.org/p/JJNa0m2_nw
The indentation is wrong, as the error tells you. As you can see, you have indented the code beginning with the indicated line too little to be in the for
loop, but too much to be at the same level as the for loop. Python sees the lack of indentation as ending the for
loop, then complains you have indented the rest of the code too much. (The def
line I'm betting is just an artifact of how Stack Overflow wants you to format your code.)
Edit: Given your correction, I'm betting you have a mixture of tabs and spaces in the source file, such that it looks to the human eye like the code lines up, but Python considers it not to. As others have suggested, using only spaces is the recommended practice (see PEP 8). If you start Python with python -t
, you will get warnings if there are mixed tabs and spaces in your code, which should help you pinpoint the issue.
For Ubuntu 12.04.3 LTS (Precise Pangolin) I had to do:
apt-get install libxml2-dev libxslt1-dev
(Note the "1" in libxslt1-dev)
Then I just installed lxml with pip/easy_install.
It indeed sets the stack size on a JVM.
You should touch it in either of these two situations:
The latter usually comes when your Xss is set too large - then you need to balance it (testing!)
HELP OTHERS AVOID A HEADACHE --- VOTE THIS UP!!!
The most popular answer on this page does not work for Firefox 14 and does not pass the jsLinter. "while" loops need a comparison operator, not an assignment. It does work on chrome, safari, and even ie. But dies in firefox.
THIS IS BROKEN!
var i = arr.length; //or 10
while(i--)
{
//...
}
THIS WILL WORK! (works on firefox, passes the jsLinter)
var i = arr.length; //or 10
while(i>-1)
{
//...
i = i - 1;
}
Not from activities only:
public static String getStringByIdName(Context context, String idName) {
Resources res = context.getResources();
return res.getString(res.getIdentifier(idName, "string", context.getPackageName()));
}
Use display: block;
margin: auto;
it will center the div
According to 3.9 version of Docker compose, you can use image: myapp:tag
to specify name and tag.
version: "3.9"
services:
webapp:
build:
context: .
dockerfile: Dockerfile
image: webapp:tag
Reference: https://docs.docker.com/compose/compose-file/compose-file-v3/
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
It looks like you were on the right track - get_FOO_display()
is most certainly what you want:
In templates, you don't include ()
in the name of a method. Do the following:
{{ person.get_gender_display }}
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
You can use RawGit:
https://rawgit.com/necolas/css3-social-signin-buttons/master/index.html
It works better (at the time of this writing) than http://htmlpreview.github.com/, serving files with proper Content-Type headers. Additionally, it also provides CDN URL for use in production.
Try this:
class Flonetwork(Object):
def __init__(self,adj = {},flow={}):
self.adj = adj
self.flow = flow
The biggest problem with your code is that it's unreadable. Python code rule number one, if it's not readable, no one's gonna look at it for long enough to get any useful information out of it. Always use descriptive variable names. Almost didn't catch the bug in your code, let's see it again with good names, slow-motion replay style:
to_modify = [5,4,3,2,1,0]
indexes = [0,1,3,5]
replacements = [0,0,0,0]
for index in indexes:
to_modify[indexes[index]] = replacements[index]
# to_modify[indexes[index]]
# indexes[index]
# Yo dawg, I heard you liked indexes, so I put an index inside your indexes
# so you can go out of bounds while you go out of bounds.
As is obvious when you use descriptive variable names, you're indexing the list of indexes with values from itself, which doesn't make sense in this case.
Also when iterating through 2 lists in parallel I like to use the zip
function (or izip
if you're worried about memory consumption, but I'm not one of those iteration purists). So try this instead.
for (index, replacement) in zip(indexes, replacements):
to_modify[index] = replacement
If your problem is only working with lists of numbers then I'd say that @steabert has the answer you were looking for with that numpy stuff. However you can't use sequences or other variable-sized data types as elements of numpy arrays, so if your variable to_modify
has anything like that in it, you're probably best off doing it with a for loop.
Add a label=
to each of your plot()
calls, and then call legend(loc='upper left')
.
Consider this sample (tested with Python 3.8.0):
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()
Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html
A variation of the materialized view "Possible alternative" outlined by Erwin Brandstetter is possible.
Say, for example, that you don't want duplicates in the randomized values that are returned. So you will need to set a boolean value on the primary table containing your (non-randomized) set of values.
Assuming this is the input table:
id_values id | used
----+--------
1 | FALSE
2 | FALSE
3 | FALSE
4 | FALSE
5 | FALSE
...
Populate the ID_VALUES
table as needed. Then, as described by Erwin, create a materialized view that randomizes the ID_VALUES
table once:
CREATE MATERIALIZED VIEW id_values_randomized AS
SELECT id
FROM id_values
ORDER BY random();
Note that the materialized view does not contain the used column, because this will quickly become out-of-date. Nor does the view need to contain other columns that may be in the id_values
table.
In order to obtain (and "consume") random values, use an UPDATE-RETURNING on id_values
, selecting id_values
from id_values_randomized
with a join, and applying the desired criteria to obtain only relevant possibilities. For example:
UPDATE id_values
SET used = TRUE
WHERE id_values.id IN
(SELECT i.id
FROM id_values_randomized r INNER JOIN id_values i ON i.id = r.id
WHERE (NOT i.used)
LIMIT 5)
RETURNING id;
Change LIMIT
as necessary -- if you only need one random value at a time, change LIMIT
to 1
.
With the proper indexes on id_values
, I believe the UPDATE-RETURNING should execute very quickly with little load. It returns randomized values with one database round-trip. The criteria for "eligible" rows can be as complex as required. New rows can be added to the id_values
table at any time, and they will become accessible to the application as soon as the materialized view is refreshed (which can likely be run at an off-peak time). Creation and refresh of the materialized view will be slow, but it only needs to be executed when new id's are added to the id_values
table.
In my case CFLAGS = -O0 -g -Wall -I. -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=soft
has helped. As you can see, i used it for my stm32f407.
In my case
-Djava.awt.headless=true
was set (indirectly by a Maven configuration). I had to actively use
-Djava.awt.headless=false
to override this.
For me only following is working:
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
Platform.exit();
Thread start = new Thread(new Runnable() {
@Override
public void run() {
//TODO Auto-generated method stub
system.exit(0);
}
});
start.start();
}
});
Here is alternate trick, it's not the best solution but it just give you a choice
HTML code:
<button clss="btn btn-primary" id="btn_upload">Choose File</button>
<input id="fileupload" class="hide" type="file" name="files[]">
Javascript:
$("#btn_upload").click(function(e){
e.preventDefault();
$("#fileupload").trigger('click');
});
If you are looking for an alternative solution and can manage the vimeo account there is another way, you simply add every video you want to show into an album and then use the API to request the album details - it then shows all the thumbnails and links. It's not ideal but might help.
Twitter convo with @vimeoapi
Here is PySpark version to create Hive table from parquet file. You may have generated Parquet files using inferred schema and now want to push definition to Hive metastore. You can also push definition to the system like AWS Glue or AWS Athena and not just to Hive metastore. Here I am using spark.sql to push/create permanent table.
# Location where my parquet files are present.
df = spark.read.parquet("s3://my-location/data/")
cols = df.dtypes
buf = []
buf.append('CREATE EXTERNAL TABLE test123 (')
keyanddatatypes = df.dtypes
sizeof = len(df.dtypes)
print ("size----------",sizeof)
count=1;
for eachvalue in keyanddatatypes:
print count,sizeof,eachvalue
if count == sizeof:
total = str(eachvalue[0])+str(' ')+str(eachvalue[1])
else:
total = str(eachvalue[0]) + str(' ') + str(eachvalue[1]) + str(',')
buf.append(total)
count = count + 1
buf.append(' )')
buf.append(' STORED as parquet ')
buf.append("LOCATION")
buf.append("'")
buf.append('s3://my-location/data/')
buf.append("'")
buf.append("'")
##partition by pt
tabledef = ''.join(buf)
print "---------print definition ---------"
print tabledef
## create a table using spark.sql. Assuming you are using spark 2.1+
spark.sql(tabledef);
Using no messy concatenations and padding :
'{:0{width}x}'.format(int(temp,2)), width=4)
Will give a hex representation with padding preserved
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
If you have the authority to edit the pages to be opened, you can href to 'A' page and in the A page you can put link to B page in onpageload attribute of body tag.
styles.xml
<style name="CircularProgress" parent="Theme.AppCompat.Light">
<item name="colorAccent">@color/yellow</item>
</style>
<ProgressBar
android:layout_width="@dimen/d_40"
android:layout_height="@dimen/d_40"
android:indeterminate="true"
style="@style/Widget.AppCompat.ProgressBar"
android:theme="@style/CircularProgress"/>
This is better solution.
Other solution is dangerous because it's hack.
extension UINavigationController {
func pushViewControllerWithoutBackButtonTitle(_ viewController: UIViewController, animated: Bool = true) {
viewControllers.last?.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
pushViewController(viewController, animated: animated)
}
}
If you are using pl/sql then the following code should work :
set server output on -- to retrieve and display a buffer
DECLARE
v_text VARCHAR2(10); -- declare
BEGIN
v_text := 'Hello'; --assign
dbms_output.Put_line(v_text); --display
END;
/
-- this must be use to execute pl/sql script
Using the standard ctypes library, this should yield the current on screen mouse coordinates without any third party modules:
from ctypes import windll, Structure, c_long, byref
class POINT(Structure):
_fields_ = [("x", c_long), ("y", c_long)]
def queryMousePosition():
pt = POINT()
windll.user32.GetCursorPos(byref(pt))
return { "x": pt.x, "y": pt.y}
pos = queryMousePosition()
print(pos)
I should mention that this code was taken from an example found here So credit goes to Nullege.com for this solution.
i was able to make it work on a single line:
byte [] byteArr= ((MemoryStream)localStream).ToArray();
as clarified by johnnyRose, Above code will only work for MemoryStream
use typescript for your coding, because it's object oriented, strictly typed and easy to maintain the code ...
for more info about typescipt click here
Here one simple example I have created to share data between two controller using Typescript...
module Demo {
//create only one module for single Applicaiton
angular.module('app', []);
//Create a searvie to share the data
export class CommonService {
sharedData: any;
constructor() {
this.sharedData = "send this data to Controller";
}
}
//add Service to module app
angular.module('app').service('CommonService', CommonService);
//Create One controller for one purpose
export class FirstController {
dataInCtrl1: any;
//Don't forget to inject service to access data from service
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl1 = this.commonService.sharedData;
}
}
//add controller to module app
angular.module('app').controller('FirstController', FirstController);
export class SecondController {
dataInCtrl2: any;
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl2 = this.commonService.sharedData;
}
}
angular.module('app').controller('SecondController', SecondController);
}
You need to put % name
straight after the string:
f = open('%s.csv' % name, 'wb')
The reason your code doesn't work is because you are trying to %
a file, which isn't string formatting, and is also invalid.
htmlentities() converts HTML Entities
So we build a constant that will contain our html tags we want to convert.
const htmlEntities = [
{regex:'&',entity:'&'},
{regex:'>',entity:'>'},
{regex:'<',entity:'<'}
];
We build a function that will convert all corresponding html characters to string : Html ==> String
function htmlentities (s){
var reg;
for (v in htmlEntities) {
reg = new RegExp(htmlEntities[v].regex, 'g');
s = s.replace(reg, htmlEntities[v].entity);
}
return s;
}
To decode, we build a reverse function that will convert all string to their equivalent html . String ==> html
function html_entities_decode (s){
var reg;
for (v in htmlEntities) {
reg = new RegExp(htmlEntities[v].entity, 'g');
s = s.replace(reg, htmlEntities[v].regex);
}
return s;
}
After, We can encode all others special characters (é è ...) with encodeURIComponent()
Use Case
var s = '<div> God bless you guy </div> '
var h = encodeURIComponent(htmlentities(s)); /** To encode */
h = html_entities_decode(decodeURIComponent(h)); /** To decode */
I use this
def cleaned( aFile ):
for line in aFile:
yield line.strip()
Then I can do things like this.
lines = list( cleaned( open("file","r") ) )
Or, I can extend cleaned with extra functions to, for example, drop blank lines or skip comment lines or whatever.
Try
$(".text").text(data);
Or to convert the data received to a string.
The problem is that PHP mail()
function has a very limited functionality. There are several ways to send mail from PHP.
mail()
uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.mail()
uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail()
function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer
class or interface with abstract send()
method. Inherit two classes MyPhpMailer
and MySwiftMailer
. Implement send()
method in appropriate ways.
try this:
return $this->db->query("
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
")->result_array();
Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html see Standard Query With Multiple Results (Array Version) section
NestedScrollView is just like ScrollView, but in NestedScrollView we can put other scrolling views as child of it, e.g. RecyclerView.
But if we put RecyclerView inside NestedScrollView, RecyclerView's smooth scrolling is disturbed. So to bring back smooth scrolling there's trick:
ViewCompat.setNestedScrollingEnabled(recyclerView, false);
put above line after setting adapter for recyclerView.
If you have a unix host within AWS, then use s3cmd from s3tools.org. Set up permissions so that your key as read access to your development bucket. Then run:
s3cmd cp -r s3://productionbucket/feed/feedname/date s3://developmentbucket/feed/feedname
These will also redirect both:
yourcommand &> /dev/null
yourcommand >& /dev/null
though the bash manual says the first is preferred.
"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"
I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.
Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.
If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.
It seems that you've omitted the value attribute in HTML markup.
Add it there as <input value="" ... >
.
Big difference, TABLOCK
will try to grab "shared" locks, and TABLOCKX
exclusive locks.
If you are in a transaction and you grab an exclusive lock on a table, EG:
SELECT 1 FROM TABLE WITH (TABLOCKX)
No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.
TABLOCK
only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED
(default). If your isolation level is higher, for example: SERIALIZABLE
, shared locks are held until the end of a transaction.
Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK
). However, if transaction A
holds a shared lock on a table, transaction B
will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.
Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).
In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.
In general you would not use TABLOCK
or TABLOCKX
unless you absolutely needed it for some edge case.
[![Change the build variant then you can see the run the application which will lead to error
You have to find SHA1 code for Release Key & enter it on your Developer Console. ( for me developer console is firebase some people might use different services) To find SHA1 Code . easy way is
Go to Build --- Select Build Variant -- On the left Side Select "Release" as build variant -- now go to module settings ( or try to run project , android studio will tell you about a error and click fix error button) --- Select Signing tab --- add your release key and passwords -- now goto build types -- select release -- on signing config select your release key config -- now run your project -- now run your signing report --- you can find SHA1 under release build -- enter that sha1 code on your developer console
Adding screen shots(examples) and some more context for the answer of @Thomas G.
import pandas as pd
is ran properly before checking below shortcut.Place the cursor in middle of parenthesis ()
before you use shortcut.
shift + tab
Display short document and few params
shift + tab + tab
Expands document with scroll bar
shift + tab + tab + tab
Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.
shift + tab + tab + tab + tab
It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.
Here's a simple way I came up with that doesn't involve unsafe code or pinning the object. Also works in reverse (object from address):
public static class AddressHelper
{
private static object mutualObject;
private static ObjectReinterpreter reinterpreter;
static AddressHelper()
{
AddressHelper.mutualObject = new object();
AddressHelper.reinterpreter = new ObjectReinterpreter();
AddressHelper.reinterpreter.AsObject = new ObjectWrapper();
}
public static IntPtr GetAddress(object obj)
{
lock (AddressHelper.mutualObject)
{
AddressHelper.reinterpreter.AsObject.Object = obj;
IntPtr address = AddressHelper.reinterpreter.AsIntPtr.Value;
AddressHelper.reinterpreter.AsObject.Object = null;
return address;
}
}
public static T GetInstance<T>(IntPtr address)
{
lock (AddressHelper.mutualObject)
{
AddressHelper.reinterpreter.AsIntPtr.Value = address;
return (T)AddressHelper.reinterpreter.AsObject.Object;
}
}
// I bet you thought C# was type-safe.
[StructLayout(LayoutKind.Explicit)]
private struct ObjectReinterpreter
{
[FieldOffset(0)] public ObjectWrapper AsObject;
[FieldOffset(0)] public IntPtrWrapper AsIntPtr;
}
private class ObjectWrapper
{
public object Object;
}
private class IntPtrWrapper
{
public IntPtr Value;
}
}
You create the collection in the Contact
controller -
app/controllers/contacts_controller.erb
Adding
@providers = Provider.all.by_name
to the new, create and edit methods, using a scope for the by_name
in the Provider
model - app/models/provider.rb
- for the ordering by name
scope by_name order(:name)
Then in the view - app/views/contacts/_form.html.erb
- you use
<%= f.collection_select :provider_id, @providers, :id, :name, include_blank: true %>
For rails forms, I also strongly recommend you look at a form builder like simple_form - https://github.com/plataformatec/simple_form - which will do all the heavy lifting.
Why not just:
import seaborn as sns
sns.barplot(list(D.keys()), list(D.values()))
You can use StringFormat in Silverlight 4 to provide a custom formatting of the value you bind to.
The date formatting has a huge range of options.
For the DateTime of “April 17, 2004, 1:52:45 PM”
You can either use a set of standard formats (standard formats)…
StringFormat=f : “Saturday, April 17, 2004 1:52 PM”
StringFormat=g : “4/17/2004 1:52 PM”
StringFormat=m : “April 17”
StringFormat=y : “April, 2004”
StringFormat=t : “1:52 PM”
StringFormat=u : “2004-04-17 13:52:45Z”
StringFormat=o : “2004-04-17T13:52:45.0000000”
… or you can create your own date formatting using letters (custom formats)
StringFormat=’MM/dd/yy’ : “04/17/04”
StringFormat=’MMMM dd, yyyy g’ : “April 17, 2004 A.D.”
StringFormat=’hh:mm:ss.fff tt’ : “01:52:45.000 PM”
To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described here:
private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
URL url = new URL(thisUrl);
builder = new Uri.Builder()
.scheme(url.getProtocol())
.authority(url.getAuthority())
.appendPath(url.getPath());
return builder.build();
}
If the variant is empty then an error will be thrown. The bullet-proof code is the following:
Public Function GetLength(a As Variant) As Integer
If IsEmpty(a) Then
GetLength = 0
Else
GetLength = UBound(a) - LBound(a) + 1
End If
End Function
Here's a vote for star imports. An import statement is intended to import a package, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. java.sql.Date
vs java.util.Date
) are easily remedied by other means, not really addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements.
Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove all of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain.
If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports.
Here's how to deal with class conflicts:
import java.sql.*;
import java.util.*;
import java.sql.Date;
It's 2020 -
Project>Right Click>Java Compiler>Compiler Compliance Level> Change this to 1.8 [or latest level]
Steps to Remove app from App Store
This is a fascinating discussion. Like many others I had never even considered this topic. I got cornered into having to have the imports in the functions because of wanting to use the Django ORM in one of my libraries. I was having to call django.setup()
before importing my model classes and because this was at the top of the file it was being dragged into completely non-Django library code because of the IoC injector construction.
I kind of hacked around a bit and ended up putting the django.setup()
in the singleton constructor and the relevant import at the top of each class method. Now this worked fine but made me uneasy because the imports weren't at the top and also I started worrying about the extra time hit of the imports. Then I came here and read with great interest everybody's take on this.
I have a long C++ background and now use Python/Cython. My take on this is that why not put the imports in the function unless it causes you a profiled bottleneck. It's only like declaring space for variables just before you need them. The trouble is I have thousands of lines of code with all the imports at the top! So I think I will do it from now on and change the odd file here and there when I'm passing through and have the time.
ComboBox1.Text = ComboBox1.Items(0).ToString
This code is show you Combobox1 first item in Vb.net
Make an equation for every li. The equation sort of:
fi(P)=0.
P is a point. For points, belonging to li, the equation is true.
So, we have to check this:
fAB(P) fAB(C) >= 0
fBC(P) fBC(D) >= 0
fCD(P) fCD(A) >= 0
fDA(P) fDA(B) >= 0
The unequations are not strict, for if a point is on the border, it belongs to the rectangle, too. If you don't need points on the border, you can change inequations for strict ones. But while you work in floating point operations, the choice is irrelevant.
The only thing left is to get an equation for a line going through two points. It is a well-known linear equation. Let's write it for a line AB and point P:
fAB(P) = (xA-xB) (yP-yB) - (yA-yB) (xP-xB)
The check could be simplified - let's go along the rectangle clockwise - A, B, C, D, A. Then all correct sides will be to the right of the lines. So, we needn't compare with the side where another vertice is. And we need check a set of shorter inequations:
fAB(P) >= 0
fBC(P) >= 0
fCD(P) >= 0
fDA(P) >= 0
But this is correct for the normal, mathematician (from the school mathematics) set of coordinates, where X is to the right and Y to the top. And for the geodesy coordinates, as are used in GPS, where X is to the top, and Y is to the right, we have to turn the inequations:
fAB(P) <= 0
fBC(P) <= 0
fCD(P) <= 0
fDA(P) <= 0
If you are not sure with the directions of axes, be careful with this simplified check - check for one point with the known placement, if you have chosen the correct inequations.
For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170
git pull &&& git push
.git push origin master:foo
and merge it on remote repo.-f
(denyCurrentBranch
needs to be ignored).Basically the error means that your repository is not up-to-date with the remote code (its index and work tree is inconsistent with what you pushed).
Normally you should pull
first to get the recent changes and push
it again.
If won't help, try pushing into different branch, e.g.:
git push origin master:foo
then merge this branch on the remote repository back with master.
If you changed some past commits intentionally via git rebase
and you want to override repo with your changes, you probably want to force the push by adding -f
/--force
parameter (not recommended if you didn't do rebase
). If still won't work, you need to set receive.denyCurrentBranch
to ignore
on remote as suggested by a git message via:
git config receive.denyCurrentBranch ignore
Here I am going to show you that how to create a BROWSE button, which when you will click, it will open up the SD card, you will select a File and as a result you will get the file name and file path of the selected one:
browse.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
startActivityForResult(intent, PICK_REQUEST_CODE);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
Uri uri = intent.getData();
if (uri.getScheme().toString().compareTo("content")==0)
{
Cursor cursor =getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
Uri filePathUri = Uri.parse(cursor.getString(column_index));
String file_name = filePathUri.getLastPathSegment().toString();
String file_path=filePathUri.getPath();
Toast.makeText(this,"File Name & PATH are:"+file_name+"\n"+file_path, Toast.LENGTH_LONG).show();
}
}
}
}
}
In linux,
sudo vi /etc/sysconfig/jenkins
set following configuration with any available port
JENKINS_PORT="8082"
If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
will give you a ScheduledExecutorService
with similar functionality to Timer
(i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer
class). Using a ScheduledExecutorService
also gives you advantages such as:
newScheduledThreadPoolExecutor()
or the ScheduledThreadPoolExecutor
class)About the only reasons for sticking to Timer
I can think of are:
System.getProperties()
can be overridden by calls to System.setProperty(String key, String value)
or with command line parameters -Dfile.separator=/
File.separator
gets the separator for the default filesystem.
FileSystems.getDefault()
gets you the default filesystem.
FileSystem.getSeparator()
gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.
For your problem, the solution might be to attach CDN hosted by google with certain library:
https://developers.google.com/speed/libraries/devguide
Also, you can add this at the bottom of page (just before </body>
):
<script type="text/javascript">
(function() {
var script = document.createElement('script')
script.setAttribute("type", "text/javascript")
script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js")
document.getElementsByTagName("head")[0].appendChild(script)
})();
</script>
However, this is risky in my opinion. You have an asynchronous call for jquery, thus your jquery has to wait until it loads (ie. $(document).ready
won't work in this case). So my answer would be: use a CDN like google suggests; put your javascript on the bottom just before </body>
; and, ignore flags from profilers.
Escaping quotes in MSSQL is done by a double quote, so a ''
or a ""
will produce one escaped '
and "
, respectively.
FIRST: make sure you have a color as a bitmap, like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
(e is from the event handler wich picked my color!)
What I did when I had this problem a whilke ago, I first got the rgba (red, green, blue and alpha) values. Next I created 3 floats: float hue, float saturation, float brightness. Then you simply do:
hue = yourcolor.Gethue;
saturation = yourcolor.GetSaturation;
brightness = yourcolor.GetBrightness;
The whole lot looks like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
float hue;
float saturation;
float brightness;
hue = paintcolor.GetHue();
saturation = paintcolor.GetSaturation();
brightness = paintcolor.GetBrightness();
If you now want to display them in a label, just do:
yourlabelname.Text = hue.ToString;
yourlabelname.Text = saturation.ToString;
yourlabelname.Text = brightness.ToString;
Here you go, you now have RGB Values into HSV values :)
Hope this helps
Start by creating a mapping of group names to values. Then transform into your desired format.
var myArray = [_x000D_
{group: "one", color: "red"},_x000D_
{group: "two", color: "blue"},_x000D_
{group: "one", color: "green"},_x000D_
{group: "one", color: "black"}_x000D_
];_x000D_
_x000D_
var group_to_values = myArray.reduce(function (obj, item) {_x000D_
obj[item.group] = obj[item.group] || [];_x000D_
obj[item.group].push(item.color);_x000D_
return obj;_x000D_
}, {});_x000D_
_x000D_
var groups = Object.keys(group_to_values).map(function (key) {_x000D_
return {group: key, color: group_to_values[key]};_x000D_
});_x000D_
_x000D_
var pre = document.createElement("pre");_x000D_
pre.innerHTML = "groups:\n\n" + JSON.stringify(groups, null, 4);_x000D_
document.body.appendChild(pre);
_x000D_
Using Array instance methods such as reduce and map gives you powerful higher-level constructs that can save you a lot of the pain of looping manually.
database_name -> Operations -> Remove database -> click on drop the database (DROP)
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
----------------------------------
}
This is standards compliant and cross-browser safe.
Example: http://jsfiddle.net/kv9pw/
var span = document.getElementById('someID');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
span.appendChild( document.createTextNode("some new content") );
Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:
import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };
See also [1] for more examples.
[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html
You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
Simple One
Note: dont use display:none instead use opacity to hide and show
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {
e.preventDefault();
menu.style.position = 'absolute';
menu.style.left = e.pageX + 'px';
menu.style.top = e.pageY + 'px';
menu.style.opacity = 1;
});
document.addEventListener("click", function(e){
if(e.target.closest('.context_menu'))
return;
menu.style.opacity = 0;
});
_x000D_
.context_menu{
width:70px;
background:lightgrey;
padding:5px;
opacity :0;
}
.context_menu div{
margin:5px;
background:grey;
}
.context_menu div:hover{
margin:5px;
background:red;
cursor:pointer;
}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
</div>
_x000D_
extra css
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {
e.preventDefault();
menu.style.position = 'absolute';
menu.style.left = e.pageX + 'px';
menu.style.top = e.pageY + 'px';
menu.style.opacity = 1;
});
document.addEventListener("click", function(e){
if(e.target.closest('.context_menu'))
return;
menu.style.opacity = 0;
});
_x000D_
.context_menu{
width:120px;
background:white;
border:1px solid lightgrey;
opacity :0;
}
.context_menu div{
padding:5px;
padding-left:15px;
margin:5px 2px;
border-bottom:1px solid lightgrey;
}
.context_menu div:last-child {
border:none;
}
.context_menu div:hover{
background:lightgrey;
cursor:pointer;
}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
<div>menu 3</div>
<div>menu 4</div>
</div>
_x000D_
I think you can use
sys.exit(0)
You may check it here in the python 2.7 doc:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.
The cleanest way in modern Python >=3.6
, is to use an f-string with string formatting:
>>> var = 1.6
>>> f"{var:.15f}"
'1.600000000000000'
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).
It's all about the key bindings which one can simply achieve from .vimrc configurations.
As far as clipboard is concerned you can use :set clipboard unnamed
and the yank from vim will go to system clipboard.
Anyways, whichever one you end up using I suggest using this vimrc config
, it contains a whole lot of plugins and bindings which will make your experience smooth.
To modify a value every time a block of code runs without having to break execution flow:
The "Logpoints" feature in the debugger is designed to let you log arbitrary values to the console without breaking. It evaluates code inside the flow of execution, which means you can actually use it to change values on the fly without stopping.
Right-click a line number and choose "Logpoint," then enter the assignment expression. It looks something like this:
I find it super useful for setting values to a state not otherwise easy to reproduce, without having to rebuild my project with debug lines in it. REMEMBER to delete the breakpoint when you're done!
To get value, use:
$.each($('input'),function(i,val){
if($(this).attr("type")=="hidden"){
var valueOfHidFiled=$(this).val();
alert(valueOfHidFiled);
}
});
or:
var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);
To set value, use:
$('input[type=hidden]').attr('value',newValue);
These are escape characters which are used to manipulate string.
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
Read more about them from here.
http://docs.oracle.com/javase/tutorial/java/data/characters.html
This is a fast and straightforward solution -
function chunkString (str, len) {_x000D_
const size = Math.ceil(str.length/len)_x000D_
const r = Array(size)_x000D_
let offset = 0_x000D_
_x000D_
for (let i = 0; i < size; i++) {_x000D_
r[i] = str.substr(offset, len)_x000D_
offset += len_x000D_
}_x000D_
_x000D_
return r_x000D_
}_x000D_
_x000D_
console.log(chunkString("helloworld", 3))_x000D_
// => [ "hel", "low", "orl", "d" ]_x000D_
_x000D_
// 10,000 char string_x000D_
const bigString = "helloworld".repeat(1000)_x000D_
console.time("perf")_x000D_
const result = chunkString(bigString, 3)_x000D_
console.timeEnd("perf")_x000D_
console.log(result)_x000D_
// => perf: 0.385 ms_x000D_
// => [ "hel", "low", "orl", "dhe", "llo", "wor", ... ]
_x000D_
with open('writing_file.json', 'w') as w:
with open('reading_file.json', 'r') as r:
for line in r:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
w.write(json.dumps(element))
this is the method i use..
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
The special thing about iterators is that they provide the glue between algorithms and containers. For generic code, the recommendation would be to use a combination of STL algorithms (e.g. find
, sort
, remove
, copy
) etc. that carries out the computation that you have in mind on your data structure (vector
, list
, map
etc.), and to supply that algorithm with iterators into your container.
Your particular example could be written as a combination of the for_each
algorithm and the vector
container (see option 3) below), but it's only one out of four distinct ways to iterate over a std::vector:
1) index-based iteration
for (std::size_t i = 0; i != v.size(); ++i) {
// access element as v[i]
// any code including continue, break, return
}
Advantages: familiar to anyone familiar with C-style code, can loop using different strides (e.g. i += 2
).
Disadvantages: only for sequential random access containers (vector
, array
, deque
), doesn't work for list
, forward_list
or the associative containers. Also the loop control is a little verbose (init, check, increment). People need to be aware of the 0-based indexing in C++.
2) iterator-based iteration
for (auto it = v.begin(); it != v.end(); ++it) {
// if the current index is needed:
auto i = std::distance(v.begin(), it);
// access element as *it
// any code including continue, break, return
}
Advantages: more generic, works for all containers (even the new unordered associative containers, can also use different strides (e.g. std::advance(it, 2)
);
Disadvantages: need extra work to get the index of the current element (could be O(N) for list or forward_list). Again, the loop control is a little verbose (init, check, increment).
3) STL for_each algorithm + lambda
std::for_each(v.begin(), v.end(), [](T const& elem) {
// if the current index is needed:
auto i = &elem - &v[0];
// cannot continue, break or return out of the loop
});
Advantages: same as 2) plus small reduction in loop control (no check and increment), this can greatly reduce your bug rate (wrong init, check or increment, off-by-one errors).
Disadvantages: same as explicit iterator-loop plus restricted possibilities for flow control in the loop (cannot use continue, break or return) and no option for different strides (unless you use an iterator adapter that overloads operator++
).
4) range-for loop
for (auto& elem: v) {
// if the current index is needed:
auto i = &elem - &v[0];
// any code including continue, break, return
}
Advantages: very compact loop control, direct access to the current element.
Disadvantages: extra statement to get the index. Cannot use different strides.
What to use?
For your particular example of iterating over std::vector
: if you really need the index (e.g. access the previous or next element, printing/logging the index inside the loop etc.) or you need a stride different than 1, then I would go for the explicitly indexed-loop, otherwise I'd go for the range-for loop.
For generic algorithms on generic containers I'd go for the explicit iterator loop unless the code contained no flow control inside the loop and needed stride 1, in which case I'd go for the STL for_each
+ a lambda.
The excellent library Type::Tiny provides an framework with which to build type-checking into your Perl code. What I show here is only the thinnest tip of the iceberg and is using Type::Tiny in the most simplistic and manual way.
Be sure to check out the Type::Tiny::Manual for more information.
use Types::Common::String qw< NonEmptyStr >;
if ( NonEmptyStr->check($name) ) {
# Do something here.
}
NonEmptyStr->($name); # Throw an exception if validation fails
Revised (works if you have multiple children): You can use jQuery (Look at the JSFiddle link)
var d= $('div');
var w;
d.children().each(function(){
w = w + $(this).outerWidth();
d.css('width', w + 'px')
});
Do not forget to include the jQuery...
Spring provides two kinds of IOC container, one is
XMLBeanFactory
and other isApplicationContext
.
+---------------------------------------+-----------------+--------------------------------+
| | BeanFactory | ApplicationContext |
+---------------------------------------+-----------------+--------------------------------+
| Annotation support | No | Yes |
| BeanPostProcessor Registration | Manual | Automatic |
| implementation | XMLBeanFactory | ClassPath/FileSystem/WebXmlApplicationContext|
| internationalization | No | Yes |
| Enterprise services | No | Yes |
| ApplicationEvent publication | No | Yes |
+---------------------------------------+-----------------+--------------------------------+
FileSystemXmlApplicationContext
Beans loaded through the full path.ClassPathXmlApplicationContext
Beans loaded through the CLASSPATHXMLWebApplicationContext
and AnnotationConfigWebApplicationContext
beans loaded through the web application context.AnnotationConfigApplicationContext
Loading Spring beans from Annotation based configuration. example:
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeansConfiguration.class);
ApplicationContext
is the container initialized by a ContextLoaderListener
or ContextLoaderServlet
defined in a web.xml
and ContextLoaderPlugin
defined in struts-config.xml
.Note: XmlBeanFactory
is deprecated as of Spring 3.1 in favor of DefaultListableBeanFactory
and XmlBeanDefinitionReader
.
Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I had the same problem. The solution turned out to be much simpler. It appears that a datatable wants the method in the form of a getter, ie getSomeMethod(), not just someMethod(). In my case in the datatable I was calling findResults. I changed the method in my backing bean to getFindResults() and it worked.
A commandButton worked find without the get which served to make it only more confusing.
You can also put DOM elements, like div
on top of the canvas that would represent your canvas elements and be positioned the same way.
Now you can attach event listeners to these divs and run the necessary actions.
This was so annoying. Open your project, click on Target, Open Build Phases tab. Check your Copy Bundle Resources for any red items.
In case of array like
result = [ '2015', '2014', '2013', '2011' ],
it gets tricky if you are using escape sequence like:
result = [ \'2015\', \'2014\', \'2013\', \'2011\' ].
Instead, good way to do it is to wrap the array with single quotes as follows:
result = "'"+result+"'";
Fully working code sample how to share file from inner app folder. Tested on Android 7 and Android 5.
AndroidManifest.xml
</application>
....
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="android.getqardio.com.gmslocationtest"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
xml/provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path
name="share"
path="external_files"/>
</paths>
Code itself
File imagePath = new File(getFilesDir(), "external_files");
imagePath.mkdir();
File imageFile = new File(imagePath.getPath(), "test.jpg");
// Write data in your file
Uri uri = FileProvider.getUriForFile(this, getPackageName(), imageFile);
Intent intent = ShareCompat.IntentBuilder.from(this)
.setStream(uri) // uri from FileProvider
.setType("text/html")
.getIntent()
.setAction(Intent.ACTION_VIEW) //Change if needed
.setDataAndType(uri, "image/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
There are to ways: Use the attribute of the image tag align="absmiddle" or locate the image and the text in a container DIV or TD in a table and use
style="vertical-align:middle"
event.target
returns the node that was targeted by the function. This means you can do anything you want to do with any other node like one you'd get from document.getElementById
I'm tried with jQuery
var _target = e.target;
console.log(_target.attr('href'));
Return an error :
.attr not function
But _target.attributes.href.value
was works.
As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root
for git rebase
:
"git rebase [-i] --root $tip
" can now be used to rewrite all the history leading to "$tip
" down to the root commit.
That new behavior was initially discussed here:
I personally think "
git rebase -i --root
" should be made to just work without requiring "--onto
" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.
The patch followed.
(original answer, February 2010)
As mentioned in the Git FAQ (and this SO question), the idea is:
git reset --hard
Rebase branch on top of changed commit, using:
git rebase --onto <tmp branch> <commit after changed> <branch>`
The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter
to make sure the content of that file does not contain in any commit the sensible information.
In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.
Normally, the exe can be found in the debug folder, as suggested previously, but not in the release folder, that is disabled by default in my configuration. If you want to activate the release folder, you can do this: BUILD->Batch Build And activate the "build" checkbox in the release configuration. When you click the build button, the exe with some dependencies will be generated. Now you can copy and use it.
Adding to Matt's answer above (as I don't have comment privileges yet), one mouse-free workflow would be:
Esc
then m
then Enter
so that you gain focus again and can start typing.
Without the last Enter
you would still be in Escape mode and would otherwise have to use your mouse to activate text input in the cell.
Another way would be to add a new cell, type out your markdown in "Code" mode and then change to markdown once you're done typing everything you need, thus obviating the need to refocus.
You can then move on to your next cells. :)
Originally from this blog post. We can achieve if else by using below code
<xsl:choose>
<xsl:when test="something to test">
</xsl:when>
<xsl:otherwise>
</xsl:otherwise>
</xsl:choose>
So here is what I did
<h3>System</h3>
<xsl:choose>
<xsl:when test="autoIncludeSystem/autoincludesystem_info/@mdate"> <!-- if attribute exists-->
<p>
<dd><table border="1">
<tbody>
<tr>
<th>File Name</th>
<th>File Size</th>
<th>Date</th>
<th>Time</th>
<th>AM/PM</th>
</tr>
<xsl:for-each select="autoIncludeSystem/autoincludesystem_info">
<tr>
<td valign="top" ><xsl:value-of select="@filename"/></td>
<td valign="top" ><xsl:value-of select="@filesize"/></td>
<td valign="top" ><xsl:value-of select="@mdate"/></td>
<td valign="top" ><xsl:value-of select="@mtime"/></td>
<td valign="top" ><xsl:value-of select="@ampm"/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</dd>
</p>
</xsl:when>
<xsl:otherwise> <!-- if attribute does not exists -->
<dd><pre>
<xsl:value-of select="autoIncludeSystem"/><br/>
</pre></dd> <br/>
</xsl:otherwise>
</xsl:choose>
My Output
Try this regex, it works for me:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.
Just make sure to add Shebang (#!/bin/bash
) line at the starting of your script and make the script executable(using chmod +x <File Name>
).
Unfortunately, many of the answers simply indicate how to access the Response’s body as text. By default, the body of the response object is text, not an object as it is passed through a stream.
What you are looking for is the json() function of the Body object property on the Response object. MDN explains it much better than I:
The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.
response.json().then(function(data) { console.log(data);});
or using ES6:
response.json().then((data) => { console.log(data) });
Source: https://developer.mozilla.org/en-US/docs/Web/API/Body/json
This function returns a Promise by default, but note that this can be easily converted to an Observable for downstream consumption (stream pun not intended but works great).
Without invoking the json() function, the data, especially when attempting to access the _body property of the Response object, will be returned as text, which is obviously not what you want if you are looking for a deep object (as in an object with properties, or than can’t be simply converted into another objected).
In cs file
DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;
In xaml file
<DataGrid Name="gridEmployees" ItemsSource="{Binding}">
There are a couple of ways that you can accomplish this. You can do the following:
<li>
@Html.ActionLink("Clients", "Index", "User", new { @class = "elements" }, null)
</li>
or this:
<li>
<a href="@Url.Action("Index", "Users")" class="elements">
<span>Clients</span>
</a>
</li>
Lately I do the following:
<a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, Request.Url.Scheme)">
<span>Clients</span>
</a>
The result would have http://localhost/10000
(or with whatever port you are using) to be appended to the URL structure like:
http://localhost:10000/Users
I hope this helps.
Most (if not all) of these answers assume you are happy to install packages globally. This answer is for you if you:
(Note: this answer adds a python2 kernel to a python3-jupyter install, but it's conceptually easy to swap things around.)
Prerequisites
Create a python3 venv and install jupyter
python3 -m venv .venv
. .venv/bin/activate
pip install jupyterlab
. This will create locally all the essential infrastructure for running notebooks. $PWD/.venv/share/jupyter/kernels/python3/
. If you want to install and run jupyter elsewhere, and only use this venv for organizing all your kernels, then you only need: pip install ipykernel
jupyter lab
(and go to your browser to the url displayed in the console). So far, you'll only see one kernel option called 'Python 3'. (This name is determined by the display_name
entry in your kernel.json
file.)Add a python2 kernel
ctrl-c
deactivate
virtualenv -p python2 .venv2
. .venv2/bin/activate
pip install ipykernel
. This will also generate default kernel specs for this python2 venv in .venv2/share/jupyter/kernels/python2
python -m ipykernel install --prefix=$PWD/.venv
. This basically just copies the dir $PWD/.venv2/share/jupyter/kernels/python2
to $PWD/.venv/share/jupyter/kernels/
deactivate; . .venv/bin/activate; jupyter lab
. If all went well, you'll see a Python 2
option in your list of kernels. You can test that they're running real python2/python3 interpreters by their handling of a simple print 'Hellow world'
vs print('Hellow world')
command.TL;DR
R -e "install.packages('IRkernel',repos='https://cran.mtu.edu/')"
. (This will install to your standard R-packages location; for home-brewed-installed R on a Mac, this will look like /usr/local/Cellar/r/3.5.2_2/lib/R/library/IRkernel
.)R -e "IRkernel::installspec(prefix=paste(getwd(),'/.venv',sep=''))"
. If you now look in $PWD/.venv/share/jupyter/kernels/
you'll find an ir
directory with kernel.json
file that looks something like this:{
"argv": ["/usr/local/Cellar/r/3.5.2_2/lib/R/bin/R", "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"],
"display_name": "R",
"language": "R"
}
In summary, a kernel just 'is' an invocation of a language-specific executable from a kernel.json
file that jupyter looks for in the .../share/jupyter/kernels
dir and lists in its interface; in this case, R is being called to run the function IRkernel::main()
, which will send messages back and forth to the Jupiter server. Likewise, the python2 kernel just 'is' an invocation of the python2 interpreter with module ipykernel_launcher
as seen in .venv/share/jupyter/kernels/python2/kernel.json
, etc.
Here is a script if you want to run all of these instructions in one fell swoop.
After reading the other advices, I'm inclined to say that:
As a GENERIC rule, you will not always define setters for ALL properties, specially "internal" ones (semaphores, internal flags...). Read-only properties will not have setters, obviously, so some properties will only have getters; that's where __get() comes to shrink the code:
Yes! we could write a private method to do that, also, but then again, we'll have MANY methods declared (++memory) that end up calling another, always the same, method. Why just not write a SINGLE method to rule them all...? [yep! pun absolutely intended! :)]
Magic setters can also respond ONLY to specific properties, so all date type properties can be screened against invalid values in one method alone. If date type properties were listed in an array, their setters can be defined easily. Just an example, of course. there are way too many situations.
About readability... Well... That's another debate: I don't like to be bound to the uses of an IDE (in fact, I don't use them, they tend to tell me (and force me) how to write... and I have my likes about coding "beauty"). I tend to be consistent about naming, so using ctags and a couple of other aids is sufficient to me... Anyway: once all this magic setters and getters are done, I write the other setters that are too specific or "special" to be generalized in a __set() method. And that covers all I need about getting and setting properties. Of course: there's not always a common ground, or there are such a few properties that is not worth the trouble of coding a magical method, and then there's still the old good traditional setter/getter pair.
Programming languages are just that: human artificial languages. So, each of them has its own intonation or accent, syntax and flavor, so I won't pretend to write a Ruby or Python code using the same "accent" than Java or C#, nor I would write a JavaScript or PHP to resemble Perl or SQL... Use them the way they're meant to be used.
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
Probably you need to set library reference as "Copy Local = True" on properties dialog. On visual studio click on "references" then right-click on the missing reference, from the context menu click properties, you should see copy local setting.
You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):
Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
Write-Host $_.IP1
Write-Host $_.IP2
...
}
console.log(document.getElementById('xx') ) evaluates to null.
document.getElementById('xx') !=null evaluates to false
You should use document.getElementById('xx') !== null
as it is a stronger equality check.
Try not closing the connection before you send data to your database. Remove client.close();
from your code and it'll work fine.
I stand by Jim McKeeth's comment.
Also, indexing and full table scans are faster if your table has only CHAR columns. Basically the optimizer will be able to predict how big each record is if it only has CHAR columns, while it needs to check the size value of every VARCHAR column.
Besides if you update a VARCHAR column to a size larger than its previous content you may force the database to rebuild its indexes (because you forced the database to physically move the record on disk). While with CHAR columns that'll never happen.
But you probably won't care about the performance hit unless your table is huge.
Remember Djikstra's wise words. Early performance optimization is the root of all evil.
Use pd.concat
to merge a list of DataFrame into a single big DataFrame.
appended_data = []
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
# store DataFrame in list
appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet
appended_data.to_excel('appended.xlsx')
It is possible using the function FORMAT available on SQL Server 2012 and above
select FORMAT(10,'x2')
Results in:
0a
this
refers to a reference of the current class.
super
refers to the parent of the current class (which called the super
keyword).
By doing this
, it allows you to access methods/attributes of the current class (including its own private methods/attributes).
super
allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.
Actually, this is subtler than it looks.
The code above would give the incorrect answer for a lower case character whose code point was above U+FFFF (such as U+1D4C3, MATHEMATICAL SCRIPT SMALL N). String.charAt would return a UTF-16 surrogate pair, which is not a character, but rather half the character, so to speak. So you have to use String.codePointAt, which returns an int above 0xFFFF (not a char). You would do:
Character.isUpperCase(s.codePointAt(0));
Don't feel bad overlooked this; almost all Java coders handle UTF-16 badly, because the terminology misleadingly makes you think that each "char" value represents a character. UTF-16 sucks, because it is almost fixed width but not quite. So non-fixed-width edge cases tend not to get tested. Until one day, some document comes in which contains a character like U+1D4C3, and your entire system blows up.
You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)
If you pass $element
into a controller, like you would $scope
, you can use its find()
function. Note that, in the jQueryLite included in Angular, find()
will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find()
can be used, including finding by attribute.
So, for this HTML:
<div ng-controller='MyCtrl'>
<div>
<div name='foo' class='myElementClass'>this one</div>
</div>
</div>
This AngularJS code should work:
angular.module('MyClient').controller('MyCtrl', [
'$scope',
'$element',
'$log',
function ($scope, $element, $log) {
// Find the element by its class attribute, within your controller's scope
var myElements = $element.find('.myElementClass');
// myElements is now an array of jQuery DOM elements
if (myElements.length == 0) {
// Not found. Are you sure you've included the full jQuery?
} else {
// There should only be one, and it will be element 0
$log.debug(myElements[0].name); // "foo"
}
}
]);
A solution without dependencies.
Node
headers.set('Authorization', 'Basic ' + Buffer.from(username + ":" + password).toString('base64'));
Browser
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
Two things are happening here.
Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.
What you want to do is the following:
<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
<div class="row">
<div class="col-md-4 myClassName"> <!-- myClassName is defined in my CSS as you defined your container -->
<img src="#.jpg" height="200px" width="300px">
</div>
</div>
</div>
Here you can find more info on the Bootstrap grid system.
That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
max-width: 900px;
overflow:hidden;
min-height:0px !important;
}
But I have always found that the "!important" clause just makes for messy CSS.
(ES5) I use forEach to iterate on the collection returned by querySelectorAll and it works well :
document.querySelectorAll('your_selector').forEach(item => { /* do the job with item element */ });
<div ng-repeat="file in files" ng-class="!$last ? 'class-for-last' : 'other'">
{{file.name}}
</div>
That works for me! Good luck!
Noneof the answers worked for me, I was getting "'HttpRequestBase' does not contain a definition for 'Query'", but this did work:
HttpContext.Current.Request.QueryString["index"]
UIButton
inherits from UIControl
. That has all of the methods to add/remove actions: UIControl Class Reference. Look at the section "Preparing and Sending Action Messages", which covers – sendAction:to:forEvent:
and – addTarget:action:forControlEvents:
.
I wouldn't put it in the same <p>
, since IMHO the two infos are semantically too different. If you must, I'd suggest this:
<p style="text-align:right">
<span style="float:left">I'll be on the left</span>
I'll be on the right
</p>
The loop attribute should do it:
<video width="320" height="240" autoplay loop>
<source src="movie.mp4" type="video/mp4" />
<source src="movie.ogg" type="video/ogg" />
Your browser does not support the video tag.
</video>
Should you have a problem with the loop attribute (as we had in the past), listen to the videoEnd
event and call the play()
method when it fires.
Note1: I'm not sure about the behavior on Apple's iPad/iPhone, because they have some restrictions against autoplay
.
Note2: loop="true"
and autoplay="autoplay"
are deprecated
Isn't this the same as updateOrCreate()?
It is similar but not the same. The updateOrCreate() will only work for one row at a time which doesn't allow bulk insert. InsertOnDuplicateKey will work on many rows.
The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens at server end and not visible to client, but in case of sendRedirect(), redirection happens at client end and it's visible to client.
And here's a jQuery example:
HTML text field:
<input type="text" id="myTextfield" />
jQuery code to limit its size:
var elem = $("#myTextfield");
if(elem) elem.val(elem.val().substr(0,10));
As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:
$(document).ready(function() {
var elem = $("#myTextfield");
if (elem) {
elem.keydown(function() {
if (elem.val().length > 10)
elem.val(elem.val().substr(0, 10));
});
}
});
Update: The above code snippet was only used to show an example usage.
The following code snippet will handle you issue with the DIV element:
$(document).ready(function() {
var elem = $(".tasks-overflow");
if(elem){
if (elem.text().length > 10)
elem.text(elem.text().substr(0,10))
}
});
Please note that I'm using text
instead of val
in this case, since the val
method doesn't seem to work with the DIV element.
In Ef .net core there are two options that you can do; first with data annotations:
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}
Or with fluent api:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired(false)//optinal case
.IsRequired()//required case
;
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
There are more details here
Tip: if you gonna use the slack cleaner https://github.com/kfei/slack-cleaner
You will need to generate a token: https://api.slack.com/custom-integrations/legacy-tokens