yes there is on-mouseover
in angular2 instead of ng-Mouseover
like in angular 1.x so you have to write this :-
<div on-mouseover='over()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>
over(){
console.log("Mouseover called");
}
As @Gunter Suggested in comment there is alternate of on-mouseover
we can use this too. Some people prefer the on- prefix alternative, known as the canonical form.
HTML Code -
<div (mouseover)='over()' (mouseout)='out()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>
Controller/.TS Code -
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
over(){
console.log("Mouseover called");
}
out(){
console.log("Mouseout called");
}
}
Some other Mouse events can be used in Angular -
(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"
Your deleted branches are not lost, they were copied into origin/contact_page and origin/new_pictures “remote tracking branches” by the fetch you showed (they were also pushed back out by the push you showed, but they were pushed into refs/remotes/origin/ instead of refs/heads/). Check git log origin/contact_page
and git log origin/new_pictures
to see if your local copies are “up to date” with whatever you think should be there. If any new commits were pushed onto those branches (from some other repo) between the fetch and push that you showed, you may have “lost” those (but probably you could probably find them in the other repo that most recently pushed those branches).
It looks like you are fetching in a normal, ‘remote mode’ (remote refs/heads/ are stored locally in refs/remotes/origin/), but pushing in ‘mirror mode’ (local refs/ are pushed onto remote refs/). Check your .git/config and reconcile the remote.origin.fetch
and remote.origin.push
settings.
Before trying any changes, make a simple tar or zip archive or your whole local repo. That way, if you do not like what happens, you can try again from a restored repo.
If you intend to use your remote repo as a mirror of your local one, do this:
git branch contact_page origin/contact_page &&
git branch new_pictures origin/new_pictures &&
git config remote.origin.fetch '+refs/*:refs/*' &&
git config --unset remote.origin.push &&
git config remote.origin.mirror true
You might also eventually want to do delete all your refs/remotes/origin/ refs, since they are not useful if you are operating in mirror mode (your normal branches take the place of the usual remote tracking branches).
But since it seems that you are using this remote repo with multiple “work” repos, you probably do not want to use mirror mode. You might try this:
git config push.default tracking &&
git config --unset remote.origin.push
git config --unset remote.origin.mirror
Then, you will eventually want to delete the bogus refs/remotes/origin refs in your remote repo: git push origin :refs/remotes/origin/contact_page :refs/remotes/origin/new_pictures …
.
Try git push --dry-run
to see what it git push
would do without having it make any changes on the remote repo. If you do not like what it says it is going to do, recover from your backup (tar/zip) and try the other option.
The /P
switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
Two ways I've used it... first:
SET /P variable=
When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.
And second:
SET /P variable=<%temp%\filename.txt
Will set variable to contents (the first line) of the txt file. This method won't work unless the /P
is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.
I had to remove the following files too since brew complained in install later after manually removing all files.
/usr/local/share/doc/node/gdbinit
/usr/local/share/systemtap/tapset/node.stp
and then do the following
brew install node
brew link node
you can use numpy.argsort
or you can do:
test = [2,3,1,4,5]
idxs = list(zip(*sorted([(val, i) for i, val in enumerate(test)])))[1]
zip
will rearange the list so that the first element is test
and the second is the idxs
.
Note: Just reposting John Zwinck's comment as answer.
One issue might be that you are using a older version of Node (for the moment, I cannot upgrade, codebase struck with v4.3.1
). Simple solution here is, using the deprecated way:
new Buffer(bufferStr)
Note #2: This is for people struck in older version, for whom Buffer.from
does not work
This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.
Syntax example :
// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]>
This is the safest approach, considering it prevents accessing indexes out of the boundaries.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
& { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }
Tests :
var myFixedLengthArray: FixedLengthArray< [string, string, string]>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? INVALID INDEX ERROR
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR
(*) This solution requires the noImplicitAny
typescript configuration directive to be enabled in order to work (commonly recommended practice)
This solution behaves as an augmentation of the Array
type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.
Syntax example :
let foo: FixedLengthArray<string, 3>
Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
& {
readonly length: L
[ I : number ] : T
[Symbol.iterator]: () => IterableIterator<T>
}
Tests :
var myFixedLengthArray: FixedLengthArray<string,3>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? SHOULD FAIL
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL
For reloading the page for a given route path :-
$location.path('/path1/path2');
$route.reload();
Use WGet instead. It supports HTTP and FTP protocols.
wget -r ftp://mydomain.com/mystuff
Good Luck!
reference: http://linux.about.com/od/commands/l/blcmdl1_wget.htm
# s1 == source string
# char == find this character
# repl == replace with this character
def findreplace(s1, char, repl):
s1 = s1.replace(char, repl)
return s1
# find each 'i' in the string and replace with a 'u'
print findreplace('it is icy', 'i', 'u')
# output
''' ut us ucy '''
This two classes are borrowed from the HTML Boilerplate main.css. Although the invisible checkbox will be focused and not the label.
/*
* Hide only visually, but have it available for screenreaders: h5bp.com/v
*/
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
/*
* Extends the .visuallyhidden class to allow the element to be focusable
* when navigated to via the keyboard: h5bp.com/p
*/
.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
width: auto;
}
Plus it's good to use -F option
to specify Name of sender.
Something like this:
mail -s "$SUBJECT" $MAILTO -- -F $MAILFROM -f ${MAILFROM}@somedomain.com
Or just look at available options: http://www.courier-mta.org/sendmail.html
This will make the div fixed at the bottom of the page but in case the page is long it will only be visible when you scroll down.
<style type="text/css">
#footer {
position : absolute;
bottom : 0;
height : 40px;
margin-top : 40px;
}
</style>
<div id="footer">I am footer</div>
The height and margin-top should be the same so that the footer doesnt show over the content.
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
Use the find and replace command accessible through ctrl+h, make sure you are searching through the functions of the cells. You can then wildcards to accommodate any deviations of the formula. * for # wildcards, ? for charcter wildcards, and ~? or ~* to search for ? or *.
This is similar to the scripts we generate on our team. Create the table first, then apply pk/fk and other constraints.
CREATE TABLE [dbo].[ImagenesUsuario] (
[idImagen] [int] IDENTITY (1, 1) NOT NULL
)
ALTER TABLE [dbo].[ImagenesUsuario] ADD
CONSTRAINT [PK_ImagenesUsuario] PRIMARY KEY CLUSTERED
(
[idImagen]
) ON [PRIMARY]
I just edited my iPhone's 'hosts' file successfully (on Jailbroken iOS 4.0).
simophone.local
]root
alpine
/etc/hosts
fileThe phone does cache some webpages and DNS queries, so a reboot or clearing the cache may help. Hope that helps someone.
Simon.
Yes. Use GetValues()
method in System.Enum
class.
If the script name has spaces in it, a more robust way is to use "$0"
or "$(basename "$0")"
- or on MacOS: "$(basename \"$0\")"
. This prevents the name from getting mangled or interpreted in any way. In general, it is good practice to always double-quote variable names in the shell.
Setting a fixed number of decimal places globally is often a bad idea since it is unlikely that it will be an appropriate number of decimal places for all of your various data that you will display regardless of magnitude. Instead, try this which will give you scientific notation only for large and very small values (and adds a thousands separator unless you omit the ","):
pd.set_option('display.float_format', lambda x: '%,g' % x)
Or to almost completely suppress scientific notation without losing precision, try this:
pd.set_option('display.float_format', str)
Here is a short, flexible snippet to convert a datetime-string in a cross-browser-safe fashion as nicel detailed by @drankin2112.
var inputTimestamp = "2014-04-29 13:00:15"; //example
var partsTimestamp = inputTimestamp.split(/[ \/:-]/g);
if(partsTimestamp.length < 6) {
partsTimestamp = partsTimestamp.concat(['00', '00', '00'].slice(0, 6 - partsTimestamp.length));
}
//if your string-format is something like '7/02/2014'...
//use: var tstring = partsTimestamp.slice(0, 3).reverse().join('-');
var tstring = partsTimestamp.slice(0, 3).join('-');
tstring += 'T' + partsTimestamp.slice(3).join(':') + 'Z'; //configure as needed
var timestamp = Date.parse(tstring);
Your browser should provide the same timestamp result as Date.parse
with:
(new Date(tstring)).getTime()
you could read and write to a seperately like others. But if you want to write into the same one, you could try with this:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
double data[size of your data];
std::ifstream input("file.txt");
for (int i = 0; i < size of your data; i++) {
input >> data[i];
std::cout<< data[i]<<std::endl;
}
}
MSSQL have its own database management tool called as "MSSQL Server Management Studio (SSMS)". Here are steps to reset SA password using SSMS :
1] Open SSMS management console, it will prompt for authentication details,
Select Server Type : "Database Engine", Server name : IP / hostname of your MSSQL server Authentication : Windows Authentication
Once you select Authentication type as "Windows Authentication", the user name and password fields will be grayed out and it will allow you to login SQL server without entering login details. Windows Authentication is possible only when you are logged on same server in RDP on which SQL service is present.
2] once you are in, under "Object Explorer" expand Security and then Logins 3] locate and right click on user SA and select Properties 4] under General section enter desired password in front of "Password:" and "Confirm Password:" 5] hit OK at bottom.
This is the easiest and secure way to reset SA password instead of using any third party non secure tools
This is an old question, but no one responded to the question regarding centering text in a terminal.
/**
* Centers a string of text in a terminal window
*
* @param string $text The text to center
* @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
*
* @return string The padded result, ready to echo
*/
function center($text, $pad_string = ' ') {
$window_size = (int) `tput cols`;
return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}
echo center('foo');
echo center('bar baz', '=');
I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.
For others who are experiencing with the same problem, here is the description of the bug in php + patch https://bugs.php.net/bug.php?id=44522
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
As mentioned, PEP 8 says to use lower_case_with_underscores
for variables, methods and functions.
I prefer using lower_case_with_underscores
for variables and mixedCase
for methods and functions makes the code more explicit and readable. Thus following the Zen of Python's "explicit is better than implicit" and "Readability counts"
In your controller use:
var path = HttpContext.Server.MapPath("~/Data/data.html");
This allows you to test the controller with Moq like so:
var queryString = new NameValueCollection();
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
var server = new Mock<HttpServerUtilityBase>();
server.Setup(m => m.MapPath("~/Data/data.html")).Returns("path/to/test/data");
mockHttpContext.Setup(m => m.Server).Returns(server.Object);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
var controller = new MyTestController();
controller.ControllerContext = mockControllerContext.Object;
Be sure to fully qualify your sheets with which workbook they are referencing!
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
This will be varchar
but should format as you need.
RIGHT('0' + LTRIM(DAY(d)), 2) + '/'
+ RIGHT('0' + LTRIM(MONTH(d)), 2) + '/'
+ LTRIM(YEAR(d)) + ' '
+ RIGHT('0' + LTRIM(DATEPART(HOUR, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(MINUTE, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(SECOND, d)), 2)
Where d
is your datetime
field or variable.
Or, if you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.
storePropertyMaxSpeed(){
axios.post('api/property', {
"property_name" : 'max_speed',
"property_amount" : this.newPropertyMaxSpeed
},
{headers : {'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.$gate.token()}})
.then(() => { //this below peace of code isn't important
Event.$emit('dbPropertyChanged');
$('#addPropertyMaxSpeedModal').modal('hide');
Swal.fire({
position: 'center',
type: 'success',
title: 'Nova brzina unešena u bazu',
showConfirmButton: false,
timer: 1500
})
})
.catch(() => {
Swal.fire("Neuspješno!", "Nešto je pošlo do davola", "warning");
})
}
},
Just add the unique key to the your Components
data.map((marker)=>{
return(
<YourComponents
key={data.id} // <----- unique key
/>
);
})
Just a quick contribution.
Since the current python docs don't have "window" in the itertool examples (i.e., at the bottom of http://docs.python.org/library/itertools.html), here's an snippet based on the code for grouper which is one of the examples given:
import itertools as it
def window(iterable, size):
shiftedStarts = [it.islice(iterable, s, None) for s in xrange(size)]
return it.izip(*shiftedStarts)
Basically, we create a series of sliced iterators, each with a starting point one spot further forward. Then, we zip these together. Note, this function returns a generator (it is not directly a generator itself).
Much like the appending-element and advancing-iterator versions above, the performance (i.e., which is best) varies with list size and window size. I like this one because it is a two-liner (it could be a one-liner, but I prefer naming concepts).
It turns out that the above code is wrong. It works if the parameter passed to iterable is a sequence but not if it is an iterator. If it is an iterator, the same iterator is shared (but not tee'd) among the islice calls and this breaks things badly.
Here is some fixed code:
import itertools as it
def window(iterable, size):
itrs = it.tee(iterable, size)
shiftedStarts = [it.islice(anItr, s, None) for s, anItr in enumerate(itrs)]
return it.izip(*shiftedStarts)
Also, one more version for the books. Instead of copying an iterator and then advancing copies many times, this version makes pairwise copies of each iterator as we move the starting position forward. Thus, iterator t provides both the "complete" iterator with starting point at t and also the basis for creating iterator t + 1:
import itertools as it
def window4(iterable, size):
complete_itr, incomplete_itr = it.tee(iterable, 2)
iters = [complete_itr]
for i in xrange(1, size):
incomplete_itr.next()
complete_itr, incomplete_itr = it.tee(incomplete_itr, 2)
iters.append(complete_itr)
return it.izip(*iters)
You can do this to only monitor own properties of the object:
var arr = [];
for (var key in p) {
if (p.hasOwnProperty(key)) {
arr.push(p[key]);
}
}
In pseudocode:
split it by colon
seconds = 3600 * HH + 60 * MM + SS
My approach to solving this problem is to use ES6 and creating a function that does the check for us. The benefit of this function is that it can be reusable through out your project to check any array of objects given the key
and the value
to check.
ENOUGH TALK, LET'S SEE THE CODE
Array
const ceos = [
{
name: "Jeff Bezos",
company: "Amazon"
},
{
name: "Mark Zuckerberg",
company: "Facebook"
},
{
name: "Tim Cook",
company: "Apple"
}
];
Function
const arrayIncludesInObj = (arr, key, valueToCheck) => {
return arr.some(value => value[key] === valueToCheck);
}
Call/Usage
const found = arrayIncludesInObj(ceos, "name", "Tim Cook"); // true
const found = arrayIncludesInObj(ceos, "name", "Tim Bezos"); // false
IfLoop's answer (and MatToufoutu's comment) work great for standalone variables, but I wanted to provide an answer for anyone trying to do something similar for individual entries in lists, tuples, or dictionaries.
Dictionaries
existing_dict = {"spam": 1, "eggs": 2}
existing_dict["foo"] = existing_dict["foo"] if "foo" in existing_dict else 3
Returns {"spam": 1, "eggs": 2, "foo": 3}
Lists
existing_list = ["spam","eggs"]
existing_list = existing_list if len(existing_list)==3 else
existing_list + ["foo"]
Returns ["spam", "eggs", "foo"]
Tuples
existing_tuple = ("spam","eggs")
existing_tuple = existing_tuple if len(existing_tuple)==3 else
existing_tuple + ("foo",)
Returns ("spam", "eggs", "foo")
(Don't forget the comma in ("foo",)
to define a "single" tuple.)
The lists and tuples solution will be more complicated if you want to do more than just check for length and append to the end. Nonetheless, this gives a flavor of what you can do.
BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN)
The name of the spyder executable was changed to spyder3.exe in python version 3. I install pyqt5 and spyder via pip and was able to launch spyder3. I first tried without installing pyqt5 and nothing happened. Once I installed pyqt5, then spyder 3 opened.
Try the following from a windows cmd.exe prompt:
C:\Users\..>pip install pyqt5
C:\Users\..>pip install spyder
C:\Users\..>spyder3
For your needs, use ConcurrentHashMap
. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map)
creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).
Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.
Use this line to get the division behavior you want:
from __future__ import division
Alternatively, you could use modulus:
if (a % b) == 0: #do something
Please try to add
encoding='unicode_escape'
This will help. Worked for me. Also, make sure you're using the correct delimiter and column names.
You can start with loading just 1000 rows to load the file quickly.
You can negate a time.Duration
:
then := now.Add(- dur)
You can even compare a time.Duration
against 0
:
if dur > 0 {
dur = - dur
}
then := now.Add(dur)
You can see a working example at http://play.golang.org/p/ml7svlL4eW
select AttDate,convert(char(5), AttDate, 108) [Time] from yourTableName
yourDGV.Rows.Add(column1,column2...columnx); //add a row to a dataGridview
yourDGV.Rows[rowindex].Cells[Cell/Columnindex].value = yourvalue; //edit the value
you can also create a new row and then add it to the DataGridView like this:
DataGridViewRow row = new DataGridViewRow();
row.Cells[Cell/Columnindex].Value = yourvalue;
yourDGV.Rows.Add(row);
Sometime gcc had created as /usr/bin/gcc32
. so please create a ln -s /usr/bin/gcc32 /usr/bin/gcc
and then compile that ./configure
.
I've improved Josh's answer. I've noticed that dig
only shows entries already present in the queried nameserver's cache, so it's better to pull an authoritative nameserver from the SOA (rather than rely on the default nameserver). I've also disabled the filtering of wildcard IPs because usually I'm usually more interested in the correctness of the setup.
The new script takes a -x
argument for expanded output and a -s NS
argument to choose a specific nameserver: dig -x example.com
#!/bin/bash
set -e; set -u
COMMON_SUBDOMAINS="www mail mx a.mx smtp pop imap blog en ftp ssh login"
EXTENDED=""
while :; do case "$1" in
--) shift; break ;;
-x) EXTENDED=y; shift ;;
-s) NS="$2"; shift 2 ;;
*) break ;;
esac; done
DOM="$1"; shift
TYPE="${1:-any}"
test "${NS:-}" || NS=$(dig +short SOA "$DOM" | awk '{print $1}')
test "$NS" && NS="@$NS"
if test "$EXTENDED"; then
dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
wild_ips=$(dig +short "$NS" "*.$DOM" "$TYPE" | tr '\n' '|')
wild_ips="${wild_ips%|}"
for sub in $COMMON_SUBDOMAINS; do
dig +nocmd $NS "$sub.$DOM" +noall +answer "$TYPE"
done | cat #grep -vE "${wild_ips}"
dig +nocmd $NS "*.$DOM" +noall +answer "$TYPE"
else
dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
fi
In ASP.Net Core it seems complicated to read several times the body request, however if your first attempt does it the right way, you should be fine for the next attempts.
I read several turnaround for example by substituting the body stream, but I think the following is the cleanest:
The most important points being
[EDIT]
As pointed out by Murad, you may also take advantage of the .Net Core 2.1 extension: EnableBuffering
It stores large requests onto the disk instead of keeping it in memory, avoiding large-streams issues stored in memory (files, images, ...).
You can change the temporary folder by setting ASPNETCORE_TEMP
environment variable, and files are deleted once the request is over.
In an AuthorizationFilter, you can do the following:
// Helper to enable request stream rewinds
using Microsoft.AspNetCore.Http.Internal;
[...]
public class EnableBodyRewind : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var bodyStr = "";
var req = context.HttpContext.Request;
// Allows using several time the stream in ASP.Net Core
req.EnableRewind();
// Arguments: Stream, Encoding, detect encoding, buffer size
// AND, the most important: keep stream opened
using (StreamReader reader
= new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
{
bodyStr = reader.ReadToEnd();
}
// Rewind, so the core is not lost when it looks the body for the request
req.Body.Position = 0;
// Do whatever work with bodyStr here
}
}
public class SomeController : Controller
{
[HttpPost("MyRoute")]
[EnableBodyRewind]
public IActionResult SomeAction([FromBody]MyPostModel model )
{
// play the body string again
}
}
Then you can use the body again in the request handler.
In your case if you get a null result, it probably means that the body has already been read at an earlier stage. In that case you may need to use a middleware (see below).
However be careful if you handle large streams, that behavior implies that everything is loaded into memory, this should not be triggered in case of a file upload.
Mine looks like this (again, if you download/upload large files, this should be disabled to avoid memory issues):
public sealed class BodyRewindMiddleware
{
private readonly RequestDelegate _next;
public BodyRewindMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try { context.Request.EnableRewind(); } catch { }
await _next(context);
// context.Request.Body.Dipose() might be added to release memory, not tested
}
}
public static class BodyRewindExtensions
{
public static IApplicationBuilder EnableRequestBodyRewind(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<BodyRewindMiddleware>();
}
}
Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:
memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
printf("RESPONSE: %s\n", response);
// HANDLE RESPONSE CHUCK HERE BY, FOR EXAMPLE, SAVING TO A FILE.
memset(response, 0, sizeof(response));
bytes = recv(sockfd, response, 1024, 0);
if (bytes < 0)
printf("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (1);
Essentially it means you don't have the index you are trying to reference. For example:
df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)
will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:
df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)
Hope that answers your question!
Also i find another solution which work for me. In our legacy spring project we use this method for give our users possibilities to use this own configurations:
<bean id="appUserProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="ignoreResourceNotFound" value="false"/>
<property name="locations">
<list>
<value>file:./conf/user.properties</value>
</list>
</property>
</bean>
And in our code to access this properties need write something like that:
@Value("#{appUserProperties.userProperty}")
private String userProperty
And if a situation arises when you need to add a new property but right now you don't want to add it in production user config it very fast become a hell when you need to patch all your test contexts or your application will be fail on startup.
To handle this problem you can use the next syntax to add a default value:
@Value("#{appUserProperties.get('userProperty')?:'default value'}")
private String userProperty
It was a real discovery for me.
I think we can you use verbatim tag, as in this tag we use any of the HTML tags
Check out the HTML5 PDF viewer:
Although parseInt
is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
In addition to the link provided by Floremin, which clears text selection using JavaScript to "clear" the selection, you can also use pure CSS to accomplish this. The CSS is here...
.noSelect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Simply add the class="noSelect"
attribute to the element you wish to apply this class to. I would highly recommend giving this CSS solution a try. Nothing wrong with using the JavaScript, I just believe this could potentially be easier, and clean things up a little bit in your code.
For chrome on android
-webkit-tap-highlight-color: transparent;
is an additional rule you may want to experiment with for support in Android.
I think it's important to note here that onBlur() fires regardless.
This is a helpful thread but the only thing it doesn't clarify is that onBlur() will fire every single time.
onChange() will only fire when the value is changed.
There's a set of useful extensions to IDLE called IDLEX that works with MacOS and Windows http://idlex.sourceforge.net/
It includes line numbering and I find it quite handy & free.
Otherwise there are a bunch of other IDEs some of which are free: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
You can try this
markers[markers.length-1].setMap(null);
Hope it works.
IUSR permissions
use on a folder if not under inetpub/wwwroot will be solution for some.
If you are familiar with iptables service like in centos 6 or earlier, you can still use iptables service by manual installation:
step 1 => install epel repo
yum install epel-release
step 2 => install iptables service
yum install iptables-services
step 3 => stop firewalld service
systemctl stop firewalld
step 4 => disable firewalld service on startup
systemctl disable firewalld
step 5 => start iptables service
systemctl start iptables
step 6 => enable iptables on startup
systemctl enable iptables
finally you're now can editing your iptables config at /etc/sysconfig/iptables.
So -> edit rule -> reload/restart.
do like older centos with same function like firewalld.
If you want the first line and then you want to perform some operation on file this code will helpful.
with open(filename , 'r') as f:
first_line = f.readline()
for line in f:
# Perform some operations
Why not use @media-queries? These are designed for that exact purpose. You can also do this with jQuery, but that's a last resort in my book.
var s = document.createElement("script");
//Check if viewport is smaller than 768 pixels
if(window.innerWidth < 768) {
s.type = "text/javascript";
s.src = "http://www.example.com/public/assets/css1";
}else { //Else we have a larger screen
s.type = "text/javascript";
s.src = "http://www.example.com/public/assets/css2";
}
$(function(){
$("head").append(s); //Inject stylesheet
})
Supposing that you are using ECLIPSE:
Right click PROJECT PROPERTIES ANDROID
If you have a version of ANDROID checked, you must change it to a GOOGLE API. Choose a version of GOOGLE APIS compatible with your project's target version.
I prefer to use WebClient, it seems to handle SSL transparently:
http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
Some troubleshooting help here:
Ok, there are two possible approaches. The simplest - is to use a sliding menu library. It allows creating a bottom sliding menu, it can animate the top container to make bottom visible, it suports both dragging it with your finger, or animating it programmatically via button (StaticDrawer).
Harder way - if you want to use Animations, as was already suggested. With animations you must FIRST change your layouts. So try first to make your layout change to the final state without any animations whatsoever. Because it is very likely that you are not laying out your views properly in RelativeLayout, so even though you show your bottom view, it remains obscured by the top one. Once you achieved proper layout change - all you need to do is to is to remember translations before layout and apply translate animation AFTER layout.
Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:
public class Record
{
public string ItemType { get; set; }
public string this[string propertyName]
{
set
{
switch (propertyName)
{
case "itemType":
ItemType = value;
break;
// etc
}
}
}
}
Alternatively, as others have mentioned, use reflection.
Register the EventEmitter
in your child component as the @Output
:
@Output() onDatePicked = new EventEmitter<any>();
Emit value on click:
public pickDate(date: any): void {
this.onDatePicked.emit(date);
}
Listen for the events in your parent component's template:
<div>
<calendar (onDatePicked)="doSomething($event)"></calendar>
</div>
and in the parent component:
public doSomething(date: any):void {
console.log('Picked date: ', date);
}
It's also well explained in the official docs: Component interaction.
If you have installed .NET desktop development and still you can't see the templates, then VS is probably getting the templates from your custom templates folder and not installed.
To fix that, copy the installed templates folder to custom.
This is your "installed" folder
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ProjectTemplates
This is your "custom" folder
C:\Users[your username]\Documents\Visual Studio\2017\Templates\ProjectTemplates
Typically this happens when you are at the office and you are running VS as an administrator and visual studio is confused how to merge both of them and if you notice they don't have the same folder structure and folder names.. One is CSHARP and the other C#....
I didn't have the same problem when I installed VS 2017 community edition at home though. This happened when I installed visual studio 2017 "enterprise" edition.
One another way is to use the same thing what firebase uses.
For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.
ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)
Caution! The scripts have a limit: it handles up to 500 values in a single drop-down list.
More Info
This solution is not perfect, but it gives some benefits:
First of all, here's working example, so you can test it before going further.
Installation:
Data > Validation
Prepare Data
Data looks like a single table with all possible variants inside it. It must be located on a separate sheet, so it can be used by the script. Look at this example:
Here we have four levels, each value repeats. Note that 2 columns on the right of data are reserved, so don't type/paste there any data.
First simple Data Validation (DV)
Prepare a list of unique values. In our example, it is a list of Planets. Find free space on sheet with data, and paste formula: =unique(A:A)
On your mainsheet select first column, where DV will start. Go to Data > Validation and select range with a unique list.
Script
Paste this code into script editor:
function onEdit(event) _x000D_
{_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data1'; // name of sheet with data_x000D_
var NumOfLevels = 4; // number of levels of data validation_x000D_
var lcol = 2; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,2]; // offsets for levels_x000D_
// ^ means offset column #4 on one position right._x000D_
_x000D_
// =====================================================================================_x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data2'; // name of sheet with data_x000D_
var NumOfLevels = 7; // number of levels of data validation_x000D_
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,1,1,1,1]; // offsets for levels_x000D_
// ===================================================================================== _x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets) _x000D_
{_x000D_
//--------------------------------------------------------------------------------------_x000D_
// The event handler, adds data validation for the input parameters_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
var FormulaSplitter = ';'; // depends on regional setting, ';' or ',' works for US_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
// =================================== key variables =================================_x000D_
//_x000D_
// ss sheet we change (TargetSheet)_x000D_
// br range to change_x000D_
// scol number of column to edit_x000D_
// srow number of row to edit _x000D_
// CurrentLevel level of drop-down, which we change_x000D_
// HeadLevel main level_x000D_
// r current cell, which was changed by user_x000D_
// X number of levels could be checked on the right_x000D_
//_x000D_
// ls Data sheet (LogSheet)_x000D_
//_x000D_
// ======================================================================================_x000D_
_x000D_
// Checks_x000D_
var ts = event.source.getActiveSheet();_x000D_
var sname = ts.getName(); _x000D_
if (sname !== TargetSheet) { return -1; } // not main sheet_x000D_
// Test if range fits_x000D_
var br = event.range;_x000D_
var scol = br.getColumn(); // the column number in which the change is made_x000D_
var srow = br.getRow() // line number in which the change is made_x000D_
var ColNum = br.getWidth();_x000D_
_x000D_
if ((scol + ColNum - 1) < lcol) { return -2; } // columns... _x000D_
if (srow < lrow) { return -3; } // rows_x000D_
// Test range is in levels_x000D_
var columnsLevels = getColumnsOffset_(offsets, lcol); // Columns for all levels _x000D_
var CurrentLevel = getCurrentLevel_(ColNum, br, scol, columnsLevels);_x000D_
if(CurrentLevel === 1) { return -4; } // out of data validations_x000D_
if(CurrentLevel > NumOfLevels) { return -5; } // last level _x000D_
_x000D_
_x000D_
/*_x000D_
ts - sheet with validation, sname = name of sheet_x000D_
_x000D_
NumOfLevels = 4 _x000D_
offsets = [1,1,1,2] - last offset is 2 because need to skip 1 column_x000D_
columnsLevels = [4,5,6,8] - Columns of validation_x000D_
_x000D_
Columns 7 is skipped_x000D_
|_x000D_
1 2 3 4 5 6 7 8 9 _x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
1 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
2 | | | | v | V | ? | x | ? | | lrow = 2 - number of row where validation starts_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
3 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
4 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
| | | | |_x000D_
| | | | Currentlevel = 3 - the number of level to change_x000D_
| | | |_x000D_
| | | br - cell, user changes: scol - column, srow - row,_x000D_
| | ColNum = 1 - width _x000D_
|__|________ _.....____|_x000D_
| v_x000D_
| Drop-down lists _x000D_
|_x000D_
| lcol = 4 - number of column where validation starts_x000D_
*/_x000D_
// Constants_x000D_
var ReplaceCommas = getDecimalMarkIsCommaLocals(); // // ReplaceCommas = true if locale uses commas to separate decimals_x000D_
var ls = SpreadsheetApp.getActive().getSheetByName(LogSheet); // Data sheet _x000D_
var RowNum = br.getHeight();_x000D_
/* Adjust the range 'br' _x000D_
??? !_x000D_
xxx x_x000D_
xxx x _x000D_
xxx => x_x000D_
xxx x_x000D_
xxx x_x000D_
*/ _x000D_
br = ts.getRange(br.getRow(), columnsLevels[CurrentLevel - 2], RowNum); _x000D_
// Levels_x000D_
var HeadLevel = CurrentLevel - 1; // main level_x000D_
var X = NumOfLevels - CurrentLevel + 1; // number of levels left _x000D_
// determine columns on the sheet "Data"_x000D_
var KudaCol = NumOfLevels + 2;_x000D_
var KudaNado = ls.getRange(1, KudaCol); // 1 place for a formula_x000D_
var lastRow = ls.getLastRow();_x000D_
var ChtoNado = ls.getRange(1, KudaCol, lastRow, KudaCol); // the range with list, returned by a formula_x000D_
_x000D_
// ============================================================================= > loop >_x000D_
var CurrLevelBase = CurrentLevel; // remember the first current level_x000D_
_x000D_
_x000D_
_x000D_
for (var j = 1; j <= RowNum; j++) // [01] loop rows start_x000D_
{ _x000D_
// refresh first val _x000D_
var currentRow = br.getCell(j, 1).getRow(); _x000D_
loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrLevelBase, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} // [01] loop rows end_x000D_
_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getColumnsOffset_(offsets, lefColumn)_x000D_
{_x000D_
// Columns for all levels_x000D_
var columnsLevels = [];_x000D_
var totalOffset = 0; _x000D_
for (var i = 0, l = offsets.length; i < l; i++)_x000D_
{ _x000D_
totalOffset += offsets[i];_x000D_
columnsLevels.push(totalOffset + lefColumn - 1);_x000D_
} _x000D_
_x000D_
return columnsLevels;_x000D_
_x000D_
}_x000D_
_x000D_
function test_getCurrentLevel()_x000D_
{_x000D_
var br = SpreadsheetApp.getActive().getActiveSheet().getRange('A5:C5');_x000D_
var scol = 1;_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/_x000D_
Logger.log(getCurrentLevel_(1, br, scol, [1,2,3])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxx| |xxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(2, br, scol, [1,3,5])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxxxxxxxx| _x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,5,6])); // 2_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxx| |xxxxx| _x000D_
levels 1 2 3_x000D_
level 3_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,8])); // 3_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 4 (error)_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,3]));_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels _x000D_
level 1 (error) _x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [5,6,7])); // 1 _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getCurrentLevel_(ColNum, br, scol, columnsLevels)_x000D_
{_x000D_
var colPlus = 2; // const_x000D_
if (ColNum === 1) { return columnsLevels.indexOf(scol) + colPlus; }_x000D_
var CurrentLevel = -1;_x000D_
var level = 0;_x000D_
var column = 0;_x000D_
for (var i = 0; i < ColNum; i++ )_x000D_
{_x000D_
column = br.offset(0, i).getColumn();_x000D_
level = columnsLevels.indexOf(column) + colPlus;_x000D_
if (level > CurrentLevel) { CurrentLevel = level; }_x000D_
}_x000D_
return CurrentLevel;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
for (var k = 1; k <= X; k++)_x000D_
{ _x000D_
HeadLevel = HeadLevel + k - 1; _x000D_
CurrentLevel = CurrLevelBase + k - 1;_x000D_
var r = ts.getRange(currentRow, columnsLevels[CurrentLevel - 2]);_x000D_
var SearchText = r.getValue(); // searched text _x000D_
X = loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} _x000D_
}_x000D_
_x000D_
_x000D_
function loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
_x000D_
_x000D_
// if nothing is chosen!_x000D_
if (SearchText === '') // condition value =''_x000D_
{_x000D_
// kill extra data validation if there were _x000D_
// columns on the right_x000D_
if (CurrentLevel <= NumOfLevels) _x000D_
{_x000D_
for (var f = 0; f < X; f++) _x000D_
{_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel + f - 1]); _x000D_
// clean & get rid of validation_x000D_
cell.clear({contentsOnly: true}); _x000D_
cell.clear({validationsOnly: true});_x000D_
// exit columns loop _x000D_
}_x000D_
}_x000D_
return 0; // end loop this row _x000D_
}_x000D_
_x000D_
_x000D_
// formula for values_x000D_
var formula = getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts); _x000D_
KudaNado.setFormula(formula);_x000D_
_x000D_
_x000D_
// get response_x000D_
var Response = getResponse_(ChtoNado, lastRow, ReplaceCommas);_x000D_
var Variants = Response.length;_x000D_
_x000D_
_x000D_
// build data validation rule_x000D_
if (Variants === 0.0) // empty is found_x000D_
{_x000D_
return;_x000D_
} _x000D_
if(Variants >= 1.0) // if some variants were found_x000D_
{_x000D_
_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel - 1]);_x000D_
var rule = SpreadsheetApp_x000D_
.newDataValidation()_x000D_
.requireValueInList(Response, true)_x000D_
.setAllowInvalid(false)_x000D_
.build();_x000D_
// set validation rule_x000D_
cell.setDataValidation(rule);_x000D_
} _x000D_
if (Variants === 1.0) // // set the only value_x000D_
{ _x000D_
cell.setValue(Response[0]);_x000D_
SearchText = null;_x000D_
Response = null;_x000D_
return X; // continue doing DV_x000D_
} // the only value_x000D_
_x000D_
return 0; // end DV in this row_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts)_x000D_
{_x000D_
_x000D_
var checkVals = [];_x000D_
var Offs = CurrentLevel - 2;_x000D_
var values = [];_x000D_
// get values and display values for a formula_x000D_
for (var s = 0; s <= Offs; s++)_x000D_
{_x000D_
var checkR = ts.getRange(currentRow, columnsLevels[s]);_x000D_
values.push(checkR.getValue());_x000D_
} _x000D_
_x000D_
var LookCol = colName(CurrentLevel-1); // gets column name "A,B,C..."_x000D_
var formula = '=unique(filter(' + LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84_x000D_
_x000D_
var mathOpPlusVal = ''; _x000D_
var value = '';_x000D_
_x000D_
// loop levels for multiple conditions _x000D_
for (var i = 0; i < CurrentLevel - 1; i++) { _x000D_
formula += FormulaSplitter; // =unique(filter(A2:A84;_x000D_
LookCol = colName(i);_x000D_
_x000D_
value = values[i];_x000D_
_x000D_
mathOpPlusVal = getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas); // =unique(filter(A2:A84;B2:B84="Text"_x000D_
_x000D_
if ( Array.isArray(mathOpPlusVal) )_x000D_
{_x000D_
formula += mathOpPlusVal[0];_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;ROUND(B2:B84_x000D_
formula += mathOpPlusVal[1];_x000D_
}_x000D_
else_x000D_
{_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;B2:B84_x000D_
formula += mathOpPlusVal;_x000D_
}_x000D_
_x000D_
_x000D_
} _x000D_
_x000D_
formula += "))"; //=unique(filter(A2:A84;B2:B84="Text"))_x000D_
_x000D_
return formula;_x000D_
}_x000D_
_x000D_
_x000D_
function getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas)_x000D_
{_x000D_
var result = '';_x000D_
var splinter = ''; _x000D_
_x000D_
var type = typeof value;_x000D_
_x000D_
_x000D_
// strings_x000D_
if (type === 'string') return '="' + value + '"';_x000D_
// date_x000D_
if(value instanceof Date)_x000D_
{_x000D_
return ['ROUND(', FormulaSplitter +'5)=ROUND(DATE(' + value.getFullYear() + FormulaSplitter + (value.getMonth() + 1) + FormulaSplitter + value.getDate() + ')' + '+' _x000D_
+ 'TIME(' + value.getHours() + FormulaSplitter + value.getMinutes() + FormulaSplitter + value.getSeconds() + ')' + FormulaSplitter + '5)']; _x000D_
} _x000D_
// numbers_x000D_
if (type === 'number')_x000D_
{_x000D_
if (ReplaceCommas)_x000D_
{_x000D_
return '+0=' + value.toString().replace('.', ','); _x000D_
}_x000D_
else_x000D_
{_x000D_
return '+0=' + value;_x000D_
}_x000D_
}_x000D_
// booleans_x000D_
if (type === 'boolean')_x000D_
{_x000D_
return '=' + value;_x000D_
} _x000D_
// other_x000D_
return '=' + value;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getResponse_(allRange, l, ReplaceCommas)_x000D_
{_x000D_
var data = allRange.getValues();_x000D_
var data_ = allRange.getDisplayValues();_x000D_
_x000D_
var response = [];_x000D_
var val = '';_x000D_
for (var i = 0; i < l; i++)_x000D_
{_x000D_
val = data[i][0];_x000D_
if (val !== '') _x000D_
{_x000D_
var type = typeof val;_x000D_
if (type === 'boolean' || val instanceof Date) val = String(data_[i][0]);_x000D_
if (type === 'number' && ReplaceCommas) val = val.toString().replace('.', ',')_x000D_
response.push(val); _x000D_
}_x000D_
}_x000D_
_x000D_
return response; _x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function colName(n) {_x000D_
var ordA = 'a'.charCodeAt(0);_x000D_
var ordZ = 'z'.charCodeAt(0);_x000D_
_x000D_
var len = ordZ - ordA + 1;_x000D_
_x000D_
var s = "";_x000D_
while(n >= 0) {_x000D_
s = String.fromCharCode(n % len + ordA) + s;_x000D_
n = Math.floor(n / len) - 1;_x000D_
}_x000D_
return s; _x000D_
}_x000D_
_x000D_
_x000D_
function getDecimalMarkIsCommaLocals() {_x000D_
_x000D_
_x000D_
// list of Locals Decimal mark = comma_x000D_
var LANGUAGE_BY_LOCALE = {_x000D_
af_NA: "Afrikaans (Namibia)",_x000D_
af_ZA: "Afrikaans (South Africa)",_x000D_
af: "Afrikaans",_x000D_
sq_AL: "Albanian (Albania)",_x000D_
sq: "Albanian",_x000D_
ar_DZ: "Arabic (Algeria)",_x000D_
ar_BH: "Arabic (Bahrain)",_x000D_
ar_EG: "Arabic (Egypt)",_x000D_
ar_IQ: "Arabic (Iraq)",_x000D_
ar_JO: "Arabic (Jordan)",_x000D_
ar_KW: "Arabic (Kuwait)",_x000D_
ar_LB: "Arabic (Lebanon)",_x000D_
ar_LY: "Arabic (Libya)",_x000D_
ar_MA: "Arabic (Morocco)",_x000D_
ar_OM: "Arabic (Oman)",_x000D_
ar_QA: "Arabic (Qatar)",_x000D_
ar_SA: "Arabic (Saudi Arabia)",_x000D_
ar_SD: "Arabic (Sudan)",_x000D_
ar_SY: "Arabic (Syria)",_x000D_
ar_TN: "Arabic (Tunisia)",_x000D_
ar_AE: "Arabic (United Arab Emirates)",_x000D_
ar_YE: "Arabic (Yemen)",_x000D_
ar: "Arabic",_x000D_
hy_AM: "Armenian (Armenia)",_x000D_
hy: "Armenian",_x000D_
eu_ES: "Basque (Spain)",_x000D_
eu: "Basque",_x000D_
be_BY: "Belarusian (Belarus)",_x000D_
be: "Belarusian",_x000D_
bg_BG: "Bulgarian (Bulgaria)",_x000D_
bg: "Bulgarian",_x000D_
ca_ES: "Catalan (Spain)",_x000D_
ca: "Catalan",_x000D_
tzm_Latn: "Central Morocco Tamazight (Latin)",_x000D_
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",_x000D_
tzm: "Central Morocco Tamazight",_x000D_
da_DK: "Danish (Denmark)",_x000D_
da: "Danish",_x000D_
nl_BE: "Dutch (Belgium)",_x000D_
nl_NL: "Dutch (Netherlands)",_x000D_
nl: "Dutch",_x000D_
et_EE: "Estonian (Estonia)",_x000D_
et: "Estonian",_x000D_
fi_FI: "Finnish (Finland)",_x000D_
fi: "Finnish",_x000D_
fr_BE: "French (Belgium)",_x000D_
fr_BJ: "French (Benin)",_x000D_
fr_BF: "French (Burkina Faso)",_x000D_
fr_BI: "French (Burundi)",_x000D_
fr_CM: "French (Cameroon)",_x000D_
fr_CA: "French (Canada)",_x000D_
fr_CF: "French (Central African Republic)",_x000D_
fr_TD: "French (Chad)",_x000D_
fr_KM: "French (Comoros)",_x000D_
fr_CG: "French (Congo - Brazzaville)",_x000D_
fr_CD: "French (Congo - Kinshasa)",_x000D_
fr_CI: "French (Côte d’Ivoire)",_x000D_
fr_DJ: "French (Djibouti)",_x000D_
fr_GQ: "French (Equatorial Guinea)",_x000D_
fr_FR: "French (France)",_x000D_
fr_GA: "French (Gabon)",_x000D_
fr_GP: "French (Guadeloupe)",_x000D_
fr_GN: "French (Guinea)",_x000D_
fr_LU: "French (Luxembourg)",_x000D_
fr_MG: "French (Madagascar)",_x000D_
fr_ML: "French (Mali)",_x000D_
fr_MQ: "French (Martinique)",_x000D_
fr_MC: "French (Monaco)",_x000D_
fr_NE: "French (Niger)",_x000D_
fr_RW: "French (Rwanda)",_x000D_
fr_RE: "French (Réunion)",_x000D_
fr_BL: "French (Saint Barthélemy)",_x000D_
fr_MF: "French (Saint Martin)",_x000D_
fr_SN: "French (Senegal)",_x000D_
fr_CH: "French (Switzerland)",_x000D_
fr_TG: "French (Togo)",_x000D_
fr: "French",_x000D_
gl_ES: "Galician (Spain)",_x000D_
gl: "Galician",_x000D_
ka_GE: "Georgian (Georgia)",_x000D_
ka: "Georgian",_x000D_
de_AT: "German (Austria)",_x000D_
de_BE: "German (Belgium)",_x000D_
de_DE: "German (Germany)",_x000D_
de_LI: "German (Liechtenstein)",_x000D_
de_LU: "German (Luxembourg)",_x000D_
de_CH: "German (Switzerland)",_x000D_
de: "German",_x000D_
el_CY: "Greek (Cyprus)",_x000D_
el_GR: "Greek (Greece)",_x000D_
el: "Greek",_x000D_
hu_HU: "Hungarian (Hungary)",_x000D_
hu: "Hungarian",_x000D_
is_IS: "Icelandic (Iceland)",_x000D_
is: "Icelandic",_x000D_
id_ID: "Indonesian (Indonesia)",_x000D_
id: "Indonesian",_x000D_
it_IT: "Italian (Italy)",_x000D_
it_CH: "Italian (Switzerland)",_x000D_
it: "Italian",_x000D_
kab_DZ: "Kabyle (Algeria)",_x000D_
kab: "Kabyle",_x000D_
kl_GL: "Kalaallisut (Greenland)",_x000D_
kl: "Kalaallisut",_x000D_
lv_LV: "Latvian (Latvia)",_x000D_
lv: "Latvian",_x000D_
lt_LT: "Lithuanian (Lithuania)",_x000D_
lt: "Lithuanian",_x000D_
mk_MK: "Macedonian (Macedonia)",_x000D_
mk: "Macedonian",_x000D_
naq_NA: "Nama (Namibia)",_x000D_
naq: "Nama",_x000D_
pl_PL: "Polish (Poland)",_x000D_
pl: "Polish",_x000D_
pt_BR: "Portuguese (Brazil)",_x000D_
pt_GW: "Portuguese (Guinea-Bissau)",_x000D_
pt_MZ: "Portuguese (Mozambique)",_x000D_
pt_PT: "Portuguese (Portugal)",_x000D_
pt: "Portuguese",_x000D_
ro_MD: "Romanian (Moldova)",_x000D_
ro_RO: "Romanian (Romania)",_x000D_
ro: "Romanian",_x000D_
ru_MD: "Russian (Moldova)",_x000D_
ru_RU: "Russian (Russia)",_x000D_
ru_UA: "Russian (Ukraine)",_x000D_
ru: "Russian",_x000D_
seh_MZ: "Sena (Mozambique)",_x000D_
seh: "Sena",_x000D_
sk_SK: "Slovak (Slovakia)",_x000D_
sk: "Slovak",_x000D_
sl_SI: "Slovenian (Slovenia)",_x000D_
sl: "Slovenian",_x000D_
es_AR: "Spanish (Argentina)",_x000D_
es_BO: "Spanish (Bolivia)",_x000D_
es_CL: "Spanish (Chile)",_x000D_
es_CO: "Spanish (Colombia)",_x000D_
es_CR: "Spanish (Costa Rica)",_x000D_
es_DO: "Spanish (Dominican Republic)",_x000D_
es_EC: "Spanish (Ecuador)",_x000D_
es_SV: "Spanish (El Salvador)",_x000D_
es_GQ: "Spanish (Equatorial Guinea)",_x000D_
es_GT: "Spanish (Guatemala)",_x000D_
es_HN: "Spanish (Honduras)",_x000D_
es_419: "Spanish (Latin America)",_x000D_
es_MX: "Spanish (Mexico)",_x000D_
es_NI: "Spanish (Nicaragua)",_x000D_
es_PA: "Spanish (Panama)",_x000D_
es_PY: "Spanish (Paraguay)",_x000D_
es_PE: "Spanish (Peru)",_x000D_
es_PR: "Spanish (Puerto Rico)",_x000D_
es_ES: "Spanish (Spain)",_x000D_
es_US: "Spanish (United States)",_x000D_
es_UY: "Spanish (Uruguay)",_x000D_
es_VE: "Spanish (Venezuela)",_x000D_
es: "Spanish",_x000D_
sv_FI: "Swedish (Finland)",_x000D_
sv_SE: "Swedish (Sweden)",_x000D_
sv: "Swedish",_x000D_
tr_TR: "Turkish (Turkey)",_x000D_
tr: "Turkish",_x000D_
uk_UA: "Ukrainian (Ukraine)",_x000D_
uk: "Ukrainian",_x000D_
vi_VN: "Vietnamese (Vietnam)",_x000D_
vi: "Vietnamese"_x000D_
}_x000D_
_x000D_
_x000D_
var SS = SpreadsheetApp.getActiveSpreadsheet();_x000D_
var LocalS = SS.getSpreadsheetLocale();_x000D_
_x000D_
_x000D_
if (LANGUAGE_BY_LOCALE[LocalS] == undefined) {_x000D_
return false;_x000D_
_x000D_
}_x000D_
//Logger.log(true);_x000D_
return true;_x000D_
}_x000D_
_x000D_
/*_x000D_
function ReplaceDotsToCommas(dataIn) {_x000D_
var dataOut = dataIn.map(function(num) {_x000D_
if (isNaN(num)) {_x000D_
return num;_x000D_
} _x000D_
num = num.toString();_x000D_
return num.replace(".", ",");_x000D_
});_x000D_
return dataOut;_x000D_
}_x000D_
*/
_x000D_
Here's set of variables that are to be changed, you'll find them in script:
var TargetSheet = 'Main'; // name of sheet with data validation
var LogSheet = 'Data2'; // name of sheet with data
var NumOfLevels = 7; // number of levels of data validation
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc.
var lrow = 2; // number of row where validation starts
var offsets = [1,1,1,1,1,1,1]; // offsets for levels
I suggest everyone, who knows scripts well, send your edits to this code. I guess, there's simpler way to find validation list and make script run faster.
If you are using osxkeychain
and had a token expire and want to update it, follow these steps:
Run in terminal, then press enter twice.
git credential-osxkeychain erase
host=github.com
protocol=https
Now you should be prompted for a username/password. However sometimes it seems this does not 'take' and you have to keep re-entering.
If so, restart your computer. Now the next time you run a git command and enter your username/password, it will be saved.
a = input('Enter a binary number : ')
ar = [int(i) for i in a]
ar = ar[::-1]
res = []
for i in range(len(ar)):
res.append(ar[i]*(2**i))
sum_res = sum(res)
print('Decimal Number is : ',sum_res)
Try this
Install
npm install primeng --save
Import
import {FileUploadModule} from 'primeng/primeng';
Html
<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
accept="image/*" auto="auto"></p-fileUpload>
BigInteger would only be used if you know it will not be a decimal and there is a possibility of the long data type not being large enough. BigInteger has no cap on its max size (as large as the RAM on the computer can hold).
From here.
It is implemented using an int[]
:
110 /**
111 * The magnitude of this BigInteger, in <i>big-endian</i> order: the
112 * zeroth element of this array is the most-significant int of the
113 * magnitude. The magnitude must be "minimal" in that the most-significant
114 * int ({@code mag[0]}) must be non-zero. This is necessary to
115 * ensure that there is exactly one representation for each BigInteger
116 * value. Note that this implies that the BigInteger zero has a
117 * zero-length mag array.
118 */
119 final int[] mag;
From the source
From the Wikipedia article Arbitrary-precision arithmetic:
Several modern programming languages have built-in support for bignums, and others have libraries available for arbitrary-precision integer and floating-point math. Rather than store values as a fixed number of binary bits related to the size of the processor register, these implementations typically use variable-length arrays of digits.
ones
and zeros
, which create arrays full of ones and zeros respectively, take an optional dtype
parameter:
>>> numpy.ones((2, 2), dtype=bool)
array([[ True, True],
[ True, True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
[False, False]], dtype=bool)
This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.
Convert.ToInt64("1100.25")
Method signature from MSDN:
public static long ToInt64(
string value
)
I just want to point out, even syntax of itemgetter looks really neat, but it's kinda slow when perform on large list.
import timeit
from operator import itemgetter
start=timeit.default_timer()
for i in range(1000000):
itemgetter(0,2,3)(myList)
print ("Itemgetter took ", (timeit.default_timer()-start))
Itemgetter took 1.065209062149279
start=timeit.default_timer()
for i in range(1000000):
myList[0],myList[2],myList[3]
print ("Multiple slice took ", (timeit.default_timer()-start))
Multiple slice took 0.6225321444745759
My system was 32 bit. I removed and re-installed Notepad++. After that from below got PluginManager_v1.4.12_UNI.zip and extracted it.
https://github.com/bruderstein/nppPluginManager/releases
I created a folder called PluginManager at C:\Program Files (x86)\Notepad++\plugins\ and copied PluginManager.dll into it. I restarted my notepad++ and now I see Plugin Manager.
Well this work for me. First in AppDelegate
import UserNotifications
Then:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForRemoteNotification()
return true
}
func registerForRemoteNotification() {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
}
To get devicetoken:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
}
In my case, I had just installed the "Authorize Project" plugin and incorrectly setup the strategy in "Manage Jenkins -> Configure Global Security -> Access Control for Builds" as "Run as anonymous". So 'anonymous' had no rights to execute the job.
Setting the first strategy as "Run as User who Triggered Build" unlocked the queued jobs.
To be clear, you don't want a "fast way to move the cursor on a terminal command line". What you actually want is a fast way to navigate over command line in you shell program.
Bash is very common shell, for example. It uses Readline library to implement command line input. And so to say, it is very convenient to know Readline bindings since it is used not only in bash. For example, gdb also uses Readline to process input.
In Readline documentation you can find all navigation related bindings (and more): http://www.gnu.org/software/bash/manual/bash.html#Readline-Interaction
Short copy-paste if the link above goes down:
Bare Essentials
Movement
Kill and yank
M is Meta key. For Max OS X Terminal you can enable "Use option as meta key" in Settings/Keyboard for that. For Linux its more complicated.
Update
Also note, that Readline can operate in two modes:
To switch Bash to use vi mode:
$ set -o vi
Personaly I prefer vi mode since I use vim for text editing.
Bonus
In macOS Terminal app (and in iTerm too) you can Option-Click to move the cursor (cursor will move to clicked position). This even works inside vim
.
For the first part, try
echo Aa | od -t x1
It prints byte-by-byte
$ echo Aa | od -t x1
0000000 41 61 0a
0000003
The 0a
is the implicit newline that echo produces.
Use echo -n
or printf
instead.
$ printf Aa | od -t x1
0000000 41 61
0000002
(I'm using React Native; targetSdkVersion 22). I'm trying to change the look of a calendar date picker dialog. The accepted answer didn't work for me, but this did. Hope this snippet helps some of you.
<style name="CalendarDatePickerDialog" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">#6bf442</item>
<item name="android:textColorPrimary">#6bf442</item>
</style>
Cloud Computing is a large group of interconnected computers.The data are hidden form the user. Grid computing is more than one computers interconnected to resolve the problem.grid computing is worked in cloud computing.
const arr= [1, 2, 3]
arr.forEach(function(element){
if(arr[arr.length-1] === element){
console.log("Last Element")
}
})
Actually, with strings, you can do something like this:
oldStr = 'Hello World!'
newStr = ''
for i in oldStr:
if 'a' < i < 'z':
newStr += chr(ord(i)-32)
else:
newStr += i
print(newStr)
'HELLO WORLD!'
Basically, I'm "adding"+"strings" together into a new string :).
This function works fine. It's a slight imporvement of the code of Parkyprg
function age($birthday){
list($day,$month,$year) = explode("/",$birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 && $month_diff==0){$year_diff--;}
if ($day_diff < 0 && $month_diff < 0){$year_diff--;}
return $year_diff;
}
This single line gives you pid , each threadid and spid.
printf("before calling pthread_create getpid: %d getpthread_self: %lu tid:%lu\n",getpid(), pthread_self(), syscall(SYS_gettid));
create table a1
(weddingTable INT(3),
tableSeat INT(3),
tableSeatID INT(6),
Name varchar(10));
insert into a1
(weddingTable, tableSeat, tableSeatID, Name)
values (001,001,001001,'Bob'),
(001,002,001002,'Joe'),
(001,003,001003,'Dan'),
(002,001,002001,'Mark');
create table a2
(weddingTable int(3),
tableSeat int(3),
Meal varchar(10));
insert into a2
(weddingTable, tableSeat, Meal)
values
(001,001,'Chicken'),
(001,002,'Steak'),
(001,003,'Salmon'),
(002,001,'Steak');
select x.*, y.Meal
from a1 as x
JOIN a2 as y ON (x.weddingTable = y.weddingTable) AND (x.tableSeat = y. tableSeat);
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
I'd upvote artem's answer, but I am a new poster. I did expand on his solution, though not what the OP asked for as follows
t=(new Date()).toString().split(" ");
timestring = (t[2]+t[1]+' <b>'+t[4]+'</b> '+t[6][1]+t[7][0]+t[8][0]);
To get
04Oct 16:31:28 PDT
This works for me...
But if you are starting with just a time quantity, I use two functions; one to format and pad, and one to calculate:
function sec2hms(timect){
if(timect=== undefined||timect==0||timect === null){return ''};
//timect is seconds, NOT milliseconds
var se=timect % 60; //the remainder after div by 60
timect = Math.floor(timect/60);
var mi=timect % 60; //the remainder after div by 60
timect = Math.floor(timect/60);
var hr = timect % 24; //the remainder after div by 24
var dy = Math.floor(timect/24);
return padify (se, mi, hr, dy);
}
function padify (se, mi, hr, dy){
hr = hr<10?"0"+hr:hr;
mi = mi<10?"0"+mi:mi;
se = se<10?"0"+se:se;
dy = dy>0?dy+"d ":"";
return dy+hr+":"+mi+":"+se;
}
Does React re-render all components and sub-components every time setState is called?
By default - yes.
There is a method boolean shouldComponentUpdate(object nextProps, object nextState), each component has this method and it's responsible to determine "should component update (run render function)?" every time you change state or pass new props from parent component.
You can write your own implementation of shouldComponentUpdate method for your component, but default implementation always returns true - meaning always re-run render function.
Quote from official docs http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate
By default, shouldComponentUpdate always returns true to prevent subtle bugs when the state is mutated in place, but if you are careful to always treat the state as immutable and to read-only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.
Next part of your question:
If so, why? I thought the idea was that React only rendered as little as needed - when the state changed.
There are two steps of what we may call "render":
Virtual DOM renders: when render method is called it returns a new virtual dom structure of the component. As I mentioned before, this render method is called always when you call setState(), because shouldComponentUpdate always returns true by default. So, by default, there is no optimization here in React.
Native DOM renders: React changes real DOM nodes in your browser only if they were changed in the Virtual DOM and as little as needed - this is that great React's feature which optimizes real DOM mutation and makes React fast.
input{
text-align:center;
}
is all you need.
Working example in FF6. This method doesn't seem to be cross-browser compatible.
Your previous CSS was attempting to center the text of an input element which had a class of "placeholder".
Make resource controller with Model.
php artisan make:controller PostController --model=Post
No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.
I can't find a way to create a table with icons in SO, so I am uploading 2 images.
It imports once when the function executes first time.
Pros:
Cons:
If you are running a script, instead of a statement, you can increase this by selecting Tools/Preferences/Worksheet and increasing "Max Rows to print in a script". The default is 5000, you can change it to any size.
I know it's an old Question, but i think some one can benefit from my solution.
select
SUBSTRING(column_name,1,CHARINDEX(' ',column_name,1)-1)
,SUBSTRING(SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name))
,1
,CHARINDEX(' ',SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name)),1)-1)
,SUBSTRING(SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name))
,CHARINDEX(' ',SUBSTRING(column_name,CHARINDEX(' ',column_name,1)+1,LEN(column_name)),1)+1
,LEN(column_name))
from table_name
Advantages:
Limitations:
Note: the solution can give sub-string up to to N.
To overcame the limitation we can use the following ref.
But again the above solution can't be use in a table (Actaully i wasn't able to use it).
Again i hope this solution can help some-one.
Update: In case of Records > 50000 it is not advisable to use LOOPS
as it will degrade the Performance
I had do this kind of automatic validation in VB and this is how I did it (converted to C#):
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = settings.ValidationFlags |
Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
XmlReader XMLvalidator = XmlReader.Create(reader, settings);
Then I subscribed to the settings.ValidationEventHandler
event while reading the file.
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);
line 2 should be replaced with
byte[] binData = b.ReadBytes(file.ContentLength);
set STATICBUILD=true && pip install lxml
run this command instead, must have VS C++ compiler installed first
https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/
It works for me with Python 3.5.2 and Windows 7
You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :--> (inside main)
Orderbook o1;
o1.m.check(side)
but that would be unnecessary. Keeping things short :-
You can't call functions inside a Class
If it's Windows, all you need to do is delete the root of that project within the file explorer. Just right click on the name of the app in Android Studio, and then "show in file explorer". Then just delete the project folder all in all.
If you got here because you're using the new ASP.NET
Identity
UserManager
, what you're actually looking for is the RoleManager
:
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
roleManager
will give you access to see if the role exists, create, etc, plus it is created for the UserManager
You can update your provisioning certificates in XCode at:
Organizer -> Devices -> LIBRARY -> Provisioning Profiles
There is a refresh button :) So if you have created the certificate manually in iTunes connect, then you need to press this button or download the certificate manually.
[parentView bringSubviewToFront:view] ;
I had a similar issue, but in my case, it was my CSS file.
I had loaded my CSS file before the JQuery library, since my jquery function was interaction with my css file, my jquery function wasn't working. I found this weird, but when I loaded the CSS file after loading the JQuery library, it worked.
This might not be directly related to the Question, but it may help others who might be facing a similar problem.
My issue:
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="slider.js"></script>
My solution:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="slider.js"></script>
I could not find a solution that our team would be happy with so we rolled our own. We use ActivityLifecycleCallbacks
to keep track of current activity and then expose it through a service. More details here: https://stackoverflow.com/a/38650587/10793
You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();
Sometimes the spring config xml file works not well on next eclipse open up.
It shows error in the xml file caused by schema definition, no matter reopen eclipse or clean up project are both not working.
But try this!
Right click on the spring config xml file, and select
validate
.
After a while, the error disappears and eclipse tells you there is no error on this file.
What a joke...
With iOS 8, Xcode 6, iTunes Connect and TestFlight you don't need UDIDs and Ad Hocs anymore. You will just need an Apple ID from your beta tester. Right now you can only beta test your app with 25 internal testers, but soon 1000 external testers will be available too. This blog post shows you how to setup a beta test with internal testers.
If you have only one checkbox, you can do this easily with just ng-model:
<input type="checkbox" ng-model="checked"/>
<button ng-disabled="!checked"> Next </button>
And initialize $scope.checked in your Controller (default=false). The official doc discourages the use of ng-init in that case.
Update the following commands in command prompt in windows:
i) android update sdk --no-ui --all // It update your SDK packages and it takes 3 minutes. ii) android update sdk --no-ui --filter platform-tools,tools //It updates the platform tools and its packages. iii) android update sdk --no-ui --all --filter extra-android-m2repository // Those who are working with maven project update this to support with latest support design library which will include extra maven android maven Repository.
1)In the command prompt it asks you for Y/N .click on the Y then it proceeds with the installation. 2) It updates all Kernel-qemu files and qt5.dll commands. so that the Emulator works fine without any issues.
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
First, you need to import from inspect
and os
from inspect import getsourcefile
from os.path import abspath
Next, wherever you want to find the source file from you just use
abspath(getsourcefile(lambda:0))
You can use ReSharper for namespace refactoring. It will give 30 days free trial. It will change namespace as per folder structure.
Steps:
Right click on the project/folder/files you want to refactor.
If you have installed ReSharper then you will get an option Refactor->Adjust Namespaces.... So click on this.
It will automatically change the name spaces of all the selected files.
A one liner would be :
str=str[::-1].replace(".",".-",1)[::-1]
Just unset the node:
$str = <<<STR
<a>
<b>
<c>
</c>
</b>
</a>
STR;
$xml = simplexml_load_string($str);
unset($xml –> a –> b –> c); // this would remove node c
echo $xml –> asXML(); // xml document string without node c
This code was taken from How to delete / remove nodes in SimpleXML.
Switch to joda-time and you can do this in three lines
DateTime jodaTime = new DateTime();
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println("jodaTime = " + formatter.print(jodaTime));
You also have direct access to the individual fields of the date without using a Calendar.
System.out.println("year = " + jodaTime.getYear());
System.out.println("month = " + jodaTime.getMonthOfYear());
System.out.println("day = " + jodaTime.getDayOfMonth());
System.out.println("hour = " + jodaTime.getHourOfDay());
System.out.println("minute = " + jodaTime.getMinuteOfHour());
System.out.println("second = " + jodaTime.getSecondOfMinute());
System.out.println("millis = " + jodaTime.getMillisOfSecond());
Output is as follows:
jodaTime = 2010-04-16 18:09:26.060
year = 2010
month = 4
day = 16
hour = 18
minute = 9
second = 26
millis = 60
According to http://www.joda.org/joda-time/
Joda-Time is the de facto standard date and time library for Java. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).
Make a virtual enviroment using python3
virtualenv env_name --python="python3"
and run the following command
pip3 install opencv-python
to check it has installed correctly run
python3 -c "import cv2"
I had the same problem. But I also had to perform additional steps. Here is what I did.
Perform the following steps (Only 64bit version of SQL Server 2005 Developer Edition tested on Windows 8 Pro 64bit)
For STEP 5 above: Although I didn't try looking into SP4 / SP3 setup for SQLSERVR.EXE and SQLOS.DLL but if you don't have an existing installation of SQL Server 2005 SP3/SP4 then maybe try looking into the SP3/SP4 EXE (Compressed file). I am not sure if this may help. In any case you can create a VM and install SQL Server 2005 with SP3/Sp4 to copy the files for Windows 8
Also simple and easy:
Start-Sleep 10
In Clean Code: A Handbook of Agile Software Craftsmanship there is an explicit recommendation against the usage of this prefix:
You also don't need to prefix member variables with
m_
anymore. Your classes and functions should be small enough that you don't need them.
There is also an example (C# code) of this:
Bad practice:
public class Part
{
private String m_dsc; // The textual description
void SetName(string name)
{
m_dsc = name;
}
}
Good practice:
public class Part
{
private String description;
void SetDescription(string description)
{
this.description = description;
}
}
We count with language constructs to refer to member variables in the case of explicitly ambiguity (i.e., description
member and description
parameter): this
.
In case you don't want to use a temporary variable, you can also do like this:
final int len = arr.length;
for (int i=0; i < (len/2); i++) {
arr[i] += arr[len - 1 - i]; // a = a+b
arr[len - 1 - i] = arr[i] - arr[len - 1 - i]; // b = a-b
arr[i] -= arr[len - 1 - i]; // a = a-b
}
Just search
open_basedir =
in php.ini and disable it. That's the simplest solution to solve this issue.
Before Changes open_basedir =
After Changes ;open_basedir =
P.s - After changes don't forget to restart your server.
Enjoy ;)
This checks if EAX
is zero. The instruction test
does bitwise AND
between the arguments, and if EAX
contains zero, the result sets the ZF, or ZeroFlag.
Or, for Python 3:
for k,v in dict.items():
print(k, v)
You also need to install software-properties-common for add-apt-repository to work. so it will be
sudo apt-get purge nodejs npm
sudo apt-get install -y python-software-properties python g++ make software-properties-common
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
You can create functions in react components. It is actually regular ES6 class which inherits from React.Component
. Just be careful and bind it to the correct context in onClick
event:
export default class Archive extends React.Component {
saySomething(something) {
console.log(something);
}
handleClick(e) {
this.saySomething("element clicked");
}
componentDidMount() {
this.saySomething("component did mount");
}
render() {
return <button onClick={this.handleClick.bind(this)} value="Click me" />;
}
}
private string MonthName(int m)
{
string res;
switch (m)
{
case 1:
res="Ene";
break;
case 2:
res = "Feb";
break;
case 3:
res = "Mar";
break;
case 4:
res = "Abr";
break;
case 5:
res = "May";
break;
case 6:
res = "Jun";
break;
case 7:
res = "Jul";
break;
case 8:
res = "Ago";
break;
case 9:
res = "Sep";
break;
case 10:
res = "Oct";
break;
case 11:
res = "Nov";
break;
case 12:
res = "Dic";
break;
default:
res = "Nulo";
break;
}
return res;
}
pmg's answer is very convincing. If you would like to know how static declarations work at object level then this below info could be interesting to you. I reused the same program written by pmg and compiler it into a .so(shared object) file
Following contents are after dumping the .so file into something human readable
0000000000000675 f1: address of f1 function
000000000000068c f2: address of f2(staticc) function
note the difference in the function address , it means something . For a function that's declared with different address , it can very well signify that f2 lives very far away or in a different segment of the object file.
Linkers use something called PLT(Procedure linkage table) and GOT(Global offsets table) to understand symbols that they have access to link to .
For now think that GOT and PLT magically bind all the addresses and a dynamic section holds information of all these functions that are visible by linker.
After dumping the dynamic section of the .so file we get a bunch of entries but only interested in f1 and f2 function.
The dynamic section holds entry only for f1 function at address 0000000000000675 and not for f2 !
Num: Value Size Type Bind Vis Ndx Name
9: 0000000000000675 23 FUNC GLOBAL DEFAULT 11 f1
And thats it !. From this its clear that the linker will be unsuccessful in finding the f2 function since its not in the dynamic section of the .so file.
In PostgreSQL there is no merge command, and actually writing it is not trivial - there are actually strange edge cases that make the task "interesting".
The best (as in: working in the most possible conditions) approach, is to use function - such as one shown in manual (merge_db).
If you don't want to use function, you can usually get away with:
updated = db.execute(UPDATE ... RETURNING 1)
if (!updated)
db.execute(INSERT...)
Just remember that it is not fault proof and it will fail eventually.
I was experiencing the same issue.. I already had 4 controllers going and working just fine but when I added this one it returned "The requested resource does not support HTTP method 'GET'". I tried everything here and in a couple other relevant articles but was indifferent to the solution since, as Dan B. mentioned in response to the answer, I already had others working fine.
I walked away for a while, came back, and immediately realized that when I added the Controller it was nested under the "Controller" class and not "ApiController" class that my other Controllers were under. I'm assuming I chose the wrong scaffolding option to build the .cs file in Visual Studio. So I included the System.Web.Http namespace, changed the parent class, and everything works without the additional attributes or routing.
From my research and starting on this post, i think this is the best option:
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">This will stick at the botton no matter what :).</p>
_x000D_
This option allow resizes of the page and even if the page is blank it will stick at the bottom.
Here is an example I think that will help you
<!DOCTYPE html>
<html>
<head>
<script src="js/min.js"></script>
<script src="js/pdf.js"></script>
<script>
$(function(){
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
var table = tableToJson($('#StudentInfoListTable').get(0))
var doc = new jsPDF('p','pt', 'a4', true);
doc.cellInitialize();
$.each(table, function (i, row){
console.debug(row);
$.each(row, function (j, cell){
doc.cell(10, 50,120, 50, cell, i); // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
})
})
doc.save('sample-file.pdf');
});
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=0; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
});
</script>
</head>
<body>
<div id="table">
<table id="StudentInfoListTable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Track</th>
<th>S.S.C Roll</th>
<th>S.S.C Division</th>
<th>H.S.C Roll</th>
<th>H.S.C Division</th>
<th>District</th>
</tr>
</thead>
<tbody>
<tr>
<td>alimon </td>
<td>Email</td>
<td>1</td>
<td>2222</td>
<td>as</td>
<td>3333</td>
<td>dd</td>
<td>33</td>
</tr>
</tbody>
</table>
<button id="cmd">Submit</button>
</body>
</html>
Here the output
You were close with
Contact.update({phone:request.phone}, contact, {upsert: true}, function(err){...})
but your second parameter should be an object with a modification operator for example
Contact.update({phone:request.phone}, {$set: { phone: request.phone }}, {upsert: true}, function(err){...})
As per doc http://dev.mysql.com/doc/refman/5.0/en/server-status-variables.html#statvar_Connections
Connections
The number of connection attempts (successful or not) to the MySQL server.
In your command line(Unix terminal) Go to your project root folder, and do this
find . -type f -name '*.iml' -exec sed -i '' s/JDK_1_5/JDK_1_8/g {} +
This will change the language level property in all your project .iml files from java 1.5 to java 1.8.
what about ...
import pandas as pd
import matplotlib.pyplot as plt
values = [[1,2], [2,5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
(df2.plot(lw=2,
colormap='jet',
marker='.',
markersize=10,
title='Video streaming dropout by category')
.set(xlabel='x axis',
ylabel='y axis'))
plt.show()
I was getting this error message when trying to close the dialog by using a button inside the dialog body. I tried to use $('#myDialog').dialog('close');
which did not work.
I ended up firing the click action of the 'x' button on the header using:
$('.modal-header:first').find('button:first').click();
I just add this in my CSS file and it works:
.custom-file-label::after{content: 'New Text Button' !important;}
Page 2 is in a new tab/window ? If it's this, use the code bellow :
try {
String winHandleBefore = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
String act = driver.getCurrentUrl();
}
}catch(Exception e){
System.out.println("fail");
}
try the following query:
SELECT ID,
Name
INTO #tempTable
FROM Table
SELECT *
FROM #tempTable
WHERE ID = 1
It doesn't need to declare table.
Based on the Microsoft support KBs, this can occur if TCP/IP is damaged or is not bound to your dial-up adapter.You can try reinstalling or resetting TCP/IP as follows:
Reset TCP/IP to Original Configuration- Using the NetShell utility,
type this command (in CommandLine): netsh int ip reset [file_name.txt]
,
[file_name.txt] is the name of the file where the actions taken by
NetShell are record, for example netsh hint ip reset fixtcpip.txt.
Remove and re-install NIC – Open Controller and select System. Click Hardware tab and select devices. Double-click on Network Adapter and right-click on the NIC, select Uninstall. Restart the computer and the Windows should auto detect the NIC and re-install it.
Hope it could help.
in the 'default' directory if you have not specifically mentioned your location.
you can use describe and describe extended to know about the table structure.
I recently needed this and required to convert the in bytes to a number in long.
Usage: Byte.Kb.ToLong(1)
should give 1024.
public enum Byte
{
Kb,
Mb,
Gb,
Tb
}
public static class ByteSize
{
private const long OneKb = 1024;
private const long OneMb = OneKb * 1024;
private const long OneGb = OneMb * 1024;
private const long OneTb = OneGb * 1024;
public static long ToLong(this Byte size, int value)
{
return size switch
{
Byte.Kb => value * OneKb,
Byte.Mb => value * OneMb,
Byte.Gb => value * OneGb,
Byte.Tb => value * OneTb,
_ => throw new NotImplementedException("This should never be hit.")
};
}
}
Tests using xunit:
[Theory]
[InlineData(Byte.Kb, 1, 1024)]
[InlineData(Byte.Kb, 2, 2048)]
[InlineData(Byte.Mb, 1, 1048576)]
[InlineData(Byte.Mb, 2, 2097152)]
[InlineData(Byte.Gb, 1, 1073741824)]
[InlineData(Byte.Gb, 2, 2147483648)]
[InlineData(Byte.Tb, 1, 1099511627776)]
[InlineData(Byte.Tb, 2, 2199023255552)]
public void ToLong_WhenConverting_ShouldMatchExpected(Byte size, int value, long expected)
{
var result = size.ToLong(value);
result.Should().Be(expected);
}
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly
attribute (or disabled
, if you want to remove it from the form submission as well) to the <input>
, like this:
<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />
you can use following UIView category -
@implementation UIView (SnapShot)
- (UIImage *)snapshotImage
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
// old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
Use it like this:
$("#searchField").focus(function() {
$(this).val("");
});
It has to work. Otherwise it probably never gets focused.
(Updated for 2017)
When you installed MySQL it generated a password for the root user. You can connect using
/usr/local/mysql/bin/mysql -u root -p
and type in the generated password.
Previously, the root
user in MySQL used to not have a password and could only connect from localhost. So you would connect using
/usr/local/mysql/bin/mysql -u root
I think the MatTableDataSource
object is some way linked with the data array that you pass to MatTableDataSource
constructor.
For instance:
dataTable: string[];
tableDS: MatTableDataSource<string>;
ngOnInit(){
// here your pass dataTable to the dataSource
this.tableDS = new MatTableDataSource(this.dataTable);
}
So, when you have to change data; change on the original list dataTable
and then reflect the change on the table by call _updateChangeSubscription()
method on tableDS
.
For instance:
this.dataTable.push('testing');
this.tableDS._updateChangeSubscription();
That's work with me through Angular 6.
If you want to effect on the menu options for changing the locale immediately.You have to do like this.
//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//1.Here you can add your locale settings .
//2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
menu.clear();
onCreateOptionsMenu(menu);
return super.onMenuOpened(featureId, menu);
}
It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.
Entity::upsert([
['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);
On mac OS X Yosemite, after installing it with brew it put it into
/usr/local/opt/openssl/bin/openssl
But kept getting an error "Linking keg-only openssl means you may end up linking against the insecure" when trying to link it
So I just linked it by supplying the full path like so
ln -s /usr/local/opt/openssl/bin/openssl /usr/local/bin/openssl
Now it's showing version OpenSSL 1.0.2o when I do "openssl version -a", I'm assuming it worked
Well, what do you try to do? If you want to use division, use "/" not "\". If it is something else, explain it in a bit more detail, please.
Expanding on the notes from Adel Mourad and Dan Hunex, I amended the code to provide an example that only accepts values that do not match the given value.
I also found that I didn't need the JavaScript.
I added the following class to my Models folder:
public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
{
private String PropertyName { get; set; }
private Object InvalidValue { get; set; }
private readonly RequiredAttribute _innerAttribute;
public RequiredIfNotAttribute(String propertyName, Object invalidValue)
{
PropertyName = propertyName;
InvalidValue = invalidValue;
_innerAttribute = new RequiredAttribute();
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);
if (dependentValue.ToString() != InvalidValue.ToString())
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredifnot",
};
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
rule.ValidationParameters["invalidvalue"] = InvalidValue is bool ? InvalidValue.ToString().ToLower() : InvalidValue;
yield return rule;
}
I didn't need to make any changes to my view, but did make a change to the properties of my model:
[RequiredIfNot("Id", 0, ErrorMessage = "Please select a Source")]
public string TemplateGTSource { get; set; }
public string TemplateGTMedium
{
get
{
return "Email";
}
}
[RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Campaign")]
public string TemplateGTCampaign { get; set; }
[RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Term")]
public string TemplateGTTerm { get; set; }
Hope this helps!
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'id' && $value == 'searched_value'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}
For Word Wrapping in Php Storm 1. Select File from the menu 2. From File select setting 3. From setting select Editor 4. Select General from Editor 5. In general checked Use soft wraps in editor from Soft wraps section
ByteArrayOutputStream buffer = (ByteArrayOutputStream) aOutputStream;
byte[] bytes = buffer.toByteArray();
InputStream inputStream = new ByteArrayInputStream(bytes);
I found this to work very well!
function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}
Use:
<?php
function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}
include(findRoot() . 'Post.php');
$posts = getPosts(findRoot() . 'posts_content');
include(findRoot() . 'includes/head.php');
for ($i=(sizeof($posts)-1); 0 <= $i; $i--) {
$posts[$i]->displayArticle();
}
include(findRoot() . 'includes/footer.php');
?>
break;
is what you need to break out of any looping statement like for
, while
or do-while
.
In your case, its going to be like this:-
for(int x = 10; x < 20; x++) {
// The below condition can be present before or after your sysouts, depending on your needs.
if(x == 15){
break; // A unlabeled break is enough. You don't need a labeled break here.
}
System.out.print("value of x : " + x );
System.out.print("\n");
}
// Add this middleware
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
To summarize the date inputs problem:
The solution I found to meet those requirements is to use the usual trick to style native form elements : ensure the element is displayed but not visible, and display its expected style through its associated label. Typically, the label will display as the input (including a placeholder), but over it.
So, an HTML like:
<div class="date-input>
<input id="myInput" type="date">
<label for="myInput">
<span class="place-holder">Enter a date</span>
</label>
</div>
Could be styled as:
.date-input {
display: inline-block;
position: relative;
}
/* Fields overriding */
input[type=date] + label {
position: absolute; /* Same origin as the input, to display over it */
background: white; /* Opaque background to hide the input behind */
left: 0; /* Start at same x coordinate */
}
/* Common input styling */
input[type=date], label {
/* Must share same size to display properly (focus, etc.) */
width: 15em;
height: 1em;
font-size: 1em;
}
Any event (click, focus) on such an associated label will be reflected on the field itself, and so trigger the date input UI.
Should you want to test such a solution live, you can run this Angular version from your tablet or mobile.
Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.
On running the command:
$ brew install lua
The command returned an error:
Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg
FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.
root-user # rm -rf /usr/local/opt/lua
And then running the brew install command returned success.
someVar
value should be accessible only in some_function()
context, not from listener's.
If you like to have it within listener, you must do something like:
someObj.addEventListener("click",
function(){
var newVar = someVar;
some_function(someVar);
},
false);
and use newVar
instead.
The other way is to return someVar
value from some_function()
for using it further in listener (as a new local var):
var someVar = some_function(someVar);
Create a new template and check DBname. Use that template for your tracefile.
Your response object is declared as a ServletResponse
. To use the sendRedirect()
method, you have to cast it to HttpServletResponse
. This is an extended interface that adds methods related to the HTTP protocol.
Don't worry about any performance differences, they're going to be minimal in this case normally.
Method 2 is preferable because
it doesn't require mutating a collection that exists outside the lambda expression,
it's more readable because the different steps that are performed in the collection pipeline are written sequentially: first a filter operation, then a map operation, then collecting the result (for more info on the benefits of collection pipelines, see Martin Fowler's excellent article),
you can easily change the way values are collected by replacing the Collector
that is used. In some cases you may need to write your own Collector
, but then the benefit is that you can easily reuse that.
Some color-syntaxing enrichment can be applied with the following blockcode syntax
```json
Here goes your json object definition
```
Note: This won't prettify the json representation. To do so, one can previously rely on an external service such as jsbeautifier.org and paste the prettified result in the wiki.
you can loop through all attributes like you do with nodes
foreach (XmlNode item in node.ChildNodes)
{
// node stuff...
foreach (XmlAttribute att in item.Attributes)
{
// attribute stuff
}
}
Dim dgv As DataGridView = Me.TblCalendarDataGridView
For i As Integer = 0 To dgv.Rows.Count - 1
For ColNo As Integer = 4 To 7
If Not dgv.Rows(i).Cells(ColNo).Value Is DBNull.Value Then
dgv.Rows(i).Cells(ColNo).Style.BackColor = vbcolor.blue
End If
Next
Next
SELECT *
FROM (SELECT ROW_NUMBER () OVER (ORDER BY user_id) user_row_no, a.* FROM temp_emp a)
WHERE user_row_no > 1 and user_row_no <11
This worked for me.If i may,i have few useful dbscripts that you can have look at
I just had to face the same kind of issue with my Laravel 7 project, in Debian 10 shared hosting. I have to add RewriteBase /
to my .htaccess within /public/ directory. So the .htaccess looks a like
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
If you want to run your scripts, then
mysql -u root -p < yourscript.sql
Just use this : Make sure using nibName otherwise preloaded views of xib will not show :
var vc : ViewController = ViewController(nibName: "ViewController", bundle: nil)
//change this to your class name
self.presentViewController(vc, animated: true, completion: nil)
Finally this is for Hibernate 5
in Tomcat
.
Compiled all the answers from the above and added my tips which works like a charm for Hibernate 5 and SQL Server 2014
.
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="hibernate.connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="hibernate.connection.url">
jdbc:sqlserver://localhost\ServerInstanceOrServerName:1433;databaseName=DATABASE_NAME
</property>
<property name="hibernate.default_schema">theSchemaNameUsuallydbo</property>
<property name="hibernate.connection.username">
YourUsername
</property>
<property name="hibernate.connection.password">
YourPasswordForMSSQL
</property>
If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.
Add a javascript class with all you KO extensions or extenders, and add the following:
ko.extenders.required = function (target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};
Then in your viewModel extend you observable by:
self.dateOfPayment: ko.observable().extend({ required: "" }),
There are a number of examples online for this style of validation.
Another option is:
<Grid container justify = "center">
<Your centered component/>
</Grid>
While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.
Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:
auth-server-whitelist
command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz"
. Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.AuthServerWhitelist
/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist
policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:
Start > Run > gpedit.msc
Local Computer Policy > Computer Configuration > Administrative Templates
Administrative Templates
, and select Add/Remove Templates
windows\adm\en-US\chrome.adm
template via the dialogComputer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication
enable and configure Authentication server whitelist
chrome://policy
to view active policiesTypically, you can copy the .classpath file from a working project since there isn’t anything project specific here assuming you’re structured as a standard Maven project.
pg_dump -s databasename -t tablename -U user -h host -p port > tablename.sql
this will limit the schema dump to the table "tablename" of "databasename"
You can work with the "margin" property:
li a {
margin: 0px 5px 0px 5px;
}
li a:hover {
margin: 0;
font-weight: bold;
}
Just make sure that the left and right margin are big enough so the extra space can contain the bold text. For long words, you might choose different margins. It's just another workaround but doing the job for me.
Just do
NSString* newString=[NSString stringWithFormat:@"first part of string (%@) third part of string", @"foo"];
This gives you
@"first part of string (foo) third part of string"
You can give like this
public static function getAll()
{
return $posts = $this->all()->take(2)->get();
}
And when you call statically inside your controller function also..
The curly braces ({}) are used to import named bindings and the concept behind it is destructuring assignment
A simple demonstration of how import statement works with an example can be found in my own answer to a similar question at When do we use '{ }' in javascript imports?.
The following code will clean the directory, but leave the root directory there (recursive).
Action<string> DelPath = null;
DelPath = p =>
{
Directory.EnumerateFiles(p).ToList().ForEach(File.Delete);
Directory.EnumerateDirectories(p).ToList().ForEach(DelPath);
Directory.EnumerateDirectories(p).ToList().ForEach(Directory.Delete);
};
DelPath(path);
Here is the code for it.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="@+id/static_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp" />
<Spinner
android:id="@+id/dynamic_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Ahotbrew.com - Dropdown</string>
<string-array name="brew_array">
<item>Cappuccino</item>
<item>Espresso</item>
<item>Mocha</item>
<item>Caffè Americano</item>
<item>Cafe Zorro</item>
</string-array>
MainActivity
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
.createFromResource(this, R.array.brew_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
staticAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
staticSpinner.setAdapter(staticAdapter);
Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
String[] items = new String[] { "Chai Latte", "Green Tea", "Black Tea" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
dynamicSpinner.setAdapter(adapter);
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
This example is from http://www.ahotbrew.com/android-dropdown-spinner-example/
WhatsApp does not have a API available for public use. As you put it, it's a closed system.
However, they provide several other ways in which your iPhone application can interact with WhatsApp: through custom URL schemes, share extension and through the Document Interaction API.
This solution helped me to skip the number of lines specified by the linetostart
variable.
You get the index (int) and the line (string) if you want to keep track of those too.
In your case, you substitute linetostart with 18, or assign 18 to linetostart variable.
f = open("file.txt", 'r')
for i, line in enumerate(f, linetostart):
#Your code
Use Context.getDatabasePath(databasename). The context can be obtained from your application.
If you get previous data back it can be either a) the data was stored in an unconventional location and therefore not deleted with uninstall or b) Titanium backed up the data with the app (it can do that).
This is a short solution to change the request UserAgent on the fly.
Change UserAgent of a request with Chrome
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
driver = webdriver.Chrome(driver_path)
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 2.7", "platform":"Windows"})
driver.get('http://amiunique.org')
then return your useragent:
agent = driver.execute_script("return navigator.userAgent")
Some sources
The source code of webdriver.py from SeleniumHQ (https://github.com/SeleniumHQ/selenium/blob/11c25d75bd7ed22e6172d6a2a795a1d195fb0875/py/selenium/webdriver/chrome/webdriver.py) extends its functionalities through the Chrome Devtools Protocol
def execute_cdp_cmd(self, cmd, cmd_args):
"""
Execute Chrome Devtools Protocol command and get returned result
We can use the Chrome Devtools Protocol Viewer to list more extended functionalities (https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) as well as the parameters type to use.
You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.
If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.
In C, you have two simple ways to declare an array.
On the stack, as a static array
int myArray[16]; // Static array of 16 integers
On the heap, as a dynamically allocated array
// Dynamically allocated array of 16 integers
int* myArray = calloc(16, sizeof(int));
Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).