Although, I'm answering this very late. I have a bad habit of checking changelogs of every library I use and while checking the release notes of Angular CLI, I figured out that they released a new patch yesterday (9th Jan 2020) which fixes this issue.
https://github.com/angular/angular-cli/releases/tag/v8.3.22
So when you will run ng update
, you should get updates for @angular/cli
:
And running ng update @angular/cli
will fix this warning.
Cheers!
Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.
Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.
Here is my working code:
List _todoList = ["AAA", "BBB"];
...
body: Column(
children: [
Container(...),
Expanded(
child: ListView.builder(
itemCount: _todoList.length,
itemBuilder: (context, index) {
return ListTile(title: Text(_todoList[index]));
}))
],
));
Here how it was when I was getting the "not laid out" error:
List _todoList = ["AAA", "BBB"];
...
body: SingleChildScrollView(child: Column(
children: [
Container(...),
Expanded(
child: ListView.builder(
itemCount: _todoList.length,
itemBuilder: (context, index) {
return ListTile(title: Text(_todoList[index]));
}))
],
)));
I hope this may be useful for someone.
I have soled the problem by changing target android version to 28 in project.properties (target=android-28) and installed cordova-plugin-androidx and cordova-plugin-androidx-adapter.
Seems like an old question but still relevant.
I think it is a blocked update issue.
The main problem is the new URL (route) is supposed to be rendered by the same component(Costumers
) as you are currently in (current URL).
So solution is rather simple, make the window url as a prop, so react has a chance to detect the prop change (therefore the url change), and act accordingly.
A nice usecase described in the official react blog called Recommendation: Fully uncontrolled component with a key.
So the solution is to change from
render() {
return(
<ul>
to
render() {
return(
<ul key={this.props.location.pathname}>
So whenever the location changed by react-router, the component got scrapped (by react) and a new one gets initiated with the right values (by react).
Oh, and pass the location
as prop to the component(Costumers
) where the redirect will happen if it is not passed already.
Hope it helps someone.
I found the following css in order to style a Bootstrap input for a jquery autocomplete:
https://gist.github.com/daz/2168334#file-style-scss
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
_width: 160px;
padding: 4px 0;
margin: 2px 0 0 0;
list-style: none;
background-color: #ffffff;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.2);
border-style: solid;
border-width: 1px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
*border-right-width: 2px;
*border-bottom-width: 2px;
}
.ui-menu-item > a.ui-corner-all {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #555555;
white-space: nowrap;
}
.ui-state-hover, &.ui-state-active {
color: #ffffff;
text-decoration: none;
background-color: #0088cc;
border-radius: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
background-image: none;
}
Just for others getting this error and looking for info on it, it is also thrown if you happen to pass a binding parameter and then never use it. I couldn't really find that stated clearly anywhere but had to prove it through trial and error.
Usually Header file syntax start with capital letter.I found that code written all in smaller letter
#ifndef DIAG_H
#define DIAG_H
#endif
Two slices can be concatenated using append
method in the standard golang library. Which is similar to the variadic
function operation. So we need to use ...
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3}
y := []int{4, 5, 6}
z := append([]int{}, append(x, y...)...)
fmt.Println(z)
}
output of the above code is: [1 2 3 4 5 6]
If you'd like to send the data to a view pass the following in.
server.get('/usersList', function(req, res) {
User.find({}, function(err, users) {
res.render('/usersList', {users: users});
});
});
Inside your view you can loop through the data using the variable users
Here are two scenarios where the keyup
event will not get fired:
Use the HTML5 input
event instead for a more robust solution:
<textarea maxlength='140'></textarea>
JavaScript (demo):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
And if you absolutely want to use jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
As the rank doesn't depend at all from the contacts
RANKED_RSLTS
QRY_ID | RES_ID | SCORE | RANK
-------------------------------------
A | 1 | 15 | 3
A | 2 | 32 | 1
A | 3 | 29 | 2
C | 7 | 61 | 1
C | 9 | 30 | 2
Thus :
SELECT
C.*
,R.SCORE
,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT *,
MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
FROM RSLTS) R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID
This jQuery function worked best for me. I'm using bootstrap 4 within a WordPress theme and I've used the full jQuery instead of jQuery slim.
// Set all carousel items to the same height
function carouselNormalization() {
window.heights = [], //create empty array to store height values
window.tallest; //create variable to make note of the tallest slide
function normalizeHeights() {
jQuery('#latest-blog-posts .carousel-item').each(function() { //add heights to array
window.heights.push(jQuery(this).outerHeight());
});
window.tallest = Math.max.apply(null, window.heights); //cache largest value
jQuery('#latest-blog-posts .carousel-item').each(function() {
jQuery(this).css('min-height',tallest + 'px');
});
}
normalizeHeights();
jQuery(window).on('resize orientationchange', function () {
window.tallest = 0, window.heights.length = 0; //reset vars
jQuery('.sc_slides .item').each(function() {
jQuery(this).css('min-height','0'); //reset min-height
});
normalizeHeights(); //run it again
});
}
jQuery( document ).ready(function() {
carouselNormalization();
});
Source:
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
The issue arose because of not including jar
file as part of the project. I was just including it in tomcat lib. Using the below in web.xml
works now:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>accept, authorization, origin</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, OPTIONS</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And the below in your project dependency:
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>1.3.2</version>
</dependency>
I faced this issue, and resolved this issue using getchar() to catch the ('\n') new char
If I understand well, you want to Join ScheduleRequest
with User
and apply the in
clause to the userName
property of the entity User
.
I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join
part (because it handles the Join
logic outside the Criteria Query).
List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);
In order to write more type-safe code you could also use Metamodel by replacing this line:
Expression<String> exp = scheduleRequest.get("createdBy");
with this:
Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
If it works, then you may try to add the Join
logic into the Criteria Query
. But right now I can't test it, so I prefer to see if somebody else wants to try.
Not a perfect answer though may be code snippets might help.
public <T> List<T> findListWhereInCondition(Class<T> clazz,
String conditionColumnName, Serializable... conditionColumnValues) {
QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
addWhereInClause(queryBuilder, conditionColumnName,
conditionColumnValues);
queryBuilder.select();
return queryBuilder.getResultList();
}
private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
String conditionColumnName, Serializable... conditionColumnValues) {
Path<Object> path = queryBuilder.root.get(conditionColumnName);
In<Object> in = queryBuilder.criteriaBuilder.in(path);
for (Serializable conditionColumnValue : conditionColumnValues) {
in.value(conditionColumnValue);
}
queryBuilder.criteriaQuery.where(in);
}
You could pipe the output to jq
. If you python script contains something like
print json.dumps(data)
then you can fire:
python foo.py | jq '.'
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
I had the same issue in Windows
and it worked since my proxy configuration in settings.xml
file was changed
So locate and edit the file inside the \conf
folder, for example : C:\Program Files\apache-maven-3.2.5\conf
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>jorgesys</username>
<password>supercalifragilisticoespialidoso</password>
<host>proxyjorgesys</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
80
to 8080
/program files
you can make a copy, edit the file and replace the file located into /program files
folder.If you are to use the
<!-- saved from url=(0014)about:internet -->
or
<!-- saved from url=(0016)http://localhost -->
make sure the HTML file is saved in windows/dos format with "\r\n" as line breaks after the statement. Otherwise I couldn't make it work.
Many of the List implementation support limited support to add/remove, and Arrays.asList(membersArray) is one of that. You need to insert the record in java.util.ArrayList or use the below approach to convert into ArrayList.
With the minimal change in your code, you can do below to convert a list to ArrayList. The first solution is having a minimum change in your solution, but the second one is more optimized, I guess.
String[] membersArray = request.getParameterValues('members');
ArrayList<String> membersList = new ArrayList<>(Arrays.asList(membersArray));
OR
String[] membersArray = request.getParameterValues('members');
ArrayList<String> membersList = Stream.of(membersArray).collect(Collectors.toCollection(ArrayList::new));
if (row.Columns.Contains("US_OTHERFRIEND"))
If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)
), you can use do it in linear time using min
:
<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
That looks gnarly at first, but looking at your previous questions, you have a List<String>
. In short: min
works on it.
For the long answer: all that super
and extends
stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)
Producer Extends, Consumer Super
It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super’ and ‘extends’ in Java Generics)
For a dynamic approach, if your labels are always in front of your text areas:
$(object).prev("label").text(charsleft);
This is a easy way to get incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date( _date.getTime() + inc )
return new Date( _date.getTime() + dec )
Sometimes, it may help switching off AllowAutoRedirect
and setting both login POST
and page GET
requests the same user agent.
request.UserAgent = userAgent;
request.AllowAutoRedirect = false;
LINQ has its origins in functional programming, which emphasises immutability of objects, so it doesn't provide a built-in way to update the original list in-place.
Note on immutability (taken from another SO answer):
Here is the definition of immutability from Wikipedia.
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.
All of the tech podcasts I listen to have been mentioned, but as long as we're discussing video I'd like to mention Hak.5. It is more focused on using existing programs rather than coding, but it has some good hardware segments, and it can often be an excellent source of inspiration.
This is what I ended up using. Temporarily sets target to _blank, then sets it back.
OnClientClick="var originalTarget = document.forms[0].target; document.forms[0].target = '_blank'; setTimeout(function () { document.forms[0].target = originalTarget; }, 3000);"
Use transform: scale(0.8);
with the value you need instead of 0.8
You could use the following:
$('[element]').trigger('reset')
I've been using this functionality in node.js, this is my fastest implementation so far:
var nLength = function(n) {
return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}
It should handle positive and negative integers (also in exponential form) and should return the length of integer part in floats.
The following reference should provide some insight into the method: Weisstein, Eric W. "Number Length." From MathWorld--A Wolfram Web Resource.
I believe that some bitwise operation can replace the Math.abs, but jsperf shows that Math.abs works just fine in the majority of js engines.
Update: As noted in the comments, this solution has some issues :(
Update2 (workaround) : I believe that at some point precision issues kick in and the Math.log(...)*0.434...
just behaves unexpectedly. However, if Internet Explorer or Mobile devices are not your cup of tea, you can replace this operation with the Math.log10
function. In Node.js I wrote a quick basic test with the function nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0;
and with Math.log10
it worked as expected. Please note that Math.log10
is not universally supported.
myDataTable.AsEnumerable().Take(5).CopyToDataTable()
public ActionResult CreatePerson(int id) //controller
window.location.href = '@Url.Action("CreatePerson", "Person")?id=' + id;
Or
var id = 'some value';
window.location.href = '@Url.Action("CreatePerson", "Person", new {id = id})';
I have just run into the same issue with VS2013, creating device drivers in C++ , and none of the above seemed to fix the issue. However, I have just discovered that in my case the issue appears to have been VMWare-related.
I was running a VMWare workstation client with a shared folder defined on the VM on my entire C: drive. When I disabled the shared folders on the VM Settings, VS2013 was able to happily build my .exe files.
My new process is:
1) Disable the shared folder on the vm (VM Settings | Options | Shared Folders - and uncheck the checkbox) 2) Run the build on the host PC 3) RE-enable the shared folder (and proceed from there)
Hopefully this might help someone else.
(BTW, the errors you receive are that the .exe (or other files) are locked or require Administrator permission, but that is a red herring - It seems to me that the VMWare share is causing those files to appear as locked.)
I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.
If that requirement is not met using command line utilities is rather tedious.
7z -a .
would be
d:\portable\z7\z7 -a c:\to\archive\folder*.*
Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.
If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.
You'll have to set your path when you hit the shell after making sure it's attached.
http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.
http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor
It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:
set path=%path%;"d:\portable\z7\";
when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/
The other answers address other problems better I'm not going to try..
http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.
PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).
Just extending other answers...
Delegated events handlers will not be removed upon element removal.
$('body').on('click', '#someEl', function (event){
console.log(event);
});
$('#someEL').remove(); // removing the element from DOM
Now check:
$._data(document.body, 'events');
Check that All Files are Included in Your Project:
I had this same error pop up after I updated cLion. After hours of tinkering, I noticed one of my files was not included in the project target. After I added it back to the active project, I stopped getting the undefined reference to winmain16, and the code compiled.
Edit: It's also worthwhile to check the build settings within your IDE.
(Not sure if this error is related to having recently updated the IDE - could be causal or simply correlative. Feel free to comment with any insight on that factor!)
on success: function (response) { alert(response.d); }
Also, a bit simpler....
>> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
>> hash.values
=> [["a", "b", "c"], ["b", "c"]]
uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{
if (r > 2) r = 0;
if (r == 0) value[i] = 0;
if (r == 1)value[i] = 0;
if (r == 2)value[i] = 255;
r++;
}
You can enable Interceptor in browser and in Postman separately. For send/recieve cookies you should enable Interceptor in Postman. So if you enable interceptor only in browser - it will not work. Actually you don't need enable Interceptor in browser at all - if you don't want to flood your postman history with unnecessary requests.
Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.
EXEC sp_addrolemember 'db_ddladmin', 'username_here';
did the trick
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
To get the keys:
function GetDictionaryKeysAsArray(dict: {[key: string]: string;}): string[] {
let result: string[] = [];
Object.keys(dict).map((key) =>
result.push(key),
);
return result;
}
Maybe (probably) I am reading the question wrongly, but are you looking for the HasExited property that will tell you that the process represented by your Process object has exited (either normally or not).
If the process you have a reference to has a UI you can use the Responding property to determine if the UI is currently responding to user input or not.
You can also set EnableRaisingEvents and handle the Exited event (which is sent asychronously) or call WaitForExit() if you want to block.
Using Javascript
<div id="mydiv" style="width:200px;background:white" onmouseover="this.style.background='gray';" onmouseout="this.style.background='white';">
Jack and Jill went up the hill
To fetch a pail of water.
Jack fell down and broke his crown,
And Jill came tumbling after.
</div>
Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.
Why not try .test()
? ... Try its and best boolean (true or false):
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)');
return results.test(window.location.href);
}
Tutorial: http://www.w3schools.com/jsref/jsref_regexp_test.asp
For CodeIgniter 4
, you can use the built-in API Response Trait
Here's sample code for reference:
<?php namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
class Home extends BaseController
{
use ResponseTrait;
public function index()
{
$data = [
'data' => 'value1',
'data2' => 'value2',
];
return $this->respond($data);
}
}
Using imagemagick, you can try:
convert page.png page.pdf
Or for multiple images:
convert page*.png mydoc.pdf
Array to string conversion
in latest versions of php 7.x is error, rather than notice, and prevents further code execution.
Using print
, echo
on array is not an option anymore.
Suppressing errors and notices is not a good practice, especially when in development environment and still debugging code.
Use var_dump
,print_r
, iterate through input value using foreach
or for
to output input data for names that are declared as input arrays ('name[]
')
Most common practice to catch errors is using try/catch
blocks, that helps us prevent interruption of code execution that might cause possible errors wrapped within try
block.
try{ //wrap around possible cause of error or notice
if(!empty($_POST['C'])){
echo $_POST['C'];
}
}catch(Exception $e){
//handle the error message $e->getMessage();
}
AFAIK $(window).height();
returns the height of your window and $(document).height();
returns the height of your document
I have been using [attr.disabled]
because I still like this template driven than programmatic enable()/disable() as it is superior IMO.
Change
<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>
to
<md-input formControlName="id" placeholder="ID" [attr.disabled]="true"></md-input>
If you are on newer material change md-input
to mat-input
.
You can use:
Handler handler = new Handler()
handler.postDelayed(new Runnable())
Or you can use:
handler.removeCallbacksAndMessages(null);
Docs
public final void removeCallbacksAndMessages (Object token)
Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
Or you could also do like the following:
Handler handler = new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
// do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);
Then:
handler.removeCallbacks(myRunnable);
Docs
public final void removeCallbacks (Runnable r)
Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.
public final void removeCallbacks (Runnable r, Object token)
Edit:
Change this:
@Override
public void onClick(View v) {
Handler handler = new Handler();
Runnable myRunnable = new Runnable() {
To:
@Override
public void onClick(View v) {
handler = new Handler();
myRunnable = new Runnable() { /* ... */}
Because you have the below. Declared before onCreate
but you re-declared and then initialized it in onClick
leading to a NPE.
Handler handler; // declared before onCreate
Runnable myRunnable;
just type "git push" if this doesn't give you a positive replay, then check if you are connected with your repository correctly.
Symfony 2.0-2.1
Use this:
$router = $this->get("router");
$route = $router->match($this->getRequest()->getPathInfo());
var_dump($route['_route']);
That one will not give you _internal
.
Update for Symfony 2.2+: This is not working starting Symfony 2.2+. I opened a bug and the answer was "by design". If you wish to get the route in a sub-action, you must pass it in as an argument
{{ render(controller('YourBundle:Menu:menu', { '_locale': app.request.locale, 'route': app.request.attributes.get('_route') } )) }}
And your controller:
public function menuAction($route) { ... }
just for the record you can always compare using JSON.stringify
const arr = [1,2,3];
expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3]));
expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));
It's all meter of taste, this will also work for complex literal objects
Use robocopy
. Robocopy is shipped by default on Windows Vista and newer, and is considered the replacement for xcopy
. (xcopy
has some significant limitations, including the fact that it can't handle paths longer than 256 characters, even if the filesystem can).
robocopy c:\ d:\ /e /zb /copyall /purge /dcopy:dat
Note that using /purge
on the root directory of the volume will cause Robocopy to apply the requested operation on files inside the System Volume Information directory. Run robocopy /?
for help. Also note that you probably want to open the command prompt as an administrator to be able to copy system files. To speed things up, use /b
instead of /zb
.
Try:
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
More from
You could use the ngSwitch directive:
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.
This is just an (untested) example. It can and should be optimized:
HTML:
<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>
Directive:
app.directive('conditionalTemplate', function($http, $compile) {
return {
restrict: 'E',
require: '^ngModel',
link: function(sope, element, attrs, ctrl) {
// get template with $http
// check model via ctrl.$viewValue
// compile with $compile
// replace element with element.replaceWith()
}
};
});
history.back()
and switch to previous state often give effect not that you want. For example, if you have form with tabs and each tab has own state, this just switched previous tab selected, not return from form. In case nested states, you usually need so think about witch of parent states you want to rollback.
This directive solves problem
angular.module('app', ['ui-router-back'])
<span ui-back='defaultState'> Go back </span>
It returns to state, that was active before button has displayed. Optional defaultState
is state name that used when no previous state in memory. Also it restores scroll position
Code
class UiBackData {
fromStateName: string;
fromParams: any;
fromStateScroll: number;
}
interface IRootScope1 extends ng.IScope {
uiBackData: UiBackData;
}
class UiBackDirective implements ng.IDirective {
uiBackDataSave: UiBackData;
constructor(private $state: angular.ui.IStateService,
private $rootScope: IRootScope1,
private $timeout: ng.ITimeoutService) {
}
link: ng.IDirectiveLinkFn = (scope, element, attrs) => {
this.uiBackDataSave = angular.copy(this.$rootScope.uiBackData);
function parseStateRef(ref, current) {
var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
if (preparsed) ref = current + '(' + preparsed[1] + ')';
parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
if (!parsed || parsed.length !== 4)
throw new Error("Invalid state ref '" + ref + "'");
let paramExpr = parsed[3] || null;
let copy = angular.copy(scope.$eval(paramExpr));
return { state: parsed[1], paramExpr: copy };
}
element.on('click', (e) => {
e.preventDefault();
if (this.uiBackDataSave.fromStateName)
this.$state.go(this.uiBackDataSave.fromStateName, this.uiBackDataSave.fromParams)
.then(state => {
// Override ui-router autoscroll
this.$timeout(() => {
$(window).scrollTop(this.uiBackDataSave.fromStateScroll);
}, 500, false);
});
else {
var r = parseStateRef((<any>attrs).uiBack, this.$state.current);
this.$state.go(r.state, r.paramExpr);
}
});
};
public static factory(): ng.IDirectiveFactory {
const directive = ($state, $rootScope, $timeout) =>
new UiBackDirective($state, $rootScope, $timeout);
directive.$inject = ['$state', '$rootScope', '$timeout'];
return directive;
}
}
angular.module('ui-router-back')
.directive('uiBack', UiBackDirective.factory())
.run(['$rootScope',
($rootScope: IRootScope1) => {
$rootScope.$on('$stateChangeSuccess',
(event, toState, toParams, fromState, fromParams) => {
if ($rootScope.uiBackData == null)
$rootScope.uiBackData = new UiBackData();
$rootScope.uiBackData.fromStateName = fromState.name;
$rootScope.uiBackData.fromStateScroll = $(window).scrollTop();
$rootScope.uiBackData.fromParams = fromParams;
});
}]);
The code below can be used for a static datasource initialization.
public class MyDataSource {
private static final String DB_USERNAME="spring.datasource.username";
private static final String DB_PASSWORD="spring.datasource.password";
private static final String DB_URL ="spring.datasource.url";
private static final String DB_DRIVER_CLASS="spring.datasource.driver-class-name";
private static Properties properties = null;
private static HikariDataSource dataSource;
static {
try {
properties = new Properties();
properties.load(new FileInputStream("src/main/resources/application.properties"));
dataSource = new HikariDataSource();
dataSource.setDriverClassName(properties.getProperty(DB_DRIVER_CLASS));
dataSource.setJdbcUrl(properties.getProperty(DB_URL));
dataSource.setUsername(properties.getProperty(DB_USERNAME));
dataSource.setPassword(properties.getProperty(DB_PASSWORD));
dataSource.setMinimumIdle(100);
dataSource.setMaximumPoolSize(2000);
dataSource.setAutoCommit(false);
dataSource.setLoginTimeout(3);
} catch (IOException | SQLException e) {
((Throwable) e).printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection() throws SQLException{
return getDataSource().getConnection();
}
}
This can be done entirely with bash string manipulation:
first="I love Suzy and Mary"
second="Sara"
first=${first/Suzy/$second}
That will replace only the first occurrence; to replace them all, double the first slash:
first="Suzy, Suzy, Suzy"
second="Sara"
first=${first//Suzy/$second}
# first is now "Sara, Sara, Sara"
SuppressFinalize
should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that this
object was cleaned up fully.
The recommended IDisposable
pattern when you have a finalizer is:
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// called via myClass.Dispose().
// OK to use any private object references
}
// Release unmanaged resources.
// Set large fields to null.
disposed = true;
}
}
public void Dispose() // Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass() // the finalizer
{
Dispose(false);
}
}
Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). SuppressFinalize
tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.
The SuppressFinalize
optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call SuppressFinalize
on other objects mind you. That's a serious defect waiting to happen.
Design guidelines inform us that a finalizer isn't necessary if your object implements IDisposable
, but if you have a finalizer you should implement IDisposable
to allow deterministic cleanup of your class.
Most of the time you should be able to get away with IDisposable
to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up.
Note: Sometimes coders will add a finalizer to debug builds of their own IDisposable
classes in order to test that code has disposed their IDisposable
object properly.
public void Dispose() // Implement IDisposable
{
Dispose(true);
#if DEBUG
GC.SuppressFinalize(this);
#endif
}
#if DEBUG
~MyClass() // the finalizer
{
Dispose(false);
}
#endif
In the accepted answer I find the optionals cumbersome. This works with Swift 3 and seems to have no problem with emojis.
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let value = textField.text else {return false} // there may be a reason for returning true in this case but I can't think of it
// now value is a String, not an optional String
let valueAfterChange = (value as NSString).replacingCharacters(in: range, with: string)
// valueAfterChange is a String, not an optional String
// now do whatever processing is required
return true // or false, as required
}
I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.
Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.
(So this means I can't answer the "Edit" to your question. Only the original question.)
CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:
9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).
RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:
[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).
Additionally,
ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))
Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).
yes it is possible you can use border-radius CSS property. For more info have a look at http://zeeshanmkhan.com/post/2/css-rounded-corner-gradient-drop-shadow-and-opacity
In case you need to do it in one line command with bash script as below:
$ cd /path/to/your/repo && /bin/bash $HOME/remove_submodule.sh /path/to/the/submodule
Create bash script file in the $HOME
dir named i.e. remove_submodule.sh
:
#!/bin/bash
git config -f .gitmodules --remove-section submodule.$1
git config -f .git/config --remove-section submodule.$1
git rm --cached $1
git add .gitmodules
git commit -m "Remove submodule in $1"
rm -rf $1
rm -rf .git/modules/$1
git push origin $(git rev-parse --abbrev-ref HEAD) --force --quiet
In newer versions of Eclipse the global configuration file can be set in
Windows > Preferences > Maven > User Settings > Global Settings
Don't beat me why global settings can be configured in user settings... Probably because of the same reason why you need to press "Start" to shutdown your PC on Windows... :D
As far your code is concerned, there doesn't seem to be anything fundamentally wrong with it except that, it is unclear how you're actually calling that function. All I can think of is that when your server is not responding then you will get this SMTPServerDisconnected error. If you lookup the getreply() function in smtplib (excerpt below), you will get an idea.
def getreply(self):
"""Get a reply from the server.
Returns a tuple consisting of:
- server response code (e.g. '250', or such, if all goes well)
Note: returns -1 if it can't read response code.
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
Raises SMTPServerDisconnected if end-of-file is reached.
"""
check an example at https://github.com/rreddy80/sendEmails/blob/master/sendEmailAttachments.py that also uses a function call to send an email, if that's what you're trying to do (DRY approach).
You can use the way like @Florin Ghita has suggested. But remember dbms_lob.substr has a limit of 4000 characters in the function For example :
dbms_lob.substr(clob_value_column,4000,1)
Otherwise you will find ORA-22835 (buffer too small)
You can also use the other sql way :
SELECT * FROM your_table WHERE clob_value_column LIKE '%your string%';
Note : There are performance problems associated with both the above ways like causing Full Table Scans, so please consider about Oracle Text Indexes as well:
https://docs.oracle.com/en/database/oracle/oracle-database/12.2/ccapp/indexing-with-oracle-text.html
The problem is that you're reading nextLine()
on the while loop and THEN reading it to a variable. Not only are you getting every 2nd line printed out you're opening yourself to the exception being thrown. An example:
File:
Hello,
Blah blah blah,
Sincerely,
CapnStank
PS. Something something
On first iteration through the loop. The check on while will consume the "Hello," as not equal to null. Inside the loop body you'll see Blah blah blah,
printed to the System.
The process will repeat with Sincerely, being consumed and Capnstank printing out.
Finally the while will consume the "PS" line while the String line = fileReader.nextLine()
retreives an exception from the file because there's nothing further to read.
To resolve the issue:
String line = fileReader.nextLine();
while (line != null) {
System.out.println(line);
line = fileReader.nextLine();
}
EDIT: nevermind, Quassnoi has a better answer.
For SQL2K, something like this:
SELECT
Orders.OrderNumber
, LineItems.Quantity
, LineItems.Description
FROM (
SELECT
Orders.OrderID
, Orders.OrderNumber
, FirstLineItemID = (
SELECT TOP 1 LineItemID
FROM LineItems
WHERE LineItems.OrderID = Orders.OrderID
ORDER BY LineItemID -- or whatever else
)
FROM Orders
) Orders
JOIN LineItems
ON LineItems.OrderID = Orders.OrderID
AND LineItems.LineItemID = Orders.FirstLineItemID
Here's a concise universal solution for base64 encoding:
const nodeBtoa = (b) => Buffer.from(b).toString('base64');
export const base64encode = typeof btoa !== 'undefined' ? btoa : nodeBtoa;
A very simple way:
import * as myFunctionContainer from 'whatever-lib';
const fooSpy = spyOn(myFunctionContainer, 'myFunc');
I think this is the best option.
temp = [line.strip() for line in file.readlines()]
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
Step 1: Make a new project
Step 2: in ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// CODE
let btn = UIButton(type: UIButtonType.System) as UIButton
btn.backgroundColor = UIColor.blueColor()
btn.setTitle("CALL TPT AGENT", forState: UIControlState.Normal)
btn.frame = CGRectMake(100, 100, 200, 100)
btn.addTarget(self, action: "clickMe:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
}
func clickMe(sender:UIButton!) {
print("CALL")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
There are a couple of reasons for this:
I know the question is about Macs, but I got here searching the answer for Ubuntu, so I guess my answer could be useful to someone.
Easy way to do it: AltF3.
If you are using tox to run tests on multiple versions of Python, you may need to install the Python dev libraries for each version of Python you are testing on.
sudo apt-get install python2.6-dev
sudo apt-get install python2.7-dev
etc.
The problem appear when we are using PHP 5.1 on Redhat or Cent OS
Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.
Python
As @numeral correctly said, column._jc.toString()
works fine in case of unaliased columns.
In case of aliased columns (i.e. column.alias("whatever")
) the alias can be extracted, even without the usage of regular expressions: str(column).split(" AS ")[1].split("`")[1]
.
I don't know Scala syntax, but I'm sure It can be done the same.
Current version:
Settings
(Preferences
on Mac) | Build, Execution, Deployment
| Compiler
|
Build process heap size.
Older versions:
Settings
(Preferences
on Mac) | Compiler
| Java Compiler
| Maximum heap size.
Compiler runs in a separate JVM by default so IDEA heap settings that you set in idea.vmoptions
have no effect on the compiler.
I wrote this based on Maerlyn's response. This function will work regardless of the character encoding on the page. It also won't turn single quotes in to dashes :)
function slugify ($string) {
$string = utf8_encode($string);
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$string = preg_replace('/[^a-z0-9- ]/i', '', $string);
$string = str_replace(' ', '-', $string);
$string = trim($string, '-');
$string = strtolower($string);
if (empty($string)) {
return 'n-a';
}
return $string;
}
I found this helpful...
http://www.cmake.org/pipermail/cmake/2011-June/045222.html
From their example:
ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)
I converted a simple NetBeans 8 Java FXML application to the Maven-driven one. Then I got problems, because the getResource()
methods weren't able to find the .fxml files. In mine original application the fxmls were scattered through the package tree - each beside its controller class file.
After I made Clean and build in NetBeans, I checked the result .jar in the target folder - the .jar didn't contain any fxml at all. All the fxmls were strangely disappeared.
Then I put all fxmls into the resources/fxml folder and set the getResource method parameters accordingly, for example: FXMLLoader(App.class.getClassLoader().getResource("fxml/ObjOverview.fxml"));
In this case everything went OK. The fxml folder appeared int the .jar's root and it contained all my fxmls. The program was working as expected.
My solution might not be the cleanest but it should work with no problems.
The logic is simply to create a static variable to store your data on the Service
and update your view each second on your Activity
.
Let's say that you have a String
on your Service
that you want to send it to a TextView
on your Activity
. It should look like this
Your Service:
public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
Your Activty:
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
This will work (pure JS, appending to a div of id myDiv
):
Demo: http://jsfiddle.net/4pwvg/
var myParent = document.body;_x000D_
_x000D_
//Create array of options to be added_x000D_
var array = ["Volvo","Saab","Mercades","Audi"];_x000D_
_x000D_
//Create and append select list_x000D_
var selectList = document.createElement("select");_x000D_
selectList.id = "mySelect";_x000D_
myParent.appendChild(selectList);_x000D_
_x000D_
//Create and append the options_x000D_
for (var i = 0; i < array.length; i++) {_x000D_
var option = document.createElement("option");_x000D_
option.value = array[i];_x000D_
option.text = array[i];_x000D_
selectList.appendChild(option);_x000D_
}
_x000D_
.pyc
contain the compiled bytecode of Python source files. The Python interpreter loads .pyc
files before .py
files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.
This is the given array.
int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};
// If you want print the last element in the array.
int lastNumerOfArray= myIntegerNumbers[9];
Log.i("MyTag", lastNumerOfArray + "");
// If you want to print the number of element in the array.
Log.i("MyTag", "The number of elements inside" +
"the array " +myIntegerNumbers.length);
// Second method to print the last element inside the array.
Log.i("MyTag", "The last elements inside " +
"the array " + myIntegerNumbers[myIntegerNumbers.length-1]);
The problem is that you are using SingleOrDefault
. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault
which will succeed no matter how many elements are in the collection.
I've always been partial to:
ctrl-E # move cursor to end of line
ctrl-A # move cursor to beginning of line
I also use shopt -s cdable_vars
, then you can create bash variables to common directories. So, for my company's source tree, I create a bunch of variables like:
export Dcentmain="/var/localdata/p4ws/centaur/main/apps/core"
then I can change to that directory by cd Dcentmain
.
I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:
dig @ns1.nameserver1.com domain.com txt
Exactly what you're looking for in these plugins:
This solution is applicable for Windows machine.
MongoDB needs data directory to store data. Default path is C:\data\db
. In case you don't have the data directory, create one in your C: drive. (P.S.: data\db means there is a directory named 'db' inside the directory 'data')
Place the json you want to import in this path: C:\data\db\
.
Open the command prompt and type the following command
mongoimport --db databaseName --collections collectionName --file fileName.json --type json --batchSize 1
Here,
Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore).
Instead, since in your example tag
is the unique key, use:
INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;
on duplicate key produces:
Query OK, 0 rows affected (0.07 sec)
The simplest solution I found was to add this to my img-element:
style="display:block;margin:auto;"
It seems I don't need to add "0" before the "auto" as suggested by others. Maybe that is the proper way, but it works well enough for my purposes without the "0" as well. At least on latest Firefox, Chrome, and Edge.
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:
if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
&& gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {
GeoPoint can be less than zero as well, I switch mine to:
if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
&& gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {
Thank you :D
Note need root than:
adb root
adb pull /data/data/com.google.android.apps.nexuslauncher/databases/launcher.db launcher.db
You will need to cast or convert the values to decimal before division. Take a look at this http://msdn.microsoft.com/en-us/library/aa226054.aspx
For example
DECLARE @num1 int = 3 DECLARE @num2 int = 2
SELECT @num1/@num2
SELECT @num1/CONVERT(decimal(4,2), @num2)
The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000
You can simply just set the selectedIndex
property on the UITabBarController to the appropriate index and the view will be changed just like the user tapped the tab button.
Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():
<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>
Directive:
myApp.directive('suLabel', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
title: '=tooltip'
},
template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
link: function(scope, element, attrs) {
if (scope.title) {
element.addClass('tooltip-title');
}
},
}
});
With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.
For me it's due react-native compatibility issue with Xcode9.4. I resolved using the following steps. on my project /ROOT
SOLVES the issue, this thread helped me to understand the issue.
Note: The linked Jenkins issue has since been solved.
As mention in JENKINS-26133 it was not possible to get shell output as a variable. As a workaround suggested using of writ-read from temporary file. So, your example would have looked like:
sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";
You can use System.currentTimeMillis()
.
At least in OpenJDK, Date
uses this under the covers.
The call in System
is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.
If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:
Let's say you have following package structure in your python project:
in - com.my.func.DifferentFunction
python file you have some function, like:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
And you want to call different functions from Example3.py
, then following way you can do it:
Define import statement in Example3.py
- file for import all function
from com.my.func.DifferentFunction import *
or define each function name which you want to import
from com.my.func.DifferentFunction import add, sub, mul
Then in Example3.py
you can call function for execute:
num1 = 20
num2 = 10
print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))
Output:
add : 30
sub : 10
mul : 200
You can parameterise it and pass gradle clean build -Pprokey=goodbye
task choiceMyMainClass(type: JavaExec) {
group = "Execution"
description = "Run Option main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
if (project.hasProperty('prokey')){
if (prokey == 'hello'){
main = 'com.sam.home.HelloWorld'
}
else if (prokey == 'goodbye'){
main = 'com.sam.home.GoodBye'
}
} else {
println 'Invalid value is enterrd';
// println 'Invalid value is enterrd'+ project.prokey;
}
It amazes me that this simple answer did not occur in the previous answers.
In my viewpoint, the easiest way to print a string on multiple lines, is the following :
print("Random String \n" * 100)
, where 100 stands for the number of lines to be printed.
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt
or rs.getString
you can pass column_id
starting from 1
, but i prefer to pass column_name
as its more informative as you don't have to look at database table
for which index
is what column
.
UPDATE : rs.next
boolean next() throws SQLException
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.
Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs or this method is called on a closed result set
The general Angular way to get access to an element that triggered an event is to write a directive and bind() to the desired event:
app.directive('myChange', function() {
return function(scope, element) {
element.bind('change', function() {
alert('change on ' + element);
});
};
});
or with DDO (as per @tpartee's comment below):
app.directive('myChange', function() {
return {
link: function link(scope, element) {
element.bind('change', function() {
alert('change on ' + element);
});
}
}
});
The above directive can be used as follows:
<input id="searchText" ng-model="searchText" type="text" my-change>
Type into the text field, then leave/blur. The change callback function will fire. Inside that callback function, you have access to element
.
Some built-in directives support passing an $event object. E.g., ng-*click, ng-Mouse*. Note that ng-change does not support this event.
Although you can get the element via the $event object:
<button ng-click="clickit($event)">Hello</button>
$scope.clickit = function(e) {
var elem = angular.element(e.srcElement);
...
this goes "deep against the Angular way" -- Misko.
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
As of PowerShell 4.0 (Windows 8.1/Server 2012 R2) it is possible to make a certificate in Windows without makecert.exe.
The commands you need are New-SelfSignedCertificate and Export-PfxCertificate.
Instructions are in Creating Self Signed Certificates with PowerShell.
For posterity / completeness's sake… Here are two FULL examples of how to implement this ridiculously versatile "way of doing things". @Robert's answer is blissfully concise and correct, but here I want to also show ways to actually "define" the blocks.
@interface ReusableClass : NSObject
@property (nonatomic,copy) CALayer*(^layerFromArray)(NSArray*);
@end
@implementation ResusableClass
static NSString const * privateScope = @"Touch my monkey.";
- (CALayer*(^)(NSArray*)) layerFromArray {
return ^CALayer*(NSArray* array){
CALayer *returnLayer = CALayer.layer
for (id thing in array) {
[returnLayer doSomethingCrazy];
[returnLayer setValue:privateScope
forKey:@"anticsAndShenanigans"];
}
return list;
};
}
@end
Silly? Yes. Useful? Hells yeah. Here is a different, "more atomic" way of setting the property.. and a class that is ridiculously useful…
@interface CALayoutDelegator : NSObject
@property (nonatomic,strong) void(^layoutBlock)(CALayer*);
@end
@implementation CALayoutDelegator
- (id) init {
return self = super.init ?
[self setLayoutBlock: ^(CALayer*layer){
for (CALayer* sub in layer.sublayers)
[sub someDefaultLayoutRoutine];
}], self : nil;
}
- (void) layoutSublayersOfLayer:(CALayer*)layer {
self.layoutBlock ? self.layoutBlock(layer) : nil;
}
@end
This illustrates setting the block property via the accessor (albeit inside init, a debatably dicey practice..) vs the first example's "nonatomic" "getter" mechanism. In either case… the "hardcoded" implementations can always be overwritten, per instance.. a lá..
CALayoutDelegator *littleHelper = CALayoutDelegator.new;
littleHelper.layoutBlock = ^(CALayer*layer){
[layer.sublayers do:^(id sub){ [sub somethingElseEntirely]; }];
};
someLayer.layoutManager = littleHelper;
Also.. if you want to add a block property in a category... say you want to use a Block instead of some old-school target / action "action"... You can just use associated values to, well.. associate the blocks.
typedef void(^NSControlActionBlock)(NSControl*);
@interface NSControl (ActionBlocks)
@property (copy) NSControlActionBlock actionBlock; @end
@implementation NSControl (ActionBlocks)
- (NSControlActionBlock) actionBlock {
// use the "getter" method's selector to store/retrieve the block!
return objc_getAssociatedObject(self, _cmd);
}
- (void) setActionBlock:(NSControlActionBlock)ab {
objc_setAssociatedObject( // save (copy) the block associatively, as categories can't synthesize Ivars.
self, @selector(actionBlock),ab ,OBJC_ASSOCIATION_COPY);
self.target = self; // set self as target (where you call the block)
self.action = @selector(doItYourself); // this is where it's called.
}
- (void) doItYourself {
if (self.actionBlock && self.target == self) self.actionBlock(self);
}
@end
Now, when you make a button, you don't have to set up some IBAction
drama.. Just associate the work to be done at creation...
_button.actionBlock = ^(NSControl*thisButton){
[doc open]; [thisButton setEnabled:NO];
};
This pattern can be applied OVER and OVER to Cocoa API's. Use properties to bring the relevant parts of your code closer together, eliminate convoluted delegation paradigms, and leverage the power of objects beyond that of just acting as dumb "containers".
Regular expressions are probably the easiest solution to this problem:
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]
I have a shared hosting on GoDaddy. I needed an answer to this question, too, and after searching around I found that it is possible.
I wrote an .htaccess file, put it in the same folder as my action page. Here are the contents of the .htaccess file:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Here is my ajax call:
$.ajax({
url: 'http://www.mydomain.com/myactionpagefolder/gbactionpage.php', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
See this article for reference:
Header set Access-Control-Allow-Origin in .htaccess doesn't work
The practical use of this construct? It is a javascript replaceAll() on strings.
var s = 'stackoverflow_is_cool';
s = s.split('_').join(' ');
console.log(s);
will output:
stackoverflow is cool
Here is my example. Note that I am writing under Windows 7, using mingw32-make.exe that comes with Dev-Cpp. (I have c:\Windows\System32\make.bat, so the command is still called "make".)
clean:
$(RM) $(OBJ) $(BIN)
@echo off
if "${backup}" NEQ "" ( mkdir ${backup} 2> nul && copy * ${backup} )
Usage for regular cleaning:
make clean
Usage for cleaning and creating a backup in mydir/:
make clean backup=mydir
I had exactly the same issue, after moving from old go version (installed from old PPA) to newer (1.2.1) default packages in ubuntu 14.04.
The first step was to purge existing go:
sudo apt-get purge golang*
Which outputs following warnings:
dpkg: warning: while removing golang-go, directory '/usr/lib/go/src' not empty so not removed
dpkg: warning: while removing golang-go.tools, directory '/usr/lib/go' not empty so not removed
It looks like removing go leaves some files behind, which in turn can confuse newer install. More precisely, installation itself will complete fine, but afterwards any go command, like "go get something" gives those "unrecognized import path" errors.
All I had to do was to remove those dirs first, reinstall golang, and all works like a charm (assuming you also set GOPATH)
# careful!
sudo rm -rf /usr/lib/go /usr/lib/go/src
sudo apt-get install golang-go golang-go.tools
The sed command allows you to use other characters instead of /
as separator:
sed 's#"http://www\.fubar\.com"#URL_FUBAR#g'
The double quotes are not a problem.
You were close
/my/bash/script <<< 'This string will be sent to stdin.'
For multiline input, here-docs are suited:
/my/bash/script <<STDIN -o other --options
line 1
line 2
STDIN
Edit To the comments:
To achieve binary input, say
xxd -r -p <<BINARY | iconv -f UCS-4BE -t UTF-8 | /my/bash/script
0000 79c1 0000 306f 0000 3061 0000 3093 0000 3077 0000 3093 0000 304b 0000 3093 0000 3077 0000 3093 0000 306a 0000 8a71 0000 306b 0000 30ca 0000 30f3 0000 30bb
0000 30f3 0000 30b9 0000 3092 0000 7ffb 0000 8a33 0000 3059 0000 308b 0000 3053 0000 3068 0000 304c 0000 3067 0000 304d 0000 000a
BINARY
If you substitute cat
for /my/bash/script
(or indeed drop the last pipe), this prints:
????????????????????????????
Or, if you wanted something a little more geeky:
0000000: 0000 0000 bef9 0e3c 59f8 8e3c 0a71 d63c .......<Y..<.q.<
0000010: c6f2 0e3d 3eaa 323d 3a5e 563d 090e 7a3d ...=>.2=:^V=..z=
0000020: 7bdc 8e3d 2aaf a03d b67e b23d c74a c43d {..=*..=.~.=.J.=
0000030: 0513 d63d 16d7 e73d a296 f93d a8a8 053e ...=...=...=...>
0000040: 6583 0e3e 5a5b 173e 5b30 203e 3d02 293e e..>Z[.>[0 >=.)>
0000050: d4d0 313e f39b 3a3e 6f63 433e 1c27 4c3e ..1>..:>ocC>.'L>
0000060: cde6 543e 59a2 5d3e 9259 663e 4d0c 6f3e ..T>Y.]>.Yf>M.o>
0000070: 60ba 773e cf31 803e ee83 843e 78d3 883e `.w>.1.>...>x..>
0000080: 5720 8d3e 766a 913e beb1 953e 1cf6 993e W .>vj.>...>...>
0000090: 7a37 9e3e c275 a23e dfb0 a63e bce8 aa3e z7.>.u.>...>...>
00000a0: 441d af3e 624e b33e 017c b73e 0ca6 bb3e D..>bN.>.|.>...>
00000b0: 6fcc bf3e 15ef c33e e90d c83e d728 cc3e o..>...>...>.(.>
00000c0: c93f d03e ac52 d43e 6c61 d83e f36b dc3e .?.>.R.>la.>.k.>
00000d0: 2f72 e03e 0a74 e43e 7171 e83e 506a ec3e /r.>.t.>qq.>Pj.>
00000e0: 945e f03e 274e f43e f738 f83e f11e fc3e .^.>'N.>.8.>...>
00000f0: 0000 003f 09ee 013f 89d9 033f 77c2 053f ...?...?...?w..?
0000100: caa8 073f 788c 093f 776d 0b3f be4b 0d3f ...?x..?wm.?.K.?
0000110: 4427 0f3f 0000 113f e8d5 123f f3a8 143f D'.?...?...?...?
0000120: 1879 163f 4e46 183f 8d10 1a3f cad7 1b3f .y.?NF.?...?...?
0000130: fe9b 1d3f 1f5d 1f3f 241b 213f 06d6 223f ...?.].?$.!?.."?
0000140: bb8d 243f 3a42 263f 7cf3 273f 78a1 293f ..$?:B&?|.'?x.)?
0000150: 254c 2b3f 7bf3 2c3f 7297 2e3f 0138 303f %L+?{.,?r..?.80?
0000160: 22d5 313f ca6e 333f ".1?.n3?
Which is the sines of the first 90 degrees in 4byte binary floats
DO NOT use this:
System.Environment.GetEnvironmentVariable("TEMP")
Environment variables can be overridden, so the TEMP
variable is not necessarily the directory.
The correct way is to use System.IO.Path.GetTempPath()
as in the accepted answer.
Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.
Swift 4 You cannot compare Any to nil.Because an optional can be nil and hence it always succeeds to true. The only way is to cast it to your desired object and compare it to nil.
if (someone as? String) != nil
{
//your code`enter code here`
}
Place single quotes around the Extended Properties
:
OleDbConnection oconn =
new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';");
Try it, it really works.
For a pure Ruby solution combine URI.parse
with CGI.parse
(this can be used even if Rails/Rack etc. are not required):
CGI.parse(URI.parse(url).query)
# => {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }
[self dismissModalViewControllerAnimated:NO];
has been deprecated.
Use [self dismissViewControllerAnimated:NO completion:nil];
instead.
Have you tried calling TcpClient.Dispose() explicitly?
And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?
You cannot (at least at the moment) use parseInt
inside angular expressions, as they're not evaluated directly. Quoting the doc:
Angular does not use JavaScript's
eval()
to evaluate expressions. Instead Angular's$parse
service processes these expressions.Angular expressions do not have access to global variables like
window
,document
orlocation
. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.
So you can define a total()
method in your controller, then use it in the expression:
// ... somewhere in controller
$scope.total = function() {
return parseInt($scope.num1) + parseInt($scope.num2)
}
// ... in HTML
Total: {{ total() }}
Still, that seems to be rather bulky for a such a simple operation as adding the numbers. The alternative is converting the results with -0
op:
Total: {{num1-0 + (num2-0)|number}}
... but that'll obviously won't parseInt values, only cast them to Numbers (|number
filter prevents showing null
if this cast results in NaN
). So choose the approach that suits your particular case.
Use unshift
, which modifies the existing array by adding the arguments to the beginning:
TheArray.unshift(TheNewObject);
You can do a column transformation by using apply
Define a clean function to remove the dollar and commas and convert your data to float.
def clean(x):
x = x.replace("$", "").replace(",", "").replace(" ", "")
return float(x)
Next, call it on your column like this.
data['Revenue'] = data['Revenue'].apply(clean)
in AndroidStudio or idea
add "VM Options" Config
“-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005”
remember "address"
Thanks to the folks on Freenode's #macdev, here is some information:
In the old days before Xcode was on the app-store, it included commandline tools.
Now you get it from the store, and with this new mechanism it can't install extra things outside of the Xcode.app, so you have to manually do it yourself, by:
xcode-select --install
On Xcode 4.x you can check to see if they are installed from within the Xcode UI:
On Xcode 5.x it is now here:
My problem of finding gcc/gdb is that they have been superseded by clang/lldb: GDB missing in OS X v10.9 (Mavericks)
Also note that Xcode contains compiler and debugger, so one of the things installing commandline tools will do is symlink or modify $PATH. It also downloads certain things like git.
If removing the in
class doesn't work for you, such was my case, you can force the collapsed initial state using the CSS display property:
...
<div id="collapseOne" class="accordion-body collapse" style="display: none;">
...
Try this code
$('window').scrollDown(function(){$(#div).hide()});
$('window').scrollUp(function(){ $(#div).show() });
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
If you cannot use new ES5 stuff such filter
I think you're stuck with two loops:
for( var i =myArray.length - 1; i>=0; i--){
for( var j=0; j<toRemove.length; j++){
if(myArray[i] === toRemove[j]){
myArray.splice(i, 1);
}
}
}
Since none of you mentioned nothing about the const keyword...
The const keyword modifies the type of a type declaration or the type of a function parameter, preventing the value from varying. (Source: MS)
In other words: passing a parameter by reference exposes it to modification by the callee. Using the const keyword prevents the modification.
It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.
<input id="myFileInput" type="file" accept="image/*;capture=camera">
var myInput = document.getElementById('myFileInput');
function sendPic() {
var file = myInput.files[0];
// Send file here either by adding it to a `FormData` object
// and sending that via XHR, or by simply passing the file into
// the `send` method of an XHR instance.
}
myInput.addEventListener('change', sendPic, false);
As someone who only occasionally needs to do Java work, this was very annoying. Inevitably, packages would have been added since the last time I ran our server inside IntelliJ and it would fail to build. I found what seems to be an easier solution: just don't build within IntelliJ. Build from the command line via Maven, then make sure that the run configuration does not list Build as a "Before launch" task.
Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])
This is not an answer, just my experience:
On my Ubuntu 12.04 apache2, didn't find Indexes
in either apache2.conf or httpd.conf, luckily I found it in sites-available/default
. After removing it, now it doesn't see directory listing. May have to do it for sites-available/default-ssl
.
Duplicating my answer in another thread.
For Angular 2 and newer, the easiest way to add no-cache
headers by overriding RequestOptions
:
import { Injectable } from '@angular/core';
import { BaseRequestOptions, Headers } from '@angular/http';
@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
headers = new Headers({
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
});
}
And reference it in your module:
@NgModule({
...
providers: [
...
{ provide: RequestOptions, useClass: CustomRequestOptions }
]
})
As @kojiro said, you don't want to "run" this file. Source it as he says. It should get "sourced" at startup. Sourcing just means running every line in the file, including the one you want to get run. If you want to make sure a folder is in a certain path environment variable (as it seems you want from one of your comments on another solution), execute
$ echo $PATH
At the command line. If you want to check that your ~/.bash_profile is being sourced, either at startup as it should be, or when you source it manually, enter the following line into your ~/.bash_profile file:
$ echo "Hello I'm running stuff in the ~/.bash_profile!"
Regarding the " I couldn't get the SSIS import / export to work as I got the error 'Failure inserting into the read-only column "id"'. This can be gotten around by specifying in the mapping screen that you do want to allow Identity elements to be inserted.
After that, everything worked fine using SQL Import/Export wizard to copy from Azure to local database.
I only had SQL Import/Export Wizard that comes with SQL Server 2008 R2 (worked fine), and Visual Studio 2012 Express to create local database.
Use '-R' to backup stored procedures, but also keep in mind that if you want a consistent dump of your database while its being modified you need to use --single-transaction
(if you only backup innodb) or --lock-all-tables
(if you also need myisam tables)
I posted my answer even though another answer has already been accepted; the accepted answer relies on a deprecated function; additionally, this deprecated function is based on Singular Value Decomposition (SVD), which (although perfectly valid) is the much more memory- and processor-intensive of the two general techniques for calculating PCA. This is particularly relevant here because of the size of the data array in the OP. Using covariance-based PCA, the array used in the computation flow is just 144 x 144, rather than 26424 x 144 (the dimensions of the original data array).
Here's a simple working implementation of PCA using the linalg module from SciPy. Because this implementation first calculates the covariance matrix, and then performs all subsequent calculations on this array, it uses far less memory than SVD-based PCA.
(the linalg module in NumPy can also be used with no change in the code below aside from the import statement, which would be from numpy import linalg as LA.)
The two key steps in this PCA implementation are:
calculating the covariance matrix; and
taking the eivenvectors & eigenvalues of this cov matrix
In the function below, the parameter dims_rescaled_data refers to the desired number of dimensions in the rescaled data matrix; this parameter has a default value of just two dimensions, but the code below isn't limited to two but it could be any value less than the column number of the original data array.
def PCA(data, dims_rescaled_data=2):
"""
returns: data transformed in 2 dims/columns + regenerated original data
pass in: data as 2D NumPy array
"""
import numpy as NP
from scipy import linalg as LA
m, n = data.shape
# mean center the data
data -= data.mean(axis=0)
# calculate the covariance matrix
R = NP.cov(data, rowvar=False)
# calculate eigenvectors & eigenvalues of the covariance matrix
# use 'eigh' rather than 'eig' since R is symmetric,
# the performance gain is substantial
evals, evecs = LA.eigh(R)
# sort eigenvalue in decreasing order
idx = NP.argsort(evals)[::-1]
evecs = evecs[:,idx]
# sort eigenvectors according to same index
evals = evals[idx]
# select the first n eigenvectors (n is desired dimension
# of rescaled data array, or dims_rescaled_data)
evecs = evecs[:, :dims_rescaled_data]
# carry out the transformation on the data using eigenvectors
# and return the re-scaled data, eigenvalues, and eigenvectors
return NP.dot(evecs.T, data.T).T, evals, evecs
def test_PCA(data, dims_rescaled_data=2):
'''
test by attempting to recover original data array from
the eigenvectors of its covariance matrix & comparing that
'recovered' array with the original data
'''
_ , _ , eigenvectors = PCA(data, dim_rescaled_data=2)
data_recovered = NP.dot(eigenvectors, m).T
data_recovered += data_recovered.mean(axis=0)
assert NP.allclose(data, data_recovered)
def plot_pca(data):
from matplotlib import pyplot as MPL
clr1 = '#2026B2'
fig = MPL.figure()
ax1 = fig.add_subplot(111)
data_resc, data_orig = PCA(data)
ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)
MPL.show()
>>> # iris, probably the most widely used reference data set in ML
>>> df = "~/iris.csv"
>>> data = NP.loadtxt(df, delimiter=',')
>>> # remove class labels
>>> data = data[:,:-1]
>>> plot_pca(data)
The plot below is a visual representation of this PCA function on the iris data. As you can see, a 2D transformation cleanly separates class I from class II and class III (but not class II from class III, which in fact requires another dimension).
No solution here worked for me. Instead I added a class to the label and was able to select it that way.
<asp:Label ID="Label1" CssClass="myLabel1Class" runat="server" Text="Label"></asp:Label>
$(".myLabel1Class").val()
And, as mentioned by others, make sure you have your jquery loaded.
there you go
$date = "04-15-2013";
$date1 = str_replace('-', '/', $date);
$tomorrow = date('m-d-Y',strtotime($date1 . "+1 days"));
echo $tomorrow;
this will output
04-16-2013
Actually I don't know what is the reason exactly, I have faced this like of problem. if you have the domain's IP address (ex 208.113.139.4), please use the IP address instead of domain (in this case www.icerts.com)
wget 192.243.111.11/images/logo.jpg
Go to find the IP from URL https://ipinfo.info/html/ip_checker.php
if (!/^[0-9]+$/.test('123456askm')) {
consol.log('Enter Only Number');
} else {
consol.log('Sucess');
}
I know this is an old post, but a good time to use PrimaryKeyColumn
would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.
In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn
.
Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.
It's probably because your SSH key has been removed/revoked. Make a new one and add it to your GitHub account.
This is the approach I'm using and you can modify it based on your needs:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})$
Explanation:
We want to make sure that the e-mail address always starts with a word:
^[\w]
A word is any character, digit or underscore. You can use [a-zA-Z0-9_] pattern, but it will give you the same result and it's longer.
Next, we want to make sure that there is at least one such character:
^[\w]{1,}
Next, we want to allow any word, digit or special characters in the name. This way, we can be sure that the e-mail won't start with the dot, but can contain the dot on other than the first position:
^[\w]{1,}[\w.+-]
And of course, there doesn't have to be any of such character because e-mail address can have only one letter followed by @:
^[\w]{1,}[\w.+-]{0,}
Next, we need the @ character which is mandatory, but there can be only one in the whole e-mail:
^[\w]{1,}[\w.+-]{0,}@
Right behind the @ character, we want the domain name. Here, you can define how many characters you want as minimum and from which range of characters. I'd go for all word characters including the hyphen [\w-] and I want at least two of them {2,}. If you want to allow domains like t.co, you would have to allow one character from this range {1,}:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}
Next, we need to deal with two cases. Either there's just the domain name followed by the domain extension, or there's subdomain name followed by the domain name followed by the extension, for example, abc.com versus abc.co.uk. To make this work, we need to use the (a|b) token where a stands for the first case, b stands for the second case and | stands for logical OR. In the first case, we will deal with just the domain extension, but since it will be always there no matter the case, we can safely add it to both cases:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][a-zA-Z]{2,})
This pattern says that we need exactly one dot character followed by letters, no digits, and we want at least two of them, in both cases.
For the second case, we will add the domain name in front of the domain extension, thus making the original domain name a subdomain:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})
The domain name can consist of word characters including the hyphen and again, we want at least two characters here.
Finally, we need to mark the end of the whole pattern:
^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})$
Go here and test if your e-mail matches the pattern: https://regex101.com/r/374XLJ/1
os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory?
os.path.isdir("bob")
If expected data format is MM-dd-yyyy
then try below,
=CDate(Now).ToString("MM-dd-yyyy")
Similarly you can try this one,
=Format(Today(),"MM-dd-yyyy")
Output: 02-04-2016
Note:
Now()
will show you current date and time stamp
Today()
will show you Date only not time part.
Also you can set any date format instead of MM-dd-yyyy
in my example.
<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>
In order to populate referenced subdocuments, you need to explicitly define the document collection to which the ID references to (like created_by: { type: Schema.Types.ObjectId, ref: 'User' }
).
Given this reference is defined and your schema is otherwise well defined as well, you can now just call populate
as usual (e.g. populate('comments.created_by')
)
Proof of concept code:
// Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: String
});
var CommentSchema = new Schema({
text: String,
created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});
var ItemSchema = new Schema({
comments: [CommentSchema]
});
// Connect to DB and instantiate models
var db = mongoose.connect('enter your database here');
var User = db.model('User', UserSchema);
var Comment = db.model('Comment', CommentSchema);
var Item = db.model('Item', ItemSchema);
// Find and populate
Item.find({}).populate('comments.created_by').exec(function(err, items) {
console.log(items[0].comments[0].created_by.name);
});
Finally note that populate
works only for queries so you need to first pass your item into a query and then call it:
item.save(function(err, item) {
Item.findOne(item).populate('comments.created_by').exec(function (err, item) {
res.json({
status: 'success',
message: "You have commented on this item",
comment: item.comments.id(comment._id)
});
});
});
I'm not sure about you, but I spent about 30 minutes troubleshooting the same issue here, until I realized that the line for app/build.gradle is:
apply plugin: 'com.google.gms.google-services'
and not:
apply plugin: 'com.google.gms:google-services'
Eg: I had copied that line from a tutorial, but when specifying the apply plugin namespace, no colon (:
) is required. It's, in fact, a dot. (.
).
Hey... it's easy to miss.
ksh93:
dt=${ printf "%(%a %d/%m/%Y)T" yesterday; }
or:
dt=$(printf "%(%a %d/%m/%Y)T" yesterday)
The first one runs in the same process, the second one in a subshell.
In any type of complex matrix, when you want alternate cell colors, either row wise or column wise, the working solution is,
If you want a alternate color of cells coloumn wise then,
=IIF(RunningValue( Fields![ColumnGroupField].Value, countDistinct, "FakeParentGroup" ) MOD 2, "White", "LightGrey")
Thats all.
Same for the alternate color row wise, just you have to edit solution accordingly.
NOTE: Here, sometimes you need to set border of cells accordingly, usually it vanishes.
Also dont forget to delete value 1 in report that came into pic when you created fake parent group.
You can do this:
create type number_tab is table of number;
select * from table (number_tab(1,2,3,4,5,6));
The column is given the name COLUMN_VALUE by Oracle, so this works too:
select column_value from table (number_tab(1,2,3,4,5,6));
I think to have the real next or previous row in SQL table we need the real value with equal, (< or >) return more than one if you need to change position of row in a ordering table.
we need the value $position
to search the neighbours
row
In my table I created a column 'position'
and SQL query for getting the needed row is :
for next :
SELECT *
FROM `my_table`
WHERE id = (SELECT (id)
FROM my_table
WHERE position = ($position+1))
LIMIT 1
for previous:
SELECT *
FROM my_table
WHERE id = (SELECT (id)
FROM my_table
WHERE `position` = ($position-1))
LIMIT 1
If you are creating a new MySQL table, you can specify the charset of all columns upon creation, and that fixed the issue for me.
CREATE TABLE tablename (
<list-of-columns>
)
CHARSET SET utf8mb4 COLLATE utf8mb4_unicode_ci;
You can read more details: https://dev.mysql.com/doc/refman/8.0/en/charset-column.html
This is what I use in Swift 5 Xcode 11:
Inside the class variables:
let languagePrefix = Bundle.main.preferredLocalizations.first?.prefix(2)
This comes as a string. It returns 2 characters, i.e. "en", "es", "de"...
From this I can easily determine what language to display:
if languagePrefix == "es" { self.flipCard.setTitle("última carta", for: .normal) }
if languagePrefix == "en" { self.flipCard.setTitle("Last Card", for: .normal) }
If you want the full information of the language, then remove ?.prefex(2)
DialogFragment is basically a Fragment that can be used as a dialog.
Using DialogFragment over Dialog due to the following reasons:
- DialogFragment is automatically re-created after configuration changes and save & restore flow
- DialogFragment inherits full Fragment’s lifecycle
- No more IllegalStateExceptions and leaked window crashes. This was pretty common when the activity was destroyed with the Alert Dialog still there.
I wanted the new application start up after the old one shuts down.
Using process.WaitForExit() to wait for your own process to shutdown makes no sense. It will always time out.
So, my approach is to use Application.Exit() then wait, but allow events to be processed, for a period of time. Then start a new application with the same arguments as the old.
static void restartApp() {
string commandLineArgs = getCommandLineArgs();
string exePath = Application.ExecutablePath;
try {
Application.Exit();
wait_allowingEvents( 1000 );
} catch( ArgumentException ex ) {
throw;
}
Process.Start( exePath, commandLineArgs );
}
static string getCommandLineArgs() {
Queue<string> args = new Queue<string>( Environment.GetCommandLineArgs() );
args.Dequeue(); // args[0] is always exe path/filename
return string.Join( " ", args.ToArray() );
}
static void wait_allowingEvents( int durationMS ) {
DateTime start = DateTime.Now;
do {
Application.DoEvents();
} while( start.Subtract( DateTime.Now ).TotalMilliseconds > durationMS );
}
Definition and Usage
the count()
method returns the number of elements with the specified value.
Syntax
list.count(value)
example:
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
Question's example:
item = someSortOfSelection()
if myList.count(item) >= 1 :
doMySpecialFunction(item)
Several years late to the party but I want to both sort on 2 criteria and use reverse=True
. In case someone else wants to know how, you can wrap your criteria (functions) in parenthesis:
s = sorted(my_list, key=lambda i: ( criteria_1(i), criteria_2(i) ), reverse=True)
A character set is a subset of all written glyphs. A character encoding specifies how those characters are mapped to numeric values. Some character encodings, like UTF-8 and UTF-16, can encode any character in the Universal Character Set. Others, like US-ASCII or ISO-8859-1 can only encode a small subset, since they use 7 and 8 bits per character, respectively. Because many standards specify both a character set and a character encoding, the term "character set" is often substituted freely for "character encoding".
A collation comprises rules that specify how characters can be compared for sorting. Collations rules can be locale-specific: the proper order of two characters varies from language to language.
Choosing a character set and collation comes down to whether your application is internationalized or not. If not, what locale are you targeting?
In order to choose what character set you want to support, you have to consider your application. If you are storing user-supplied input, it might be hard to foresee all the locales in which your software will eventually be used. To support them all, it might be best to support the UCS (Unicode) from the start. However, there is a cost to this; many western European characters will now require two bytes of storage per character instead of one.
Choosing the right collation can help performance if your database uses the collation to create an index, and later uses that index to provide sorted results. However, since collation rules are often locale-specific, that index will be worthless if you need to sort results according to the rules of another locale.
With one feature my Dataframe list converts to a Series. I had to convert it back to a Dataframe list and it worked.
if type(X) is Series:
X = X.to_frame()
Just with the above answer I hope it was the problem.
$_POST['search']
instead of $_post['search']
And again use LIKE '%$name%'
instead of LIKE '%{$name}%'
Power point supports converting to mp4 which can be posted using a html5 video tag.
Save As > MPEG-4 Video (*.mp4)
<video controls autoplay reload="none" style="width:1000px;">
<source src="my_power_point.mp4" type="video/mp4" />
</video>
Pandas will recognise a value as null if it is a np.nan
object, which will print as NaN
in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan
objects using replace()
, and then call dropna()
on your DataFrame to delete rows with null tenants.
To demonstrate, we create a DataFrame with some random values and some empty strings in a Tenants
column:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640
Now we replace any empty strings in the Tenants
column with np.nan
objects, like so:
>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239 NaN
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214 NaN
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640 NaN
Now we can drop the null values:
>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
You need to prevent the default behaviour. You can either use e.preventDefault()
or return false;
In this case, the best thing is, you can use return false;
here:
<form onsubmit="completeAndRedirect(); return false;">
You need to use
$(this).parents('form').submit()
The variables/parameters within the class
definition requires { get; set; }
I was using like a variable declaration (stupid of me, because it was working for other scenarios) without
{ get; set; }
Because of which, whatever I send from the JavaScript, it was not being received in the Action method. It was always getting null or empty model.
Once the {get; set;} is added, it worked like charm.
I hope it helps someone who is coming from VB6 style of programming line.
Very hard when you have to do this with three select statments
I tried all proposed techniques up there but it's in-vain
Please see below script. please advice if you have alternative solution
select distinct x.best_Achiver_ever,y.Today_best_Achiver ,z.Most_Violator from
(SELECT Top(4) ROW_NUMBER() over (order by tl.username) AS conj, tl.
[username] + '-->' + str(count(*)) as best_Achiver_ever
FROM[TiketFollowup].[dbo].N_FCR_Tikect_Log_Archive tl
group by tl.username
order by count(*) desc) x
left outer join
(SELECT
Top(4) ROW_NUMBER() over (order by tl.username) as conj, tl.[username] + '-->' + str(count(*)) as Today_best_Achiver
FROM[TiketFollowup].[dbo].[N_FCR_Tikect_Log] tl
where convert(date, tl.stamp, 121) = convert(date,GETDATE(),121)
group by tl.username
order by count(*) desc) y
on x.conj=y.conj
left outer join
(
select ROW_NUMBER() over (order by count(*)) as conj,username+ '--> ' + str( count(dbo.IsViolated(stamp))) as Most_Violator from N_FCR_Ticket
where dbo.IsViolated(stamp) = 'violated' and convert(date,stamp, 121) < convert(date,GETDATE(),121)
group by username
order by count(*) desc) z
on x.conj = z.conj
Run this
for (Method m : sex.class.getDeclaredMethods()) {
System.out.println(m);
}
you will see
public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()
These are all public methods that "sex" class has. They are not in the source code, javac.exe added them
Notes:
never use sex as a class name, it's difficult to read your code, we use Sex in Java
when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class
1.open the terminal.
2.backup your database with following command
your postgres bin - /opt/PostgreSQL/9.1/bin/
your source database server - 192.168.1.111
your backup file location and name - /home/dinesh/db/mydb.backup
your source db name - mydatabase
/opt/PostgreSQL/9.1/bin/pg_dump --host '192.168.1.111' --port 5432 --username "postgres" --no-password --format custom --blobs --file "/home/dinesh/db/mydb.backup" "mydatabase"
3.restore mydb.backup file into destination.
your destination server - localhost
your destination database name - mydatabase
create database for restore the backup.
/opt/PostgreSQL/9.1/bin/psql -h 'localhost' -p 5432 -U postgres -c "CREATE DATABASE mydatabase"
restore the backup.
/opt/PostgreSQL/9.1/bin/pg_restore --host 'localhost' --port 5432 --username "postgres" --dbname "mydatabase" --no-password --clean "/home/dinesh/db/mydb.backup"
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
If you are using FirstResponderKit from Brent Ozar team, you can run this query also:
exec sp_blitzindex @tablename='MyTable'
It will return all information about table:
Of course it's not a system and not so universal stp like sp_help or sp_columns, but it returns all possible information about your table and I think it's worth creating it at your environment and mentioning it here.
We got the same exact exception error returned, to fix it was easy after hours surfing the internet.
We downloaded the highest version of jdk we could find on oracle.com, installed it and pointed Jboss application server to the directory of the installed new jdk.
Restarted Jboss, reprocessed, problemo fixed!!!
You are setting the datasource inside of the loop and sleeping 500 after each add. Why not just add to itemstates and then set your datasource AFTER you have added everything. If you want the thread sleep after that fine. The first block of code here is yours the second block I modified.
for (int i = 0; i < 10; i++) {
itemStates.Add(new ItemState { Id = i.ToString() });
dataGridView1.DataSource = null;
dataGridView1.DataSource = itemStates;
System.Threading.Thread.Sleep(500);
}
Change your Code As follows: this is much faster.
for (int i = 0; i < 10; i++) {
itemStates.Add(new ItemState { Id = i.ToString() });
}
dataGridView1.DataSource = typeof(List);
dataGridView1.DataSource = itemStates;
System.Threading.Thread.Sleep(500);
This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.
typedef double (*pf)(double x); /*this defines a type pf */
double f1(double x) { return(x+x);}
double f2(double x) { return(x*x);}
pf pa[] = {f1, f2};
main()
{
pf p;
p = pa[0];
printf("%f\n", p(3.0));
p = pa[1];
printf("%f\n", p(3.0));
}
A flexible solution using IOUtils from Apache commons-io in combination with StringWriter:
Reader input = new FileReader();
StringWriter output = new StringWriter();
try {
IOUtils.copy(input, output);
} finally {
input.close();
}
String fileContents = output.toString();
It works with any reader or input stream (not just with files), for example when reading from a URL.
As far as I understand you need mean terminate as Thread.Abort()
right? In this case, you can just exit the Foo(). Or you can use Process to catch the thread.
Thread myThread = new Thread(DoWork);
myThread.Abort();
myThread.Start();
Process example:
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using Microsoft.VisualBasic;
class PrintProcessClass
{
private Process myProcess = new Process();
private int elapsedTime;
private bool eventHandled;
// Print a file with any known extension.
public void PrintDoc(string fileName)
{
elapsedTime = 0;
eventHandled = false;
try
{
// Start a process to print a file and raise an event when done.
myProcess.StartInfo.FileName = fileName;
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
return;
}
// Wait for Exited event, but not more than 30 seconds.
const int SLEEP_AMOUNT = 100;
while (!eventHandled)
{
elapsedTime += SLEEP_AMOUNT;
if (elapsedTime > 30000)
{
break;
}
Thread.Sleep(SLEEP_AMOUNT);
}
}
// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
eventHandled = true;
Console.WriteLine("Exit time: {0}\r\n" +
"Exit code: {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
}
public static void Main(string[] args)
{
// Verify that an argument has been entered.
if (args.Length <= 0)
{
Console.WriteLine("Enter a file name.");
return;
}
// Create the process and print the document.
PrintProcessClass myPrintProcess = new PrintProcessClass();
myPrintProcess.PrintDoc(args[0]);
}
}
Well, I totally agree with answers already exist on this point:
bootstrap.yml
is used to save parameters that point out where the remote configuration is and Bootstrap Application Context is created with these remote configuration.Actually, it is also able to store normal properties just the same as what application.yml
do. But pay attention on this tricky thing:
bootstrap.yml
, they will get lower precedence than almost any other property sources, including application.yml. As described here.Let's make it clear, there are two kinds of properties related to bootstrap.yml
:
bootstrap.yml
to find the properties holder (A file system, git repository or something else), and the properties we get in this way are with high precedence, so they cannot be overridden by local configuration. As described here.bootstrap.yml
. As explained early, they will get lower precedence. Use them to set defaults maybe a good idea.So the differences between putting a property on application.yml
or bootstrap.yml
in spring boot are:
bootstrap.yml
.application.yml
will get higher precedence.For getting a table by name in SQL Server:
SELECT *
FROM sys.Tables
WHERE name LIKE '%Employees%'
For finding a stored procedure by name:
SELECT name
FROM sys.objects
WHERE name = 'spName'
To get all stored procedures related to a table:
----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'
I would use buildAndExpand
from UriComponentsBuilder
to pass all types of URI parameters.
For example:
String url = "http://test.com/solarSystem/planets/{planet}/moons/{moon}";
// URI (URL) parameters
Map<String, String> urlParams = new HashMap<>();
urlParams.put("planets", "Mars");
urlParams.put("moons", "Phobos");
// Query parameters
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
// Add query parameter
.queryParam("firstName", "Mark")
.queryParam("lastName", "Watney");
System.out.println(builder.buildAndExpand(urlParams).toUri());
/**
* Console output:
* http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney
*/
restTemplate.exchange(builder.buildAndExpand(urlParams).toUri() , HttpMethod.PUT,
requestEntity, class_p);
/**
* Log entry:
* org.springframework.web.client.RestTemplate Created PUT request for "http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney"
*/
Alternatively you can use command line to get your SHA-1 fingerprint:
for your debug certificate you should use:
keytool -list -v -keystore C:\Users\user\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
you should change "c:\Users\user
" with the path to your windows user directory
if you want to get the production SHA-1 for your own certificate, replace "C:\Users\user\.android\debug.keystore
" with your custom KeyStore path and use your KeystorePass and Keypass instead of android/android.
Than declare the SHA-1
fingerprints you get to your firebase console as Damini said
Microsoft recently open sourced their jdbc driver.
You can now find the driver on maven central:
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
or for java 7:
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre7</version>
</dependency>
There are (at least) two different use cases which could be described as "search the bucket":
Search for something inside every object stored at the bucket; this assumes a common format for all the objects in that bucket (say, text files), etc etc. For something like this, you're forced to do what Cody Caughlan just answered. The AWS S3 docs has example code showing how to do this with the AWS SDK for Java: Listing Keys Using the AWS SDK for Java (there you'll also find PHP and C# examples).
List item Search for something in the object keys contained in that bucket; S3 does have partial support for this, in the form of allowing prefix exact matches + collapsing matches after a delimiter. This is explained in more detail at the AWS S3 Developer Guide. This allows, for example, to implement "folders" through using as object keys something like
folder/subfolder/file.txtIf you follow this convention, most of the S3 GUIs (such as the AWS Console) will show you a folder view of your bucket.
You can clone just the latest commit using git clone --depth 1 <url>
and then perform your own analysis using Linguist, the same software Github uses. That's the only way I know you're going to get lines of code.
Another option is to use the API to list the languages the project uses. It doesn't give them in lines but in bytes. For example...
$ curl https://api.github.com/repos/evalEmpire/perl5i/languages
{
"Perl": 274835
}
Though take that with a grain of salt, that project includes YAML and JSON which the web site acknowledges but the API does not.
Finally, you can use code search to ask which files match a given language. This example asks which files in perl5i are Perl. https://api.github.com/search/code?q=language:perl+repo:evalEmpire/perl5i
. It will not give you lines, and you have to ask for the file size separately using the returned url
for each file.
Am using windows 8 n this issue got resolved by changing the environment variables
follow these steps: Open my computer properties->advanced system settings->Environment variables. Under 'system variables', select 'path' and click on 'edit' In 'variable value', add 'C:\php;' OR the path where php installed.
click OK and apply the settings and restart the system. It should work.
My solution to this issue was to create the function shown below. My requirements included that the number had to be a standard integer, not a BIGINT, and I needed to allow negative numbers and positive numbers. I have not found a circumstance where this fails.
CREATE FUNCTION [dbo].[udfIsInteger]
(
-- Add the parameters for the function here
@Value nvarchar(max)
)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @Result int = 0
-- Add the T-SQL statements to compute the return value here
DECLARE @MinValue nvarchar(11) = '-2147483648'
DECLARE @MaxValue nvarchar(10) = '2147483647'
SET @Value = ISNULL(@Value,'')
IF LEN(@Value)=0 OR
ISNUMERIC(@Value)<>1 OR
(LEFT(@Value,1)='-' AND LEN(@Value)>11) OR
(LEFT(@Value,1)='-' AND LEN(@Value)=11 AND @Value>@MinValue) OR
(LEFT(@Value,1)<>'-' AND LEN(@Value)>10) OR
(LEFT(@Value,1)<>'-' AND LEN(@Value)=10 AND @Value>@MaxValue)
GOTO FINISHED
DECLARE @cnt int = 0
WHILE @cnt<LEN(@Value)
BEGIN
SET @cnt=@cnt+1
IF SUBSTRING(@Value,@cnt,1) NOT IN ('-','0','1','2','3','4','5','6','7','8','9') GOTO FINISHED
END
SET @Result=1
FINISHED:
-- Return the result of the function
RETURN @Result
END
This should work:
soup = BeautifulSoup(sdata)
mydivs = soup.findAll('div')
for div in mydivs:
if (div.find(class_ == "stylelistrow"):
print div
In my case I had to give the IIS_IUSRS
Read\write permission to the log file.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
A solution that works no matter if you are developing on a local server or live is to add "//" in front of your link. This will effectivly remove the URL of the site you are currently on.
Example:
<a href="www.google.com">Google.com</a>
This will in output http://localhost/mySite/currentPage/www.google.com
What you should do instead is this:
<a href="//www.google.com">Google.com</a>
This will output www.google.com
Scenario/Test steps:
1. Open a browser and navigate to TestURL
2. Scroll down some pixel and scroll up
For Scroll down:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)");
OR, you can do as follows:
jse.executeScript("scroll(0, 250);");
For Scroll up:
jse.executeScript("window.scrollBy(0,-250)");
OR,
jse.executeScript("scroll(0, -250);");
Scroll to the bottom of the page:
Scenario/Test steps:
1. Open a browser and navigate to TestURL
2. Scroll to the bottom of the page
Way 1: By using JavaScriptExecutor
jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Way 2: By pressing ctrl+end
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.END);
Way 3: By using Java Robot class
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_CONTROL);
It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.
It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.
Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146
If you are using numpy, you can perform extended slicing like that:
>>> import numpy
>>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
>>> Idx = [0, 3, 7]
>>> a[Idx]
array(['a', 'd', 'h'],
dtype='|S1')
...and is probably much faster (if performance is enough of a concern to to bother with the numpy import)
my_styles.xml
and save it in res/values
.Add the following code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ListFont" parent="@android:style/Widget.ListView">
<item name="android:textColor">#FF0000</item>
<item name="android:typeface">sans</item>
</style>
</resources>
Add your style to your Activity
definition in your AndroidManifest.xml
as an android:theme
attribute, and assign as value the name of the style you created. For example:
<activity android:name="your.activityClass" android:theme="@style/ListFont">
render
will be called every time you setState
to re-render the component if there are changes. If you move your call to drawGrid
there rather than calling it in your update*
methods, you shouldn't have a problem.
If that doesn't work for you, there is also an overload of setState
that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.
Try this
body {
max-width: max-content;
margin: auto;
}
You need to make the strings raw and use latex:
fig.gca().set_ylabel(r'$\lambda$')
As of matplotlib 2.0 the default font supports most western alphabets and can simple do
ax.set_xlabel('?')
with unicode.
You have to enable curl with php.
Here is the instructions for same
#The Best way is to use `fStrings` (very easy and powerful in python3)
#Format: f'your-string'
#For Example:
mylist=['laks',444,'M']
cursor.execute(f'INSERT INTO mytable VALUES ("{mylist[0]}","{mylist[1]}","{mylist[2]}")')
#THATS ALL!! EASY!!
#You can use it with for loop!
After browsing search engines for a few hours I came across a site with a great ERD example here: http://www.exploredatabase.com/2016/07/description-about-weak-entity-sets-in-DBMS.html
I've recreated the ERD. Unfortunately they did not specify the primary key of the weak entity.
If the building could only have one and only one apartment, then it seems the partial discriminator room number would not be created (i.e. discarded).
My recyclerview was slow in loading so by reading the stackoverflow.com I changed hardwareAccelerated to "false" then the elevation is not showing in the device. The I changed back to true. It works for me.
You should use a with statement to qualify both your Rows
and Columns
counts. This will prevent any errors while working with older pre 2007 and newer 2007 Excel Workbooks.
Last Column
With Sheets("Sheet2")
.Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Last Row
With Sheets("Sheet2")
.Range("A" & .Rows.Count).End(xlUp).Row
End With
Or
With Sheets("Sheet2")
.Cells(.Rows.Count, 1).End(xlUp).Row
End With
Try the below code:
[Route("/test")]
[HttpPost]
public async Task Test()
{
using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
{
var textFromBody = await reader.ReadToEndAsync();
}
}
Is there a command that does?
thread apply all where
css :hover
kinda is like js onmouseover
row1 {
// your css
}
row1:hover {
color: red;
}
row1:hover #a, .b, .c:nth-child[3] {
border: 1px solid red;
}
not too sure how it works but css applies styles to echo'ed ids
You're on the right track. You may read the user input into an integer and switch
on that:
enum Choice
{
EASY = 1,
MEDIUM = 2,
HARD = 3
};
int i = -1;
// ...<present the user with a menu>...
cin >> i;
switch(i)
{
case EASY:
cout << "Easy\n";
break;
case MEDIUM:
cout << "Medium\n";
break;
case HARD:
cout << "Hard\n";
break;
default:
cout << "Invalid Selection\n";
break;
}
If you have your text in your_text
variable, you can use:
your_text[0..29]
If you want a generic solution using MutationObserver you can use this function
// MIT Licensed
// Author: jwilson8767
/**
* Waits for an element satisfying selector to exist, then resolves promise with the element.
* Useful for resolving race conditions.
*
* @param selector
* @returns {Promise}
*/
export function elementReady(selector) {
return new Promise((resolve, reject) => {
const el = document.querySelector(selector);
if (el) {resolve(el);}
new MutationObserver((mutationRecords, observer) => {
// Query for elements matching the specified selector
Array.from(document.querySelectorAll(selector)).forEach((element) => {
resolve(element);
//Once we have resolved we don't need the observer anymore.
observer.disconnect();
});
})
.observe(document.documentElement, {
childList: true,
subtree: true
});
});
}
Source: https://gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e
Example how to use it
elementReady('#someWidget').then((someWidget)=>{someWidget.remove();});
Note: MutationObserver has a great browser support; https://caniuse.com/#feat=mutationobserver
Et voilà ! :)
Implement IEquatable<T>
(typically in conjunction with overriding the inherited Object.Equals
and Object.GetHashCode
methods) on all your custom types. In the case of composite types, invoke the contained types’ Equals
method within the containing types. For contained collections, use the SequenceEqual
extension method, which internally calls IEquatable<T>.Equals
or Object.Equals
on each element. This approach will obviously require you to extend your types’ definitions, but its results are faster than any generic solutions involving serialization.
Edit: Here is a contrived example with three levels of nesting.
For value types, you can typically just call their Equals
method. Even if the fields or properties were never explicitly assigned, they would still have a default value.
For reference types, you should first call ReferenceEquals
, which checks for reference equality – this would serve as an efficiency boost when you happen to be referencing the same object. It would also handle cases where both references are null. If that check fails, confirm that your instance's field or property is not null (to avoid NullReferenceException
) and call its Equals
method. Since our members are properly typed, the IEquatable<T>.Equals
method gets called directly, bypassing the overridden Object.Equals
method (whose execution would be marginally slower due to the type cast).
When you override Object.Equals
, you’re also expected to override Object.GetHashCode
; I didn’t do so below for the sake of conciseness.
public class Person : IEquatable<Person>
{
public int Age { get; set; }
public string FirstName { get; set; }
public Address Address { get; set; }
public override bool Equals(object obj)
{
return this.Equals(obj as Person);
}
public bool Equals(Person other)
{
if (other == null)
return false;
return this.Age.Equals(other.Age) &&
(
object.ReferenceEquals(this.FirstName, other.FirstName) ||
this.FirstName != null &&
this.FirstName.Equals(other.FirstName)
) &&
(
object.ReferenceEquals(this.Address, other.Address) ||
this.Address != null &&
this.Address.Equals(other.Address)
);
}
}
public class Address : IEquatable<Address>
{
public int HouseNo { get; set; }
public string Street { get; set; }
public City City { get; set; }
public override bool Equals(object obj)
{
return this.Equals(obj as Address);
}
public bool Equals(Address other)
{
if (other == null)
return false;
return this.HouseNo.Equals(other.HouseNo) &&
(
object.ReferenceEquals(this.Street, other.Street) ||
this.Street != null &&
this.Street.Equals(other.Street)
) &&
(
object.ReferenceEquals(this.City, other.City) ||
this.City != null &&
this.City.Equals(other.City)
);
}
}
public class City : IEquatable<City>
{
public string Name { get; set; }
public override bool Equals(object obj)
{
return this.Equals(obj as City);
}
public bool Equals(City other)
{
if (other == null)
return false;
return
object.ReferenceEquals(this.Name, other.Name) ||
this.Name != null &&
this.Name.Equals(other.Name);
}
}
Update: This answer was written several years ago. Since then, I've started to lean away from implementing IEquality<T>
for mutable types for such scenarios. There are two notions of equality: identity and equivalence. At a memory representation level, these are popularly distinguished as “reference equality” and “value equality” (see Equality Comparisons). However, the same distinction can also apply at a domain level. Suppose that your Person
class has a PersonId
property, unique per distinct real-world person. Should two objects with the same PersonId
but different Age
values be considered equal or different? The answer above assumes that one is after equivalence. However, there are many usages of the IEquality<T>
interface, such as collections, that assume that such implementations provide for identity. For example, if you're populating a HashSet<T>
, you would typically expect a TryGetValue(T,T)
call to return existing elements that share merely the identity of your argument, not necessarily equivalent elements whose contents are completely the same. This notion is enforced by the notes on GetHashCode
:
In general, for mutable reference types, you should override
GetHashCode()
only if:
- You can compute the hash code from fields that are not mutable; or
- You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.
For me it was an error in my path. You should directly call the script using the directory where it is stored.
C:\Users\YourUserName\AppData\Local\Programs\Python\Python36\Scripts\pip install requests
And for running python scripts you can do this:
C:\Users\Avanish\AppData\Local\Programs\Python\Python36\python -m pip install requests
For SQL 2008 and newer, a more concise method, coding-wise, to detect index existence is by using the INDEXPROPERTY
built-in function:
INDEXPROPERTY ( object_ID , index_or_statistics_name , property )
The simplest usage is with the IndexID
property:
If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexID') Is Null
If the index exists, the above will return its ID; if it doesn't, it will return NULL
.
Select team in the general settings of the target
One thing that's definitely wrong in the function which forms the original question in this thread, which I haven't seen anyone mention, is that it is concatenating extra characters onto the end of the string literal that has been passed in as a parameter. This will give unpredictable results. In the example call of the function, the string literal "Hello" will be hard-coded into the program, so presumably concatenating onto the end of it will dangerously write over code. If you want to return a string which is bigger than the original then you need to make sure you allocate it dynamically and then delete it in the calling code when you're done.