It is simple for me i downloaded the apk file in my computer and drag that file to emulator it install the google play for me Hope it help some one
You might use ArrayList overloaded method toString()
String tmp=arr.toString();
PrintWriter pw=new PrintWriter(new FileOutputStream(file));
pw.println(tmp.substring(1,tmp.length()-1));
Here, this might help...
<html>_x000D_
_x000D_
<head>_x000D_
<style type="text/css">_x000D_
div.box {_x000D_
background: #EEE;_x000D_
height: 100px;_x000D_
width: 500px;_x000D_
}_x000D_
div.left {_x000D_
background: #999;_x000D_
float: left;_x000D_
height: 100%;_x000D_
width: auto;_x000D_
}_x000D_
div.right {_x000D_
background: #666;_x000D_
height: 100%;_x000D_
}_x000D_
div.clear {_x000D_
clear: both;_x000D_
height: 1px;_x000D_
overflow: hidden;_x000D_
font-size: 0pt;_x000D_
margin-top: -1px;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="box">_x000D_
<div class="left">Tree</div>_x000D_
<div class="right">View</div>_x000D_
<div class="clear" />_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I prefer:
cin.clear();
fflush(stdin);
There's an example where cin.ignore just doesn't cut it, but I can't think of it at the moment. It was a while ago when I needed to use it (with Mingw).
However, fflush(stdin) is undefined behavior according to the standard. fflush() is only meant for output streams. fflush(stdin) only seems to work as expected on Windows (with GCC and MS compilers at least) as an extension to the C standard.
So, if you use it, your code isn't going to be portable.
See Using fflush(stdin).
Also, see http://ubuntuforums.org/showpost.php?s=9129c7bd6e5c8fd67eb332126b59b54c&p=452568&postcount=1 for an alternative.
Yes, struct
is exactly like class
except the default accessibility is public
for struct
(while it's private
for class
).
If you are looking for previous month data:
date(date_created)>=date_sub(date_format(curdate(),"%Y-%m-01"),interval 1 month) and
date(date_created)<=date_sub(date_format(curdate(),'%Y-%m-01'),interval 1 day)
This will also work when the year changes. It will also work on MySQL.
Try this for IE11
<iframe name="Stack" src="http://stackoverflow.com/" style='height: 100%; width: 100%;' frameborder="0" scrolling="no" id="iframe">...</iframe>
I use the Monitoring Plugin for this task. After the installation of the plugin
Search for the Job Name that is hung
The Thread's name will start like this
Executor #2 for master : executing <your-job-name> #<build-number>
Click the red, round button on the very right in the table of the line your desired job has
If you are using pyenv, it is possible to delete your virtual environment:
$ pyenv virtualenv-delete <name>
Recently I have read a Java SE 8 Programmer Guide ii Book.
I found something about the difference between AutoCloseable
vs Closeable
.
The AutoCloseable
interface was introduced in Java 7. Before that, another interface
existed called Closeable
. It was similar to what the language designers wanted, with the
following exceptions:
Closeable
restricts the type of exception thrown to IOException
.Closeable
requires implementations to be idempotent.The language designers emphasize backward compatibility. Since changing the existing
interface was undesirable, they made a new one called AutoCloseable
. This new
interface is less strict than Closeable
. Since Closeable
meets the requirements for
AutoCloseable
, it started implementing AutoCloseable
when the latter was introduced.
if you want to always use git log
in such way you could add git alias by
git config --global alias.log log --oneline
after that git log
will print what normally would be printed by git log --oneline
I might be late to the part but here is a very easy way to do it
Type:
def cls():
os.system("cls")
So what ever you want to clear the screen just type in your code
cls()
Best way possible! (Credit : https://www.youtube.com/watch?annotation_id=annotation_3770292585&feature=iv&src_vid=bguKhMnvmb8&v=LtGEp9c6Z-U)
In 8-2017 Microsoft came out with System.Configuration
for .NET CORE v4.4. Currently v4.5 and v4.6 preview.
For those of us, who works on transformation from .Net Framework to CORE, this is essential. It allows to keep and use current app.config
files, which can be accessed from any assembly. It is probably even can be an alternative to appsettings.json
, since Microsoft realized the need for it. It works same as before in FW. There is one difference:
In the web applications, [e.g. ASP.NET CORE WEB API] you need to use app.config
and not web.config for your appSettings
or configurationSection
. You might need to use web.config
but only if you deploying your site via IIS. You place IIS-specific settings into web.config
I've tested it with netstandard20 DLL and Asp.net Core Web Api and it is all working.
You can use stored procedure in this way..
DELIMITER |
CREATE PROCEDURE explode( pDelim VARCHAR(32), pStr TEXT)
BEGIN
DROP TABLE IF EXISTS temp_explode;
CREATE TEMPORARY TABLE temp_explode (id INT AUTO_INCREMENT PRIMARY KEY NOT NULL, word VARCHAR(40));
SET @sql := CONCAT('INSERT INTO temp_explode (word) VALUES (', REPLACE(QUOTE(pStr), pDelim, '\'), (\''), ')');
PREPARE myStmt FROM @sql;
EXECUTE myStmt;
END |
DELIMITER ;
example call:
SET @str = "The quick brown fox jumped over the lazy dog";
SET @delim = " ";
CALL explode(@delim,@str);
SELECT id,word FROM temp_explode;
Answer from Varun Rathore is OK but you must consider that starting from Windows Server 2008 R2 and higher the SQLServer service will run under a local virtual account and not anymore under the old well known "NETWORK SERVICE". Due to this, to switch a newly attached DB to "not read only mode", you must setup permissions on the ldf and mdf files for local machine user line "NT SERVICE\MSSQLSERVER" where MSSQLSERVER would be the service name in a pretty standard installation.
Checkout this https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-windows-service-accounts-and-permissions#VA_Desc for details configuring service permissions
The standard way is cin.get()
before your return statement.
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Hello World";
cin.get();
return 0;
}
This is the only thing I've found for JavaScript formatting in Dreamweaver. Not many options, but it seems to work well.
JavaScript source format extension for dreamweaver: Adobe CFusion
On Several occasions, we would need comma separated list of all the columns from a table in a schema. In such cases we can use this generic function which fetches the comma separated list as a string.
CREATE OR REPLACE FUNCTION cols(
p_schema_name IN VARCHAR2,
p_table_name IN VARCHAR2)
RETURN VARCHAR2
IS
v_string VARCHAR2(4000);
BEGIN
SELECT LISTAGG(COLUMN_NAME , ',' ) WITHIN GROUP (
ORDER BY ROWNUM )
INTO v_string
FROM ALL_TAB_COLUMNS
WHERE OWNER = p_schema_name
AND table_name = p_table_name;
RETURN v_string;
END;
/
So, simply calling the function from the query yields a row with all the columns.
select cols('HR','EMPLOYEES') FROM DUAL;
EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_ID,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID
Note: LISTAGG
will fail if the combined length of all columns exceed 4000
characters which is rare. For most cases , this will work.
Even I run npm install -g npm@4
, it is not ok for me.
Finally, I download and install the old node.js version.
https://nodejs.org/download/release/v7.10.1/
It is npm version 4.
You can choose any version here https://nodejs.org/download/release/
boolean compare(String str1, String str2) {
if(str1==null || str2==null) {
//return false; if you assume null not equal to null
return str1==str2;
}
return str1.equals(str2);
}
is this what you desired?
* First we declare JTextField like this
JTextField testField = new JTextField(10);
* We can get textfield value in String like this on any button click event.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String getValue = testField.getText()
}
})
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
A better polyfill from the MDN that supports removal of BOM and NBSP:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string)
instead. That being said, if you are targeting an older environment without native .trim()
support, you are likely to have more important performance issues to deal with.
I'd probably use a LEFT JOIN
, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULL
s.
So, something like:
SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL
Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.
This works for me
Move your .htaccess file to root folder (locate before application folder in my case)
RewriteEngine on
RewriteBase /yourProjectFolder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
Mine config.php looks like this (application/config/config.php)
$config['base_url'] = "";
$config['index_page'] = "index.php";
$config['uri_protocol'] = "AUTO";
Let me know if its working for you guys too ! Cheers !
Use the re.escape()
function for this:
escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.
def simplistic_plural(word, text):
word_or_plural = re.escape(word) + 's?'
return re.match(word_or_plural, text)
@Vertexwahns answer, but written in bash. For the people who are lazy:
boost_version=$(cat /usr/include/boost/version.hpp | grep define | grep "BOOST_VERSION " | cut -d' ' -f3)
echo "installed boost version: $(echo "$boost_version / 100000" | bc).$(echo "$boost_version / 100 % 1000" | bc).$(echo "$boost_version % 100 " | bc)"
Gives me installed boost version: 1.71.0
Program to get the current working directory=user.dir
public class CurrentDirectoryExample {
public static void main(String args[]) {
String current = System.getProperty("user.dir");
System.out.println("Current working directory in Java : " + current);
}
}
Install the View In Browser plugin using Package Control or download package from github and unzip this package in your packages folder(that from browse packages)
after this, go to Preferences, Key Bindings - User, paste this
[{ "keys": [ "f12" ], "command": "view_in_browser" }]
now F12 will be your shortcut key.
input(char_val,current_date_format);
You can specify any date format at display time, like set char_val=date9.;
You can use ng-repeat
with option
like this:
<form>
<select ng-model="yourSelect"
ng-options="option as option for option in ['var1', 'var2', 'var3']"
ng-init="yourSelect='var1'"></select>
<input type="hidden" name="yourSelect" value="{{yourSelect}}" />
</form>
When you submit your form
you can get value of input hidden.
In my case the issue was caused by the same name of target and folder inside a group.
Just rename conflicted file or folder to resolve the issue.
In order to ignore untracked files especially if they are located in (a few) folders that are not tracked, a simple solution is to add a .gitignore
file to every untracked folder and enter in a single line containing *
followed by a new line. It's a really simple and straightforward solution if the untracked files are in a few folders. For me, all files were coming from a single untracked folder vendor
and the above just worked.
If you have Java installed, you can compress to a ZIP archive using the jar
command:
jar -cMf targetArchive.zip sourceDirectory
c = Creates a new archive file.
M = Specifies that a manifest file should not be added to the archive.
f = Indicates target file name.
This is the way I do it:
num = 123.456
split_num = str(num).split('.')
int_part = int(split_num[0])
decimal_part = int(split_num[1])
Check the charset encoding of the file. Make sure that it is in ASCII.
Use the od
command to see if there is a UTF-8 BOM at the beginning, for example.
You could:
Define a userStatus
parameter for the child component and provide the value when using this component from the parent:
@Component({
(...)
})
export class Profile implements OnInit {
@Input()
userStatus:UserStatus;
(...)
}
and in the parent:
<profile [userStatus]="userStatus"></profile>
Inject the parent into the child component:
@Component({
(...)
})
export class Profile implements OnInit {
constructor(app:App) {
this.userStatus = app.userStatus;
}
(...)
}
Be careful about cyclic dependencies between them.
If you editing info.plist
directly, below should help you, don't key in "YES" as string below:
<key>UIFileSharingEnabled</key>
<string>YES</string>
You should use this:
<key>UIFileSharingEnabled</key>
<true/>
This is what worked for me:
In the build.gradle
file, setting the minSdkVersion
under defaultConfig
:
Good Luck...
I am using Eclipse v4.3 (Kepler), and this is how I solved my problem.
Goto menu Help ? Install new software ? click Add.
In the popup, give any name (I named it as Eclipse ADT Plugin), and in the link's place, use https://dl-ssl.google.com/android/eclipse/
Once you click OK, you will be displayed with new packages that will be installed and old packages that will be deleted. Don't worry about these packages. Click OK.
New packages will be installed, and this should solve your problem.
My understanding is that "-u" or "--set-upstream" allows you to specify the upstream (remote) repository for the branch you're on, so that next time you run "git push", you don't even have to specify the remote repository.
Push and set upstream (remote) repository as origin:
$ git push -u origin
Next time you push, you don't have to specify the remote repository:
$ git push
For Swift 4.2
This code will allow you to control the Y axis moment of the frame for a specific device screen size.
PS: This code will not intelligently move the frame based on the location of TextField.
Create an extension for UIDevice
extension UIDevice {
enum ScreenType: String {
case iPhone4_4S = "iPhone 4 or iPhone 4s"
case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE"
case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6s, iPhone 7 or iPhone 8"
case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6s Plus, iPhone 7 Plus or iPhone 8 Plus"
case iPhoneX_Xs = "iPhone X, iPhone Xs"
case iPhoneXR = "iPhone XR"
case iPhoneXSMax = "iPhone Xs Max"
case unknown
}
var screenType: ScreenType {
switch UIScreen.main.nativeBounds.height {
case 960:
return .iPhone4_4S
case 1136:
return .iPhones_5_5s_5c_SE
case 1334:
return .iPhones_6_6s_7_8
case 1920, 2208:
return .iPhones_6Plus_6sPlus_7Plus_8Plus
case 1792:
return .iPhoneXR
case 2436:
return .iPhoneX_Xs
case 2688:
return .iPhoneXSMax
default:
return .unknown
}
}
}
Add NotificationObserver on viewDidLoad
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
Selector
@objc func keyboardWillShow(notification: NSNotification) {
if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
if self.view.frame.origin.y == 0 {
switch (UIDevice.current.screenType.rawValue) {
case (UIDevice.ScreenType.iPhones_5_5s_5c_SE.rawValue):
self.view.frame.origin.y -= 210
case (UIDevice.ScreenType.iPhones_6_6s_7_8.rawValue):
self.view.frame.origin.y -= 110
case (UIDevice.ScreenType.iPhones_6Plus_6sPlus_7Plus_8Plus.rawValue):
self.view.frame.origin.y -= 80
case (UIDevice.ScreenType.iPhoneX_Xs.rawValue):
self.view.frame.origin.y -= 70
case (UIDevice.ScreenType.iPhoneXR.rawValue):
self.view.frame.origin.y -= 70
case (UIDevice.ScreenType.iPhoneXSMax.rawValue):
self.view.frame.origin.y -= 70
default:
self.view.frame.origin.y -= 150
}
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
if self.view.frame.origin.y != 0 {
switch (UIDevice.current.screenType.rawValue) {
case (UIDevice.ScreenType.iPhones_5_5s_5c_SE.rawValue):
self.view.frame.origin.y += 210
case (UIDevice.ScreenType.iPhones_6_6s_7_8.rawValue):
self.view.frame.origin.y += 110
case (UIDevice.ScreenType.iPhones_6Plus_6sPlus_7Plus_8Plus.rawValue):
self.view.frame.origin.y += 80
case (UIDevice.ScreenType.iPhoneX_Xs.rawValue):
self.view.frame.origin.y += 70
case (UIDevice.ScreenType.iPhoneXR.rawValue):
self.view.frame.origin.y += 70
case (UIDevice.ScreenType.iPhoneXSMax.rawValue):
self.view.frame.origin.y += 70
default:
self.view.frame.origin.y += 150
}
}
}
}
select * from table order by random() limit 1000;
If you know how many rows you want, check out tsm_system_rows
.
module provides the table sampling method SYSTEM_ROWS, which can be used in the TABLESAMPLE clause of a SELECT command.
This table sampling method accepts a single integer argument that is the maximum number of rows to read. The resulting sample will always contain exactly that many rows, unless the table does not contain enough rows, in which case the whole table is selected. Like the built-in SYSTEM sampling method, SYSTEM_ROWS performs block-level sampling, so that the sample is not completely random but may be subject to clustering effects, especially if only a small number of rows are requested.
First install the extension
CREATE EXTENSION tsm_system_rows;
Then your query,
SELECT *
FROM table
TABLESAMPLE SYSTEM_ROWS(1000);
Write your first unit test
Write a JUnit test -- here's mine:
import org.junit.Assert;
import org.junit.Test;
public class MyFirstTest {
@Test
public void firstTest() {
Assert.assertTrue(true);
}
}
In addition to the answer posted by Tim Banks, which followed to solving my issue I had to edit one simple thing.
Someone else might have the same issue; I'm working with a Bootstrap dropdown in a dropdown. But the text can be wider as the current content at this point (and there aren't many good ways to resolve that through css).
I used:
$table.css({ position: "absolute", visibility: "hidden", display: "table" });
instead, which sets the container to a table which always scales in width if the contents are wider.
Had some same problems, used addEventListener for events "mousenter", "mouseleave":
let DOMelement = document.querySelector('CSS selector for your HTML element');
// if you want to change e.g color:
let origColorStyle = DOMelement.style.color;
DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });
DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })
Or something else for style when cursor is above the DOMelement. DOMElement can be chosen by various ways.
Another possible way, when the blocking function is made with jquery, use:
$(document).unbind();
It will clear all the onmousedown and contextmenu events attributed dynamically, that can't be erased with document.contextmenu=null; etc.
To answer your question, there is no "proper way" to do that.
Now if it's just the warning that bothers you, the best way to avoid its proliferation is to wrap the Query.list()
method into a DAO :
public class MyDAO {
@SuppressWarnings("unchecked")
public static <T> List<T> list(Query q){
return q.list();
}
}
This way you get to use the @SuppressWarnings("unchecked")
only once.
In C if you implement count line it will never fail. Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.
File might look some thing like this:
"hello 1
"Hello 2
"
Code below
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "file1.txt"
int main() {
FILE *fd = NULL;
int cnt, ch;
fd = fopen(FILE_NAME,"r");
if (fd == NULL) {
perror(FILE_NAME);
exit(-1);
}
while(EOF != (ch = fgetc(fd))) {
/*
* int fgetc(FILE *) returns unsigned char cast to int
* Because it has to return EOF or error also.
*/
if (ch == '\n')
++cnt;
}
printf("cnt line in %s is %d\n", FILE_NAME, cnt);
fclose(fd);
return 0;
}
Typecast the envelope to SoapPrimitive:
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String strRes = result.toString();
and it will work.
I searched for the top NodeJS html parser libraries.
Because my use cases didn't require a library with many features, I could focus on stability and performance.
By stability I mean that I want the library to be used long enough by the community in order to find bugs and that it will be still maintained and that open issues will be closed.
Its hard to understand the future of an open source library, but I did a small summary based on the top 10 libraries in openbase.
I divided into 2 groups according to the last commit (and on each group the order is according to Github starts):
Last commit is in the last 6 months:
jsdom - Last commit: 3 Months, Open issues: 331, Github stars: 14.9K
.
htmlparser2 - Last commit: 8 days, Open issues: 2, Github stars: 2.7K
.
parse5 - Last commit: 2 Months, Open issues: 21, Github stars: 2.5K
.
swagger-parser - Last commit: 2 Months, Open issues: 48, Github stars: 663
.
html-parse-stringify - Last commit: 4 Months, Open issues: 3, Github stars: 215
.
node-html-parser - Last commit: 7 days, Open issues: 15, Github stars: 205
.
Last commit is 6 months and above:
cheerio - Last commit: 1 year, Open issues: 174, Github stars: 22.9K
.
koa-bodyparser - Last commit: 6 months, Open issues: 9, Github stars: 1.1K
.
sax-js - Last commit: 3 Years, Open issues: 65, Github stars: 941
.
draftjs-to-html - Last commit: 1 Year, Open issues: 27, Github stars: 233
.
I picked Node-html-parser because it seems quiet fast and very active at this moment.
(*) Openbase adds much more information regarding each library like the number of contributors (with +3 commits), weekly downloads, Monthly commits, Version etc'.
(**) The table above is a snapshot according to the specific time and date - I would check the reference again and as a first step check the level of recent activity and then dive into the smaller details.
I was facing same problem when I installed JRE by Oracle and solved this problem after my research.
I moved the environment path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
below H:\Program Files\Java\jdk-13.0.1\bin
Like this:
Path
H:\Program Files\Java\jdk-13.0.1\bin
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
OR
Path
%JAVA_HOME%
%JRE_HOME%
I think a better answer here is simply this:
mike@sleepycat:~? kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
As for the "significance" of 9... I would say there is probably none. According to The Linux Programming Interface(p 388):
Each signal is defined as a unique (small) integer, starting sequentially from 1. These integers are defined in with symbolic names of the form SIGxxxx . Since the actual numbers used for each signal vary across implementations, it is these symbolic names that are always used in programs.
require 'pp'
pp my_hash
Use pp
if you need a built-in solution and just want reasonable line breaks.
Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false
option to turn off displaying array indices.)
I had the same issue get value for my property in my service class. I resolved it by using @ConfigurationProperties instead of @Value.
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "file")
public class FileProperties {
private String directory;
public String getDirectory() {
return directory;
}
public void setDirectory(String dir) {
this.directory = dir;
}
}
@EnableConfigurationProperties({
FileProperties.class
})
Use Linq's Union method.
Note: This solution requires no knowledge of Linq, aside from that it exists.
Code
Begin by adding the following to the top of your class file:
using System.Linq;
Now, you can use the following to remove duplicates from an object called, obj1
:
obj1 = obj1.Union(obj1).ToList();
Note: Rename obj1
to the name of your object.
How it works
The Union command lists one of each entry of two source objects. Since obj1 is both source objects, this reduces obj1 to one of each entry.
The ToList()
returns a new List. This is necessary, because Linq commands like Union
returns the result as an IEnumerable result instead of modifying the original List or returning a new List.
Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains
and unique
Array.prototype.contains = function(v) {_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
if (this[i] === v) return true;_x000D_
}_x000D_
return false;_x000D_
};_x000D_
_x000D_
Array.prototype.unique = function() {_x000D_
var arr = [];_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
if (!arr.contains(this[i])) {_x000D_
arr.push(this[i]);_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
_x000D_
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];_x000D_
var uniques = duplicates.unique(); // result = [1,3,4,2,8]_x000D_
_x000D_
console.log(uniques);
_x000D_
For more reliability, you can replace contains
with MDN's indexOf
shim and check if each element's indexOf
is equal to -1: documentation
You could try the following:
select customer1.Id,customer1.Name,customer1.city,CustAdd.phone,CustAdd.Country
from customer1
inner join [EBST08].[Test].[dbo].[customerAddress] CustAdd
on customer1.Id=CustAdd.CustId
To exit from Python terminal, simply just do:
exit()
Please pay attention it's a function which called as most user mix it with exit without calling, but new Pyhton terminal show a message...
or as a shortcut, press:
Ctrl + D
on your keyboard...
I have built a mashup of existing answers to simplify everything and reduce the amount of code needed for Swift 3.
func hmsFrom(seconds: Int, completion: @escaping (_ hours: Int, _ minutes: Int, _ seconds: Int)->()) {
completion(seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
func getStringFrom(seconds: Int) -> String {
return seconds < 10 ? "0\(seconds)" : "\(seconds)"
}
Usage:
var seconds: Int = 100
hmsFrom(seconds: seconds) { hours, minutes, seconds in
let hours = getStringFrom(seconds: hours)
let minutes = getStringFrom(seconds: minutes)
let seconds = getStringFrom(seconds: seconds)
print("\(hours):\(minutes):\(seconds)")
}
Prints:
00:01:40
Extracting the address all by itself is a bit difficult, but you can get the entire IP Address line easily.
To show all IP addresses on any English-language Windows OS:
ipconfig | findstr /R /C:"IP.* Address"
To show only IPv4 or IPv6 addresses on Windows 7+:
ipconfig | findstr /R /C:"IPv4 Address"
ipconfig | findstr /R /C:"IPv6 Address"
Here's some sample output from an XP machine with 3 network adapters.
IP Address. . . . . . . . . . . . : 192.168.1.10
IP Address. . . . . . . . . . . . : 10.6.102.205
IP Address. . . . . . . . . . . . : 192.168.56.1
for i in range (1, len(list))
try:
print (list[i])
except ValueError:
print("Error Value.")
except indexError:
print("Erorr index")
except :
print('error ')
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
IMHO this code could be simplified:
if(boolean1 != boolean2)
{
//do it
}
The most reliable way is with
String cleanedString = StringEscapeUtils.unescapeHtml4(originalString);
from org.apache.commons.lang3.StringEscapeUtils
.
And to escape the whitespaces
cleanedString = cleanedString.trim();
This will ensure that whitespaces due to copy and paste in web forms to not get persisted in DB.
I wrote a simple ini config library in golang.
goroutine-safe, easy to use
package cfg
import (
"testing"
)
func TestCfg(t *testing.T) {
c := NewCfg("test.ini")
if err := c.Load() ; err != nil {
t.Error(err)
}
c.WriteInt("hello", 42)
c.WriteString("hello1", "World")
v, err := c.ReadInt("hello", 0)
if err != nil || v != 42 {
t.Error(err)
}
v1, err := c.ReadString("hello1", "")
if err != nil || v1 != "World" {
t.Error(err)
}
if err := c.Save(); err != nil {
t.Error(err)
}
}
===================Update=======================
Recently I need an INI parser with section support, and I write a simple package:
github.com/c4pt0r/cfg
u can parse INI like using "flag" package:
package main
import (
"log"
"github.com/c4pt0r/ini"
)
var conf = ini.NewConf("test.ini")
var (
v1 = conf.String("section1", "field1", "v1")
v2 = conf.Int("section1", "field2", 0)
)
func main() {
conf.Parse()
log.Println(*v1, *v2)
}
import java.util.*;
public class Parenthesis
{
public static void main(String...okok)
{
Scanner sc= new Scanner(System.in);
String str=sc.next();
System.out.println(isValid(str));
}
public static int isValid(String a) {
if(a.length()%2!=0)
{
return 0;
}
else if(a.length()==0)
{
return 1;
}
else
{
char c[]=a.toCharArray();
Stack<Character> stk = new Stack<Character>();
for(int i=0;i<c.length;i++)
{
if(c[i]=='(' || c[i]=='[' || c[i]=='{')
{
stk.push(c[i]);
}
else
{
if(stk.isEmpty())
{
return 0;
//break;
}
else
{
char cc=c[i];
if(cc==')' && stk.peek()=='(' )
{
stk.pop();
}
else if(cc==']' && stk.peek()=='[' )
{
stk.pop();
}
else if(cc=='}' && stk.peek()=='{' )
{
stk.pop();
}
}
}
}
if(stk.isEmpty())
{
return 1;
}else
{
return 0;
}
}
}
}
I tried to use socket.io on AWS, I can at most keep around 600 connections stable.
And I found out it is because socket.io used long polling first and upgraded to websocket later.
after I set the config to use websocket only, I can keep around 9000 connections.
Set this config at client side:
const socket = require('socket.io-client')
const conn = socket(host, { upgrade: false, transports: ['websocket'] })
Well, to answer the immediate question:
>>> s = "http://www.domain.com/?s=some&two=20"
The rfind
method returns the index of right-most substring:
>>> s.rfind("&")
29
You can take all elements up to a given index with the slicing operator:
>>> "foobar"[:4]
'foob'
Putting the two together:
>>> s[:s.rfind("&")]
'http://www.domain.com/?s=some'
If you are dealing with URLs in particular, you might want to use built-in libraries that deal with URLs. If, for example, you wanted to remove two
from the above query string:
First, parse the URL as a whole:
>>> import urlparse, urllib
>>> parse_result = urlparse.urlsplit("http://www.domain.com/?s=some&two=20")
>>> parse_result
SplitResult(scheme='http', netloc='www.domain.com', path='/', query='s=some&two=20', fragment='')
Take out just the query string:
>>> query_s = parse_result.query
>>> query_s
's=some&two=20'
Turn it into a dict
:
>>> query_d = urlparse.parse_qs(parse_result.query)
>>> query_d
{'s': ['some'], 'two': ['20']}
>>> query_d['s']
['some']
>>> query_d['two']
['20']
Remove the 'two'
key from the dict:
>>> del query_d['two']
>>> query_d
{'s': ['some']}
Put it back into a query string:
>>> new_query_s = urllib.urlencode(query_d, True)
>>> new_query_s
's=some'
And now stitch the URL back together:
>>> result = urlparse.urlunsplit((
parse_result.scheme, parse_result.netloc,
parse_result.path, new_query_s, parse_result.fragment))
>>> result
'http://www.domain.com/?s=some'
The benefit of this is that you have more control over the URL. Like, if you always wanted to remove the two
argument, even if it was put earlier in the query string ("two=20&s=some"
), this would still do the right thing. It might be overkill depending on what you want to do.
I liked learnvst's answer of using the tables because it is quite readable (which is one purpose of writing Markdown).
However, in the case of GitBook's Markdown parser I had to, in addition to an empty header line, add a separator line under it, for the table to be recognized and properly rendered:
| - | - |
|---|---|
| I am text to the left | ![Flowers](/flowers.jpeg) |
| ![Flowers](/flowers.jpeg) | I am text to the right |
Separator lines need to include at least three dashes ---
.
One bizarre thing is that in Chrome + Firefox, the MOUSE_LEAVE event isn't dispatched for OPAQUE
and TRANSPARENT
.
With WINDOW
it works fine. That one took some time to find out! grr...
(note: jediericb mentioned this bug - which is similar but doesn't mention MOUSE_LEAVE
)
Start Visual Studio
Tools -> Import and Export Settings -> Export selected environment settings
You need to be really quick to navigate the menu before Licensing pop-up appears, (this step is optional: worst case scenario you would have to restore all the settings manually).
Once in "Import and Export Settings" dialogue you can relax.
Exit Visual Studio.
From the command prompt run:
devenv /resetuserdata
for the particular Visual Studio version.
Safest way is to right-click on the shortcut -> Properties -> Shortcut -> Target -> copy
.
Final command should look something like:
"C:\Program Files (x86)\Microsoft Visual Studio NN.N\Common7\IDE\devenv.exe" /resetuserdata
Go through log-in and initial settings.
Tools -> Import and Export Settings -> Import selected environment settings
to restore your original settings.
This worked when the error:
We were unable to establish the connection because it is configured for user email@address but you attempted to connect using user email@address. To connect as a different user perform a switch user operation. To connect with the configured identity just attempt the last operation again.
...has both instances of email@address identical.
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
If you want to disable the highlight for a single list view item, but keep the cell enabled, set the background color for that cell to disable the highlighting.
For instance, in your cell layout, set android:background="@color/white"
You can use this code snippet ...
<html>
<body>
<form>
<input type="radio" name="color" value="black" required />
<input type="radio" name="color" value="white" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Specify "required" keyword in one of the select statements. If you want to change the default way of its appearance. You can follow these steps. This is just for extra info if you have any intention to modify the default behavior.
Add the following into you .css
file.
/* style all elements with a required attribute */
:required {
background: red;
}
For more information you can refer following URL.
Another trick is to use
.class {
position: absolute;
visibility:hidden;
display:none;
}
This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none
works later on it will be working. Keep in mind that visibility:hidden
may not remove it from screen readers.
My problem was that I was looking at it from the long angle:
function new_line() {
var html= '<div><br><input type="text" value="" id="dateP_'+ i +'"></div>';
document.getElementById("container").innerHTML += html;
$('#dateP_'+i).datepicker({
showOn: 'button',
buttonImage: 'calendar.gif',
buttonImageOnly: true
});
i++;
}
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
.vue
files<script>
var mylib = require('./mylib');
export default {
....
mylib
exports.myfunc = () => {....}
import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
If you are a windows 10 + TortoiseGit 2.7 user:
This expands on @Reigel's answer. It will return an answer for horizontal or vertical scrollbars.
(function($) {
$.fn.hasScrollBar = function() {
var e = this.get(0);
return {
vertical: e.scrollHeight > e.clientHeight,
horizontal: e.scrollWidth > e.clientWidth
};
}
})(jQuery);
Example:
element.hasScrollBar() // Returns { vertical: true/false, horizontal: true/false }
element.hasScrollBar().vertical // Returns true/false
element.hasScrollBar().horizontal // Returns true/false
From the screenshot I can see that you want to pass "user" and "password" values to the service. You have send the parameter values in the request header part which is wrong.
The values are sent in the request body and not in the request header.
Also your syntax is wrong.
Correct syntax is: {"user":"user_val","password":"password_val"}.
Also check what is the the content type. It should match with the content type you have set to your service.
Just in case someone has the same issue as me, I was missing "/" before one of the "/p" arguments. Not very clear from the description. I hope this helps someone.
import sys
for x in range(10000):
print "HAPPY >> %s <<\r" % str(x),
sys.stdout.flush()
The following regex extracts the sub, root and tld of a given domain:
^(?<domain>(?<domain_sub>(?:[^\/\"\]:\.\s\|\-][^\/\"\]:\.\s\|]*?\.)*?)(?<domain_root>[^\/\"\]:\s\.\|\n]+\.(?<domain_tld>(?:xn--)?[\w-]{2,7}(?:\.[a-zA-Z-]{2,3})*)))$
Tested for the following domains:
* stack.com
* sta-ck.com
* sta---ck.com
* 9sta--ck.com
* sta--ck9.com
* stack99.com
* 99stack.com
* sta99ck.com
* google.com.uk
* google.co.in
* google.com
* maselkowski.pl
* maselkowski.pl
* m.maselkowski.pl
* www.maselkowski.pl.com
* xn--masekowski-d0b.pl
* xn--fiqa61au8b7zsevnm8ak20mc4a87e.xn--fiqs8s
* xn--stackoverflow.com
* stackoverflow.xn--com
* stackoverflow.co.uk
I fixed it myself, the key is android:width="0dip"
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="4dip"
android:layout_weight="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="4dip">
<TextView
android:id="@+id/reviewItemEntityName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/maroon"
android:singleLine="true"
android:ellipsize="end"
android:textSize="14sp"
android:textStyle="bold"
android:layout_weight="1" />
<ImageView
android:id="@+id/reviewItemStarRating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" />
</LinearLayout>
<TextView
android:id="@+id/reviewItemDescription"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="12sp"
android:width="0dip" />
</LinearLayout>
<ImageView
android:id="@+id/widget01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/arrow_nxt"
android:layout_gravity="center_vertical"
android:paddingRight="5dip" />
</LinearLayout>
a)
from selenium.common.exceptions import NoSuchElementException
def check_exists_by_xpath(xpath):
try:
webdriver.find_element_by_xpath(xpath)
except NoSuchElementException:
return False
return True
b) use xpath - the most reliable. Moreover you can take the xpath as a standard throughout all your scripts and create functions as above mentions for universal use.
UPDATE: I wrote the initial answer over 4 years ago and at the time I thought xpath would be the best option. Now I recommend to use css selectors. I still recommend not to mix/use "by id", "by name" and etc and use one single approach instead.
Try this:
const element = document.querySelector('#elementId');
if (element.classList.contains("classToBeRemoved")) {
element.classList.remove("classToBeRemoved");
}
E: Since this answer seems to have gained some popularity, I will add: doing things globally is most of the time not a great idea. Almost always the correct answer is: use a project environment where you're not installing things globally, e.g. with virtualenv
.
For those that may run into the same issue:
Run the command prompt as administrator. Having administrator permissions in the account is not always enough. In Windows, things can be run as administrator by right-clicking the executable and selecting "Run as Administrator". So, type "cmd" to the Start menu, right click cmd.exe, and run it as administrator.
The Android Training class, "Displaying Bitmaps Efficiently", offers some great information for understanding and dealing with the exception java.lang.OutOfMemoryError: bitmap size exceeds VM budget
when loading Bitmaps.
The BitmapFactory
class provides several decoding methods (decodeByteArray()
, decodeFile()
, decodeResource()
, etc.) for creating a Bitmap
from various sources. Choose the most appropriate decode method based on your image data source. These methods attempt to allocate memory for the constructed bitmap and therefore can easily result in an OutOfMemory
exception. Each type of decode method has additional signatures that let you specify decoding options via the BitmapFactory.Options
class. Setting the inJustDecodeBounds
property to true
while decoding avoids memory allocation, returning null
for the bitmap object but setting outWidth
, outHeight
and outMimeType
. This technique allows you to read the dimensions and type of the image data prior to construction (and memory allocation) of the bitmap.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
To avoid java.lang.OutOfMemory
exceptions, check the dimensions of a bitmap before decoding it, unless you absolutely trust the source to provide you with predictably sized image data that comfortably fits within the available memory.
Now that the image dimensions are known, they can be used to decide if the full image should be loaded into memory or if a subsampled version should be loaded instead. Here are some factors to consider:
For example, it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x96 pixel thumbnail in an ImageView
.
To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize
to true
in your BitmapFactory.Options
object. For example, an image with resolution 2048x1536 that is decoded with an inSampleSize
of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of ARGB_8888
). Here’s a method to calculate a sample size value that is a power of two based on a target width and height:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Note: A power of two value is calculated because the decoder uses a final value by rounding down to the nearest power of two, as per the
inSampleSize
documentation.
To use this method, first decode with inJustDecodeBounds
set to true
, pass the options through and then decode again using the new inSampleSize
value and inJustDecodeBounds
set to false
:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
This method makes it easy to load a bitmap of arbitrarily large size into an ImageView
that displays a 100x100 pixel thumbnail, as shown in the following example code:
mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
You can follow a similar process to decode bitmaps from other sources, by substituting the appropriate BitmapFactory.decode*
method as needed.
I would checkout the remote file from the "master" (the remote/origin repository) like this:
git checkout master <FileWithPath>
Example: git checkout master components/indexTest.html
On my linux system, I start Tomcat with the startup.sh script. To know whether it is running or not, i use
ps -ef | grep tomcat
If the output result contains the whole path to my tomcat folder, then it is running
Try CSS3 Textshadow.
.box_textshadow {
text-shadow: 2px 2px 0px #FF0000; /* FF3.5+, Opera 9+, Saf1+, Chrome, IE10 */
}
Try it yourself on css3please.com.
Alternative way of converting to csv. Use libreoffice
:
libreoffice --headless --convert-to csv *
Please be aware that this will only convert the first worksheet of your Excel file.
you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.
Not IsNull(Fields!W_O_Count.Value)
Difference between Comparator and Comparable interfaces
Comparable
is used to compare itself by using with another object.
Comparator
is used to compare two datatypes are objects.
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
If working on EJB client library:
You need to mention the argument for getting the initial context.
InitialContext ctx = new InitialContext();
If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
InitialContext ctx = new InitialContext(props);
URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.
The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.
Since the values are actually inside of an HTML attribute, you should use '
"<img src='something' onmouseover='change('ex1')' />";
For SQL Server (2008 and above):
SELECT COLUMNPROPERTY(OBJECT_ID('mytable'), 'Remarks', 'PRECISION');
COLUMNPROPERTY returns information for a column or parameter (id, column/parameter, property). The PRECISION property returns the length of the data type of the column or parameter.
If you like to use gnuplot for plotting, you should consider Gnuplot.py. It provides an object-oriented interface to gnuplot, and also allows you to pass commands directly to gnuplot. Unfortunately, it is no longer being actively developed.
I found out that with HostGator you have to set files to CMOD 644 and Folders to 755. Since I did this based on their tech support it works with HostGator
You must use the column names and then set the values to insert (both ? marks):
//insert 1st row
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();
If origin
points to a bare repository on disk, this error can happen if that directory has been moved (even if you update the working copy's remotes). For example
$ mv /path/to/origin /somewhere/else
$ git remote set-url origin /somewhere/else
$ git diff origin/master
fatal: ambiguous argument 'origin': unknown revision or path not in the working tree.
Pulling once from the new origin
solves the problem:
$ git stash
$ git pull origin master
$ git stash pop
If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.
Ex:
--id is primary key of MainTable
declare @id int
set @id = 1
declare theMain cursor for select FK from MainTable where MainID = @id
declare @fk_Id int
open theMain
fetch next from theMain into @fk_Id
while @@fetch_status=0
begin
--fkid is the foreign key
--Must delete from Main Table first then child.
delete from MainTable where fkid = @fk_Id
delete from ReferencingTable where fkid = @fk_Id
fetch next from theMain into @fk_Id
end
close theMain
deallocate theMain
hope is useful
The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:
int x = 0; //x is 0
int y = ++x; //x is 1 and y is 1
If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:
int x = 0; //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0
I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:
while (x < 5) //evaluates conditional statement
{
//some code
++x; //increments x
}
or
while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
//some code
}
You can also do this while indexing arrays and such:
int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678; //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);
Etc, etc...
The better way of sending GET
or POST
requests with PHP
is as below:
<?php
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
try {
echo $r->send()->getBody();
} catch (HttpException $ex) {
echo $ex;
}
?>
The code is taken from official documentation here http://docs.php.net/manual/da/httprequest.send.php
You've got to override your Canvas's paint(Graphics g)
method and perform your drawing there. See the paint() documentation.
As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.
create or replace procedure ex(j in number) as
i number;
begin
select id into i from student where id=j;
if i is not null then
dbms_output.put_line('exists');
end if;
exception
when no_data_found then
dbms_output.put_line(i||' does not exists');
end;
It is safe to store your token in localStorage as long as you encrypt it. Below is a compressed code snippet showing one of many ways you can do it.
import SimpleCrypto from 'simple-crypto-js';
const saveToken = (token = '') => {
const encryptInit = new SimpleCrypto('PRIVATE_KEY_STORED_IN_ENV_FILE');
const encryptedToken = encryptInit.encrypt(token);
localStorage.setItem('token', encryptedToken);
}
Then, before using your token decrypt it using PRIVATE_KEY_STORED_IN_ENV_FILE
StringBuilder sb= new StringBuilder();
for (int i = 0; i < tmpHash.Length; i++)
{
sb.Append(tmpHash[i].ToString("x2"));
}
This is an alternative:
- name: Install this only for local dev machine
pip: name=pyramid
delegate_to: localhost
What is the basic problem in your code?
Your code needs to be separated out in to interfaces(.h) and Implementations(.cpp).
The compiler needs to see the composition of a type when you write something like
ClassTwo obj;
This is because the compiler needs to reserve enough memory for object of type ClassTwo
to do so it needs to see the definition of ClassTwo
. The most common way to do this in C++ is to split your code in to header files and source files.
The class definitions go in the header file while the implementation of the class goes in to source files. This way one can easily include header files in to other source files which need to see the definition of class who's object they create.
Why can't I simply put all code in cpp files and include them in other files?
You cannot simple put all the code in source file and then include that source file in other files.C++ standard mandates that you can declare a entity as many times as you need but you can define it only once(One Definition Rule(ODR)). Including the source file would violate the ODR because a copy of the entity is created in every translation unit where the file is included.
How to solve this particular problem?
Your code should be organized as follows:
//File1.h
Define ClassOne
//File2.h
#include <iostream>
#include <string>
class ClassTwo
{
private:
string myType;
public:
void setType(string);
std::string getType();
};
//File1.cpp
#include"File1.h"
Implementation of ClassOne
//File2.cpp
#include"File2.h"
void ClassTwo::setType(std::string sType)
{
myType = sType;
}
void ClassTwo::getType(float fVal)
{
return myType;
}
//main.cpp
#include <iostream>
#include <string>
#include "file1.h"
#include "file2.h"
using namespace std;
int main()
{
ClassOne cone;
ClassTwo ctwo;
//some codes
}
Is there any alternative means rather than including header files?
If your code only needs to create pointers and not actual objects you might as well use Forward Declarations but note that using forward declarations adds some restrictions on how that type can be used because compiler sees that type as an Incomplete type.
Swift: Ui Button create programmatically,
var button: UIButton = UIButton(type: .Custom)
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0)
button.addTarget(self, action: #selector(self.aMethod), forControlEvents: .TouchUpInside)
button.tag=2
button.setTitle("Hallo World", forState: .Normal)
view.addSubview(button)
func aMethod(sender: AnyObject) {
print("you clicked on button \(sender.tag)")
}
The problem you encounter comes from the lack of call to super.prepareForReuse()
.
Some other solutions above, suggesting to update the UI of the cell from the delegate's functions, are leading to a flawed design where the logic of the cell's behaviour is outside of its class. Furthermore, it's extra code that can be simply fixed by calling super.prepareForReuse()
. For example :
class myCell: UICollectionViewCell {
// defined in interface builder
@IBOutlet weak var viewSelection : UIView!
override var isSelected: Bool {
didSet {
self.viewSelection.alpha = isSelected ? 1 : 0
}
}
override func prepareForReuse() {
// Do whatever you want here, but don't forget this :
super.prepareForReuse()
// You don't need to do `self.viewSelection.alpha = 0` here
// because `super.prepareForReuse()` will update the property `isSelected`
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.viewSelection.alpha = 0
}
}
With such design, you can even leave the delegate's functions collectionView:didSelectItemAt:
/collectionView:didDeselectItemAt:
all empty, and the selection process will be totally handled, and behave properly with the cells recycling.
One other significant point if you're using C# 6:
'=>' can be used instead of 'get' and is only for 'get only' methods - it can't be used with a 'set'.
For C# 7, see the comment from @avenmore below - it can now be used in more places. Here's a good reference - https://csharp.christiannagel.com/2017/01/25/expressionbodiedmembers/
You're probably better off comparing the fields individually, rather than concatenating the strings.
SELECT t1.*
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.MAKE = t2.MAKE
AND t1.MODEL = t2.MODEL
AND t1.[serial number] = t2.[serial number]
WHERE t2.MAKE IS NULL
Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>
", other links associated with Facebook turns into "on.fb.me/*****
". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.
My particular use-case was selecting a text range inside an editable span element, which, as far as I could see, is not described in any of the answers here.
The main difference is that you have to pass a node of type Text
to the Range
object, as described in the documentation of Range.setStart():
If the startNode is a Node of type Text, Comment, or CDATASection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode.
The Text
node is the first child node of a span element, so to get it, access childNodes[0]
of the span element. The rest is the same as in most other answers.
Here a code example:
var startIndex = 1;
var endIndex = 5;
var element = document.getElementById("spanId");
var textNode = element.childNodes[0];
var range = document.createRange();
range.setStart(textNode, startIndex);
range.setEnd(textNode, endIndex);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
Other relevant documentation:
Range
Selection
Document.createRange()
Window.getSelection()
You should introduce a cast inside the click
event handler
MouseEventArgs me = (MouseEventArgs) e;
The simplest (Non Win32) way is to add a UserForm to your VBA project (if you don't already have one) or alternatively add a reference to Microsoft Forms 2 Object Library, then from a sheet/module you can simply:
With New MSForms.DataObject
.SetText "http://zombo.com"
.PutInClipboard
End With
Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.
<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
Not as put off time and language at a time I put this and not work
$(function () {
$('#datetimepicker2').datetimepicker({
locale: 'es',
pickTime: false
});
});
simply in your css use '.ui-datepicker{ z-index: 9999 !important;}
' Here 9999 can be replaced to whatever layer value you want your datepicker available. Neither any code is to be commented nor adding 'position:relative;
' css on input elements. Because increasing the z-index of input elements will have effect on all input type buttons, which may not be needed for some cases.
A method to get the greatest power of ten smaller or equal to an integer: (in recursion)
public static int powerOfTen(int n) {
if ( n < 10)
return 1;
else
return 10 * powerOfTen(n/10);
}
The method to reverse the actual integer:(in recursion)
public static int reverseInteger(int i) {
if (i / 10 < 1)
return i ;
else
return i%10*powerOfTen(i) + reverseInteger(i/10);
}
string[] lines = File.ReadLines("c:\\file.txt").ToArray();
Although one wonders why you'll want to do that when ReadAllLines
works just fine.
Or perhaps you just want to enumerate with the return value of File.ReadLines
:
var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
Console.WriteLine("\t" + line);
}
this code is tested with pdfminer for python 3 (pdfminer-20191125)
from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.layout import LTTextBoxHorizontal
def parsedocument(document):
# convert all horizontal text into a lines list (one entry per line)
# document is a file stream
lines = []
rsrcmgr = PDFResourceManager()
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.get_pages(document):
interpreter.process_page(page)
layout = device.get_result()
for element in layout:
if isinstance(element, LTTextBoxHorizontal):
lines.extend(element.get_text().splitlines())
return lines
java.sql.ResultSet rs;
//fill rs somehow
java.sql.Timestamp timestamp = rs.getTimestamp(1); //get first column
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
java.util.Date date = return new java.util.Date(milliseconds);
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
This solves the problem:
df['newcolumn'] = df.A * df.B
You could also do:
def fab(row):
return row['A'] * row['B']
df['newcolumn'] = df.apply(fab, axis=1)
HTML
<div id='parent'>
<div id='centered-child'></div>
</div>
CSS
#parent {
position: relative;
}
#centered-child {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto auto;
}
A bit more old-school
svn diff -r 150:140 > ../r140.patch
patch -p0 < ../r140.patch
then the usual
svn diff
svn commit
Luhn's algorithm is used for adding validation of credit and debit card numbers. This JavaScript function should work out.
function validate_creditcardnumber(inputNum) {
var digit, digits, flag, sum, _i, _len;
flag = true;
sum = 0;
digits = (inputNum + '').split('').reverse();
for (_i = 0, _len = digits.length; _i < _len; _i++) {
digit = digits[_i];
digit = parseInt(digit, 10);
if ((flag = !flag)) {
digit *= 2;
}
if (digit > 9) {
digit -= 9;
}
sum += digit;
}
return sum % 10 === 0;
};
If you want to check the display value, https://stackoverflow.com/a/1189281/5622596 already posted the answer.
However if instead of checking whether an element has a style of style="display:none"
you want to know if that element is visible. Then use .is(":visible")
For example:
$('#idDetails').is(":visible");
This will be true
if it is visible & false
if it is not.
It turns out that you can set window.undefined to whatever you want, and so get object.x !== undefined
when object.x is the real undefined. In my case I inadvertently set undefined to null.
The easiest way to see this happen is:
window.undefined = null;
alert(window.xyzw === undefined); // shows false
Of course, this is not likely to happen. In my case the bug was a little more subtle, and was equivalent to the following scenario.
var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false
List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "[email protected]", "[email protected]", "[email protected]" };
var result = (from t2 in test2
where test1.Any(t => t2.Contains(t)) == false
select t2);
If query form is what you want to use, this is legible and more or less as "performant" as this could be.
What i mean is that what you are trying to do is an O(N*M) algorithm, that is, you have to traverse N items and compare them against M values. What you want is to traverse the first list only once, and compare against the other list just as many times as needed (worst case is when the email is valid since it has to compare against every black listed domain).
from t2 in test
we loop the email list once.
test1.Any(t => t2.Contains(t)) == false
we compare with the blacklist and when we found one match return (hence not comparing against the whole list if is not needed)
select t2
keep the ones that are clean.
So this is what I would use.
It seems you don't want to keep the whole DataTable as a copy, because you only need some rows, right? If you got a creteria you can specify with a select on the table, you could copy just those rows to an extra backup array of DataRow like
DataRow[] rows = sourceTable.Select("searchColumn = value");
The .Select() function got several options and this one e.g. can be read as a SQL
SELECT * FROM sourceTable WHERE searchColumn = value;
Then you can import the rows you want as described above.
targetTable.ImportRows(rows[n])
...for any valid n you like, but the columns need to be the same in each table.
Some things you should know about ImportRow is that there will be errors during runtime when using primary keys!
First I wanted to check whether a row already existed which also failed due to a missing primary key, but then the check always failed. In the end I decided to clear the existing rows completely and import the rows I wanted again.
The second issue did help to understand what happens. The way I'm using the import function is to duplicate rows with an exchanged entry in one column. I realized that it always changed and it still was a reference to the row in the array. I first had to import the original and then change the entry I wanted.
The reference also explains the primary key errors that appeared when I first tried to import the row as it really was doubled up.
Here's a plain JavaScript version:
function scroll(e) {
var delta = (e.type === "mousewheel") ? e.wheelDelta : e.detail * -40;
if (delta < 0 && (this.scrollHeight - this.offsetHeight - this.scrollTop) <= 0) {
this.scrollTop = this.scrollHeight;
e.preventDefault();
} else if (delta > 0 && delta > this.scrollTop) {
this.scrollTop = 0;
e.preventDefault();
}
}
document.querySelectorAll(".scroller").addEventListener("mousewheel", scroll);
document.querySelectorAll(".scroller").addEventListener("DOMMouseScroll", scroll);
This solution is a little older school, and should be memory efficient.
public static String toHexString(byte bytes[]) {
if (bytes == null) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int iter = 0; iter < bytes.length; iter++) {
byte high = (byte) ( (bytes[iter] & 0xf0) >> 4);
byte low = (byte) (bytes[iter] & 0x0f);
sb.append(nibble2char(high));
sb.append(nibble2char(low));
}
return sb.toString();
}
private static char nibble2char(byte b) {
byte nibble = (byte) (b & 0x0f);
if (nibble < 10) {
return (char) ('0' + nibble);
}
return (char) ('a' + nibble - 10);
}
Another option is to download and install a new version using an installer.
If there are up to 10 strings then you should use a list in order to iterate through all values.
{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}
Applied the instructions from this answer and it worked
Just to point out a more copy paste like answer ( because cygwin installation procedure is kind of anti-copy-paste wise implemented )
Click WinLogo button , type cmd.exe , right click it , choose "Start As Administrator". In cmd prompt:
cd <directory_where_i_forgot_the setup-x86_64.exe> cygwin installer:
set package_name=cygrunsrv cron
setup-x86_64.exe -n -q -s http://cygwin.mirror.constant.com -P %package_name%
Ensure the installer does not throw any errors in the prompt ... If it has - you probably have some cygwin binaries running or you are not an Windows admin, or some freaky bug ...
Now in cmd promt:
C:\cygwin64\bin\cygrunsrv.exe -I cron -p /usr/sbin/cron -a -D
or whatever full file path you might have to the cygrunsrv.exe and start the cron as windows service in the cmd prompt
net start cron
Now in bash terminal run crontab -e
set up you cron entry an example bellow:
#sync my gdrive each 10th minute
*/10 * * * * /home/Yordan/sync_gdrive.sh
# * * * * * command to be executed
# - - - - -
# | | | | |
# | | | | +- - - - day of week (0 - 6) (Sunday=0)
# | | | +- - - - - month (1 - 12)
# | | +- - - - - - day of month (1 - 31)
# | +- - - - - - - hour (0 - 23)
# +--------------- minute
Here's one way:
CString str;
str.Format("%d", 5);
In your case, try _T("%d")
or L"%d"
rather than "%d"
You need to specify the minimum width of the field.
String.format("%" + numberOfSpaces + "s", "");
Why do you want to generate a String of spaces of a certain length.
If you want a column of this length with values then you can do:
String.format("%" + numberOfSpaces + "s", "Hello");
which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.
Late answer, but my solution works in Eclipse XSLT. Eclipse uses XSLT 1 at time of this writing. You can install an XSLT 2 engine like Saxon. Or you can use the XSLT 1 solution below to insert current date and time.
<xsl:value-of select="java:util.Date.new()"/>
This will call Java's Data class to output the date. It will not work unless you also put the following "java:" definition in your <xsl:stylesheet>
tag.
<xsl:stylesheet [...snip...]
xmlns:java="java"
[...snip...]>
I hope that helps someone. This simple answer was difficult to find for me.
If you are running against IIS rather than the VS webdev server, ensure that Index.aspx is one of your default files and that directory browsing is turned off.
There are a handful of options:
Using the Interop will require that the Excel be installed on the machine from which it is running. In a server side solution, this will be awful. Instead, you should use a tool like the ones above that lets you build an Excel file without Excel being installed.
If the user does not have Excel but has a tool that will read Excel (like Open Office), then obviously they will be able to open it. Microsoft has a free Excel viewer available for those users that do not have Excel.
In my case it was because of me used +
as in other language but in PHP strings concatenation operator is .
.
When using the window[objname], please make sure the objname is global variables. Otherwise, will work sometime, and fail sometimes. window[objname].value.
If the answers already posted didn't help, one can try with $location.search().myParam; with URLs http://example.domain#?myParam=paramValue
I created a project like you did. The structure looks like this
The Classes are just copy pasted from yours.
I changed the application.properties to this:
spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
But I think your problem is in your 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Check these files for differences. Hope this helps
Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL
substr(i,j)
means that you start from the index i
(assuming the first index to be 0) and take next j
chars.
It does not mean going up to the index j
.
Ok, it is apocalyptical 2020 now, and you can find these methods in NuGet package System.Net.Http.Json
. But beware that it uses System.Text.Json
internally.
And if you really need to find out which API resides where, just use https://apisof.net/
v.Dt is likely not a Date() object.
See http://jsfiddle.net/southerd/xG2t8/
but in your controller:
scope.v.Dt = Date.parse(scope.v.Dt);
Use continue;
instead of break;
to enter the next iteration of the loop without executing any more of the contained code.
foreach (Item item in myItemsList)
{
if (item.Name == string.Empty)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
if (item.Weight > 100)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
}
Official docs are here, but they don't add very much color.
Very close! In your select
expression, you have to use a pipe (|
) before contains
.
This filter produces the expected output.
. - map(select(.Names[] | contains ("data"))) | .[] .Id
The jq Cookbook has an example of the syntax.
Filter objects based on the contents of a key
E.g., I only want objects whose genre key contains "house".
$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]' $ echo "$json" | jq -c '.[] | select(.genre | contains("house"))' {"genre":"deep house"} {"genre":"progressive house"}
Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.
The simplest way is to wrap the whole expression in an array constructor:
$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]
You can also use the map function:
$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]
map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f)
is equivalent to [.[]|f]
.
The best way to extract the values is to just do the following
json.loads(dataframe[column].value_counts().to_json())
This returns a dictionary which you can use like any other dict. Using values or keys.
{"apple": 5, "sausage": 2, "banana": 2, "cheese": 1}
Take a look at Linq-to-Excel. It's pretty neat.
var book = new LinqToExcel.ExcelQueryFactory(@"File.xlsx");
var query =
from row in book.Worksheet("Stock Entry")
let item = new
{
Code = row["Code"].Cast<string>(),
Supplier = row["Supplier"].Cast<string>(),
Ref = row["Ref"].Cast<string>(),
}
where item.Supplier == "Walmart"
select item;
It also allows for strongly-typed row access too.
Install the Pillow library by following commands:
pip install pillow
Note, the selected answer has been outdated. See the docs of SciPy
Note that Pillow (https://python-pillow.org/) is not a dependency of SciPy, but the image manipulation functions indicated in the list below are not available without it.
DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];
for (int i = 0; i < dr_art_line_2.Rows.Count; i++)
{
QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);
//Similarly for QuantityInIssueUnit_uom.
}
Don't use String.prototype.toCamelCase() because String.prototypes are read-only, most of the js compilers will give you this warning.
Like me, those who know that the string will always contains only one space can use a simpler approach:
let name = 'test string';
let pieces = name.split(' ');
pieces = pieces.map((word, index) => word.charAt(0)[index===0 ? 'toLowerCase' :'toUpperCase']() + word.toLowerCase().slice(1));
return pieces.join('');
Have a good day. :)
If you need to get the int value, just have a getter for the value in your ENUM:
private enum DownloadType {
AUDIO(1), VIDEO(2), AUDIO_AND_VIDEO(3);
private final int value;
private DownloadType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public static void main(String[] args) {
System.out.println(DownloadType.AUDIO.getValue()); //returns 1
System.out.println(DownloadType.VIDEO.getValue()); //returns 2
System.out.println(DownloadType.AUDIO_AND_VIDEO.getValue()); //returns 3
}
Or you could simple use the ordinal()
method, which would return the position of the enum constant in the enum.
private enum DownloadType {
AUDIO(0), VIDEO(1), AUDIO_AND_VIDEO(2);
//rest of the code
}
System.out.println(DownloadType.AUDIO.ordinal()); //returns 0
System.out.println(DownloadType.VIDEO.ordinal()); //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.ordinal()); //returns 2
Use splatting.
$CurlArgument = '-u', '[email protected]:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument
If someone ends up here from google, looking to convert a single figure to a .pdf (that was what I was looking for):
import matplotlib.pyplot as plt
f = plt.figure()
plt.plot(range(10), range(10), "o")
plt.show()
f.savefig("foo.pdf", bbox_inches='tight')
Ok, I had a problem with Notepad++ not remembering that I had chosen not the "Remember Current Session". I tried hacking the config file, but that didn't work. Then I found out that there is a secret config file in your C:\Users\myuseraccount\AppData\Roaming\Notepad++ directory (Windows 7 x64). Mine was empty, meaning who know where the config was really coming from, but I copied over the file with the one in C:\Program Files (x86)\Notepad++ and now everything works just like you would expect it to.
I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.
CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM dbo.MyTable
Schema is a container of objects. It is owned by a user.
Hope this helps someone who's still struggling.
Don't keep your table inside any container. Make the table's wrapper your container after the table's rendered. I know this might be invalid at places where you have something else along with the table but then you could always append that content back.
For me,this problem arises if you have a sidebar and a container that is actually an offset to that sidebar.
$(YourTableName+'_wrapper').addClass('mycontainer');
(I added a panel panel-default)
And your class :
.mycontainer{background-color:white;padding:5px;}
You can achieve the following by using a single line in your spinner declaration in XML:
Just add this: style="@android:style/Widget.Holo.Light.Spinner"
This is a default generated style in android. It doesn't contain borders around it though. For that you'd better search something on google.
Hope this helps.
UPDATE: AFter a lot of digging I got something which works well for introducing border around spinner.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="8dp"
android:top="8dp">
<shape>
<solid android:color="@android:color/white" />
<corners android:radius="4dp" />
<stroke
android:width="2dp"
android:color="#9E9E9E" />
<padding
android:bottom="16dp"
android:left="8dp"
android:right="16dp"
android:top="16dp" />
</shape>
</item>
</layer-list>
Place this in the drawable folder and use it as a background for spinner. Like this:
<RelativeLayout
android:id="@+id/speaker_relative_layout"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:background="@drawable/spinner_style"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Spinner
android:id="@+id/select_speaker_spinner"
style="@style/Widget.AppCompat.DropDownItem.Spinner"
android:layout_width="match_parent"
android:layout_height="70dp"
android:entries="@array/select_speaker_spinner_array"
android:spinnerMode="dialog" />
</RelativeLayout>
If adding allowfullscreen
does not help, make sure you don't have &fs=0
in your iframe url.
For starters ignore all answers with tell you to use $watch. Angular works off of a listener already. I guarantee you that you are complicating things by merely thinking in this direction.
Ignore all answers that tell you to user $timeout. You cannot know how long the page will take to load, therefore this is not the best solution.
You only need to know when the page is done rendering.
<div ng-app='myApp'>
<div ng-controller="testctrl">
<label>{{total}}</label>
<table>
<tr ng-repeat="item in items track by $index;" ng-init="end($index);">
<td>{{item.number}}</td>
</tr>
</table>
</div>
var app = angular.module('myApp', ["testctrl"]);
var controllers = angular.module("testctrl", []);
controllers.controller("testctrl", function($scope) {
$scope.items = [{"number":"one"},{"number":"two"},{"number":"three"}];
$scope.end = function(index){
if(index == $scope.items.length -1
&& typeof $scope.endThis == 'undefined'){
/// DO STUFF HERE
$scope.total = index + 1;
$scop.endThis = true;
}
}
});
Track the ng-repeat by $index and when the length of array equals the index stop the loop and do your logic.
Another possible way, in order to make the colors a bit more intense, is this one:
<span class="badge progress-bar-info">10</span>
<span class="badge progress-bar-success">20</span>
<span class="badge progress-bar-warning">30</span>
<span class="badge progress-bar-danger">40</span>
See Bootply
For backend GTK3Agg, use maximize()
-- notably with a lower case m:
manager = plt.get_current_fig_manager()
manager.window.maximize()
Tested in Ubuntu 20.04 with Python 3.8.
I don't know if the solution below is more or less efficient than jspcal's answer, but I'm pretty sure it requires less object creation than Jamie's and George's.
string s = "THIS IS MY TEXT RIGHT NOW";
StringBuilder sb = new StringBuilder(s.Length);
bool capitalize = true;
foreach (char c in s) {
sb.Append(capitalize ? Char.ToUpper(c) : Char.ToLower(c));
capitalize = !Char.IsLetter(c);
}
return sb.ToString();
You can use "netstat" to check whether a port is available or not.
Use the netstat -anp | find "port number"
command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.
You have to put : before port number to get the actual output
Ex
netstat -anp | find ":8080"
A lot of microbenchmarks given here have found numbers of a few nanoseconds for things like array/ArrayList reads. This is quite reasonable if everything is in your L1 cache.
A higher level cache or main memory access can have order of magnitude times of something like 10nS-100nS, vs more like 1nS for L1 cache. Accessing an ArrayList has an extra memory indirection, and in a real application you could pay this cost anything from almost never to every time, depending on what your code is doing between accesses. And, of course, if you have a lot of small ArrayLists this might add to your memory use and make it more likely you'll have cache misses.
The original poster appears to be using just one and accessing a lot of contents in a short time, so it should be no great hardship. But it might be different for other people, and you should watch out when interpreting microbenchmarks.
Java Strings, however, are appallingly wasteful, especially if you store lots of small ones (just look at them with a memory analyzer, it seems to be > 60 bytes for a string of a few characters). An array of strings has an indirection to the String object, and another from the String object to a char[] which contains the string itself. If anything's going to blow your L1 cache it's this, combined with thousands or tens of thousands of Strings. So, if you're serious - really serious - about scraping out as much performance as possible then you could look at doing it differently. You could, say, hold two arrays, a char[] with all the strings in it, one after another, and an int[] with offsets to the starts. This will be a PITA to do anything with, and you almost certainly don't need it. And if you do, you've chosen the wrong language.
As @Roko mentioned you can do this in multiple ways.
1.Using the jQuery first-child selector - SnoopCode
$(document).ready(function(){
$(".alldivs onediv:first-child").css("background-color","yellow");
}
Using jQuery eq Selector - SnoopCode
$( "body" ).find( "onediv" ).eq(1).addClass( "red" );
Using jQuery Id Selector - SnoopCode
$(document).ready(function(){
$("#div1").css("background-color: red;");
});
Basic Authentication wasn't designed to manage logging out. You can do it, but not completely automatically.
What you have to do is have the user click a logout link, and send a ‘401 Unauthorized’ in response, using the same realm and at the same URL folder level as the normal 401 you send requesting a login.
They must be directed to input wrong credentials next, eg. a blank username-and-password, and in response you send back a “You have successfully logged out” page. The wrong/blank credentials will then overwrite the previous correct credentials.
In short, the logout script inverts the logic of the login script, only returning the success page if the user isn't passing the right credentials.
The question is whether the somewhat curious “don't enter your password” password box will meet user acceptance. Password managers that try to auto-fill the password can also get in the way here.
Edit to add in response to comment: re-log-in is a slightly different problem (unless you require a two-step logout/login obviously). You have to reject (401) the first attempt to access the relogin link, than accept the second (which presumably has a different username/password). There are a few ways you could do this. One would be to include the current username in the logout link (eg. /relogin?username), and reject when the credentials match the username.
The proper way to fully uninstall conda (Anaconda / Miniconda):
Remove all conda-related files and directories using the Anaconda-Clean package
conda activate your_conda_env_name
conda install anaconda-clean
anaconda-clean # add `--yes` to avoid being prompted to delete each one
Remove your entire conda directory
rm -rf ~/miniconda3
Remove the line which adds the conda path to the PATH
environment variable
vi ~/.bashrc
# -> Search for conda and delete the lines containing it
# -> If you're not sure if the line belongs to conda, comment it instead of deleting it just to be safe
source ~/.bashrc
Remove the backup folder created by the the Anaconda-Clean package NOTE: Think twice before doing this, because after that you won't be able to restore anything from your old conda installation!
rm -rf ~/.anaconda_backup
Reference: Official conda documentation
I'd say these answers miss a trick.
Bloch, in his essential, wonderful, concise Effective Java, says, in item 47, title "Know and use the libraries", "To summarize, don't reinvent the wheel". And he gives several very clear reasons why not.
There are a few answers here which suggest methods from CollectionUtils
in the Apache Commons Collections library but none has spotted the most beautiful, elegant way of answering this question:
Collection<Object> culprits = CollectionUtils.disjunction( list1, list2 );
if( ! culprits.isEmpty() ){
// ... do something with the culprits, i.e. elements which are not common
}
Culprits: i.e. the elements which are not common to both Lists
. Determining which culprits belong to list1
and which to list2
is relatively straightforward using CollectionUtils.intersection( list1, culprits )
and CollectionUtils.intersection( list2, culprits )
.
However it tends to fall apart in cases like { "a", "a", "b" } disjunction
with { "a", "b", "b" } ... except this is not a failing of the software, but inherent to the nature of the subtleties/ambiguities of the desired task.
You can always examine the source code (l. 287) for a task like this, as produced by the Apache engineers. One benefit of using their code is that it will have been thoroughly tried and tested, with many edge cases and gotchas anticipated and dealt with. You can copy and tweak this code to your heart's content if need be.
NB I was at first disappointed that none of the CollectionUtils
methods provides an overloaded version enabling you to impose your own Comparator
(so you can redefine equals
to suit your purposes).
But from collections4 4.0 there is a new class, Equator
which "determines equality between objects of type T". On examination of the source code of collections4 CollectionUtils.java they seem to be using this with some methods, but as far as I can make out this is not applicable to the methods at the top of the file, using the CardinalityHelper
class... which include disjunction
and intersection
.
I surmise that the Apache people haven't got around to this yet because it is non-trivial: you would have to create something like an "AbstractEquatingCollection" class, which instead of using its elements' inherent equals
and hashCode
methods would instead have to use those of Equator
for all the basic methods, such as add
, contains
, etc. NB in fact when you look at the source code, AbstractCollection
does not implement add
, nor do its abstract subclasses such as AbstractSet
... you have to wait till the concrete classes such as HashSet
and ArrayList
before add
is implemented. Quite a headache.
In the mean time watch this space, I suppose. The obvious interim solution would be to wrap all your elements in a bespoke wrapper class which uses equals
and hashCode
to implement the kind of equality you want... then manipulate Collections
of these wrapper objects.
Your main problem is that you are calling a method called first()
in the iterator. What you are meant to do is use the property called first
:
...append(iter->first) rather than ...append(iter->first())
As a matter of style, you shouldn't be using new
to create that string.
std::string something::toString()
{
std::map<std::string, std::string>::iterator iter;
std::string strToReturn; //This is no longer on the heap
for (iter = table.begin(); iter != table.end(); ++iter) {
strToReturn.append(iter->first); //Not a method call
strToReturn.append("=");
strToReturn.append(iter->second);
//....
// Make sure you don't modify table here or the iterators will not work as you expect
}
//...
return strToReturn;
}
edit: facildelembrar pointed out (in the comments) that in modern C++ you can now rewrite the loop
for (auto& item: table) {
...
}
Here's a quick way I've found to make a two dimensional array.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(e => Array(y));
}
You can easily turn this function into an ES5 function as well.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(function(e) {
return Array(y);
});
}
Why this works: the new Array(n)
constructor creates an object with a prototype of Array.prototype
and then assigns the object's length
, resulting in an unpopulated array. Due to its lack of actual members we can't run the Array.prototype.map
function on it.
However, when you provide more than one argument to the constructor, such as when you do Array(1, 2, 3, 4)
, the constructor will use the arguments
object to instantiate and populate an Array
object correctly.
For this reason, we can use Array.apply(null, Array(x))
, because the apply
function will spread the arguments into the constructor. For clarification, doing Array.apply(null, Array(3))
is equivalent to doing Array(null, null, null)
.
Now that we've created an actual populated array, all we need to do is call map
and create the second layer (y
).
You can use the bit_length() function to convert numbers to their two's complement:
def twos_complement(j):
return j-(1<<(j.bit_length()))
In [1]: twos_complement(0b111111111111)
Out[1]: -1
You can use a2enmod
or a2dismod
to enable/disable modules by name.
From terminal, run: sudo a2enmod php5
to enable PHP5 (or some other module), then sudo service apache2 reload
to reload the Apache2 configuration.
There's a shorthand-type way to do this that I have been using recently. This might need to be configured, but it should work in most mainline PHP installations. If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:
<html>
<body>
<?php
$link = "http://www.google.com";
?>
<a href="<?= $link ?>">Click here to go to Google.</a>
</body>
</html>
This will evaluate the variable as a string, in essence shorthand for echo $link;
I would use Valgrind and Callgrind as a base for my profiling tool suite. What is important to know is that Valgrind is basically a Virtual Machine:
(wikipedia) Valgrind is in essence a virtual machine using just-in-time (JIT) compilation techniques, including dynamic recompilation. Nothing from the original program ever gets run directly on the host processor. Instead, Valgrind first translates the program into a temporary, simpler form called Intermediate Representation (IR), which is a processor-neutral, SSA-based form. After the conversion, a tool (see below) is free to do whatever transformations it would like on the IR, before Valgrind translates the IR back into machine code and lets the host processor run it.
Callgrind is a profiler build upon that. Main benefit is that you don't have to run your aplication for hours to get reliable result. Even one second run is sufficient to get rock-solid, reliable results, because Callgrind is a non-probing profiler.
Another tool build upon Valgrind is Massif. I use it to profile heap memory usage. It works great. What it does is that it gives you snapshots of memory usage -- detailed information WHAT holds WHAT percentage of memory, and WHO had put it there. Such information is available at different points of time of application run.
I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind
function:
cbind(data, total = rowSums(data))
This method adds a total
column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).
My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer
as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .
How do we do for CI CD
It's better if you use string.Join
.
class Product
{
public int ProductID { get; set; }
}
static void Main(string[] args)
{
List<Product> products = new List<Product>()
{
new Product { ProductID = 1 },
new Product { ProductID = 2 },
new Product { ProductID = 3 }
};
string theURL = string.Join("&", products.Select(p => string.Format("productID={0}", p.ProductID)));
Console.WriteLine(theURL);
}
If your backend uses a secure connection ant you get using NSURLSession
CFNetwork SSLHandshake failed (-9801)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)
you need to check your server configuration especially to get ATS version and SSL certificate Info:
Instead of just Allowing Insecure Connection by setting NSExceptionAllowsInsecureHTTPLoads = YES
, instead you need to Allow Lowered Security in case your server do not meet the min requirement (v1.2) for ATS (or better to fix server side).
Allowing Lowered Security to a Single Server
<key>NSExceptionDomains</key>
<dict>
<key>api.yourDomaine.com</key>
<dict>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
use openssl client to investigate certificate and get your server configuration using openssl client :
openssl s_client -connect api.yourDomaine.com:port //(you may need to specify port or to try with https://... or www.)
..find at the end
SSL-Session:
Protocol : TLSv1
Cipher : AES256-SHA
Session-ID: //
Session-ID-ctx:
Master-Key: //
Key-Arg : None
Start Time: 1449693038
Timeout : 300 (sec)
Verify return code: 0 (ok)
App Transport Security (ATS) require Transport Layer Security (TLS) protocol version 1.2.
Requirements for Connecting Using ATS:
The requirements for a web service connection to use App Transport Security (ATS) involve the server, connection ciphers, and certificates, as follows:
Certificates must be signed with one of the following types of keys:
Secure Hash Algorithm 2 (SHA-2) key with a digest length of at least 256 (that is, SHA-256 or greater)
Elliptic-Curve Cryptography (ECC) key with a size of at least 256 bits
Rivest-Shamir-Adleman (RSA) key with a length of at least 2048 bits An invalid certificate results in a hard failure and no connection.
The following connection ciphers support forward secrecy (FS) and work with ATS:
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
Update: it turns out that openssl only provide the minimal protocol version Protocol : TLSv1 links
Suggest the following simplification: capture return value from Workbooks.Add
instead of subscripting Windows()
afterward, as follows:
Set wkb = Workbooks.Add
wkb.SaveAs ...
wkb.Activate ' instead of Windows(expression).Activate
General Philosophy Advice:
Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.
Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.
Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection
During and within macros do not rely on these built-in names, instead capture return values, e.g.
Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate
Also, try to use qualified expressions, e.g.
wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"
or
Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"
Use qualified expressions, e.g.
newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar"
These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.
Also please note that you'll likely find that you don't need to .Activate
nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate
could simply be eliminated instead of even being replaced by wkb.Activate
.
(Also note: I think the .Select statements you show are not contributing and can be omitted.)
(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)
If you use make generators like cmake, JUCE, etc. try to set a correct VS version target (2013, 2015, 2017) and regenerate the solution again.
This is my solution, it's not that tricky and allow you to use it for several markup throught a simple ng-class directive. Like so you can choose the class and the scrollPos for each case.
Your App.js :
angular.module('myApp',[])
.controller('mainCtrl',function($window, $scope){
$scope.scrollPos = 0;
$window.onscroll = function(){
$scope.scrollPos = document.body.scrollTop || document.documentElement.scrollTop || 0;
$scope.$apply(); //or simply $scope.$digest();
};
});
Your index.html :
<html ng-app="myApp">
<head></head>
<body>
<section ng-controller="mainCtrl">
<p class="red" ng-class="{fix:scrollPos >= 100}">fix me when scroll is equals to 100</p>
<p class="blue" ng-class="{fix:scrollPos >= 150}">fix me when scroll is equals to 150</p>
</section>
</body>
</html>
working JSFiddle here
EDIT :
As
$apply()
is actually calling$rootScope.$digest()
you can directly use$scope.$digest()
instead of$scope.$apply()
for better performance depending on context.
Long story short :$apply()
will always work but force the$digest
on all scopes that may cause perfomance issue.
Polymorphism is an ability of object which can be taken in many forms. For example in human class a man can act in many forms when we talk about relationships. EX: A man is a father to his son and he is husband to his wife and he is teacher to his students.
Change position
position:fixed;
overflow: hidden;
to
position:absolute;
overflow:scroll;
I resolved this issue in my project by deleting a library:
Reason: I included a library-project in my project, and mistakenly did not removed the previous lib from my project, so when I was running the project then same library dex files were generating twice, when I removed the same-library from lib folder of my project, the error gone away and build was created successfully, I hope others may face the same issue.
You can get it from your local driver as below:
<dependency>
<groupId>sample</groupId>
<artifactId>com.sample</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>
no need to do a replacement. the regex will give you what u wanted directly:
"(?<=_)[^_]*\.jpg"
tested with grep:
echo "3.04_somename.jpg"|grep -oP "(?<=_)[^_]*\.jpg"
somename.jpg