You were close. This will work:
.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }
You needed to put the :hover
on image, and make the .overlay
cover the whole image by adding right:0;
and bottom:0
.
jsfiddle: http://jsfiddle.net/Zf5am/569/
Update for 4.0
Android 4.0.3 Platform
Arabic, Egypt (ar_EG)
Arabic, Israel (ar_IL)
Bulgarian, Bulgaria (bg_BG)
Catalan, Spain (ca_ES)
Chinese, PRC (zh_CN)
Chinese, Taiwan (zh_TW)
Croatian, Croatia (hr_HR)
Czech, Czech Republic (cs_CZ)
Danish, Denmark(da_DK)
Dutch, Belgium (nl_BE)
Dutch, Netherlands (nl_NL)
English, Australia (en_AU)
English, Britain (en_GB)
English, Canada (en_CA)
English, India (en_IN)
English, Ireland (en_IE)
English, New Zealand (en_NZ)
English, Singapore(en_SG)
English, South Africa (en_ZA)
English, US (en_US)
Finnish, Finland (fi_FI)
French, Belgium (fr_BE)
French, Canada (fr_CA)
French, France (fr_FR)
French, Switzerland (fr_CH)
German, Austria (de_AT)
German, Germany (de_DE)
German, Liechtenstein (de_LI)
German, Switzerland (de_CH)
Greek, Greece (el_GR)
Hebrew, Israel (he_IL)
Hindi, India (hi_IN)
Hungarian, Hungary (hu_HU)
Indonesian, Indonesia (id_ID)
Italian, Italy (it_IT)
Italian, Switzerland (it_CH)
Japanese (ja_JP)
Korean (ko_KR)
Latvian, Latvia (lv_LV)
Lithuanian, Lithuania (lt_LT)
Norwegian bokmål, Norway (nb_NO)
Polish (pl_PL)
Portuguese, Brazil (pt_BR)
Portuguese, Portugal (pt_PT)
Romanian, Romania (ro_RO)
Russian (ru_RU)
Serbian (sr_RS)
Slovak, Slovakia (sk_SK)
Slovenian, Slovenia (sl_SI)
Spanish (es_ES)
Spanish, US (es_US)
Swedish, Sweden (sv_SE)
Tagalog, Philippines (tl_PH)
Thai, Thailand (th_TH)
Turkish, Turkey (tr_TR)
Ukrainian, Ukraine (uk_UA)
Vietnamese, Vietnam (vi_VN)
SOURCE: http://us.dinodirect.com/Forum/Latest-Posts-5/Android-Versions-and-their-Locales-1-86587/
Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945
Also, the Angular docs now have a cookbook example that uses a Subject.
Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.
Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.
nav.service.ts
import {EventEmitter} from 'angular2/core';
export class NavService {
navchange: EventEmitter<number> = new EventEmitter();
constructor() {}
emitNavChangeEvent(number) {
this.navchange.emit(number);
}
getNavChangeEmitter() {
return this.navchange;
}
}
components.ts
import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';
@Component({
selector: 'obs-comp',
template: `obs component, item: {{item}}`
})
export class ObservingComponent {
item: number = 0;
subscription: any;
constructor(private navService:NavService) {}
ngOnInit() {
this.subscription = this.navService.getNavChangeEmitter()
.subscribe(item => this.selectedNavItem(item));
}
selectedNavItem(item: number) {
this.item = item;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
@Component({
selector: 'my-nav',
template:`
<div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
<div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
`,
})
export class Navigation {
item = 1;
constructor(private navService:NavService) {}
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this.navService.emitNavChangeEvent(item);
}
}
Multiple things can cause this, I didn't bother to check your entire repository, so I'm going out on a limb here.
First off, you could be missing an annotation (@Service or @Component) from the implementation of com.example.my.services.user.UserService
, if you're using annotations for configuration. If you're using (only) xml, you're probably missing the <bean>
-definition for the UserService-implementation.
If you're using annotations and the implementation is annotated correctly, check that the package where the implementation is located in is scanned (check your <context:component-scan base-package=
-value).
If you have phpMyAdmin installed use its Search feature.
Select your DataBase.
Be sure you do have selected DataBase, not a table, otherwise you'll get a completely different search dialog.
Thank to Brian for the code. I was trying to connect to the sql server with {call spname(?,?)}
and I got errors, but when I change my code to exec sp...
it works very well.
I post my code in hope this helps others with problems like mine:
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?,?,?,?,?,?");
cs.setEscapeProcessing(true);
cs.setQueryTimeout(90);
cs.setString(1, "valueA");
cs.setString(2, "valueB");
cs.setString(3, "0418");
//commented, because no need to register parameters out!, I got results from the resultset.
//cs.registerOutParameter(1, Types.VARCHAR);
//cs.registerOutParameter(2, Types.VARCHAR);
rs = cs.executeQuery();
ArrayList<ObjectX> listaObjectX = new ArrayList<ObjectX>();
while (rs.next()) {
ObjectX to = new ObjectX();
to.setFecha(rs.getString(1));
to.setRefId(rs.getString(2));
to.setRefNombre(rs.getString(3));
to.setUrl(rs.getString(4));
listaObjectX.add(to);
}
return listaObjectX;
} catch (SQLException se) {
System.out.println("Error al ejecutar SQL"+ se.getMessage());
se.printStackTrace();
throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
@Annk you can make a variable in the __component.ts file
myImage : string = "http://example.com/path/image.png";
and inside the __.component.html file you can use one of those 3 methods :
1 .
<div> <img src="{{myImage}}"> </div>
2 .
<div> <img [src]="myImage"/> </div>
3 .
<div> <img bind-src="myImage"/> </div>
For me to get rid of this error, I needed to delete the Pods
directory and delete the Podfile.lock
file.
I don't know how was the plugin the time the question was asked (2010), but I faced the same problem today and solved it this way:
Give your select tag a name attribute. For example in this case
<select name="myselect">
Instead of working with the attribute value="default" in the tag option, disable the default option or set value="" as suggested by Andrew Coats
<option disabled="disabled">Choose...</option>
or
<option value="">Choose...</option>
Set the plugin validation rule
$( "#YOUR_FORM_ID" ).validate({
rules: {
myselect: { required: true }
}
});
or
<select name="myselect" class="required">
Obs: Andrew Coats' solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.
Hope it helps! :)
You can use floats for pushing content down:
You have a fixed size container:
#container {
width: 300px; height: 300px;
}
Content is allowed to flow next to a float. Unless we set the float to full width:
#up {
float: left;
width: 100%;
}
While #up
and #down
share the top position, #down
's content can only start after the bottom of the floated #up
:
#down {
height:100%;
}?
I am going to assume you were having the same issue I was. Even though you specify larger sizes for the TextBox and mark it as important, the box would not get larger. That is likely because in your site.css file the MaxWidth is being set to 280px.
Add a style attribute to your input to remove the MaxWidth like this:
<input type="text" style="max-width:none !important" class="input-medium">
The following shows an example of a shared class library shared.[h,cpp] and a main.cpp module using the library. It's a very simple example and the makefile could be made much better. But it works and may help you:
shared.h defines the class:
class myclass {
int myx;
public:
myclass() { myx=0; }
void setx(int newx);
int getx();
};
shared.cpp defines the getx/setx functions:
#include "shared.h"
void myclass::setx(int newx) { myx = newx; }
int myclass::getx() { return myx; }
main.cpp uses the class,
#include <iostream>
#include "shared.h"
using namespace std;
int main(int argc, char *argv[])
{
myclass m;
cout << m.getx() << endl;
m.setx(10);
cout << m.getx() << endl;
}
and the makefile that generates libshared.so and links main with the shared library:
main: libshared.so main.o
$(CXX) -o main main.o -L. -lshared
libshared.so: shared.cpp
$(CXX) -fPIC -c shared.cpp -o shared.o
$(CXX) -shared -Wl,-soname,libshared.so -o libshared.so shared.o
clean:
$rm *.o *.so
To actual run 'main' and link with libshared.so you will probably need to specify the load path (or put it in /usr/local/lib or similar).
The following specifies the current directory as the search path for libraries and runs main (bash syntax):
export LD_LIBRARY_PATH=.
./main
To see that the program is linked with libshared.so you can try ldd:
LD_LIBRARY_PATH=. ldd main
Prints on my machine:
~/prj/test/shared$ LD_LIBRARY_PATH=. ldd main
linux-gate.so.1 => (0xb7f88000)
libshared.so => ./libshared.so (0xb7f85000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7e74000)
libm.so.6 => /lib/libm.so.6 (0xb7e4e000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb7e41000)
libc.so.6 => /lib/libc.so.6 (0xb7cfa000)
/lib/ld-linux.so.2 (0xb7f89000)
const
is pointless when the argument is passed by value since you will not be modifying the caller's object.
Wrong.
It's about self-documenting your code and your assumptions.
If your code has many people working on it and your functions are non-trivial then you should mark const
any and everything that you can. When writing industrial-strength code, you should always assume that your coworkers are psychopaths trying to get you any way they can (especially since it's often yourself in the future).
Besides, as somebody mentioned earlier, it might help the compiler optimize things a bit (though it's a long shot).
-For me, the fix was to change the output path in the build tab.
I changed the output path to bin\
and the error went away.
-Another fix could be that you have the wrong start up project set.
Multiple box shadows did it for me.
box-shadow:
inset 0 -8px 4px 4px rgb(255,255,255),
inset 0 2px 4px 0px rgba(50, 50, 50, 0.75);
If you are using sass as style preprocessor, you can switch back to native Sass compiler for dev dependency by:
npm install node-sass --save-dev
So that you can keep using /deep/ for development.
Get is supposed to return, one and exactly one record, to fix this use filter()
, and then take first element of the queryset returned to get the object you were expecting from get, also it would be useful to check if atleast one record is returned before taking out the first element to avoid IndexError
points
or lines
comes handy if
y2
is generated later, orx
but still should go into the same coordinate system.As your y
s share the same x
, you can also use matplot
:
matplot (x, cbind (y1, y2), pch = 19)
(without the pch
matplopt
will plot the column numbers of the y
matrix instead of dots).
arrays store their size in a local variable called 'length'. Given an array named "a" you could use the following to reference the last index without knowing the index value
a[a.length-1]
to assign a value of 5 to this last index you would use:
a[a.length-1]=5;
If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.
Try this CSS:
body {
margin: 0;
padding: 0;
}
.logo {
float: left;
}
/* ~~ Top Navigation Bar ~~ */
#navigation-container {
width: 1200px;
margin: 0 auto;
height: 70px;
}
.navigation-bar {
background-color: #352d2f;
height: 70px;
width: 100%;
}
#navigation-container img {
float: left;
}
#navigation-container ul {
padding: 0px;
margin: 0px;
text-align: center;
display:inline-block;
}
#navigation-container li {
list-style-type: none;
padding: 0px;
height: 24px;
margin-top: 4px;
margin-bottom: 4px;
display: inline;
}
#navigation-container li a {
color: white;
font-size: 16px;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
text-decoration: none;
line-height: 70px;
padding: 5px 15px;
opacity: 0.7;
}
#menu {
float: right;
}
Keep in mind that the for-loop and foreach-loop are not always equivalent. List enumerators will throw an exception if the list changes, but you won't always get that warning with a normal for loop. You might even get a different exception if the list changes at just the wrong time.
To add to MattDMo's answer, you can get the exact font that's used on Linux like so (the example is from Xubuntu 14.04):
$ fc-match Monospace
DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
use DECIMAL()
or NUMERIC()
as they are fixed precision and scale numbers.
SELECT fullName,
CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info
ORDER BY _totalBal DESC
This issue come when I am using PHP as server side language and the work around was to generate base64 enconding of my image before sending the result to client
$path = 'E:/pat/rwanda.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I think may give someone idea to create his own work around
Thanks
I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:
Hope that helps!
If you combine the answers above, finally a pom.xml that configured for UTF-8 should seem like that.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>YOUR_COMPANY</groupId>
<artifactId>YOUR_APP</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<project.java.version>1.8</project.java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!-- Your dependencies -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${project.java.version}</source>
<target>${project.java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.
We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.
It goes like ng-bind-html-unsafe="opt.text"
:
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
{{ opt.text }}
</li>
</ul>
<p>{{opt}}</p>
</div>
Or you can define a function in scope:
$scope.getContent = function(obj){
return obj.value + " " + obj.text;
}
And use it this way:
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="getContent(opt)" >
{{ opt.value }}
</li>
Note that you can not do it with an option
tag: Can I use HTML tags in the options for select elements?
Presumably you want this conversion for using functions from the C standard library.
In that case, do (C++ syntax)
typedef unsigned char UChar;
char myCppFunc( char c )
{
return char( someCFunc( UChar( c ) ) );
}
The expression UChar( c )
converts to unsigned char
in order to get rid of negative values, which, except for EOF, are not supported by the C functions.
Then the result of that expression is used as actual argument for an int
formal argument. Where you get automatic promotion to int
. You can alternatively write that last step explicitly, like int( UChar( c ) )
, but personally I find that too verbose.
Cheers & hth.,
When would you use Session Beans or Message Driven Beans ?
How are transactions handled in session beans ?
What is the difference between local and remote session beans ? This question is more about knowing that RPCs are in the picture or not, since a method that is exposed as both Local or Remote might still work differently (side-effects on parameters are possible with Locals, while not possible with Remotes).
A good test is: never ask the questions in the same order. We had the experience with offshoring that sometimes they were actually giving the response in the wrong order :-). As a result you should make sure that you can actually see the person you are interrogating.
You can probably put something together with Tables table. I've never done it, but it looks like it has a column for TABLE_ROWS and one for TABLE NAME.
To get rows per table, you can use a query like this:
SELECT table_name, table_rows
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '**YOUR SCHEMA**';
<property name="cronExpression" value="0 0/30 * * * ?" />
I think the simplest way to achieve your goal is this:
var str = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);
<ion-col size="12">
<ion-card class="box-shadow ion-text-center background-size"
*ngIf="data != null"
[ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">
</ion-card>
It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.
Also, related question
They're just trawling lists of web sites, and recording the resulting IP addresses in a database.
All you're seeing is the reverse mapping of that list. It's not guaranteed to be a full list (indeed more often than not it won't be) because it's impossible to learn every possible web site address.
Use the createFromFormat
method:
$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);
UPDATE
I now recommend the use of Carbon
I had to specify user name to work on 1.7.1 git version:
git remote set-url origin https://[email protected]/org/project.git
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
There is absolutely nothing wrong with the code you've written. Both some_function
and someVar
should be accessible, in case they were available in the context where anonymous
function() { some_function(someVar); }
was created.
Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar
variable next to the call to addEventListener
)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
A SortedMap
is the logical/best choice, however another option is to use a LinkedHashMap
which maintains two order modes, most-recently-added goes last, and most-recently-accessed goes last. See the Javadocs for more details.
I will tell , how i solved almost similar problem. I developed a application using VS 2013 and tried to create wizard for it failed to do. Later i installed premium VS and tried and failed.
at last i used "ClickOnce" and it worked fine.
So i believe here also , "CLICKONCE" would help you.
Your android app needs to correct 12-digit number id (aka GCM Project Number). If this 12-digit number is incorrect, then you will also get this error.
This 12-digit number is found in your Google Play Console under your specific app, 'Service & API' -> 'LINKED SENDER IDS'
What about using the a
option?
According to the docs:
'a+' - Open file for reading and appending. The file is created if it does not exist.
It seems to work perfectly with createWriteStream
Finally decided to downgrade the junit 5 to junit 4 and rebuild the testing environment.
For a completely stateless utility class in Java, I suggest the class be declared public
and final
, and have a private constructor to prevent instantiation. The final
keyword prevents sub-classing and can improve efficiency at runtime.
The class should contain all static
methods and should not be declared abstract
(as that would imply the class is not concrete and has to be implemented in some way).
The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).
The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).
Methods in the class should have appropriate names.
Methods only used by the class itself should be private.
The class should not have any non-final/non-static class fields.
The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).
Example:
public final class ExampleUtilities {
// Example Utility method
public static int foo(int i, int j) {
int val;
//Do stuff
return val;
}
// Example Utility method overloaded
public static float foo(float i, float j) {
float val;
//Do stuff
return val;
}
// Example Utility method calling private method
public static long bar(int p) {
return hid(p) * hid(p);
}
// Example private method
private static long hid(int i) {
return i * 2 + 1;
}
}
Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.
This isn't exactly what the question is asking for but in case you accidentally saved basic auth credentials and want to clear them or update them:
https://support.google.com/accounts/answer/6197437
Steps 1-4 can be quickly navigated with this link: chrome://settings/passwords
This worked in Chrome Version 59.0.3071.115
check
System.getProperty("sun.jnu.encoding")
it seems to be the same encoding as the one used in your system's command line.
Here is a lattice version:
library(lattice)
eq<-function(x) {x*x}
X<-1:1000
xyplot(eq(X)~X,type="l")
Try this (I've used Home controller and Index View):
return RedirectToAction("Index", "Home");
You can just cast the WebRequest to an HttpWebRequest showed below:
var request = (HttpWebRequest)WebRequest.Create(myUri);
and then instead of trying to manipulate the header list, apply it directly in the request property request.Referer:
request.Referer = "yourReferer";
These properties are available in the request object.
If you have arrived at this question three years after its initial posting because this is still a problem for you, consider backing this proposal to support a new BUILD_PATH
environment variable.
https://github.com/facebook/create-react-app/pull/8986
From the proposal's documentation:
By default, Create React App will output compiled assets to a
/build
directory adjacent to/src
. You may use this variable to specify a new path for Create React App to output assets.BUILD_PATH
should be specified as a path relative to the root of your project.
If this proposal is adopted, it would mean that customizing the output target for create-react-app becomes as simple as updating updating your build script:
// package.json
"scripts": {
"build": "BUILD_PATH='./dist' react-scripts build",
// ...
},
or adding a .env file to the root of your project:
# .env
BUILD_PATH='./dist'
I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:
#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl
def runMacro():
if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):
# DispatchEx is required in the newest versions of Python.
excel_macro = wincl.DispatchEx("Excel.application")
excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
excel_macro.Application.Run\
("ThisWorkbook.Template2G")
#Save the results in case you have generated data
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
The best way to get filetype-specific indentation is to use filetype plugin indent on
in your vimrc. Then you can specify things like set sw=4 sts=4 et
in .vim/ftplugin/c.vim, for example, without having to make those global for all files being edited and other non-C type syntaxes will get indented correctly, too (even lisps).
I had pip
referring by default to pip3, which made me download the libs for python3. On the contrary I launched the shell as python
(which opened python 2) and the library wasn't installed there obviously.
Once I matched the names pip3 -> python3, pip -> python (2) all worked.
Okay try this, simple and for IE11 and IE below 11 version
browserIsIE = navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 || navigator.userAgent.toUpperCase().indexOf("MSIE") != -1;
navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1
for IE 11 version
navigator.userAgent.toUpperCase().indexOf("MSIE") != -1
for IE below 11 version
browserIsIE = navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 || navigator.userAgent.toUpperCase().indexOf("MSIE") != -1;_x000D_
_x000D_
console.log('Is IE Browser : '+ browserIsIE)
_x000D_
In Oracle SQL,
select * from (select row_number() over (order by rowid desc) rn, emp.* from emp) where rn=1;
This is the easier way I had ever found. Fast and only two lines of code :-D
$keys = array_keys($array);
echo $array[$keys[0]];
Just for sake of completeness, you can also use the same technique above with excel tables.
In the example below, I'm looking of a text in any cell of a Excel Table named "tblConfig", place in the sheet named Config that normally is set to be hidden. I'm accepting the defaults of the Find method.
Dim list As ListObject
Dim config As Worksheet
Dim cell as Range
Set config = Sheets("Config")
Set list = config.ListObjects("tblConfig")
'search in any cell of the data range of excel table
Set cell = list.DataBodyRange.Find(searchTerm)
If cell Is Nothing Then
'when information is not found
Else
'when information is found
End If
No need to import anything when using lambda functions.
The following sorts list
by the first element, then by the second element.
sorted(list, key=lambda x: (x[0], -x[1]))
You could try using the -Clear
parameter
Example:-Clear Attribute1LDAPDisplayName, Attribute2LDAPDisplayName
also had same problem once,
if you are unable to solve the problem you can run the following command on command line
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
Note: you have to navigate to the installation path of your chrome.
For example:cd C:\Program Files\Google\Chrome\Application
A developer session chrome browser will be opened, you can now launch your app on the new chrome browse.
I hope this should be helpful
Activation by system properties can be done as follows
<activation>
<property>
<name>foo</name>
<value>bar</value>
</property>
</activation>
And run the mvn build with -D to set system property
mvn clean install -Dfoo=bar
This method also helps select profiles in transitive dependency of project artifacts.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dt As New DataTable
Dim dc As DataColumn
dc = New DataColumn("Question", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("Ans1", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("Ans2", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("Ans3", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("Ans4", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
dc = New DataColumn("AnsType", System.Type.GetType("System.String"))
dt.Columns.Add(dc)
Dim Dr As DataRow
Dr = dt.NewRow
Dr("Question") = "What is Your Name"
Dr("Ans1") = "Ravi"
Dr("Ans2") = "Mohan"
Dr("Ans3") = "Sohan"
Dr("Ans4") = "Gopal"
Dr("AnsType") = "Multi"
dt.Rows.Add(Dr)
Dr = dt.NewRow
Dr("Question") = "What is your father Name"
Dr("Ans1") = "Ravi22"
Dr("Ans2") = "Mohan2"
Dr("Ans3") = "Sohan2"
Dr("Ans4") = "Gopal2"
Dr("AnsType") = "Multi"
dt.Rows.Add(Dr)
Panel1.GrowStyle = TableLayoutPanelGrowStyle.AddRows
Panel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
Panel1.BackColor = Color.Azure
Panel1.RowStyles.Insert(0, New RowStyle(SizeType.Absolute, 50))
Dim i As Integer = 0
For Each dri As DataRow In dt.Rows
Dim lab As New Label()
lab.Text = dri("Question")
lab.AutoSize = True
Panel1.Controls.Add(lab, 0, i)
Dim Ans1 As CheckBox
Ans1 = New CheckBox()
Ans1.Text = dri("Ans1")
Panel1.Controls.Add(Ans1, 1, i)
Dim Ans2 As RadioButton
Ans2 = New RadioButton()
Ans2.Text = dri("Ans2")
Panel1.Controls.Add(Ans2, 2, i)
i = i + 1
'Panel1.Controls.Add(Pan)
Next
It's been a while since this was posted but I found a more elegant solution if you are not needing to support old browsers.
You can do a check with
performance.navigation.type
Documentation including browser support is here: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
So to see if the page was loaded from history using back you can do
if(performance.navigation.type == 2){
location.reload(true);
}
The 2
indicates the page was accessed by navigating into the history. Other possibilities are-
0:
The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.
1:
The page was accessed by clicking the Reload button or via the Location.reload() method.
255:
Any other way
These are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation
Note Performance.navigation.type is now deprecated in favour of PerformanceNavigationTiming.type which returns 'navigate' / 'reload' / 'back_forward' / 'prerender': https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type
Just a recommendation:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
There are situations where you can't use the (quite convincing) with... for...
structure. In that case, do the following:
line = self.fo.readline()
if len(line) != 0:
if 'str' in line:
break
This will work because the the readline()
leaves a trailing newline character, where as EOF is just an empty string.
Using str.format
:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1
or using format
>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1
Note: In the format statements, the
02
means it will pad with up to 2 leading0
s if necessary. This is important since[0x1, 0x1, 0x1] i.e. (0x010101)
would be formatted to"111"
instead of"010101"
or using bytearray
with binascii.hexlify
:
>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'
Here is a benchmark of above methods in Python 3.6.1:
from timeit import timeit
import binascii
number = 10000
def using_str_format() -> str:
return "".join("{:02x}".format(x) for x in test_obj)
def using_format() -> str:
return "".join(format(x, "02x") for x in test_obj)
def using_hexlify() -> str:
return binascii.hexlify(bytearray(test_obj)).decode('ascii')
def do_test():
print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
if using_str_format() != using_format() != using_hexlify():
raise RuntimeError("Results are not the same")
print("Using str.format -> " + str(timeit(using_str_format, number=number)))
print("Using format -> " + str(timeit(using_format, number=number)))
print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))
test_obj = bytes([i for i in range(255)])
do_test()
test_obj = bytearray([i for i in range(255)])
do_test()
Result:
Testing with 255-byte bytes:
Using str.format -> 1.459474583090427
Using format -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format -> 1.443447684109402
Using format -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684
Methods using format
do provide additional formatting options, as example separating numbers with spaces " ".join
, commas ", ".join
, upper-case printing "{:02X}".format(x)
/format(x, "02X")
, etc., but at a cost of great performance impact.
I know this is an old question, but nobody mentioned that when your data looks like an array, numpy's loadtxt comes in handy:
>>> import numpy as np
>>> np.loadtxt("myfile.txt")[:, 1]
array([10., 20., 30., 40., 23., 13.])
As of this writing, in OS X, it will usually look like this
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files
If you are a freak like me, and put your apps in ~/Applications
, then it will be
"/Users/yougohere/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files
If neither of those are working, then type chrome://version
in your Chrome address bar, and it will tell you what "command line" invocation you should be using. Just add --allow-file-access-from-files
to that.
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
Perhaps the easiest way would be to add an image, scale it, and set it to the JFrame/JPanel (in my case JPanel) but remember to "add" it to the container only after you've added the other children components.
ImageIcon background=new ImageIcon("D:\\FeedbackSystem\\src\\images\\background.jpg");
Image img=background.getImage();
Image temp=img.getScaledInstance(500,600,Image.SCALE_SMOOTH);
background=new ImageIcon(temp);
JLabel back=new JLabel(background);
back.setLayout(null);
back.setBounds(0,0,500,600);
Well, this answer has become its own beast. Many new versions, it was getting stupid long. Many thanks to all of the great many contributors to this answer. But, in order to keep it simple for the masses. I archived all the versions/history of this answer's evolution to my github. And started it over clean on StackOverflow here with the newest version. A special thanks goes out to Mike 'Pomax' Kamermans for this version. He gave me the new math.
This function (pSBC
) will take a HEX or RGB web color. pSBC
can shade it darker or lighter, or blend it with a second color, and can also pass it right thru but convert from Hex to RGB (Hex2RGB) or RGB to Hex (RGB2Hex). All without you even knowing what color format you are using.
This runs really fast, probably the fastest, especially considering its many features. It was a long time in the making. See the whole story on my github. If you want the absolutely smallest and fastest possible way to shade or blend, see the Micro Functions below and use one of the 2-liner speed demons. They are great for intense animations, but this version here is fast enough for most animations.
This function uses Log Blending or Linear Blending. However, it does NOT convert to HSL to properly lighten or darken a color. Therefore, results from this function will differ from those much larger and much slower functions that use HSL.
Features:
"#AA6622"
or "#bb551144"
."rgb(123,45,76)"
or "rgba(45,15,74,0.45)"
."#C41"
becomes "#CC4411"
.c0
(from) color or the c1
(to) color has an alpha channel, then the returned color will have an alpha channel. If both colors have an alpha channel, then the returned color will be a linear blend of the two alpha channels using the percentage given (just as if it were a normal color channel). If only one of the two colors has an alpha channel, this alpha will just be passed thru to the returned color. This allows one to blend/shade a transparent color while maintaining the transparency level. Or, if the transparency levels should blend as well, make sure both colors have alphas. When shading, it will pass the alpha channel straight thru. If you want basic shading that also shades the alpha channel, then use rgb(0,0,0,1)
or rgb(255,255,255,1)
as your c1
(to) color (or their hex equivalents). For RGB colors, the returned color's alpha channel will be rounded to 3 decimal places.c0
(from) color; the returned color will always be in the color format of the c1
(to) color, if one exists. If there is no c1
(to) color, then pass 'c'
in as the c1
color and it will shade and convert whatever the c0
color is. If conversion only is desired, then pass 0
in as the percentage (p
) as well. If the c1
color is omitted or a non-string
is passed in, it will not convert.pSBCr
can be passed a Hex or RGB color and it returns an object containing this color information. Its in the form: {r: XXX, g: XXX, b: XXX, a: X.XXX}. Where .r
, .g
, and .b
have range 0 to 255. And when there is no alpha: .a
is -1. Otherwise: .a
has range 0.000 to 1.000.rgba()
over rgb()
when a color with an alpha channel was passed into c0
(from) and/or c1
(to).null
. An example: pSBC(0.5,"salt") == null
, where as it thinks #salt
is a valid color. Delete the four lines which end with return null;
to remove this feature and make it faster and smaller.true
in for l
(the 4th parameter) to use Linear Blending.// Version 4.0
const pSBC=(p,c0,c1,l)=>{
let r,g,b,P,f,t,h,i=parseInt,m=Math.round,a=typeof(c1)=="string";
if(typeof(p)!="number"||p<-1||p>1||typeof(c0)!="string"||(c0[0]!='r'&&c0[0]!='#')||(c1&&!a))return null;
if(!this.pSBCr)this.pSBCr=(d)=>{
let n=d.length,x={};
if(n>9){
[r,g,b,a]=d=d.split(","),n=d.length;
if(n<3||n>4)return null;
x.r=i(r[3]=="a"?r.slice(5):r.slice(4)),x.g=i(g),x.b=i(b),x.a=a?parseFloat(a):-1
}else{
if(n==8||n==6||n<4)return null;
if(n<6)d="#"+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(n>4?d[4]+d[4]:"");
d=i(d.slice(1),16);
if(n==9||n==5)x.r=d>>24&255,x.g=d>>16&255,x.b=d>>8&255,x.a=m((d&255)/0.255)/1000;
else x.r=d>>16,x.g=d>>8&255,x.b=d&255,x.a=-1
}return x};
h=c0.length>9,h=a?c1.length>9?true:c1=="c"?!h:false:h,f=this.pSBCr(c0),P=p<0,t=c1&&c1!="c"?this.pSBCr(c1):P?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},p=P?p*-1:p,P=1-p;
if(!f||!t)return null;
if(l)r=m(P*f.r+p*t.r),g=m(P*f.g+p*t.g),b=m(P*f.b+p*t.b);
else r=m((P*f.r**2+p*t.r**2)**0.5),g=m((P*f.g**2+p*t.g**2)**0.5),b=m((P*f.b**2+p*t.b**2)**0.5);
a=f.a,t=t.a,f=a>=0||t>=0,a=f?a<0?t:t<0?a:a*P+t*p:0;
if(h)return"rgb"+(f?"a(":"(")+r+","+g+","+b+(f?","+m(a*1000)/1000:"")+")";
else return"#"+(4294967296+r*16777216+g*65536+b*256+(f?m(a*255):0)).toString(16).slice(1,f?undefined:-2)
}
// Setup:
let color1 = "rgb(20,60,200)";
let color2 = "rgba(20,60,200,0.67423)";
let color3 = "#67DAF0";
let color4 = "#5567DAF0";
let color5 = "#F3A";
let color6 = "#F3A9";
let color7 = "rgb(200,60,20)";
let color8 = "rgba(200,60,20,0.98631)";
// Tests:
/*** Log Blending ***/
// Shade (Lighten or Darken)
pSBC ( 0.42, color1 ); // rgb(20,60,200) + [42% Lighter] => rgb(166,171,225)
pSBC ( -0.4, color5 ); // #F3A + [40% Darker] => #c62884
pSBC ( 0.42, color8 ); // rgba(200,60,20,0.98631) + [42% Lighter] => rgba(225,171,166,0.98631)
// Shade with Conversion (use "c" as your "to" color)
pSBC ( 0.42, color2, "c" ); // rgba(20,60,200,0.67423) + [42% Lighter] + [Convert] => #a6abe1ac
// RGB2Hex & Hex2RGB Conversion Only (set percentage to zero)
pSBC ( 0, color6, "c" ); // #F3A9 + [Convert] => rgba(255,51,170,0.6)
// Blending
pSBC ( -0.5, color2, color8 ); // rgba(20,60,200,0.67423) + rgba(200,60,20,0.98631) + [50% Blend] => rgba(142,60,142,0.83)
pSBC ( 0.7, color2, color7 ); // rgba(20,60,200,0.67423) + rgb(200,60,20) + [70% Blend] => rgba(168,60,111,0.67423)
pSBC ( 0.25, color3, color7 ); // #67DAF0 + rgb(200,60,20) + [25% Blend] => rgb(134,191,208)
pSBC ( 0.75, color7, color3 ); // rgb(200,60,20) + #67DAF0 + [75% Blend] => #86bfd0
/*** Linear Blending ***/
// Shade (Lighten or Darken)
pSBC ( 0.42, color1, false, true ); // rgb(20,60,200) + [42% Lighter] => rgb(119,142,223)
pSBC ( -0.4, color5, false, true ); // #F3A + [40% Darker] => #991f66
pSBC ( 0.42, color8, false, true ); // rgba(200,60,20,0.98631) + [42% Lighter] => rgba(223,142,119,0.98631)
// Shade with Conversion (use "c" as your "to" color)
pSBC ( 0.42, color2, "c", true ); // rgba(20,60,200,0.67423) + [42% Lighter] + [Convert] => #778edfac
// RGB2Hex & Hex2RGB Conversion Only (set percentage to zero)
pSBC ( 0, color6, "c", true ); // #F3A9 + [Convert] => rgba(255,51,170,0.6)
// Blending
pSBC ( -0.5, color2, color8, true ); // rgba(20,60,200,0.67423) + rgba(200,60,20,0.98631) + [50% Blend] => rgba(110,60,110,0.83)
pSBC ( 0.7, color2, color7, true ); // rgba(20,60,200,0.67423) + rgb(200,60,20) + [70% Blend] => rgba(146,60,74,0.67423)
pSBC ( 0.25, color3, color7, true ); // #67DAF0 + rgb(200,60,20) + [25% Blend] => rgb(127,179,185)
pSBC ( 0.75, color7, color3, true ); // rgb(200,60,20) + #67DAF0 + [75% Blend] => #7fb3b9
/*** Other Stuff ***/
// Error Checking
pSBC ( 0.42, "#FFBAA" ); // #FFBAA + [42% Lighter] => null (Invalid Input Color)
pSBC ( 42, color1, color5 ); // rgb(20,60,200) + #F3A + [4200% Blend] => null (Invalid Percentage Range)
pSBC ( 0.42, {} ); // [object Object] + [42% Lighter] => null (Strings Only for Color)
pSBC ( "42", color1 ); // rgb(20,60,200) + ["42"] => null (Numbers Only for Percentage)
pSBC ( 0.42, "salt" ); // salt + [42% Lighter] => null (A Little Salt is No Good...)
// Error Check Fails (Some Errors are not Caught)
pSBC ( 0.42, "#salt" ); // #salt + [42% Lighter] => #a5a5a500 (...and a Pound of Salt is Jibberish)
// Ripping
pSBCr ( color4 ); // #5567DAF0 + [Rip] => [object Object] => {'r':85,'g':103,'b':218,'a':0.941}
The picture below will help show the difference in the two blending methods:
If you really want speed and size, you will have to use RGB not HEX. RGB is more straightforward and simple, HEX writes too slow and comes in too many flavors for a simple two-liner (IE. it could be a 3, 4, 6, or 8 digit HEX code). You will also need to sacrifice some features, no error checking, no HEX2RGB nor RGB2HEX. As well, you will need to choose a specific function (based on its function name below) for the color blending math, and if you want shading or blending. These functions do support alpha channels. And when both input colors have alphas it will Linear Blend them. If only one of the two colors has an alpha, it will pass it straight thru to the resulting color. Below are two liner functions that are incredibly fast and small:
const RGB_Linear_Blend=(p,c0,c1)=>{
var i=parseInt,r=Math.round,P=1-p,[a,b,c,d]=c0.split(","),[e,f,g,h]=c1.split(","),x=d||h,j=x?","+(!d?h:!h?d:r((parseFloat(d)*P+parseFloat(h)*p)*1000)/1000+")"):")";
return"rgb"+(x?"a(":"(")+r(i(a[3]=="a"?a.slice(5):a.slice(4))*P+i(e[3]=="a"?e.slice(5):e.slice(4))*p)+","+r(i(b)*P+i(f)*p)+","+r(i(c)*P+i(g)*p)+j;
}
const RGB_Linear_Shade=(p,c)=>{
var i=parseInt,r=Math.round,[a,b,c,d]=c.split(","),P=p<0,t=P?0:255*p,P=P?1+p:1-p;
return"rgb"+(d?"a(":"(")+r(i(a[3]=="a"?a.slice(5):a.slice(4))*P+t)+","+r(i(b)*P+t)+","+r(i(c)*P+t)+(d?","+d:")");
}
const RGB_Log_Blend=(p,c0,c1)=>{
var i=parseInt,r=Math.round,P=1-p,[a,b,c,d]=c0.split(","),[e,f,g,h]=c1.split(","),x=d||h,j=x?","+(!d?h:!h?d:r((parseFloat(d)*P+parseFloat(h)*p)*1000)/1000+")"):")";
return"rgb"+(x?"a(":"(")+r((P*i(a[3]=="a"?a.slice(5):a.slice(4))**2+p*i(e[3]=="a"?e.slice(5):e.slice(4))**2)**0.5)+","+r((P*i(b)**2+p*i(f)**2)**0.5)+","+r((P*i(c)**2+p*i(g)**2)**0.5)+j;
}
const RGB_Log_Shade=(p,c)=>{
var i=parseInt,r=Math.round,[a,b,c,d]=c.split(","),P=p<0,t=P?0:p*255**2,P=P?1+p:1-p;
return"rgb"+(d?"a(":"(")+r((P*i(a[3]=="a"?a.slice(5):a.slice(4))**2+t)**0.5)+","+r((P*i(b)**2+t)**0.5)+","+r((P*i(c)**2+t)**0.5)+(d?","+d:")");
}
Want more info? Read the full writeup on github.
PT
(P.s. If anyone has the math for another blending method, please share.)
Read up on the configuration settings (e.g., display_errors
, display_startup_errors
, log_errors
) and update your php.ini
or .htaccess
or .user.ini
file, whichever is appropriate.
It works.
In similar case I used: white-space: nowrap;
Just add <br>
where you would like to make the new line.
$S$: a set of shops
<br>
$I$: a set of items M wants to get
Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html
Note that newlines using <br>
does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br>
as a space.
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
Although I don't know what RDBMS you are using, you probably need to give the whole column specification, not just say that you now want it to be nullable. For example, if it's currently INT NOT NULL
, you should issue ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations INT
.
try this
using System.Drawing;
driver.Manage().Window.Size = new Size(width, height);
The Adjusted R-squared is close to, but different from, the value of R2. Instead of being based on the explained sum of squares SSR and the total sum of squares SSY, it is based on the overall variance (a quantity we do not typically calculate), s2T = SSY/(n - 1) and the error variance MSE (from the ANOVA table) and is worked out like this: adjusted R-squared = (s2T - MSE) / s2T.
This approach provides a better basis for judging the improvement in a fit due to adding an explanatory variable, but it does not have the simple summarizing interpretation that R2 has.
If I haven't made a mistake, you should verify the values of adjusted R-squared and R-squared as follows:
s2T <- sum(anova(v.lm)[[2]]) / sum(anova(v.lm)[[1]])
MSE <- anova(v.lm)[[3]][2]
adj.R2 <- (s2T - MSE) / s2T
On the other side, R2 is: SSR/SSY, where SSR = SSY - SSE
attach(v)
SSE <- deviance(v.lm) # or SSE <- sum((epm - predict(v.lm,list(n_days)))^2)
SSY <- deviance(lm(epm ~ 1)) # or SSY <- sum((epm-mean(epm))^2)
SSR <- (SSY - SSE) # or SSR <- sum((predict(v.lm,list(n_days)) - mean(epm))^2)
R2 <- SSR / SSY
#define INS(c) private:void operator=(c const&){};public:static c& I(){static c _instance;return _instance;}
Example:
class CCtrl
{
private:
CCtrl(void);
virtual ~CCtrl(void);
public:
INS(CCtrl);
I know this is old, but I was having this same issue, found this post, and while it didn't explain exactly what was wrong, it helped me to the right answer - so hopefully my answer helps someone else who might be having a similar problem to mine.
I had an element I wanted rotated vertical, so naturally I added the filter: for IE8 and then the -ms-transform property for IE9. What I found is that having the -ms-transform property AND the filter applied to the same element causes IE9 to render the element very poorly. My solution:
If you are using the transform-origin property, add one for MS too (-ms-transform-origin: left bottom;). If you don't see your element, it could be that it's rotating on it's middle axis and thus leaving the page somehow - so double check that.
Move the filter: property for IE7&8 to a separate style sheet and use an IE conditional to insert that style sheet for browsers less than IE9. This way it doesn't affect the IE9 styles and all should work fine.
Make sure to use the correct DOCTYPE tag as well; if you have it wrong IE9 will not work properly.
Update: Current Spring cache implementation uses all method parameters as the cache key if not specified otherwise. If you want to use selected keys, refer to Arjan's answer which uses SpEL list {#isbn, #includeUsed}
which is the simplest way to create unique keys.
From Spring Documentation
The default key generation strategy changed with the release of Spring 4.0. Earlier versions of Spring used a key generation strategy that, for multiple key parameters, only considered the hashCode() of parameters and not equals(); this could cause unexpected key collisions (see SPR-10237 for background). The new 'SimpleKeyGenerator' uses a compound key for such scenarios.
Before Spring 4.0
I suggest you to concat the values of the parameters in Spel expression with something like key="#checkWarehouse.toString() + #isbn.toString()")
, I believe this should work as org.springframework.cache.interceptor.ExpressionEvaluator returns Object, which is later used as the key so you don't have to provide an int
in your SPEL expression.
As for the hash code with a high collision probability - you can't use it as the key.
Someone in this thread has suggested to use T(java.util.Objects).hash(#p0,#p1, #p2)
but it WILL NOT WORK and this approach is easy to break, for example I've used the data from SPR-9377 :
System.out.println( Objects.hash("someisbn", new Integer(109), new Integer(434)));
System.out.println( Objects.hash("someisbn", new Integer(110), new Integer(403)));
Both lines print -636517714 on my environment.
P.S. Actually in the reference documentation we have
@Cacheable(value="books", key="T(someType).hash(#isbn)")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
I think that this example is WRONG and misleading and should be removed from the documentation, as the keys should be unique.
P.P.S. also see https://jira.springsource.org/browse/SPR-9036 for some interesting ideas regarding the default key generation.
I'd like to add for the sake of correctness and as an entertaining mathematical/computer science fact that unlike built-in hash, using a secure cryptographic hash function like MD5 or SHA256, due to the properties of such function IS absolutely possible for this task, but to compute it every time may be too expensive, checkout for example Dan Boneh cryptography course to learn more.
The above has a mix of correct answers. What worked for me for having the exact same errors are:
1) edit your bash config file
$ cd ~ && vim .bashrc
2) in your bash config file, make sure default editor is vim rather than vi (which causes the problem)
export EDITOR=vim
3) edit your vim config file
$cd ~ && vim .vimrc
4) make sure set backupcopy is yes in your .vimrc
set backupcopy=yes
5) restart terminal
6) now try crontab edit
$ crontab -e
10 * * * * echo "hello world"
You should see that it creates the crontab file correctly. If you exit vim (either ZZ or :wq) and list crontab with following command; you should see the new cron job. Hope this helps.
$ crontab -l
def random_items(array)
array.sample(1 + rand(array.count))
end
my_array = ["one", "two", "three"]
my_array.sample(1 + rand(my_array.count))
=> ["two", "three"]
=> ["one", "three", "two"]
=> ["two"]
%hash = map { $_ => 1 } @array;
It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.
What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.
Since your config file is a normal text file, just read it using the open
function:
file = open("abc.txt", 'r')
content = file.read()
paths = content.split("\n") #split it into lines
for path in paths:
print path.split(" = ")[1]
This will print your paths. You can also store them using dictionaries or lists.
path_list = []
path_dict = {}
for path in paths:
p = path.split(" = ")
path_list.append(p)[1]
path_dict[p[0]] = p[1]
More on reading/writing file here. Hope this helps!
You can find your sample code completely here: http://www.java2s.com/Code/Java/Hibernate/OneToManyMappingbasedonSet.htm
Have a look and check the differences. specially the even_id in :
<set name="attendees" cascade="all">
<key column="event_id"/>
<one-to-many class="Attendee"/>
</set>
Here's why you saw the menu with the code you listed in your onClick
method:
You were creating an Intent with the constructor that takes a string for the action parameter of the Intent
's IntentFilter
. You passed "android.intent.action.MAIN"
as the argument to that constructor, which specifies that the Intent
can be satisfied by any Activity
with an IntentFilter including <action="android.intent.action.MAIN">
.
When you called startActivity
with that Intent
, you effectively told the Android OS to go find an Activity
(in any app installed on the system) that specifies the android.intent.action.MAIN
action. When there are multiple Activities that qualify (and there are in this case since every app will have a main Activity
with an IntentFilter
including the "android.intent.action.MAIN"
action), the OS presents a menu to let the user choose which app to use.
As to the question of how to get back to your main activity, as with most things, it depends on the specifics of your app. While the accepted answer probably worked in your case, I don't think it's the best solution, and it's probably encouraging you to use a non-idiomatic UI in your Android app. If your Button
's onClick()
method contains only a call to finish()
then you should most likely remove the Button
from the UI and just let the user push the hardware/software back button, which has the same functionality and is idiomatic for Android. (You'll often see back Buttons used to emulate the behavior of an iOS UINavigationController navigationBar which is discouraged in Android apps).
If your main activity launches a stack of Activities and you want to provide an easy way to get back to the main activity without repeatedly pressing the back button, then you want to call startActivity
after setting the flag Intent.FLAG_ACTIVITY_CLEAR_TOP
which will close all the Activities in the call stack which are above your main activity and bring your main activity to the top of the call stack. See below (assuming your main activity subclass is called MainActivity:
btnReturn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
)};
You need to make sure that node
is in your PATH
. To set up your path, this out.
Make sure that the directory that has node.exe
is in your PATH
. Then you should be able to
run node path_to_js_file.js
.
For a good "Hello World" example, check out: http://howtonode.org/hello-node
This is the same solution as you have probably seen already, but by doing it this way it's more clearer:
>>> num = 3.141592654
>>> print(f"Number: {num:.2f}")
If you are using virtualenv, it is not as trivial to get the driver using the installer. What you can do then: install it as described by Devon. Then copy over cx_Oracle.pyd and the cx_Oracle-XXX.egg-info folder from Python\Lib\site-packages into the Lib\site-packages from your virtual env. Of course, also here, architecture and version are important.
Used below code to display custom list in AlertDialog
AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Select One Name:-");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Hardik");
arrayAdapter.add("Archit");
arrayAdapter.add("Jignesh");
arrayAdapter.add("Umang");
arrayAdapter.add("Gatti");
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String strName = arrayAdapter.getItem(which);
AlertDialog.Builder builderInner = new AlertDialog.Builder(DialogActivity.this);
builderInner.setMessage(strName);
builderInner.setTitle("Your Selected Item is");
builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
dialog.dismiss();
}
});
builderInner.show();
}
});
builderSingle.show();
Since Java 8 you can use the Math.floorMod() method:
Math.floorMod(-1, 2); //== 1
Note: If the modulo-value (here 2
) is negative, all output values will be negative too. :)
Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21"
to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
After reading the accepted answer's comments, I tried the robocopy command, which worked for me (using the standard command prompt from Windows 7 64 bits SP 1):
robocopy source_dir dest_dir /s /e
Pretty neat with seaborn for Python users:
>>> import seaborn as sns
>>> sns.color_palette(n_colors=4)
it returns list of RGB tuples:
[(0.12156862745098039, 0.4666666666666667, 0.7058823529411765),
(1.0, 0.4980392156862745, 0.054901960784313725),
(0.17254901960784313, 0.6274509803921569, 0.17254901960784313),
(0.8392156862745098, 0.15294117647058825, 0.1568627450980392)]
My issue was by putting wrong parameters in the header, the requested parameters was
Authorization: Token <string>
and is was trying
Authorization Token: <string>
As of 2018, there is also iText7 (A next iteration of old iTextSharp library) and its HTML to PDF package available: itext7.pdfhtml
Usage is straightforward:
HtmlConverter.ConvertToPdf(
new FileInfo(@"Path\to\Html\File.html"),
new FileInfo(@"Path\to\Pdf\File.pdf")
);
Method has many more overloads.
Update: iText* family of products has dual licensing model: free for open source, paid for commercial use.
RRULE standard is built for exactly this requirement i.e. saving and understanding recurrences. Microsoft and google both use it in their calendar events. Please go through this document for more details. https://icalendar.org/iCalendar-RFC-5545/3-8-5-3-recurrence-rule.html
The result produced by the Query is having no of rows that need proper handling this issue can be resolved if you provide the valid handler in the query like 1. limiting the query to return one single row 2. this can also be done by providing "select max(column)" that will return the single row
System.out
's main purpose is giving standard output.
System.err
's main purpose is giving standard error.
Look at these
http://www.devx.com/tips/Tip/14698
http://wiki.eclipse.org/FAQ_Where_does_System.out_and_System.err_output_go%3F
var selected=[];
$('#multipleSelect :selected').each(function(){
selected[$(this).val()]=$(this).text();
});
console.log(selected);
Yet another approch to this problem. The selected array will have the indexes as the option values and the each array item will have the text as its value.
for example
<select id="multipleSelect" multiple="multiple">
<option value="abc">Text 1</option>
<option value="def">Text 2</option>
<option value="ghi">Text 3</option>
</select>
if say option 1 and 2 are selected.
the selected array will be :
selected['abc']=1;
selected['def']=2.
You should use
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "my log message");
}
It seems that the version "20140702" of the example link in the question was the final version, because I downloaded this file on the 12th November 2014, i.e. the version from the 2nd of July 2014 was still the latest version on 12th of November. When I try manually all the possible versions/dates between today in this date, then I always get a page with error code "404" (file not found), which indicates that no new version was released since the 12th of November.
View Remote URLs
> git remote -v
heroku https://git.heroku.com/###########.git (fetch) < your Heroku Remote URL
heroku https://git.heroku.com/############.git (push)
origin https://github.com/#######/#####.git (fetch) < if you use GitHub then this is your GitHub remote URL
origin https://github.com/#######/#####.git (push)
Remove Heroku remote URL
> git remote rm heroku
Set new Heroku URL
> heroku git:remote -a ############
And you are done.
The I
attribute only exists on matrix
objects, not ndarray
s. You can use numpy.linalg.inv
to invert arrays:
inverse = numpy.linalg.inv(x)
Note that the way you're generating matrices, not all of them will be invertible. You will either need to change the way you're generating matrices, or skip the ones that aren't invertible.
try:
inverse = numpy.linalg.inv(x)
except numpy.linalg.LinAlgError:
# Not invertible. Skip this one.
pass
else:
# continue with what you were doing
Also, if you want to go through all 3x3 matrices with elements drawn from [0, 10), you want the following:
for comb in itertools.product(range(10), repeat=9):
rather than combinations_with_replacement
, or you'll skip matrices like
numpy.array([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
Steps to create Hash Key.
1: Download openssl from Openssl for Windows . I downloaded the Win64 version
2:Unzip and copy all the files in the bin folder including openssl.exe(All file of bin folder)
3:Goto to the folder where you installed JDK for me it’s C:\Program Files\Java\jdk1.8.0_05\bin
4:Paste all the files you copied from Openssl’s bin folder to the Jdk folder.
then go C:\Program Files\Java\jdk1.8.0_05\bin and press shift key and right click and open cmd
C:\Program Files\Java\jdk1.8.0_05\bin>//cmd path
that is for Sha1 past this
keytool -exportcert -alias androiddebugkey -keystore "C:\User\ABC\.android.keystore" | openssl sha1 -binary | openssl base64
//and ABC is system name put own system name
I suggest to use utf8mb4_unicode_ci
, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.
In the case of CROSS ORIGIN request read this:
I faced this situation and at first I chose to use the Authorization
Header and later removed it after facing the following issue.
Authorization
Header is considered a custom header. So if a cross-domain request is made with the Autorization
Header set, the browser first sends a preflight request. A preflight request is an HTTP request by the OPTIONS method, this request strips all the parameters from the request. Your server needs to respond with Access-Control-Allow-Headers
Header having the value of your custom header (Authorization
header).
So for each request the client (browser) sends, an additional HTTP request(OPTIONS) was being sent by the browser. This deteriorated the performance of my API. You should check if adding this degrades your performance. As a workaround I am sending tokens in http parameters, which I know is not the best way of doing it but I couldn't compromise with the performance.
I had problems with collations as I had most of the tables with Modern_Spanish_CI_AS
, but a few, which I had inherited or copied from another Database, had SQL_Latin1_General_CP1_CI_AS
collation.
In my case, the easiest way to solve the problem has been as follows:
I hope this helps other users.
Well, you are having a valid access token to access your information and not others( this is because you got logged in and you have given permission to access your information). But the picture owner has not done the same (logged in + permission ) and so you are getting a violation error.
To obtain permission see this link and decide what kind of informations you want from any user and decide the permissions. Later on embed this in your code. (In the login function call)
Thanks
Here is my 2 cents:
double dX = x1 - x2;
double dY = y1 - y2;
double multi = dX * dX + dY * dY;
double rad = Math.Round(Math.Sqrt(multi), 3, MidpointRounding.AwayFromZero);
x1, y1 is the first coordinate and x2, y2 the second. The last line is the square root with it rounded to 3 decimal places.
I resolved problem by adding following to my build.gradle file
android {
useLibrary 'org.apache.http.legacy'}
However this only works if you are using gradle 1.3.0-beta2 or greater, so you will have to add this to buildscript dependencies if you are on a lower version:
classpath 'com.android.tools.build:gradle:1.3.0-beta2'
you can set the types explicitly with pandas DataFrame.astype(dtype, copy=True, raise_on_error=True, **kwargs)
and pass in a dictionary with the dtypes you want to dtype
here's an example:
import pandas as pd
wheel_number = 5
car_name = 'jeep'
minutes_spent = 4.5
# set the columns
data_columns = ['wheel_number', 'car_name', 'minutes_spent']
# create an empty dataframe
data_df = pd.DataFrame(columns = data_columns)
df_temp = pd.DataFrame([[wheel_number, car_name, minutes_spent]],columns = data_columns)
data_df = data_df.append(df_temp, ignore_index=True)
In [11]: data_df.dtypes
Out[11]:
wheel_number float64
car_name object
minutes_spent float64
dtype: object
data_df = data_df.astype(dtype= {"wheel_number":"int64",
"car_name":"object","minutes_spent":"float64"})
now you can see that it's changed
In [18]: data_df.dtypes
Out[18]:
wheel_number int64
car_name object
minutes_spent float64
Simple solution which worked for me.
In VB.NET, but it's the same in C#:
Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20
I agree with:
hashCode()
implementation could result to multiple collisions, which means that in the worst case every object goes to the same bucket, thus O(N) if each bucket is backed by a List
.HashMap
dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree when a list gets bigger than 8 elements) resulting to a worst performance of O(logN).But, this is not the full truth if we want to be 100% precise. The implementation of hashCode()
and the type of key Object
(immutable/cached or being a Collection) might also affect real time complexity in strict terms.
Let's assume the following three cases:
HashMap<Integer, V>
HashMap<String, V>
HashMap<List<E>, V>
Do they have the same complexity? Well, the amortised complexity of the 1st one is, as expected, O(1). But, for the rest, we also need to compute hashCode()
of the lookup element, which means we might have to traverse arrays and lists in our algorithm.
Lets assume that the size of all of the above arrays/lists is k.
Then, HashMap<String, V>
and HashMap<List<E>, V>
will have O(k) amortised complexity and similarly, O(k + logN) worst case in Java8.
*Note that using a String
key is a more complex case, because it is immutable and Java caches the result of hashCode()
in a private variable hash
, so it's only computed once.
/** Cache the hash code for the string */
private int hash; // Default to 0
But, the above is also having its own worst case, because Java's String.hashCode()
implementation is checking if hash == 0
before computing hashCode
. But hey, there are non-empty Strings that output a hashcode
of zero, such as "f5a5a608", see here, in which case memoization might not be helpful.
for asp.net core 3.1.3 this worked for me
services.AddControllers().AddNewtonsoftJson(opt=>{
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Mine got solved by enabling multiDex for debug builds.
defaultConfig {
multiDexEnabled true
}
Sometimes the columns will have commas within themselves, such as:
"Some item", "Another Item", "Also, One more item"
In these cases, splitting on "," will break some columns. Maybe an easier way, but I just made my own method (as a bonus, handles spaces after commas and returns an IList):
private IList<string> GetColumns(string columns)
{
IList<string> list = new List<string>();
if (!string.IsNullOrWhiteSpace(columns))
{
if (columns[0] != '\"')
{
// treat as just one item
list.Add(columns);
}
else
{
bool gettingItemName = true;
bool justChanged = false;
string itemName = string.Empty;
for (int index = 1; index < columns.Length; index++)
{
justChanged = false;
if (subIndustries[index] == '\"')
{
gettingItemName = !gettingItemName;
justChanged = true;
}
if ((gettingItemName == false) &&
(justChanged == true))
{
list.Add(itemName);
itemName = string.Empty;
justChanged = false;
}
if ((gettingItemName == true) && (justChanged == false))
{
itemName += columns[index];
}
}
}
}
return list;
}
See http://www.w3schools.com/tags/att_input_accept.asp:
The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage
The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).
Note: The accept attribute can only be used with
<input type="file">
.Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.
Syntax
<input accept="audio/*|video/*|image/*|MIME_type" />
Tip: To specify more than one value, separate the values with a comma (e.g.
<input accept="audio/*,video/*,image/*" />
.
For those looking for an answer and the others haven't worked, this might:
If you're using a component within a component (e.g. something like this in the Vue DOM):
App
MyComponent
ADifferentComponent
MyComponent
Here the issue is that MyComponent
is both the parent and child of itself. This throws Vue into a loop, with each component depending on the other.
There's a few solutions to this:
MyComponent
vue.component("MyComponent", MyComponent)
beforeCreate
beforeCreate: function () {
this.$options.components.MyComponent = require('./MyComponent.vue').default
}
import
into a lambda function within the components
objectcomponents: {
MyComponent: () => import('./MyComponent.vue')
}
My preference is the third option, it's the simplest tweak and fixes the issue in my case.
More info: Vue.js Official Docs — Handling Edge Cases: Circular References Between Components
Note: if you choose method's 2 or 3, in my instance I had to use this method in both the parent and child components to stop this issue arising.
If you need to get the generic type of a returned type, I used this approach when I needed to find methods in a class which returned a Collection
and then access their generic types:
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
public class Test {
public List<String> test() {
return null;
}
public static void main(String[] args) throws Exception {
for (Method method : Test.class.getMethods()) {
Class returnClass = method.getReturnType();
if (Collection.class.isAssignableFrom(returnClass)) {
Type returnType = method.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) returnType;
Type[] argTypes = paramType.getActualTypeArguments();
if (argTypes.length > 0) {
System.out.println("Generic type is " + argTypes[0]);
}
}
}
}
}
}
This outputs:
Generic type is class java.lang.String
You can use date(t_stamp)
to get only the date part from a timestamp.
You can check the date() function in the docs
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'
Lukasz answer in Swift:
// iOS 7:
UITableView.appearance().separatorStyle = .SingleLine
UITableView.appearance().separatorInset = UIEdgeInsetsZero
UITableViewCell.appearance().separatorInset = UIEdgeInsetsZero
// iOS 8:
if UITableView.instancesRespondToSelector("setLayoutMargins:") {
UITableView.appearance().layoutMargins = UIEdgeInsetsZero
UITableViewCell.appearance().layoutMargins = UIEdgeInsetsZero
UITableViewCell.appearance().preservesSuperviewLayoutMargins = false
}
I would suggest making the div
s a little smaller and adding a margin of a percentage.
<div style="width:100%; height: 200px; background-color: grey;">_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: red;">A</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: orange;">B</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: green;">C</div>_x000D_
<div style="width: 23%; float:left; margin: 1%; background-color: blue;">D</div>_x000D_
</div>
_x000D_
In the command prompt, type the command below and press Enter.
bcdedit /enum
Under the Windows Boot Loader sections, make note of the identifier value.
To start in safe mode from command prompt :
bcdedit /set {identifier} safeboot minimal
Then enter the command line to reboot your computer.
To make a batch file for its current directory and sub directories:
cd %~dp0
attrib -h -r -s /s /d /l *.*
You did everything correctly!
You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.
this is in pure javascript
document.addEventListener('keypress', function (e) {_x000D_
if (e.keyCode === 13 || e.which === 13) {_x000D_
e.preventDefault();_x000D_
return false;_x000D_
}_x000D_
_x000D_
});
_x000D_
ClsConectaBanco bd = new ClsConectaBanco();
StringBuilder sb = new StringBuilder();
sb.Append(" INSERT INTO FAT_BALANCETE ");
sb.Append(" ([DT_LANCAMENTO] ");
sb.Append(" ,[ID_LANCAMENTO_CONTABIL] ");
sb.Append(" ,[NR_DOC_CONTABIL] ");
sb.Append(" ,[TP_LANCAMENTO_GERADO] ");
sb.Append(" ,[VL_LANCAMENTO] ");
sb.Append(" ,[TP_NATUREZA] ");
sb.Append(" ,[CD_EMPRESA] ");
sb.Append(" ,[CD_FILIAL] ");
sb.Append(" ,[CD_CONTA_CONTABIL] ");
sb.Append(" ,[DS_CONTA_CONTABIL] ");
sb.Append(" ,[ID_CONTA_CONTABIL] ");
sb.Append(" ,[DS_TRIMESTRE] ");
sb.Append(" ,[DS_SEMESTRE] ");
sb.Append(" ,[NR_TRIMESTRE] ");
sb.Append(" ,[NR_SEMESTRE] ");
sb.Append(" ,[NR_ANO] ");
sb.Append(" ,[NR_MES] ");
sb.Append(" ,[NM_FILIAL]) ");
sb.Append(" VALUES ");
sb.Append(" (@DT_LANCAMENTO ");
sb.Append(" ,@ID_LANCAMENTO_CONTABIL ");
sb.Append(" ,@NR_DOC_CONTABIL ");
sb.Append(" ,@TP_LANCAMENTO_GERADO ");
sb.Append(" ,@VL_LANCAMENTO ");
sb.Append(" ,@TP_NATUREZA ");
sb.Append(" ,@CD_EMPRESA ");
sb.Append(" ,@CD_FILIAL ");
sb.Append(" ,@CD_CONTA_CONTABIL ");
sb.Append(" ,@DS_CONTA_CONTABIL ");
sb.Append(" ,@ID_CONTA_CONTABIL ");
sb.Append(" ,@DS_TRIMESTRE ");
sb.Append(" ,@DS_SEMESTRE ");
sb.Append(" ,@NR_TRIMESTRE ");
sb.Append(" ,@NR_SEMESTRE ");
sb.Append(" ,@NR_ANO ");
sb.Append(" ,@NR_MES ");
sb.Append(" ,@NM_FILIAL) ");
SqlCommand cmd = new SqlCommand(sb.ToString(), bd.CriaConexaoSQL());
bd.AbrirConexao();
cmd.Parameters.Add("@DT_LANCAMENTO", SqlDbType.Date);
cmd.Parameters.Add("@ID_LANCAMENTO_CONTABIL", SqlDbType.Int);
cmd.Parameters.Add("@NR_DOC_CONTABIL", SqlDbType.VarChar,255);
cmd.Parameters.Add("@TP_LANCAMENTO_GERADO", SqlDbType.VarChar,255);
cmd.Parameters.Add("@VL_LANCAMENTO", SqlDbType.Decimal);
cmd.Parameters["@VL_LANCAMENTO"].Precision = 15;
cmd.Parameters["@VL_LANCAMENTO"].Scale = 2;
cmd.Parameters.Add("@TP_NATUREZA", SqlDbType.VarChar, 1);
cmd.Parameters.Add("@CD_EMPRESA",SqlDbType.Int);
cmd.Parameters.Add("@CD_FILIAL", SqlDbType.Int);
cmd.Parameters.Add("@CD_CONTA_CONTABIL", SqlDbType.VarChar, 255);
cmd.Parameters.Add("@DS_CONTA_CONTABIL", SqlDbType.VarChar, 255);
cmd.Parameters.Add("@ID_CONTA_CONTABIL", SqlDbType.VarChar,50);
cmd.Parameters.Add("@DS_TRIMESTRE", SqlDbType.VarChar, 4);
cmd.Parameters.Add("@DS_SEMESTRE", SqlDbType.VarChar, 4);
cmd.Parameters.Add("@NR_TRIMESTRE", SqlDbType.Int);
cmd.Parameters.Add("@NR_SEMESTRE", SqlDbType.Int);
cmd.Parameters.Add("@NR_ANO", SqlDbType.Int);
cmd.Parameters.Add("@NR_MES", SqlDbType.Int);
cmd.Parameters.Add("@NM_FILIAL", SqlDbType.VarChar, 255);
cmd.Prepare();
foreach (dtoVisaoBenner obj in lista)
{
cmd.Parameters["@DT_LANCAMENTO"].Value = obj.CTLDATA;
cmd.Parameters["@ID_LANCAMENTO_CONTABIL"].Value = obj.CTLHANDLE.ToString();
cmd.Parameters["@NR_DOC_CONTABIL"].Value = obj.CTLDOCTO.ToString();
cmd.Parameters["@TP_LANCAMENTO_GERADO"].Value = obj.LANCAMENTOGERADO;
cmd.Parameters["@VL_LANCAMENTO"].Value = obj.CTLANVALORF;
cmd.Parameters["@TP_NATUREZA"].Value = obj.NATUREZA;
cmd.Parameters["@CD_EMPRESA"].Value = obj.EMPRESA;
cmd.Parameters["@CD_FILIAL"].Value = obj.FILIAL;
cmd.Parameters["@CD_CONTA_CONTABIL"].Value = obj.CONTAHANDLE.ToString();
cmd.Parameters["@DS_CONTA_CONTABIL"].Value = obj.CONTANOME.ToString();
cmd.Parameters["@ID_CONTA_CONTABIL"].Value = obj.CONTA;
cmd.Parameters["@DS_TRIMESTRE"].Value = obj.TRIMESTRE;
cmd.Parameters["@DS_SEMESTRE"].Value = obj.SEMESTRE;
cmd.Parameters["@NR_TRIMESTRE"].Value = obj.NRTRIMESTRE;
cmd.Parameters["@NR_SEMESTRE"].Value = obj.NRSEMESTRE;
cmd.Parameters["@NR_ANO"].Value = obj.NRANO;
cmd.Parameters["@NR_MES"].Value = obj.NRMES;
cmd.Parameters["@NM_FILIAL"].Value = obj.NOME;
cmd.ExecuteNonQuery();
rowAffected++;
}
You could make it absolute
and put zeros to top
and bottom
that is:
#fullHeightDiv {
position: absolute;
top: 0;
bottom: 0;
}
Yet another way
$("#wizard li").click(function ()
{
$($(this),'#wizard"').index();
});
I was just playing a bit to try to make a dict comprehension with reduce, and come up with this one liner hack:
In [1]: from functools import reduce
In [2]: reduce(lambda d, i: (i[0] < 7 and d.__setitem__(*i[::-1]), d)[-1], [{}, *{1:2, 3:4, 5:6, 7:8}.items()])
Out[3]: {2: 1, 4: 3, 6: 5}
I was just trying to do the same as what was done in this Javascript dict comprehension: https://stackoverflow.com/a/11068265
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
We can mock list properly for foreach loop. Please find below code snippet and explanation.
This is my actual class method where I want to create test case by mocking list.
this.nameList
is a list object.
public void setOptions(){
// ....
for (String str : this.nameList) {
str = "-"+str;
}
// ....
}
The foreach loop internally works on iterator, so here we crated mock of iterator.
Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn()
, i.e. on hasNext()
we pass 1st true and on second call false, so that our loop will continue only two times. On next()
we just return actual return value.
@Test
public void testSetOptions(){
// ...
Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
Mockito.when(itr.hasNext()).thenReturn(true, false);
Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);
List mockNameList = Mockito.mock(List.class);
Mockito.when(mockNameList.iterator()).thenReturn(itr);
// ...
}
In this way we can avoid sending actual list to test by using mock of list.
Try this:
import matplotlib as plt
after importing the file we can use matplotlib library but remember to use it as plt
df.plt(kind='line',figsize=(10,5))
after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.
In my case I have to use something like <username>@<domain>
to successfully login.
sample_user@sample_domain
The webdriver
will wait for a page to load by default via .get()
method.
As you may be looking for some specific element as @user227215 said, you should use WebDriverWait
to wait for an element located in your page:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
try:
myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))
print "Page is ready!"
except TimeoutException:
print "Loading took too much time!"
I have used it for checking alerts. You can use any other type methods to find the locator.
EDIT 1:
I should mention that the webdriver
will wait for a page to load by default. It does not wait for loading inside frames or for ajax requests. It means when you use .get('url')
, your browser will wait until the page is completely loaded and then go to the next command in the code. But when you are posting an ajax request, webdriver
does not wait and it's your responsibility to wait an appropriate amount of time for the page or a part of page to load; so there is a module named expected_conditions
.
The following will return NULL if the array is empty, else the last element.
var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
As of 2015, it now just works.
<input type="file">
This will ask user for the upload of any file. On iOS 8.x this can be a camera video, camera photo, or a photo/video from Photo Library.
<input type="file" accept="image/*">
This is as above, but limits the uploads to photos only from camera or library, no videos.
Here is the regex for Ethiopian Phone Number. For my fellow Ethiopian developers ;)
phoneExp = /^(^\+251|^251|^0)?9\d{8}$/;
It matches the following (restrict any unwanted character in start and end position)
You can test it on this site regexr.
When we do something like this obj[key] Typescript can't know for sure if that key exists in that object. What I did:
Object.entries(data).forEach(item => {
formData.append(item[0], item[1]);
});
Ruby aliases the method Array#map to Array#collect; they can be used interchangeably. (Ruby Monk)
In other words, same source code :
static VALUE
rb_ary_collect(VALUE ary)
{
long i;
VALUE collect;
RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
collect = rb_ary_new2(RARRAY_LEN(ary));
for (i = 0; i < RARRAY_LEN(ary); i++) {
rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
}
return collect;
}
Assuming the data file is actually Tab separated, not space aligned:
<test.tsv awk '{print $4}' | sort | uniq
Where $4 will be:
Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's
As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:
Web Development:
You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.
Data Analysis:
Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.
Machine Learning:
What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.
Computer Vision:
You can do many interesting things such as Face detection, Color detection while using Opencv and Python.
Internet Of Things With Raspberry Pi:
Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!
Game Development:
Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.
Web Scraping:
If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.
Writing Scripts:
If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.
Browser Automation:
Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.
GUI Development:
Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.
Rapid Prototyping:
Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.
Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.
text-overflow:ellipsis;
only works when the following are true:
px
(pixels). Width in %
(percentage) won't work.overflow:hidden
and white-space:nowrap
set.The reason you're having problems here is because the width
of your a
element isn't constrained. You do have a width
setting, but because the element is set to display:inline
(i.e. the default) it is ignoring it, and nothing else is constraining its width either.
You can fix this by doing one of the following:
display:inline-block
or display:block
(probably the former, but depends on your layout needs).display:block
and give that element a fixed width
or max-width
.float:left
or float:right
(probably the former, but again, either should have the same effect as far as the ellipsis is concerned).I'd suggest display:inline-block
, since this will have the minimum collateral impact on your layout; it works very much like the display:inline
that it's using currently as far as the layout is concerned, but feel free to experiment with the other points as well; I've tried to give as much info as possible to help you understand how these things interact together; a large part of understanding CSS is about understanding how various styles work together.
Here's a snippet with your code, with a display:inline-block
added, to show how close you were.
.app a {_x000D_
height: 18px;_x000D_
width: 140px;_x000D_
padding: 0;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
margin: 0 5px 0 5px;_x000D_
text-align: center;_x000D_
text-decoration: none;_x000D_
text-overflow: ellipsis;_x000D_
white-space: nowrap;_x000D_
color: #000;_x000D_
}
_x000D_
<div class="app">_x000D_
<a href="">Test Test Test Test Test Test</a>_x000D_
</div>
_x000D_
Useful references:
I'll put in my two cents for tapply()
.
tapply(df$dt, df$group, summary)
You could write a custom function with the specific statistics you want to replace summary.
In the spirit of arrow sexiness, you could create a micro clamp/constrain/gate/&c. function using rest parameters
var clamp = (...v) => v.sort((a,b) => a-b)[1];
Then just pass in three values
clamp(100,-3,someVar);
That is, again, if by sexy, you mean 'short'
Adding also Kotlin version with:
strings.xml
)colors.xml
)fun getMulticolorSpanned(): Spanned {
// Get text from resources
val text: String = getString(R.string.your_text_from_resources)
// Get color from resources and parse it to HEX (RGB) value
val warningHexColor = getHexFromColors(R.color.your_error_color)
// Use above string & color in HTML
val html = "<string>$text<span style=\"color:#$warningHexColor;\">*</span></string>"
// Parse HTML (base on API version)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(html)
}
}
And Kotlin extension (with removing alpha):
fun Context.getHexFromColors(
colorRes: Int
): String {
val labelColor: Int = ContextCompat.getColor(this, colorRes)
return String.format("%X", labelColor).substring(2)
}
Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?
Yes.
Create the .o (as per normal):
g++ -c header.cpp
Create the archive:
ar rvs header.a header.o
Test:
g++ test.cpp header.a -o executable_name
Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:
g++ test.cpp header.cpp -o executable_name
Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.
Hope this helps!
This error is from google security... This Can Be Resolved by Enabling Less Secure .
Go To This Link : "https://www.google.com/settings/security/lesssecureapps" and Make "TURN ON" then your application runs For Sure.
Yo can simply google for "exit sub in c#".
Also why would you check every text box if it is empty. You can place requiredfieldvalidator for these text boxes if this is an asp.net app and check if(Page.IsValid)
Or another solution is to get not of these conditions:
private void button1_Click(object sender, EventArgs e)
{
if (!(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""))
{
//do events
}
}
And better use String.IsNullOrEmpty:
private void button1_Click(object sender, EventArgs e)
{
if (!(String.IsNullOrEmpty(textBox1.Text)
|| String.IsNullOrEmpty(textBox2.Text)
|| String.IsNullOrEmpty(textBox3.Text)))
{
//do events
}
}
You can use the jQuery ajax method link if you want to pass data from client to server.
In this case you can use $_SERVER['HTTP_USER_AGENT']
variable to found browser user agent.
I create now the log-css.js https://codepen.io/luis7lobo9b/pen/QWyobwY
// log-css.js v1
const log = console.log.bind();
const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) {
return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')];
};
// example
log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px'));
For Python 2:
>>> execfile('filename.py')
For Python 3:
>>> exec(open("filename.py").read())
# or
>>> from pathlib import Path
>>> exec(Path("filename.py").read_text())
See the documentation. If you are using Python 3.0, see this question.
See answer by @S.Lott for an example of how you access globals from filename.py after executing it.
Most IIS sections are locked by default but you can "unlock" them by setting the attribute overrideModeDefault
from "Deny" to "Allow" for the relevant section group by modifying the ApplicationHost.config file located in %windir%\system32\inetsrv\config
in Administrator mode
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
WHEN course_enrollment_settings.base_price>0 AND
course_enrollment_settings.base_price<=100 THEN 2
WHEN course_enrollment_settings.base_price>100 AND
course_enrollment_settings.base_price<201 THEN 3
ELSE 6
END AS 'calc_base_price',
course_enrollment_settings.base_price
FROM
course_enrollment_settings
WHERE course_enrollment_settings.base_price = 0
Use sqlite3 database.sqlite3 < db.sql
. You'll need to make sure that your files contain valid SQL for SQLite.
Try this C# Reflection link.
Note I think that BindingFlags.Instance and BindingFlags.Static are exclusive.
This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).
Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d
(and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.
You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb
.
Here's the breakdown of the fields:
address
(after the at
) - the location in memory the code is trying to access (it's likely that 10
and 11
are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0
)ip
- instruction pointer, ie. where the code which is trying to do this livessp
- stack pointererror
- An error code for page faults; see below for what this means on x86.
/*
* Page fault error code bits:
*
* bit 0 == 0: no page found 1: protection fault
* bit 1 == 0: read access 1: write access
* bit 2 == 0: kernel-mode access 1: user-mode access
* bit 3 == 1: use of reserved bit detected
* bit 4 == 1: fault was an instruction fetch
*/
echo
has the problem that if var
contains something like -e
, it will be interpreted as a flag. Another option is printf
, but printf "$var" > "$destdir"
will expand any escaped characters in the variable, so if the variable contains backslashes the file contents won't match. However, because printf
only interprets backslashes as escapes in the format string, you can use the %s
format specifier to store the exact variable contents to the destination file:
printf "%s" "$var" > "$destdir"
Install the gd library also.
check this link http://www.php.net/manual/en/mbstring.installation.php
screen.orientation.lock('landscape');
Will force it to change to and stay in landscape mode. Tested on Nexus 5.
As DOC says, you can pass data to the handler as next:
// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
// access element's id where click occur
alert( event.target.id );
}
try plot(var); saveFigure('title'); it will save as a jpeg automatically
First of all consider using query parameters in prepared statements:
PreparedStatement stm = c.prepareStatement("UPDATE user_table SET name=? WHERE id=?");
stm.setString(1, "the name");
stm.setInt(2, 345);
stm.executeUpdate();
The other thing that can be done is to keep all queries in properties file. For example in a queries.properties file can place the above query:
update_query=UPDATE user_table SET name=? WHERE id=?
Then with the help of a simple utility class:
public class Queries {
private static final String propFileName = "queries.properties";
private static Properties props;
public static Properties getQueries() throws SQLException {
InputStream is =
Queries.class.getResourceAsStream("/" + propFileName);
if (is == null){
throw new SQLException("Unable to load property file: " + propFileName);
}
//singleton
if(props == null){
props = new Properties();
try {
props.load(is);
} catch (IOException e) {
throw new SQLException("Unable to load property file: " + propFileName + "\n" + e.getMessage());
}
}
return props;
}
public static String getQuery(String query) throws SQLException{
return getQueries().getProperty(query);
}
}
you might use your queries as follows:
PreparedStatement stm = c.prepareStatement(Queries.getQuery("update_query"));
This is a rather simple solution, but works well.
I have another solution that works great.
On one hand, Ortwin's approach & solution works only with iOS 6.0 and later, but fails to work correctly on iOS 5.0, 5.1 and 5.1.1, and on the other hand there is something that I don't like and can't understand with Ortwin's approach, it's the use of the method [webView sizeThatFits:CGSizeZero]
with the parameter CGSizeZero
: If you read Apple Official documentation about this methods and its parameter, it says clearly :
The default implementation of this method returns the size portion of the view’s bounds rectangle. Subclasses can override this method to return a custom value based on the desired layout of any subviews. For example, a UISwitch object returns a fixed size value that represents the standard size of a switch view, and a UIImageView object returns the size of the image it is currently displaying.
What I mean is that it's like he came across his solution without any logic, because reading the documentation, the parameter passed to [webView sizeThatFits: ...]
should at least have the desired width
. With his solution, the desired width is set to the webView
's frame before calling sizeThatFits
with a CGSizeZero
parameter. So I maintain this solution is working on iOS 6 by "chance".
I imagined a more rational approach, which has the advantage of working for iOS 5.0 and later... And also in complex situations where more than one webView (With its property webView.scrollView.scrollEnabled = NO
is embedded in a scrollView
.
Here is my code to force the Layout of the webView
to the desired width
and get the corresponding height
set back to the webView
itself:
Obj-C
- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{
aWebView.scrollView.scrollEnabled = NO; // Property available in iOS 5.0 and later
CGRect frame = aWebView.frame;
frame.size.width = 200; // Your desired width here.
frame.size.height = 1; // Set the height to a small one.
aWebView.frame = frame; // Set webView's Frame, forcing the Layout of its embedded scrollView with current Frame's constraints (Width set above).
frame.size.height = aWebView.scrollView.contentSize.height; // Get the corresponding height from the webView's embedded scrollView.
aWebView.frame = frame; // Set the scrollView contentHeight back to the frame itself.
}
Swift 4.x
func webViewDidFinishLoad(_ aWebView: UIWebView) {
aWebView.scrollView.isScrollEnabled = false
var frame = aWebView.frame
frame.size.width = 200
frame.size.height = 1
aWebView.frame = frame
frame.size.height = aWebView.scrollView.contentSize.height
aWebView.frame = frame;
}
Note that in my example, the webView
was embedded in a custom scrollView
having other webViews
... All these webViews
had their webView.scrollView.scrollEnabled = NO
, and the last piece of code I had to add was the calculation of the height
of the contentSize
of my custom scrollView
embedding these webViews
, but it was as easy as summing my webView
's frame.size.height
computed with the trick described above...
As of Python 3.2+, you can also accomplish this using the to_bytes
native int method:
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
I.e., each single call to to_bytes
in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte
. You can also shorten the last two lines into a single one:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))
width="100" height="100"
in the svg file then add this x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100"
while keeping the already defined width="100" height="100"
. img
so you could then do this: img{height: 20px; width: 20px;}
and the image will scale.If you're using oh-my-zsh
Type
omz update
in the terminal
Note: upgrade_oh_my_zsh
is deprecated
I did not know the answer so asked the ASP.NET team here.
So the trick is to change the signature to HttpResponseMessage
and use Request.CreateResponse
.
[ResponseType(typeof(User))]
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return new HttpResponseMessage(HttpStatusCode.NotModified);
}
return request.CreateResponse(HttpStatusCode.OK, user);
}
You can animate the scrolltop of the page with jQuery.
$('html, body').animate({
scrollTop: $(".middle").offset().top
}, 2000);
See this site: http://papermashup.com/jquery-page-scrolling/
CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml
file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.
IQueryCollection
has a TryGetValue()
on it that returns a value with the given key. So, if you had a query parameter called someInt
, you could use it like so:
var queryString = httpContext.Request.Query;
StringValues someInt;
queryString.TryGetValue("someInt", out someInt);
var daRealInt = int.Parse(someInt);
Notice that unless you have multiple parameters of the same name, the StringValues
type is not an issue.
for angular 4, the working solution was to do inside the component
@HostListener('window:scroll', ['$event']) onScrollEvent($event){
console.log($event);
console.log("scrolling");
}
This answer is for Mongo 3.2.1 Reference
Terminal 1:
$ mongod --auth
Terminal 2:
db.createUser({user:"admin_name", pwd:"1234",roles:["readWrite","dbAdmin"]})
if you want to add without roles (optional):
db.createUser({user:"admin_name", pwd:"1234", roles:[]})
to check if authenticated or not:
db.auth("admin_name", "1234")
it should give you:
1
else :
Error: Authentication failed.
0
I was getting this error with Laravel Sanctum. I fixed it by adding \Illuminate\Session\Middleware\StartSession::class,
to the api
middleware group in Kernel.php, but I later figured out this "worked" because my authentication routes were added in api.php
instead of web.php
, so Laravel was using the wrong auth guard.
I moved these routes here into web.php
and then they started working properly with the AuthenticatesUsers.php
trait:
Route::group(['middleware' => ['guest', 'throttle:10,5']], function () {
Route::post('register', 'Auth\RegisterController@register')->name('register');
Route::post('login', 'Auth\LoginController@login')->name('login');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
Route::post('email/verify/{user}', 'Auth\VerificationController@verify')->name('verification.verify');
Route::post('email/resend', 'Auth\VerificationController@resend');
Route::post('oauth/{driver}', 'Auth\OAuthController@redirectToProvider')->name('oauth.redirect');
Route::get('oauth/{driver}/callback', 'Auth\OAuthController@handleProviderCallback')->name('oauth.callback');
});
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
I figured out the problem after I got another weird error about RequestGuard::logout()
does not exist.
It made me realize that my custom auth routes are calling methods from the AuthenticatesUsers trait, but I wasn't using Auth::routes()
to accomplish it. Then I realized Laravel uses the web guard by default and that means routes should be in routes/web.php
.
This is what my settings look like now with Sanctum and a decoupled Vue SPA app:
Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
'throttle:60,1',
],
];
Note: With Laravel Sanctum and same-domain Vue SPA, you use httpOnly cookies for session cookie, and remember me cookie, and unsecure cookie for CSRF, so you use the
web
guard for auth, and every other protected, JSON-returning route should useauth:sanctum
middleware.
config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
...
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
Then you can have unit tests such as this, where critically, Auth::check()
, Auth::user()
, and Auth::logout()
work as expected with minimal config and maximal usage of AuthenticatesUsers
and RegistersUsers
traits.
Here are a couple of my login unit tests:
TestCase.php
/**
* Creates and/or returns the designated regular user for unit testing
*
* @return \App\User
*/
public function user() : User
{
$user = User::query()->firstWhere('email', '[email protected]');
if ($user) {
return $user;
}
// User::generate() is just a wrapper around User::create()
$user = User::generate('Test User', '[email protected]', self::AUTH_PASSWORD);
return $user;
}
/**
* Resets AuthManager state by logging out the user from all auth guards.
* This is used between unit tests to wipe cached auth state.
*
* @param array $guards
* @return void
*/
protected function resetAuth(array $guards = null) : void
{
$guards = $guards ?: array_keys(config('auth.guards'));
foreach ($guards as $guard) {
$guard = $this->app['auth']->guard($guard);
if ($guard instanceof SessionGuard) {
$guard->logout();
}
}
$protectedProperty = new \ReflectionProperty($this->app['auth'], 'guards');
$protectedProperty->setAccessible(true);
$protectedProperty->setValue($this->app['auth'], []);
}
LoginTest.php
protected $auth_guard = 'web';
/** @test */
public function it_can_login()
{
$user = $this->user();
$this->postJson(route('login'), ['email' => $user->email, 'password' => TestCase::AUTH_PASSWORD])
->assertStatus(200)
->assertJsonStructure([
'user' => [
...expectedUserFields,
],
]);
$this->assertEquals(Auth::check(), true);
$this->assertEquals(Auth::user()->email, $user->email);
$this->assertAuthenticated($this->auth_guard);
$this->assertAuthenticatedAs($user, $this->auth_guard);
$this->resetAuth();
}
/** @test */
public function it_can_logout()
{
$this->actingAs($this->user())
->postJson(route('logout'))
->assertStatus(204);
$this->assertGuest($this->auth_guard);
$this->resetAuth();
}
I overrided the registered
and authenticated
methods in the Laravel auth traits so that they return the user object instead of just the 204 OPTIONS:
public function authenticated(Request $request, User $user)
{
return response()->json([
'user' => $user,
]);
}
protected function registered(Request $request, User $user)
{
return response()->json([
'user' => $user,
]);
}
Look at the vendor code for the auth traits. You can use them untouched, plus those two above methods.
Here is my Vue SPA's Vuex actions for login:
async login({ commit }, credentials) {
try {
const { data } = await axios.post(route('login'), {
...credentials,
remember: credentials.remember || undefined,
});
commit(FETCH_USER_SUCCESS, { user: data.user });
commit(LOGIN);
return commit(CLEAR_INTENDED_URL);
} catch (err) {
commit(LOGOUT);
throw new Error(`auth/login# Problem logging user in: ${err}.`);
}
},
async logout({ commit }) {
try {
await axios.post(route('logout'));
return commit(LOGOUT);
} catch (err) {
commit(LOGOUT);
throw new Error(`auth/logout# Problem logging user out: ${err}.`);
}
},
It took me over a week to get Laravel Sanctum + same-domain Vue SPA + auth unit tests all working up to my standard, so hopefully my answer here can help save others time in the future.
Since the question was "display" :
@Html.ValueFor(model => model.RegistrationDate, "{0:dd/MM/yyyy}")
example of textarea for disable the resize option
<textarea CLASS="foo"></textarea>
<style>
textarea.foo
{
resize:none;
}
</style>
I was looking for the same thing since the background of my select is the same as the arrow color. As previously mentioned, it is impossible yet to add anything using :before or :after on a select element. My solution was to create a wrapper element on which I added the following :before code.
.select-wrapper {
position: relative;
}
.select-wrapper:before {
content: '\f0d7';
font-family: FontAwesome;
color: #fff;
display: inline-block;
position: absolute;
right: 20px;
top: 15px;
pointer-events: none;
}
And this my select
select {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
width: 100%;
padding: 10px 20px;
background: #000;
color: #fff;
border: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
select::-ms-expand {
display: none;
}
I have used FontAwesome.io for my new arrow, but you can use whatever else you want. Obviously this is not a perfect solution, but depending on your needs it might be enough.
the parent element has not to be empty at least put
before the child element.
This problem happened for me only in special cases, when I called website from some internet providers,
I've configured only ip v4 in VirtualHost configuration of apache, but some of router use ip v6, and when I added ip v6 to apache config the problem solved.
Simple way:
repository.findAll(Sort.by(Sort.Direction.DESC, "colName"));
In kotlin you can use unaryPlus and unaryMinus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html
Use Either Debug.WriteLine()
or Trace.WriteLine()
. If in release mode, only the latter will appear in the output window, in debug mode, both will.
If you're using Twitter Bootstrap styling and base JS for a drop down menu:
.child{ display:none; }
.parent:hover .child{ display:block; }
This is the missing piece to create sticky-dropdowns (that aren't annoying)
assuming the item numbers are unique, a VLOOKUP
should get you the information you need.
first value would be =VLOOKUP(E1,A:B,2,FALSE)
, and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE)
. Wrap them in an IFERROR
if you want to return anything other than #N/A if there is no corresponding value in the item column(s)
Best answer is probably https://stackoverflow.com/a/1472562/601990.
Here is some code that shows how to use it:
App.xaml.cs
public sealed partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
// setting up the Dependency Injection container
var resolver = ResolverFactory.Get();
// getting the ILogger or ILog interface
var logger = resolver.Resolve<ILogger>();
RegisterGlobalExceptionHandling(logger);
// Bootstrapping Dependency Injection
// injects ViewModel into MainWindow.xaml
// remember to remove the StartupUri attribute in App.xaml
var mainWindow = resolver.Resolve<Pages.MainWindow>();
mainWindow.Show();
}
private void RegisterGlobalExceptionHandling(ILogger log)
{
// this is the line you really want
AppDomain.CurrentDomain.UnhandledException +=
(sender, args) => CurrentDomainOnUnhandledException(args, log);
// optional: hooking up some more handlers
// remember that you need to hook up additional handlers when
// logging from other dispatchers, shedulers, or applications
Application.Dispatcher.UnhandledException +=
(sender, args) => DispatcherOnUnhandledException(args, log);
Application.Current.DispatcherUnhandledException +=
(sender, args) => CurrentOnDispatcherUnhandledException(args, log);
TaskScheduler.UnobservedTaskException +=
(sender, args) => TaskSchedulerOnUnobservedTaskException(args, log);
}
private static void TaskSchedulerOnUnobservedTaskException(UnobservedTaskExceptionEventArgs args, ILogger log)
{
log.Error(args.Exception, args.Exception.Message);
args.SetObserved();
}
private static void CurrentOnDispatcherUnhandledException(DispatcherUnhandledExceptionEventArgs args, ILogger log)
{
log.Error(args.Exception, args.Exception.Message);
// args.Handled = true;
}
private static void DispatcherOnUnhandledException(DispatcherUnhandledExceptionEventArgs args, ILogger log)
{
log.Error(args.Exception, args.Exception.Message);
// args.Handled = true;
}
private static void CurrentDomainOnUnhandledException(UnhandledExceptionEventArgs args, ILogger log)
{
var exception = args.ExceptionObject as Exception;
var terminatingMessage = args.IsTerminating ? " The application is terminating." : string.Empty;
var exceptionMessage = exception?.Message ?? "An unmanaged exception occured.";
var message = string.Concat(exceptionMessage, terminatingMessage);
log.Error(exception, message);
}
}
Since the question is not restricted to Android Studio, So I am giving the path for Visual Studio 2015 (worked for Xamarin).
Special Thanks to other answerers of this question.
On my machine (Win10), the uninstaller was located at C:\ProgramData\Anaconda3\Uninstall-Anaconda3.exe
.
Another alternative is to use a lambda:
ent.bind("<Return>", (lambda event: name_of_function()))
Full code:
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title="Reply", message = "Hello %s!" % name)
top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")
Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)
top.mainloop()
As you can see, creating a lambda function with an unused variable "event" solves the problem.
If you use the "select()" statement, you can do this:
$category = $catrep->createQueryBuilder('cc')
->select('DISTINCT cc.contenttype')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->getQuery();
$categories = $category->getResult();
Using inline styles:
<input type="text" style="text-align: right"/>
or, put it in a style sheet, like so:
<style>
.rightJustified {
text-align: right;
}
</style>
and reference the class:
<input type="text" class="rightJustified"/>
JChronic is your best choice. Here's an example that adds a .fromString()
method to the Date class that parses just about anything you can throw at it:
Date.metaClass.'static'.fromString = { str ->
com.mdimension.jchronic.Chronic.parse(str).beginCalendar.time
}
You can call it like this:
println Date.fromString("Tue Aug 10 16:02:43 PST 2010")
println Date.fromString("july 1, 2012")
println Date.fromString("next tuesday")