You need something like a regular expression.
You have to be in Extended
mode
If you want all the lines to end up on a single line use \r\n
. If you want to simply remove empty lines, use \n\r
as @Link originally suggested.
Replace either expression with nothing.
I'm using Android Studio 3.0.1
and if the above answer doesn't work for you, try to change the icon type
into Legacy
and select Shape
to None
, the default one is Adaptive and Legacy
.
Note: Some device has installed a launcher with automatically adding white background in icon, that's normal.
var text = $(".title").contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
This gets the contents
of the selected element, and applies a filter function to it. The filter function returns only text nodes (i.e. those nodes with nodeType == Node.TEXT_NODE
).
I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.
Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
In my case I was getting latin cross sign instead of nbsp, even that a page was correctly encoded into the UTF-8. Nothing of above helped in resolving the issue and I tried all.
In the end changing font for IE (with browser specific css) helped, I was using Helvetica-Nue as a body font changing to the Arial resolved the issue .
VSCode 1.42 (January 2020) introduces:
Panel on the left/right
The panel can now be moved to the left side of the editor with the setting:
"workbench.panel.defaultLocation": "left"
This removes the command
View: Toggle Panel Position
(workbench.action.togglePanelPosition
) in favor of the following new commands:
View: Move Panel Left
(workbench.action.positionPanelLeft
)View: Move Panel Right
(workbench.action.positionPanelRight
)View: Move Panel To Bottom
(workbench.action.positionPanelBottom
)
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: Arrays and Lists in SQL Server.
There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons.
I really can't recommend enough to read the article to learn about the tradeoffs among all these options.
There are a least these apt-get
extension packages that can help:
apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media
This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.
Otherwise, the --download-only
option to apt-get
is your friend:
-d, --download-only
Download only; package files are only retrieved, not unpacked or installed.
Configuration Item: APT::Get::Download-Only.
Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.
2 options
Don't use camel case
<Option data-img-src='value' ... />
And then in the component, because of the dashes, you need to refer to the prop in quotes.
// @flow
class Option extends React.Component {
props: {
'data-img-src': string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props['data-img-src']} >...</option>
)
}
}
Or use camel case
<Option dataImgSrc='value' ... />
And then in the component, you need to convert.
// @flow
class Option extends React.Component {
props: {
dataImgSrc: string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props.dataImgSrc} >...</option>
)
}
}
Mainly just realize data-
attributes and aria-
attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.
It's possible using jQuery it depends on your site load time you can adjust your timeout. It can be your custom image or you can use youtube image maxres1.jpg, maxres2.jpg or maxres3.jpg
var newImage = 'http://i.ytimg.com/vi/[Video_ID]/maxres1.jpg';
window.setTimeout(function() {
jQuery('div > div.video-container-thumb > div > a > img').attr('src',newImage );
}, 300);
You can Highlight text in a <textarea>
, using a <div>
carefully placed behind it.
check out Highlight Text Inside a Textarea.
Disabled elements don't fire mouse events. Most browsers will propagate an event originating from the disabled element up the DOM tree, so event handlers could be placed on container elements. However, Firefox doesn't exhibit this behaviour, it just does nothing at all when you click on a disabled element.
I can't think of a better solution but, for complete cross browser compatibility, you could place an element in front of the disabled input and catch the click on that element. Here's an example of what I mean:
<div style="display:inline-block; position:relative;">
<input type="text" disabled />
<div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>?
jq:
$("div > div").click(function (evt) {
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
});?
Example: http://jsfiddle.net/RXqAm/170/ (updated to use jQuery 1.7 with prop
instead of attr
).
Given an instance of the struct, you set the values.
student thisStudent;
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
thisStudent.s_id = int.Parse(Console.ReadLine());
thisStudent.s_name = Console.ReadLine();
thisStudent.c_name = Console.ReadLine();
thisStudent.s_dob = Console.ReadLine();
Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.
I came to this post when i was searching for the same issue but in android
.
I don't say this is the best way to get sorted files by last modified date, but its the easiest way I found yet.
Below code may be helpful to someone-
File downloadDir = new File("mypath");
File[] list = downloadDir.listFiles();
for (int i = list.length-1; i >=0 ; i--) {
//use list.getName to get the name of the file
}
Thanks
Go to file "settings.json" and disable the Python pydocstyle
:
"python.linting.pydocstyleEnabled": false
java.util.Date
object can't represent date in custom format instead you've to use SimpleDateFormat.format
method that returns string
.
String myString=format1.format(date);
I think the easiest way to do is with backticks
mv `ls -1 ~/Linux/Old/ | grep -v Tux.png` ~/Linux/New/
Edit:
Use backslash with ls instead to prevent using it with alias, i.e. mostly ls is aliased as ls --color.
mv `\ls -1 ~/Linux/Old/ | grep -v Tux.png` ~/Linux/New/
Thanks @Arnold Roa
If you are using PHP's password_hash()
with the PASSWORD_DEFAULT
algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash()
might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).
From the manual page:
Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT
to force password_hash()
to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.
JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula
is perfect for this when using Hibernate. You can use an SQL fragment:
@Formula("PRICE*1.155")
private float finalPrice;
Or even complex queries on other tables:
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;
Where id
is the id
of the current entity.
The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.
Without more details, I can't give a more precise answer but the above link should be helpful.
Based in the answer of @G M and paying attention to the @John La Rooy's warning, I was able to append a new row opening the file in 'a'
mode.
Even in windows, in order to avoid the newline problem, you must declare it as
newline=''
.Now you can open the file in
'a'
mode (without the b).
import csv
with open(r'names.csv', 'a', newline='') as csvfile:
fieldnames = ['This','aNew']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'This':'is', 'aNew':'Row'})
I didn't try with the regular writer (without the Dict), but I think that it'll be ok too.
Try this:
foreach($samplearr as $key => $item){
print "<tr><td>"
. $key
. "</td><td>"
. $item['value1']
. "</td><td>"
. $item['value2']
. "</td></tr>";
}
I believe if you used the double
data type, the re-calculation in Excel would work just fine.
You should use let keyword as to declare local variables e.g *ngFor="let talk of talks"
If you wish to use jQuery CDN other than Google hosted jQuery library, you might consider using this and ensures uses the latest version of jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
I don't believe there is a direct supported way. However, if you are desparate, then under navigation options, select to show system objects. Then in your table list, system tables will appear. Two tables are of interest here: MSysIMEXspecs and MSysIMEXColumns. You'll be able edit import and export information. Good luck!
The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.
Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way. Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET". However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.
Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.
Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource. It could respond with a session cookie which will be carried by the subsequent request for the image or link.
Yes. add a linked server entry, and use select into using the four part db object naming convention.
Example:
SELECT * INTO targetTable
FROM [sourceserver].[sourcedatabase].[dbo].[sourceTable]
You can use the AND or OR operators, depending on what you want the search to return.
SELECT title FROM pages WHERE my_col LIKE %$param1% AND another_col LIKE %$param2%;
Both clauses have to match for a record to be returned. Alternatively:
SELECT title FROM pages WHERE my_col LIKE %$param1% OR another_col LIKE %$param2%;
If either clause matches then the record will be returned.
For more about what you can do with MySQL SELECT queries, try the documentation.
This is not answering the question itself, but I found this question searching for the solution to convert a string to symbol and use it on a hash.
hsh = Hash.new
str_to_symbol = "Book Author Title".downcase.gsub(/\s+/, "_").to_sym
hsh[str_to_symbol] = 10
p hsh
# => {book_author_title: 10}
Hope it helps someone like me!
The answer about going under "Other Users" was close, but not nearly explicit enough, so I felt the need to add this answer, below.
In Oracle, it will only show you tables that belong to schemas (databases in MS SQL Server) that are owned by the account you are logged in with. If the account owns/has created nothing, you will see nothing, even if you have rights/permissions to everything in the database! (This is contrary to MS SQL Server Management Studio, where you can see anything you have rights on and the owner is always "dbo", barring some admin going in and changing it for some unforeseeable reason.)
The owner will be the only one who will see those tables under "Tables" in the tree. If you do not see them because you are not their owner, you will have to go under "Other Users" and expand each user until you find out who created/owns that schema, if you do not know it, already. It will not matter if your account has permissions to the tables or not, you still have to go under "Other Users" and find that user that owns it to see it, under "Tables"!
One thing that can help you: when you write queries, you actually specify in the nomenclature who that owner is, ex.
Select * from admin.mytable
indicates that "admin" is the user that owns it, so you go under "Other Users > Admin" and expand "Tables" and there it is.
In addition to pattern matching with 'like' keyword. You can also perform search by using fulltext feature as below;
SELECT * FROM clients WHERE MATCH (shipping_name, billing_name, email) AGAINST ('mary')
To see non-staged (non-added) changes to existing files
git diff
Note that this does not track new files. To see staged, non-commited changes
git diff --cached
This is because, in the constructor, you declared a local variable with the same name as an attribute.
To allocate an integer array which all elements are initialized to zero, write this in the constructor:
data = new int[3];
To allocate an integer array which has other initial values, put this code in the constructor:
int[] temp = {2, 3, 7};
data = temp;
or:
data = new int[] {2, 3, 7};
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.
Thus, try the following:
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except ValueError: # includes simplejson.decoder.JSONDecodeError
print 'Decoding JSON has failed'
EDIT: Since simplejson.decoder.JSONDecodeError
actually inherits from ValueError
(proof here), I simplified the catch statement by just using ValueError
.
My understanding of SQLiteDatabase APIs is that in case you have a multi threaded application, you cannot afford to have more than a 1 SQLiteDatabase object pointing to a single database.
The object definitely can be created but the inserts/updates fail if different threads/processes (too) start using different SQLiteDatabase objects (like how we use in JDBC Connection).
The only solution here is to stick with 1 SQLiteDatabase objects and whenever a startTransaction() is used in more than 1 thread, Android manages the locking across different threads and allows only 1 thread at a time to have exclusive update access.
Also you can do "Reads" from the database and use the same SQLiteDatabase object in a different thread (while another thread writes) and there would never be database corruption i.e "read thread" wouldn't read the data from the database till the "write thread" commits the data although both use the same SQLiteDatabase object.
This is different from how connection object is in JDBC where if you pass around (use the same) the connection object between read and write threads then we would likely be printing uncommitted data too.
In my enterprise application, I try to use conditional checks so that the UI Thread never have to wait, while the BG thread holds the SQLiteDatabase object (exclusively). I try to predict UI Actions and defer BG thread from running for 'x' seconds. Also one can maintain PriorityQueue to manage handing out SQLiteDatabase Connection objects so that the UI Thread gets it first.
add
compile 'com.mcxiaoke.volley:library:1.0.19'
compile project('volley')
in the dependencies, under build.gradle file of your app
DO NOT DISTURB THE build.gradle FILE OF YOUR LIBRARY. IT'S YOUR APP'S GRADLE FILE ONLY YOU NEED TO ALTER
With the latest version of dotnet cli (2.1.400 or greater), you can just set this msbuild property $(EnvironmentName)
and publish tooling will take care of adding ASPNETCORE_ENVIRONMENT to the web.config with the environment name.
Also, XDT support is available starting 2.2.100-preview1.
Sample: https://github.com/vijayrkn/webconfigtransform/blob/master/README.md
You can also have this
name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)
Each link has five different states: link
, hover
, active
, focus
and visited
.
Link
is the normal appearance, hover
is when you mouse over, active
is the state when it's clicked, focus
follows active and visited
is the state you end up when you unfocus the recently clicked link.
I'm guessing you want to achieve a different style on either focus
or visited
, then you can add the following CSS:
a { color: #00c; }
a:visited { #ccc; }
a:focus { #cc0; }
A recommended order in your CSS to not cause any trouble is the following:
a
a:visited { ... }
a:focus { ... }
a:hover { ... }
a:active { ... }
You can use your web browser's developer tools to force the states of the element like this (Chrome->Developer Tools/Inspect Element->Style->Filter :hov): Force state in Chrome Developer Tools
Here's a solution which requires you to provide an object with the values. If you don't provide an object as parameter, it will default to using global variables. But better stick to using the parameter, it's much cleaner.
String.prototype.interpolate = function(props) {_x000D_
return this.replace(/\{(\w+)\}/g, function(match, expr) {_x000D_
return (props || window)[expr];_x000D_
});_x000D_
};_x000D_
_x000D_
// Test:_x000D_
_x000D_
// Using the parameter (advised approach)_x000D_
document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 });_x000D_
_x000D_
// Using the global scope_x000D_
var eruption2 = 116;_x000D_
document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate();
_x000D_
<div id="resultA"></div><div id="resultB"></div>
_x000D_
You can set the System.out print stream via setOut() (and for in
and err
). Can you redirect this to a print stream that records to a string, and then inspect that ? That would appear to be the simplest mechanism.
(I would advocate, at some stage, convert the app to some logging framework - but I suspect you already are aware of this!)
I don't have enough reputation to comment on answers but wanted to note that the Google Chart API has been deprecated.
From the API homepage:
The Infographics portion of Google Chart Tools has been officially deprecated as of April 20, 2012.
I have used this in quick and dirty situations:
// react render method:
render() {
return (
<div>
{ this.props.textOrHtml.indexOf('</') !== -1
? (
<div dangerouslySetInnerHTML={{__html: this.props.textOrHtml.replace(/(<? *script)/gi, 'illegalscript')}} >
</div>
)
: this.props.textOrHtml
}
</div>
)
}
MarginTop
should be marginTop
.
As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.
var mockFileBrowser = new Mock<FileBrowser>();
instead of
var mockFileBrowser = new Mock<IFileBrowser>();
Here is an option I have not seen so far:
Just add the column you want to restrict on to the view:
create view emp_v as (
select emp_name, emp_id from emp;
)
select emp_v.emp_name from emp_v
where emp_v.emp_id = (id to restrict by)
This error can occur even if the name of the function is valid if some mandatory arguments are missing (i.e you did not provide enough arguments).
I got this in an Rcpp context, where I wrote a C++ function with optionnal arguments, and did not provided those arguments in R. It appeared that optionnal arguments from the C++ were seen as mandatory by R. As a result, R could not find a matching function for the correct name but an incorrect number of arguments.
Rcpp Function : SEXP RcppFunction(arg1, arg2=0) {}
R Calls :
RcppFunction(0)
raises the error
RcppFunction(0, 0)
does not
In this code's thread creation, the address of a function pointer is being passed.
The original
pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0
It should read as
pthread_create(&some_thread, NULL, print_the_arguments, (void *) &args)
A good way to remember is that all of this function's arguments should be addresses.
some_thread
is declared statically, so the address is sent properly using &
.
I would create a pthread_attr_t
variable, then use pthread_attr_init()
on it and pass that variable's address. But, passing a NULL
pointer is valid as well.
The &
in front of the function label is what is causing the issue here. The label used is already a void*
to a function, so only the label is necessary.
To say != 0
with the final argument would seem to cause undetermined behavior. Adding this means that a boolean is being passed instead of a reference.
Akash Agrawal's answer is also part of the solution to this code's problem.
You can also do this easily with gitk.
> gitk branch1 branch2
First click on the tip of branch1. Now right-click on the tip of branch2 and select Diff this->selected.
Put this in a file called main.cpp:
#include <cstdlib>
#include <iostream>
#include "student.h"
using namespace std; //Watchout for clashes between std and other libraries
int main(int argc, char** argv) {
struct Student s1;
s1.firstName = "fred"; s1.lastName = "flintstone";
cout << s1.firstName << " " << s1.lastName << endl;
return 0;
}
put this in a file named student.h
#ifndef STUDENT_H
#define STUDENT_H
#include<string>
struct Student {
std::string lastName, firstName;
};
#endif
Compile it and run it, it should produce this output:
s1.firstName = "fred";
Protip:
You should not place a using namespace std;
directive in the C++ header file because you may cause silent name clashes between different libraries. To remedy this, use the fully qualified name: std::string foobarstring;
instead of including the std namespace with string foobarstring;
.
There is such a confusion on this question, as there is way too much complexity in this question. First MacOS vs. Win10. Then the different auth mechanisms.
I will start a consolidated answer here and probably need some help, if I do not get help, I will keep working on the answer until it is complete, but that will take time.
Windows 10: |
|-- Run this command. You will be prompted on next push/pull to enter username and password:
| git config --global credential.helper wincred (Thanks to @Andrew Pye)
` MacOS:
|
|-- Using git config to store username and password:
| git config --global --add user.password
|
|---- first time entry
| git config --global --add user.password <new_pass>
|
|---- password update
| git config --global --unset user.password
| git config --global --add user.password <new_pass>
|
|-- Using keychain:
| git config --global credential.helper osxkeychain
|
|---- first time entry
| Terminal will ask you for the username and password. Just enter it, it will be
| stored in keychain from then on.
|
|---- password update
| Open keychain, delete the entry for the repository you are trying to use.
| (git remote -v will show you)
| On next use of git push or something that needs permissions, git will ask for
| the credentials, as it can not find them in the keychain anymore.
`
using Microsoft.visualBasic;
public class test{
public void main(){
string randomString = "Random Word";
print (Strings.right(randomString,4));
}
}
output is "Word"
You might want to try one of the following ways:
createNativeQuery(sqlString, resultClass)
Native queries can also be defined dynamically using the EntityManager.createNativeQuery()
API.
String sql = "SELECT USER.* FROM USER_ AS USER WHERE ID = ?";
Query query = em.createNativeQuery(sql, User.class);
query.setParameter(1, id);
User user = (User) query.getSingleResult();
@NamedNativeQuery
Native queries are defined through the @NamedNativeQuery
and @NamedNativeQueries
annotations, or <named-native-query>
XML element.
@NamedNativeQuery(
name="complexQuery",
query="SELECT USER.* FROM USER_ AS USER WHERE ID = ?",
resultClass=User.class
)
public class User { ... }
Query query = em.createNamedQuery("complexQuery", User.class);
query.setParameter(1, id);
User user = (User) query.getSingleResult();
You can read more in the excellent open book Java Persistence (available in PDF).
-------
NOTE: With regard to use of getSingleResult()
, see Why you should never use getSingleResult()
in JPA.
I'll provide an answer here since the ones here didn't quite click for me.
Perl's bless function associates any reference to all functions inside a package.
Why would we need this?
Let's begin by expressing an example in JavaScript:
(() => {
'use strict';
class Animal {
constructor(args) {
this.name = args.name;
this.sound = args.sound;
}
}
/* [WRONG] (global scope corruption)
* var animal = Animal({
* 'name': 'Jeff',
* 'sound': 'bark'
* });
* console.log(animal.name + ', ' + animal.sound); // seems good
* console.log(window.name); // my window's name is Jeff?
*/
// new is important!
var animal = new Animal(
'name': 'Jeff',
'sound': 'bark'
);
console.log(animal.name + ', ' + animal.sound); // still fine.
console.log(window.name); // undefined
})();
Now lets strip away the class construct and make do without it:
(() => {
'use strict';
var Animal = function(args) {
this.name = args.name;
this.sound = args.sound;
return this; // implicit context hashmap
};
// the "new" causes the Animal to be unbound from global context, and
// rebinds it to an empty hash map before being constructed. The state is
// now bound to animal, not the global scope.
var animal = new Animal({
'name': 'Jeff',
'sound': 'bark'
});
console.log(animal.sound);
})();
The function takes a hash table of unordered properties(since it makes no sense to have to write properties in a specific order in dynamic languages in 2016) and returns a hash table with those properties, or if you forgot to put the new keyword, it will return the whole global context(eg window in browser or global in nodejs).
Perl has no "this" nor "new" nor "class", but it can still have a function that behaves similarly. We won't have a constructor nor a prototype, but we will be able to create new animals at will and modify their individual properties.
# self contained scope
(sub {
my $Animal = (sub {
return {
'name' => $_[0]{'name'},
'sound' => $_[0]{'sound'}
};
});
my $animal = $Animal->({
'name' => 'Jeff',
'sound' => 'bark'
});
print $animal->{sound};
})->();
Now, we have a problem: What if we want the animal to perform the sounds by themselves instead of us printing what their voice is. That is, we want a function performSound that prints the animal's own sound.
One way to do this is by teaching each individual Animal how to do it's sound. This means that each Cat has its own duplicate function to performSound.
# self contained scope
(sub {
my $Animal = (sub {
$name = $_[0]{'name'};
$sound = $_[0]{'sound'};
return {
'name' => $name,
'sound' => $sound,
'performSound' => sub {
print $sound . "\n";
}
};
});
my $animal = $Animal->({
'name' => 'Jeff',
'sound' => 'bark'
});
$animal->{'performSound'}();
})->();
This is bad because performSound is put as a completely new function object each time an animal is constructed. 10000 animals means 10000 performSounds. We want to have a single function performSound that is used by all animals that looks up their own sound and prints it.
(() => {
'use strict';
/* a function that creates an Animal constructor which can be used to create animals */
var Animal = (() => {
/* function is important, as fat arrow does not have "this" and will not be bound to Animal. */
var InnerAnimal = function(args) {
this.name = args.name;
this.sound = args.sound;
};
/* defined once and all animals use the same single function call */
InnerAnimal.prototype.performSound = function() {
console.log(this.name);
};
return InnerAnimal;
})();
/* we're gonna create an animal with arguments in different order
because we want to be edgy. */
var animal = new Animal({
'sound': 'bark',
'name': 'Jeff'
});
animal.performSound(); // Jeff
})();
Here is where the parallel to Perl kinda stops.
JavaScript's new operator is not optional, without it, "this" inside object methods corrupts global scope:
(() => {
// 'use strict'; // uncommenting this prevents corruption and raises an error instead.
var Person = function() {
this.name = "Sam";
};
// var wrong = Person(); // oops! we have overwritten window.name or global.main.
// console.log(window.name); // my window's name is Sam?
var correct = new Person; // person's name is actually stored in the person now.
})();
We want to have one function for each Animal that looks up that animal's own sound rather than hardcoding it at construction.
Blessing lets us use a package as the prototype of objects. This way, the object is aware of the "package" it is "referenced to", and in turn can have the functions in the package "reach into" the specific instances that were created from the constructor of that "package object":
package Animal;
sub new {
my $packageRef = $_[0];
my $name = $_[1]->{'name'};
my $sound = $_[1]->{'sound'};
my $this = {
'name' => $name,
'sound' => $sound
};
bless($this, $packageRef);
return $this;
}
# all animals use the same performSound to look up their sound.
sub performSound {
my $this = shift;
my $sound = $this->{'sound'};
print $sound . "\n";
}
package main;
my $animal = Animal->new({
'name' => 'Cat',
'sound' => 'meow'
});
$animal->performSound();
Summary/TL;DR:
Perl has no "this", "class", nor "new". blessing an object to a package gives that object a reference to the package, and when it calls functions in the package, their arguments will be offset by 1 slot, and the first argument($_[0] or shift) will be equivalent to javascript's "this". In turn, you can somewhat simulate JavaScript's prototype model.
Unfortunately it makes it impossible(to my understanding) to create "new classes" at runtime, as you need each "class" to have its own package, whereas in javascript, you don't need packages at all, as "new" keyword makes up an anonymous hashmap for you to use as a package at runtime to which you can add new functions and remove functions on the fly.
There are some Perl libraries creating their own ways of bridging this limitation in expressiveness, such as Moose.
Why the confusion?:
Because of packages. Our intuition tells us to bind the object to a hashmap containing its' prototype. This lets us create "packages" at runtime like JavaScript can. Perl does not have such flexibility(at least not built in, you have to invent it or get it from other modules), and in turn your runtime expressiveness is hindered. Calling it "bless" doesn't do it much favors neither.
What we want to do:
Something like this, but have binding to the prototype map recursive, and be implicitly bound to the prototype rather than having to explicitly do it.
Here is a naive attempt at it: the issue is that "call" does not know "what called it", so it may as well be a universal perl function "objectInvokeMethod(object, method)" which checks whether the object has the method, or its prototype has it, or its prototype has it, until it reaches the end and finds it or not (prototypical inheritence). Perl has nice eval magic to do it but I'll leave that for something I can try doing later.
Anyway here is the idea:
(sub {
my $Animal = (sub {
my $AnimalPrototype = {
'performSound' => sub {
return $_[0]->{'sound'};
}
};
my $call = sub {
my $this = $_[0];
my $proc = $_[1];
if (exists $this->{$proc}) {
return $this->{$proc}->();
} else {
return $this->{prototype}->{$proc}->($this, $proc);
}
};
return sub {
my $name = $_[0]->{name};
my $sound = $_[0]->{sound};
my $this = {
'this' => $this,
'name' => $name,
'sound' => $sound,
'prototype' => $AnimalPrototype,
'call' => $call
};
};
})->();
my $animal = $Animal->({
'name' => 'Jeff',
'sound'=> 'bark'
});
print($animal->{call}($animal, 'performSound'));
})->();
Anyway hopefully somebody will find this post useful.
In my case problem was in using PowerShell instead of CMD :)
According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO
option or a certificate directory can be specified with the CURLOPT_CAPATH
option.
Also look at CURLOPT_SSL_VERIFYHOST:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
Individual components of a filename (i.e. each subdirectory along the path, and the final filename) are limited to 255 characters, and the total path length is limited to approximately 32,000 characters.
However, on Windows, you can't exceed MAX_PATH
value (259 characters for files, 248 for folders). See http://msdn.microsoft.com/en-us/library/aa365247.aspx for full details.
So.. I was also looking into this matter and saw that most of the answers here are asking to fade the container element, not the actual background-image. Then a hack crossed my mind. We can give multiple background right? what if we overlay other color and make it transparent, like code below-
background: url("//unsplash.it/500/400") rgb(255, 255, 255, 0.5) no-repeat center;
This code actually works stand alone. Try it. We gave a bg image and asked other white color with transparency on top of the image and Voila. TIP- we can give different colors and transparencies to get different filter kind of effect.
You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink
Assuming you have foo.conf in sites-available
Try
cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l
Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf
Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.
If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.
ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf
Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:
lrwxrwxrwx 1 root root 26 Jun 24 21:06 000-default -> ../sites-available/default
See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).
Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.
I think we are missing an explanation of how these type conversions work.
char
is platform dependent signed
or unsigned
. In x86 char
is equivalent to signed char
.
When an integral type (char
, short
, int
, long
) is converted to a larger capacity type, the conversion is made by adding zeros to the left in case of unsigned
types and by sign extension for signed
ones. Sign extension consists in replicating the most significant (leftmost) bit of the original number to the left till we reach the bit size of the target type.
Hence if I am in a signed char
by default system and I do this:
char a = 0xF0; // Equivalent to the binary: 11110000
std::cout << std::hex << static_cast<int>(a);
We would obtain F...F0
since the leading 1
bit has been extended.
If we want to make sure that we only print F0
in any system we would have to make an additional intermediate type cast to an unsigned char
so that zeros are added instead and, since they are not significant for a integer with only 8-bits, not printed:
char a = 0xF0; // Equivalent to the binary: 11110000
std::cout << std::hex << static_cast<int>(static_cast<unsigned char>(a));
This produces F0
You can use WScript.ScriptFullName which will return the full path of the executing script.
You can then use string manipulation (jscript example) :
scriptdir = WScript.ScriptFullName.substring(0,WScript.ScriptFullName.lastIndexOf(WScript.ScriptName)-1)
Or get help from FileSystemObject, (vbscript example) :
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
I use this:
//http://detectmobilebrowsers.com/ + tablets
(function(a) {
if(/android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(ad|hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|playbook|silk/i.test(a)
||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))
{
window.location="yourNewIndex.html"
}
})(navigator.userAgent||navigator.vendor||window.opera);
you may try like this using jquery
var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];
var uniqueVals = [];
$.each(arr, function(i, el){
if($.inArray(el, uniqueVals) === -1) uniqueVals.push(el);
});
Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date()
is DateTime::format
.
An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.
You'll want to store in the database as UTC and convert on the application level.
try with this
$ cat /tmp/topfs.txt
/dev/sda2 xfs 32G 10G 22G 32% /
awk print last column
$ cat /tmp/topfs.txt | awk '{print $NF}'
awk print before last column
$ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
32%
awk - print last two columns
$ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
32% /
I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path
But the main issue was not here. The problem was with these 2 lines of code
strFile = Dir(strPath & "*.csv")
Which should have written as
strFile = Dir(strPath & "\*.csv")
and
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Which should have written as
With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _
Another way is to write
@user.route('/<user_id>', defaults={'username': None})
@user.route('/<user_id>/<username>')
def show(user_id, username):
pass
But I guess that you want to write a single route and mark username
as optional? If that's the case, I don't think it's possible.
In the case where you have multiple variables containing the arguments for a command you're running, and not just a single string, you should not use eval directly, as it will fail in the following case:
function echo_arguments() {
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Argument 3: $3"
echo "Argument 4: $4"
}
# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"
Result:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg
Note that even though "Some arg" was passed as a single argument, eval
read it as two.
Instead, you can just use the string as the command itself:
# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {
"$@";
}
Note the difference between the output of eval
and the new eval_command
function:
eval_command echo_arguments arg1 arg2 "Some arg"
Result:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:
Simple and Complete Solution working for me. Supports ASP.NET MVC 4 and 5 (Supports ASP.NET 4.0, 4.5, and 4.5.1)
Step 1: Install NuGet Package by "Install-Package reCAPTCH.MVC"
Step 2: Add your Public and Private key to your web.config file in appsettings section
<appSettings>
<add key="ReCaptchaPrivateKey" value=" -- PRIVATE_KEY -- " />
<add key="ReCaptchaPublicKey" value=" -- PUBLIC KEY -- " />
</appSettings>
You can create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page
Step 3: Modify your form to include reCaptcha
@using reCAPTCHA.MVC
@using (Html.BeginForm())
{
@Html.Recaptcha()
@Html.ValidationMessage("ReCaptcha")
<input type="submit" value="Register" />
}
Step 4: Implement the Controller Action that will handle the form submission and Captcha validation
[CaptchaValidator(
PrivateKey = "your private reCaptcha Google Key",
ErrorMessage = "Invalid input captcha.",
RequiredMessage = "The captcha field is required.")]
public ActionResult MyAction(myVM model)
{
if (ModelState.IsValid) //this will take care of captcha
{
}
}
OR
public ActionResult MyAction(myVM model, bool captchaValid)
{
if (captchaValid) //manually check for captchaValid
{
}
}
Simply add the following rules to your td
:
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
// These ones do the trick
width: 100%;
max-width: 0;
Example:
table {_x000D_
width: 100%_x000D_
}_x000D_
_x000D_
td {_x000D_
white-space: nowrap;_x000D_
}_x000D_
_x000D_
.td-truncate {_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
width: 100%;_x000D_
max-width: 0;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>content</td>_x000D_
<td class="td-truncate">long contenttttttt ttttttttt ttttttttttttttttttttttt tttttttttttttttttttttt ttt tttt ttttt ttttttt tttttttttttt ttttttttttttttttttttttttt</td>_x000D_
<td>other content</td>_x000D_
</tr>_x000D_
</table>
_x000D_
PS:
If you want to set a custom width to another td
use property min-width
.
JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.
Now you can:
case L ->
):
The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.
To yield a value from a switch expression, the
break
with value statement is dropped in favor of ayield
statement.
Switch expression example:
public class SwitchExpression {
public static void main(String[] args) {
int month = 9;
int year = 2018;
int numDays = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> {
if (java.time.Year.of(year).isLeap()) {
System.out.println("Wow! It's leap year!");
yield 29;
} else {
yield 28;
}
}
default -> {
System.out.println("Invalid month.");
yield 0;
}
};
System.out.println("Number of Days = " + numDays);
}
}
If you want to select a value based on true / false use
[selected]="opt.selected == true"
<option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>
checkit out
To encode mp3 audio ffmpeg.org shows the following example:
ffmpeg -i input.wav -codec:a libmp3lame -qscale:a 2 output.mp3
I extracted the audio from a video just by replacing input.wav
with the video filename. The 2
means 190 kb/sec. You can see the other quality levels at my link above.
Swift only solution
Similar to Luca's anwer, I use a UIView
extension. Compared to his solution I use DispatchQueue.main.async
to make sure animations are done on the main thread, alpha
parameter for fading to a specific value and optional duration
parameters for cleaner code.
extension UIView {
func fadeTo(_ alpha: CGFloat, duration: TimeInterval = 0.3) {
DispatchQueue.main.async {
UIView.animate(withDuration: duration) {
self.alpha = alpha
}
}
}
func fadeIn(_ duration: TimeInterval = 0.3) {
fadeTo(1.0, duration: duration)
}
func fadeOut(_ duration: TimeInterval = 0.3) {
fadeTo(0.0, duration: duration)
}
}
How to use it:
// fadeIn() - always animates to alpha = 1.0
yourView.fadeIn() // uses default duration of 0.3
yourView.fadeIn(1.0) // uses custom duration (1.0 in this example)
// fadeOut() - always animates to alpha = 0.0
yourView.fadeOut() // uses default duration of 0.3
yourView.fadeOut(1.0) // uses custom duration (1.0 in this example)
// fadeTo() - used if you want a custom alpha value
yourView.fadeTo(0.5) // uses default duration of 0.3
yourView.fadeTo(0.5, duration: 1.0)
You have to define your jdk folder in variable JAVA_HOME, add %JAVA_HOME% to your variable path
Delete or change name of your java.exe, javaw.exe and javaws in your folder system32
execute cmd.exe, java -version now take the new version that you define in JAVA_HOME.
Your command is completely incorrect. The output format is not rawvideo
and you don't need the bitstream filter h264_mp4toannexb
which is used when you want to convert the h264
contained in an mp4
to the Annex B
format used by MPEG-TS
for example. What you want to use instead is the aac_adtstoasc
for the AAC
streams.
ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4
if (element.nodeName == "A") {
...
} else if (element.nodeName == "TD") {
...
}
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
Method 1 :
var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true
Method 2 :
var stringValue = "true";
var boolValue = (stringValue =="true"); //returns true
Method 3 :
var stringValue = "true";
var boolValue = JSON.parse(stringValue); //returns true
Method 4 :
var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; //returns true
Method 5 :
var stringValue = "true";
var boolValue = getBoolean(stringValue); //returns true
function getBoolean(value){
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
source: http://codippa.com/how-to-convert-string-to-boolean-javascript/
it was my problem too .. in my case i changed the PERSIAN number to LATIN number and it worked. AND also trime your string before converting.
PersianCalendar pc = new PersianCalendar();
char[] seperator ={'/'};
string[] date = txtSaleDate.Text.Split(seperator);
int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());
// Get unique value for table 'add_new_videos' column name 'project_id'
$project_id = DB::table('add_new_videos')->distinct()->get(['project_id']);
You can pass the event as argument to the function and then prevent the default behaviour.
var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(event){
event.preventDefault();
alert('it works!');
}
return <form onSubmit={this.doSomething}>
<button>Click me</button>
</form>;
}
});
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'attrs.dynamic' , function(html){
element.html(scope.dynamic);
$compile(element.contents())(scope);
});
}
};
});
Try this element.html(scope.dynamic); than element.html(attr.dynamic);
The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)
QObject(self.pb, SIGNAL("clicked()"), self.button_clicked) def button_clicked(self): self.le.setText("shost")
I think this is what you want. I hope i got your question correctly :)
The line starting ALREADYEXISTS
uses ’
as the closing quote, it should be using '
. The open quote on the next line (where the error is reported) is seen as the closing quote, and this mix up is causing the error.
Only 3 commands will make it work
git fetch origin
git reset --hard origin/HEAD
git clean -f
Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as
This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer
I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation
dependency with NSJSONSerialization
as Rob's comment with 15 upvotes suggests.
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:@"question"];
The variable can be declared in the .js
file and simply referenced in the HTML file.
My version of helpers.js
:
var myFunctionWasCalled = false;
function doFoo()
{
if (!myFunctionWasCalled) {
alert("doFoo called for the very first time!");
myFunctionWasCalled = true;
}
else {
alert("doFoo called again");
}
}
And a page to test it:
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>
<body>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
<script type="text/javascript">doFoo();</script>
<p>Some stuff in between</p>
<script type="text/javascript">doFoo();</script>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
</body>
</html>
You'll see the test alert()
will display two different things, and the value written to the page will be different the second time.
I find it useful to understand the underlying tools. These are cl.exe (compiler) and link.exe (linker). You need to tell the compiler the signatures of the functions you want to call in the dynamic library (by including the library's header) and you need to tell the linker what the library is called and how to call it (by including the "implib" or import library).
This is roughly the same process gcc uses for linking to dynamic libraries on *nix, only the library object file differs.
Knowing the underlying tools means you can more quickly find the appropriate settings in the IDE and allows you to check that the commandlines generated are correct.
Say A.exe depends B.dll. You need to include B's header in A.cpp (#include "B.h"
) then compile and link with B.lib:
cl A.cpp /c /EHsc
link A.obj B.lib
The first line generates A.obj, the second generates A.exe. The /c
flag tells cl not to link and /EHsc
specifies what kind of C++ exception handling the binary should use (there's no default, so you have to specify something).
If you don't specify /c
cl will call link
for you. You can use the /link
flag to specify additional arguments to link
and do it all at once if you like:
cl A.cpp /EHsc /link B.lib
If B.lib is not on the INCLUDE
path you can give a relative or absolute path to it or add its parent directory to your include path with the /I
flag.
If you're calling from cygwin (as I do) replace the forward slashes with dashes.
If you write #pragma comment(lib, "B.lib")
in A.cpp you're just telling the compiler to leave a comment in A.obj telling the linker to link to B.lib. It's equivalent to specifying B.lib on the link commandline.
Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec
Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec
, as I have ~/bin
in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...
Launch it from the root of your project, where you can see src and target dirs.
The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)
$ mvnexec
1) org.jmeld.ui.JMeldComponent
2) org.jmeld.ui.text.FileDocument
3) org.jmeld.JMeld
4) org.jmeld.util.UIDefaultsPrint
5) org.jmeld.util.PrintProperties
6) org.jmeld.util.file.DirectoryDiff
7) org.jmeld.util.file.VersionControlDiff
8) org.jmeld.vc.svn.InfoCmd
9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#?
If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P
)
By default it compiles project every run. but you can avoid that using mvnexec -B
It allows to search only in test classes -M
or --no-main
, or only in main classes -T
or --no-test
. also has a filter by name option -f <whatever>
Hope this could save you some time, for me it does.
Here's another, perhaps more familiar-looking way to do it:
for i in (0..10).step(2) do
puts i
end
Another way to do is is to use file_get_contents() and have a template HTML page
TEMPLATE PAGE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>$title</title></head>
<body>$content</body>
</html>
PHP Function
function YOURFUNCTIONNAME($url){
$html_string = file_get_contents($url);
return $html_string;
}
FOR UNINSTALLING AND THEN BEING ABLE TO REINSTALL XCODE 9 CORRECTLY
I followed the topmost answer for deleting Xcode 7 and found a major error, deleting ~/Library/Developer
will delete an important folder called PrivateFrameworks
, which will actually crash Xcode everytime you reinstall and force you to have to get your friends to send you the PrivateFrameworks folder again, a complete waste of time seeing if you needed to uninstall and reinstall Xcode urgently for immediate work purposes.
I have tried editing the topmost answer but see no changes so below is the modified steps you should take for Xcode 9:
Delete
/Applications/Xcode.app
~/Library/Preferences/com.apple.dt.*
(Generally anything with com.apple.dt. as prefix is removable in the Preferences folder)
~/Library/Caches/com.apple.dt.Xcode
~/Library/Application Support/Xcode
Everything in
/Library/Developer
directory except for
/Library/Developer/PrivateFrameworks
This worked for me.
sed -e 's/\s\+/,/g' input.txt >> output.csv
I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example: http://jsfiddle.net/p9dey/1/
First of all, two things that we need to understand,
bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
here mServiceConn
is instance of ServiceConnection
class(inbuilt) it is actually interface
that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.
IBinder
Object. So, IBinder
object is our handler which accesses all the methods of Service
by using (.) operator. .
MyService myService;
public ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.d("ServiceConnection","connected");
myService = binder;
}
//binder comes from server to communicate with method's of
public void onServiceDisconnected(ComponentName className) {
Log.d("ServiceConnection","disconnected");
myService = null;
}
}
myservice.serviceMethod();
Here myService
is object and serviceMethod is method in service.
and by this way communication is established between client and server.
Toastr is a very nice component, and you can show messages with theses commands:
// for success - green box
toastr.success('Success messages');
// for errors - red box
toastr.error('errors messages');
// for warning - orange box
toastr.warning('warning messages');
// for info - blue box
toastr.info('info messages');
If you want to provide a title on the toastr message, just add a second argument:
// for info - blue box
toastr.success('The process has been saved.', 'Success');
you also can change the default behaviour using something like this:
toastr.options.timeOut = 3000; // 3s
See more on the github of the project.
A sample of use:
$(document).ready(function() {
// show when page load
toastr.info('Page Loaded!');
$('#linkButton').click(function() {
// show when the button is clicked
toastr.success('Click Button');
});
});
and a html:
<a id='linkButton'>Show Message</a>
To insert a CR into XML, you need to use its character entity
.
This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
This is because, the amount of memory you wish to assign for JVM is not available or may be you are assigning more than available memory. Try small size then u can see the difference.
Try:
set JAVA_OPTS=-Xms128m -Xmx512m -XX:PermSize=128m
When it says JDK not found, just press ‘back’ button and then press again ‘next’ button..
I got this from the bottom of this post: http://codearetoy.wordpress.com/2010/12/23/jdk-not-found-on-installing-android-sdk/
Use Observable pattern. You can put Observable value (not Subject) into Input parameter and manage it from parent component. You do not need callback function.
See example: https://stackoverflow.com/a/49662611/4604351
I think this is the easiest and shortest solution to running a batch file without opening the DOS window, it can be very distracting when you want to schedule a set of commands to run periodically, so the DOS window keeps popping up, here is your solution. Use a VBS Script to call the batch file ...
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run chr(34) & "C:\Batch Files\ mycommands.bat" & Chr(34), 0
Set WshShell = Nothing
Copy the lines above to an editor and save the file with .VBS extension. Edit the .BAT file name and path accordingly.
If you are using numpy, printing a single (or multiply) strings to a file can be done with just one line:
numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')
''.join(sequenceofstrings)
is what usually works best -- simplest and fastest.
find /abs/path/ -name '*.js'
Edit: As Brian points out, add -type f
if you want only plain files, and not directories, links, etc.
You can also use
CREATE PROCEDURE [Search](
@Filter nvarchar(max)
)
AS
BEGIN
SELECT name
FROM procedures
WHERE definition LIKE '%'+@Filter+'%'
END
and then run
exec [Search] 'text'
pod outdated
When you run pod outdated, CocoaPods will list all pods that have newer versions that the ones listed in the Podfile.lock (the versions currently installed for each pod) and that could be updated (as long as it matches the restrictions like pod 'MyPod', '~>x.y' set in your Podfile)
You just need to pass --recursive & --include "*"
aws --region "${BUCKET_REGION}" s3 cp s3://${BUCKET}${BUCKET_PATH}/ ${LOCAL_PATH}/tmp --recursive --include "*" 2>&1
Using aiopg - The snippet below works perfectly fine
# items = [10, 11, 12, 13]
# group = 1
tup = [(gid, pid) for pid in items]
args_str = ",".join([str(s) for s in tup])
# insert into group values (1, 10), (1, 11), (1, 12), (1, 13)
yield from cur.execute("INSERT INTO group VALUES " + args_str)
Collection is the main interface of Java Collections hierarchy and List(Sequence) is one of the sub interfaces that defines an ordered collection.
When you're doing it by code the trick is to call
WindowStyle = WindowStyle.None;
first and then
WindowState = WindowState.Maximized;
to get it to display over the Taskbar.
If you don't care about any local changes (including untracked or generated files or subrepositories which just happen to be here) and just want a copy from the repo:
git reset --hard HEAD
git clean -xffd
git pull
Again, this will nuke any changes you've made locally so use carefully. Think about rm -Rf
when doing this.
Inspired by VB.Net Generics List(Of Integer), I created my own module for that. Maybe you find it useful, too or you'd like to extend for additional methods e.g. to remove items again:
'Save module with name: ListOfInteger
Public Function ListLength(list() As Integer) As Integer
On Error Resume Next
ListLength = UBound(list) + 1
On Error GoTo 0
End Function
Public Sub ListAdd(list() As Integer, newValue As Integer)
ReDim Preserve list(ListLength(list))
list(UBound(list)) = newValue
End Sub
Public Function ListContains(list() As Integer, value As Integer) As Boolean
ListContains = False
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
If list(MyCounter) = value Then
ListContains = True
Exit For
End If
Next
End Function
Public Sub DebugOutputList(list() As Integer)
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
Debug.Print list(MyCounter)
Next
End Sub
You might use it as follows in your code:
Public Sub IntegerListDemo_RowsOfAllSelectedCells()
Dim rows() As Integer
Set SelectedCellRange = Excel.Selection
For Each MyCell In SelectedCellRange
If IsEmpty(MyCell.value) = False Then
If ListOfInteger.ListContains(rows, MyCell.Row) = False Then
ListAdd rows, MyCell.Row
End If
End If
Next
ListOfInteger.DebugOutputList rows
End Sub
If you need another list type, just copy the module, save it at e.g. ListOfLong and replace all types Integer by Long. That's it :-)
You can make this method static.
public static void startChronometer(){
mChronometer.start();
showElapsedTime();
}
you can call this function in other class as below:
MainActivity.startChronometer();
OR
You can make an object of the main class in second class like,
MainActivity mActivity = new MainActivity();
mActivity.startChronometer();
In order to view only first few entries you can use, pandas head function which is used as
dataframe.head(any number) // default is 5
dataframe.head(n=value)
or you can also you slicing for this purpose, which can also give the same result,
dataframe[:n]
In order to view the last few entries you can use pandas tail() in a similar way,
dataframe.tail(any number) // default is 5
dataframe.tail(n=value)
For windows users:
To download into a file open your cmd and folow this:
cd <*the file-path where you want to save it*>
pip download <*package name*>
the package and the dependencies will be downloaded in the current working directory.
To install from the current working directory:
set your folder where you downloaded as the cwd then follow these:
pip install <*the package name which is downloded as .whl*> --no-index --find-links <*the file locaation where the files are downloaded*>
this will search for dependencies in that location.
function printCrossword(printContainer) {
var DocumentContainer = getElement(printContainer);
var WindowObject = window.open('', "PrintWindow", "width=5,height=5,top=200,left=200,toolbars=no,scrollbars=no,status=no,resizable=no");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
I think that CONTAINS
took longer and used Merge
because you had a dash("-") in your query adventure-works.com
.
The dash is a break word so the CONTAINS
searched the full-text index for adventure
and than it searched for works.com
and merged the results.
Use -B, -A or -C option
grep --help
...
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
...
Latest swift3 this code is simply to convert string to int
let myString = "556"
let myInt = Int(myString)
Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.
To explain the differences as relevant to your posted example:
a. When you use RegisterStartupScript
, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.
Here is the rendered source of the page when you invoke the RegisterStartupScript
method:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<div> <span id="lblDisplayDate">Label</span>
<br />
<input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
<br />
<input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
</div>
<!-- Note this part -->
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
lbl.style.color = 'red';
</script>
</form>
<!-- Note this part -->
</body>
</html>
b. When you use RegisterClientScriptBlock
, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.
Here is the rendered source of the page when you invoke the RegisterClientScriptBlock
method:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
// Error is thrown in the next line because lbl is null.
lbl.style.color = 'green';
Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).
Edit after comments:
For instance, the following function would work:
protected void btnPostBack2_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>function ChangeColor() {");
sb.Append("var lbl = document.getElementById('lblDisplayDate');");
sb.Append("lbl.style.color='green';");
sb.Append("}</script>");
//Render the function definition.
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
}
//Render the function invocation.
string funcCall = "<script language='javascript'>ChangeColor();</script>";
if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
}
}
You can try this too:
public class Match
{
[Key]
public int MatchId { get; set; }
[ForeignKey("HomeTeam"), Column(Order = 0)]
public int? HomeTeamId { get; set; }
[ForeignKey("GuestTeam"), Column(Order = 1)]
public int? GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
When you make a FK column allow NULLS, you are breaking the cycle. Or we are just cheating the EF schema generator.
In my case, this simple modification solve the problem.
The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name).
A markup language is a way of adding extra information to free-flowing plain text, e.g
Here is some text.
With XML (using a certain element vocabulary) you can put:
<Document>
<Paragraph Align="Center">
Here <Bold>is</Bold> some text.
</Paragraph>
</Document>
This is what makes markup languages so useful for representing documents.
An object notation like JSON is not as flexible. But this is usually a good thing. When you're representing objects, you simply don't need the extra flexibility. To represent the above example in JSON, you'd actually have to solve some problems manually that XML solves for you.
{
"Paragraphs": [
{
"align": "center",
"content": [
"Here ", {
"style" : "bold",
"content": [ "is" ]
},
" some text."
]
}
]
}
It's not as nice as the XML, and the reason is that we're trying to do markup with an object notation. So we have to invent a way to scatter snippets of plain text around our objects, using "content" arrays that can hold a mixture of strings and nested objects.
On the other hand, if you have typical a hierarchy of objects and you want to represent them in a stream, JSON is better suited to this task than HTML.
{
"firstName": "Homer",
"lastName": "Simpson",
"relatives": [ "Grandpa", "Marge", "The Boy", "Lisa", "I think that's all of them" ]
}
Here's the logically equivalent XML:
<Person>
<FirstName>Homer</FirstName>
<LastName>Simpsons</LastName>
<Relatives>
<Relative>Grandpa</Relative>
<Relative>Marge</Relative>
<Relative>The Boy</Relative>
<Relative>Lisa</Relative>
<Relative>I think that's all of them</Relative>
</Relatives>
</Person>
JSON looks more like the data structures we declare in programming languages. Also it has less redundant repetition of names.
But most importantly of all, it has a defined way of distinguishing between a "record" (items unordered, identified by names) and a "list" (items ordered, identified by position). An object notation is practically useless without such a distinction. And XML has no such distinction! In my XML example <Person>
is a record and <Relatives>
is a list, but they are not identified as such by the syntax.
Instead, XML has "elements" versus "attributes". This looks like the same kind of distinction, but it's not, because attributes can only have string values. They cannot be nested objects. So I couldn't have applied this idea to <Person>
, because I shouldn't have to turn <Relatives>
into a single string.
By using an external schema, or extra user-defined attributes, you can formalise a distinction between lists and records in XML. The advantage of JSON is that the low-level syntax has that distinction built into it, so it's very succinct and universal. This means that JSON is more "self describing" by default, which is an important goal of both formats.
So JSON should be the first choice for object notation, where XML's sweet spot is document markup.
Unfortunately for XML, we already have HTML as the world's number one rich text markup language. An attempt was made to reformulate HTML in terms of XML, but there isn't much advantage in this.
So XML should (in my opinion) have been a pretty limited niche technology, best suited only for inventing your own rich text markup languages if you don't want to use HTML for some reason. The problem was that in 1998 there was still a lot of hype about the Web, and XML became popular due to its superficial resemblance to HTML. It was a strange design choice to try to apply to hierarchical data a syntax actually designed for convenient markup.
This is the solution that I use.
function Enum() {
this._enums = [];
this._lookups = {};
}
Enum.prototype.getEnums = function() {
return _enums;
}
Enum.prototype.forEach = function(callback){
var length = this._enums.length;
for (var i = 0; i < length; ++i){
callback(this._enums[i]);
}
}
Enum.prototype.addEnum = function(e) {
this._enums.push(e);
}
Enum.prototype.getByName = function(name) {
return this[name];
}
Enum.prototype.getByValue = function(field, value) {
var lookup = this._lookups[field];
if(lookup) {
return lookup[value];
} else {
this._lookups[field] = ( lookup = {});
var k = this._enums.length - 1;
for(; k >= 0; --k) {
var m = this._enums[k];
var j = m[field];
lookup[j] = m;
if(j == value) {
return m;
}
}
}
return null;
}
function defineEnum(definition) {
var k;
var e = new Enum();
for(k in definition) {
var j = definition[k];
e[k] = j;
e.addEnum(j)
}
return e;
}
And you define your enums like this:
var COLORS = defineEnum({
RED : {
value : 1,
string : 'red'
},
GREEN : {
value : 2,
string : 'green'
},
BLUE : {
value : 3,
string : 'blue'
}
});
And this is how you access your enums:
COLORS.BLUE.string
COLORS.BLUE.value
COLORS.getByName('BLUE').string
COLORS.getByValue('value', 1).string
COLORS.forEach(function(e){
// do what you want with e
});
I usually use the last 2 methods for mapping enums from message objects.
Some advantages to this approach:
Some disadvantages:
You can't remove items from a list while iterating over it. It's much easier to build a new list based on the old one:
y = [s for s in x if len(s) == 2]
First, you need to get the ID of the playlist that represents the uploads from the user/channel:
https://developers.google.com/youtube/v3/docs/channels/list#try-it
You can specify the username with the forUsername={username}
param, or specify mine=true
to get your own (you need to authenticate first). Include part=contentDetails
to see the playlists.
GET https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=jambrose42&key={YOUR_API_KEY}
In the result "relatedPlaylists"
will include "likes"
and "uploads"
playlists. Grab that "upload"
playlist ID. Also note the "id"
is your channelID for future reference.
Next, get a list of videos in that playlist:
https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it
Just drop in the playlistId!
GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId=UUpRmvjdu3ixew5ahydZ67uA&key={YOUR_API_KEY}
You can do it manually if you want.
Reference: http://php.net/manual/en/function.get-browser.php
preg_match('/windows|win32/i', $_SERVER['HTTP_USER_AGENT'])
preg_match('/iPhone|iPod|iPad/', $_SERVER['HTTP_USER_AGENT'])
You can even make it a script
$device = 'Blackberry'
preg_match("/$device/", $_SERVER['HTTP_USER_AGENT'])
Here is somewhat of a small list
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
Browsers
'/msie/i' => 'Internet Explorer',
'/firefox/i' => 'Firefox',
'/safari/i' => 'Safari',
'/chrome/i' => 'Chrome',
'/opera/i' => 'Opera',
'/netscape/i' => 'Netscape',
'/maxthon/i' => 'Maxthon',
'/konqueror/i' => 'Konqueror',
'/mobile/i' => 'Handheld Browser'
For a general solution that works regardless of how many digits are in data$anim
, use the sprintf
function. It works like this:
sprintf("%04d", 1)
# [1] "0001"
sprintf("%04d", 104)
# [1] "0104"
sprintf("%010d", 104)
# [1] "0000000104"
In your case, you probably want: data$anim <- sprintf("%06d", data$anim)
Deleting derived data saved it for me
I discoverd the same Error message trying to pull from a Bitbuck Repo into my lokal copy. There is also only one Branche Master and the command git pull origin master
lead to this Error Message
From https://bitbucket.org/xxx
* branch master -> FETCH_HEAD
error: Couldn't set ORIG_HEAD
fatal: Cannot update the ref 'ORIG_HEAD'.
Solution as follows
git reflog
find the number of the last commitgit reset --hard <numnber>
reset to the last commit git pull origin master
pull again without errorI think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
From version 0.8.0, dplyr
offers a handy function called group_split()
:
# On sample data from @Aus_10
df %>%
group_split(g)
[[1]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 2.04 0.627 A
2 0.530 -0.703 A
3 -0.475 0.541 A
4 1.20 -0.565 A
5 -0.380 -0.126 A
6 1.25 -1.69 A
7 -0.153 -1.02 A
8 1.52 -0.520 A
9 0.905 -0.976 A
10 0.517 -0.535 A
# … with 15 more rows
[[2]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 1.61 0.858 B
2 1.05 -1.25 B
3 -0.440 -0.506 B
4 -1.17 1.81 B
5 1.47 -1.60 B
6 -0.682 -0.726 B
7 -2.21 0.282 B
8 -0.499 0.591 B
9 0.711 -1.21 B
10 0.705 0.960 B
# … with 15 more rows
To not include the grouping column:
df %>%
group_split(g, keep = FALSE)
No need to complicate stuff - this should work:
#/bin/bash
echo "
verbose
open ftp.mydomain.net
user myusername mypassword
ascii
put textfile1
put textfile2
bin
put binaryfile1
put binaryfile2
bye
" | ftp -n > ftp_$$.log
or you can use mput if you have many files ...
This poblem is solved for me after Run as administrator
the Andorid Studio
Watch out for lots of incorrect answers to this question!
Gerard's logic is correct, though it will return a list rather than a queryset (which might not matter).
If you need a queryset, use Q:
from django.db.models import Q
results = Model.objects.filter(Q(a=false) | Q(x=5))
If you've copied a disk (vmdk file) from one machine to another and need to change a disk's UUID in the copy, you don't need to change the Machine UUID as has been suggested by another answer.
All you need to do is to assign a new UUID to the disk image:
VBoxManage internalcommands sethduuid your-box-disk2.vmdk
UUID changed to: 5d34479f-5597-4b78-a1fa-94e200d16bbb
and then replace the old UUID with the newly generated one in two places in your *.vbox file
<MediaRegistry>
<HardDisks>
<HardDisk uuid="{5d34479f-5597-4b78-a1fa-94e200d16bbb}" location="box-disk2.vmdk" format="VMDK" type="Normal"/>
</HardDisks>
and in
<AttachedDevice type="HardDisk" hotpluggable="false" port="0" device="0">
<Image uuid="{5d34479f-5597-4b78-a1fa-94e200d16bbb}"/>
</AttachedDevice>
It worked for me for VirtualBox ver. 5.1.8 running on Mac OS X El Capitan.
public static int reverse(int x) {
boolean negetive = false;
if (x < 0) {
x = Math.abs(x);
negative = true;
}
int y = 0, i = 0;
while (x > 0) {
if (i > 0) {
y *= 10;
}
y += x % 10;
x = x / 10;
i++;
}
return negative ? -y : y;
}
Use:
$( '#form' ).serializeArray();
Php get array, dont need unserialize ;)
This function validates a string date in digit formats delimited by a character, e.g. dd/mm/yyyy, mm/dd/yyyy
/*
Param :
1)the date in string data type
2)[optional - string - default is "/"] the date delimiter, most likely "/" or "-"
3)[optional - int - default is 0] the position of the day component when the date string is broken up via the String.split function (into arrays)
4)[optional - int - default is 1] the position of the month component when the date string is broken up via the String.split function (into arrays)
5)[optional - int - default is 2] the position of the year component when the date string is broken up via the String.split function (into arrays)
Return : a javascript date is returned if the params are OK else null
*/
function IsValidDate(strDate, strDelimiter, iDayPosInArray, iMonthPosInArray, iYearPosInArray) {
var strDateArr; //a string array to hold constituents day, month, and year components
var dtDate; //our internal converted date
var iDay, iMonth, iYear;
//sanity check
//no integer checks are performed on day, month, and year tokens as parsing them below will result in NaN if they're invalid
if (null == strDate || typeof strDate != "string")
return null;
//defaults
strDelimiter = strDelimiter || "/";
iDayPosInArray = undefined == iDayPosInArray ? 0 : iDayPosInArray;
iMonthPosInArray = undefined == iMonthPosInArray ? 1 : iMonthPosInArray;
iYearPosInArray = undefined == iYearPosInArray ? 2 : iYearPosInArray;
strDateArr = strDate.split(strDelimiter);
iDay = parseInt(strDateArr[iDayPosInArray],10);
iMonth = parseInt(strDateArr[iMonthPosInArray],10) - 1; // Note: months are 0-based
iYear = parseInt(strDateArr[iYearPosInArray],10);
dtDate = new Date(
iYear,
iMonth, // Note: months are 0-based
iDay);
return (!isNaN(dtDate) && dtDate.getFullYear() == iYear && dtDate.getMonth() == iMonth && dtDate.getDate() == iDay) ? dtDate : null; // Note: months are 0-based
}
Example call:
var strDate="18-01-1971";
if (null == IsValidDate(strDate)) {
alert("invalid date");
}
I'm guessing that you need to assign the Exception
to a variable. As shown in the Python 3 tutorial:
def fails():
x = 1 / 0
try:
fails()
except Exception as ex:
print(ex)
To give a brief explanation, as
is a pseudo-assignment keyword used in certain compound statements to assign or alias the preceding statement to a variable.
In this case, as
assigns the caught exception to a variable allowing for information about the exception to stored and used later, instead of needing to be dealt with immediately. (This is discussed in detail in the Python 3 Language Reference: The try
Statement.)
The other compound statement using as
is the with
statement:
@contextmanager
def opening(filename):
f = open(filename)
try:
yield f
finally:
f.close()
with opening(filename) as f:
# ...read data from f...
Here, with
statements are used to wrap the execution of a block with methods defined by context managers. This functions like an extended try...except...finally
statement in a neat generator package, and the as
statement assigns the generator-produced result from the context manager to a variable for extended use.
(This is discussed in detail in the Python 3 Language Reference: The with
Statement.)
Finally, as
can be used when importing modules, to alias a module to a different (usually shorter) name:
import foo.bar.baz as fbb
This is discussed in detail in the Python 3 Language Reference: The import
Statement.
What the error is telling you, is that refresh
isn't initialized. Note that you chose to make refresh
not optional, which in Swift means that it has to have a value before you call super.init
(or it's implicitly called, which seems to be your case). Either make refresh
optional (probably what you want) or initialize it in some way.
I would suggest reading the Swift introductory documentation again, which covers this in great length.
One last thing, not part of the answer, as pointed out by @Anil, there is a built in pull to refresh control in iOS called UIRefresControl
, which might be something worth looking into.
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
I wanted to edit several events in descendant chonologic order, and I just made a :
select
TO_CHAR(startdate,'YYYYMMDD') dateorder,
TO_CHAR(startdate,'DD/MM/YYYY') startdate,
...
from ...
...
order by dateorder desc
and it works for me. But surely not adapted for every case... Just hope it'll help someone !
Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.
Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY();
rule.
If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?
This can be achieved by using the following CSS:
.dynamic-height {
-webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
margin-top: -10px;
}
In this instance, it is important to remember that translateY(100%)
will move the element in question downwards by a total of it's own length.
The problem with this route is that it will not push element below it out of the way, where a margin would.
If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.
jQuery(document).ready(function($){ //wait for the document to load
$('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
$(this).css({
'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
});
});
});
For Windows users something like this should work:
PS C:\angular> npm install --python=C:\Python27\python.exe
The way I do it is to do a Topological Sort, counting the number of vertices visited. If that number is less than the total number of vertices in the DAG, you have a cycle.
You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase
is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase
)
One notable difference is that if you pass a .c
file to gcc it will compile as C.
The default behavior of g++ is to treat .c
files as C++ (unless -x c
is specified).
You could do something like this:
> +(Math.floor(y/x)*x).toFixed(15);
1.2
There are a few problems with your code:
def MyThread ( threading.thread ):
If you really want to do this with only functions, you have two options:
With threading:
import threading
def MyThread1():
pass
def MyThread2():
pass
t1 = threading.Thread(target=MyThread1, args=[])
t2 = threading.Thread(target=MyThread2, args=[])
t1.start()
t2.start()
With thread:
import thread
def MyThread1():
pass
def MyThread2():
pass
thread.start_new_thread(MyThread1, ())
thread.start_new_thread(MyThread2, ())
Doc for thread.start_new_thread
Don't know if this question is relevant anymore, but this happened to me on a client wich had an incorrect datetime set on Windows. This will be an alternative to watch. If is this case, it will reproduce on other browsers as well (at least, on firefox and chrome).
I fixed it updating datetime on Windows to actual's real datetime. Hope it helps somebody.
To get the form that the submit is inside why not just
this.form
Easiest & quickest path to the result.
/* Important part */
.modal-dialog{
overflow-y: initial !important
}
.modal-body{
max-height: calc(100vh - 200px);
overflow-y: auto;
}
This works for Bootstrap 3 without JS code and is responsive.
Which is a JavaScript library that provides a whole mess of useful functional programming
helpers without extending any built-in objects.
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
var item = _.findWhere(data.items, {
id: 2
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
//using find -
var item = _.find(data.items, function(item) {
return item.id === 2;
});
if (!_.isUndefined(item)) {
console.log('NAME =>', item.name);
}
For removing the default 'blue-border' from button on button focus:
In Html:
<button class="new-button">New Button...</button>
And in Css
button.new-button:focus {
outline: none;
}
Hope it helps :)
If you just want to remove it from the existing array and not create a new one, try:
var items = [{Id: 1},{Id: 2},{Id: 3}];
items.splice(_.indexOf(items, _.find(items, function (item) { return item.Id === 2; })), 1);
STEPS
Finally install a clean copy of apache(xampp) software.
(By Engineer Rafiq Ahmad Qureshi) [email protected]
Here are two very short texts to compare:
Julie loves me more than Linda loves me
Jane likes me more than Julie loves me
We want to know how similar these texts are, purely in terms of word counts (and ignoring word order). We begin by making a list of the words from both texts:
me Julie loves Linda than more likes Jane
Now we count the number of times each of these words appears in each text:
me 2 2
Jane 0 1
Julie 1 1
Linda 1 0
likes 0 1
loves 2 1
more 1 1
than 1 1
We are not interested in the words themselves though. We are interested only in those two vertical vectors of counts. For instance, there are two instances of 'me' in each text. We are going to decide how close these two texts are to each other by calculating one function of those two vectors, namely the cosine of the angle between them.
The two vectors are, again:
a: [2, 0, 1, 1, 0, 2, 1, 1]
b: [2, 1, 1, 0, 1, 1, 1, 1]
The cosine of the angle between them is about 0.822.
These vectors are 8-dimensional. A virtue of using cosine similarity is clearly that it converts a question that is beyond human ability to visualise to one that can be. In this case you can think of this as the angle of about 35 degrees which is some 'distance' from zero or perfect agreement.
Alternatively, you can start output buffering, do an include/require, and then stop buffering. With ob_get_contents(), you can just get the stuff that was outputted by that other PHP file into a variable.
I was successful with this method today. It's similar to the other answers in that it also converts the contents to XML, just using a different method. As I didn't see FOR XML PATH
mentioned amongst the answers, I thought I'd add it for completeness:
SELECT [COL_NVARCHAR_MAX]
FROM [SOME_TABLE]
FOR XML PATH(''), ROOT('ROOT')
This will deliver a valid XML containing the contents of all rows, nested in an outer <ROOT></ROOT>
element. The contents of the individual rows will each be contained within an element that, for this example, is called <COL_NVARCHAR_MAX>
. The name of that can be changed using an alias via AS
.
Special characters like &
, <
or >
or similar will be converted to their respective entities. So you may have to convert <
, >
and &
back to their original character, depending on what you need to do with the result.
EDIT
I just realized that CDATA
can be specified using FOR XML
too. I find it a bit cumbersome though. This would do it:
SELECT 1 as tag, 0 as parent, [COL_NVARCHAR_MAX] as [COL_NVARCHAR_MAX!1!!CDATA]
FROM [SOME_TABLE]
FOR XML EXPLICIT, ROOT('ROOT')
Q1:Could the time it takes for a transaction to execute make the associated process more likely to be flagged as a deadlock victim.
No. The SELECT is the victim because it had only read data, therefore the transaction has a lower cost associated with it so is chosen as the victim:
By default, the Database Engine chooses as the deadlock victim the session running the transaction that is least expensive to roll back. Alternatively, a user can specify the priority of sessions in a deadlock situation using the
SET DEADLOCK_PRIORITY
statement. DEADLOCK_PRIORITY can be set to LOW, NORMAL, or HIGH, or alternatively can be set to any integer value in the range (-10 to 10).
Q2. If I execute the select with a NOLOCK hint, will this remove the problem?
No. For several reasons:
Q3. I suspect that a datetime field that is checked as part of the WHERE clause in the select statement is causing the slow lookup time. Can I create an index based on this field? Is it advisable?
Probably. The cause of the deadlock is almost very likely to be a poorly indexed database.10 minutes queries are acceptable in such narrow conditions, that I'm 100% certain in your case is not acceptable.
With 99% confidence I declare that your deadlock is cased by a large table scan conflicting with updates. Start by capturing the deadlock graph to analyze the cause. You will very likely have to optimize the schema of your database. Before you do any modification, read this topic Designing Indexes and the sub-articles.
RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.
You can also Uuencode you original binary data. This format is a bit older but it does the same thing as base63 encoding.
I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.
Have you tried compiling from the command line?
I have the exact same version:
Probably you're thinking the warning is an error.
UPDATE
It looks like you have a Arrays.class
file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class
There is at least one other cause of the message "out of date" error. In my case the problem was .svn/dir-props which was created by running "svn propset svn:ignore -F .gitignore ." for the first time. Deleting .svn/dir-props seems like a bad idea and can cause other errors, so it may be best to use "svn propdel" to clean up the errant "svn propset".
# Normal state, works fine.
> svn commit -m"bump"
Sending eac_cpf.xsl
Transmitting file data .
Committed revision 509.
# Set a property, but forget to commit.
> svn propset svn:ignore -F .gitignore .
property 'svn:ignore' set on '.'
# Edit a file. Should have committed before the edit.
> svn commit -m"bump"
Sending .
svn: Commit failed (details follow):
svn: File or directory '.' is out of date; try updating
svn: resource out of date; try updating
# Delete the property.
> svn propdel svn:ignore .
property 'svn:ignore' deleted from '.'.
# Now the commit works fine.
> svn commit -m"bump"
Sending eac_cpf.xsl
Transmitting file data .
Committed revision 510.
What i did to solve this problem in the terminal(Ubuntu 18.04):
openssl s_client -showcerts -servername www.github.com -connect www.github.com:443
I got two chunks of certificate chunks. And i copied the certificate chunks to my certificate file to /etc/ssl/certs/ca-certificates.crt
.
Try this one too:
let base64="iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
let buffer=Uint8Array.from(atob(base64), c => c.charCodeAt(0));
let blob=new Blob([buffer], { type: "image/gif" });
let url=URL.createObjectURL(blob);
let img=document.createElement("img");
img.src=url;
document.body.appendChild(img);
Not recommended for production as it is only compatible with modern browsers.
Simply add this tad to your textarea.
onkeydown="if(event.keyCode == 13) return false;"
The first argument after the "run" that is not a flag or parameter to a flag is parsed as an image name. When that parsing fails, it tells you the reference format, aka image name (but could be an image id, pinned image, or other syntax) is invalid. In your command:
docker run -p 8888:8888 -v `pwd`/../src:/src -v `pwd`/../data:/data -w /src supervisely_anpr --rm -it bash
The image name "supervisely_anpr" is valid, so you need to look earlier in the command. In this case, the error is most likely from pwd
outputting a path with a space in it. Everything after the space is no longer a parameter to -v
and docker tries to parse it as the image name. The fix is to quote the volume parameters when you cannot guarantee it is free of spaces or other special characters.
When you do that, you'll encounter the next error, "executable not found". Everything after the image name is parsed as the command to run inside the container. In your case, it will try to run the command --rm -it bash
which will almost certainly fail since --rm
will no exist as a binary inside your image. You need to reorder the parameters to resolve that:
docker run --rm -it -p 8888:8888 -v "`pwd`/../src:/src" -v "`pwd`/../data:/data" -w /src supervisely_anpr bash
I've got some more details on these two errors and causes in my slides here: https://sudo-bmitch.github.io/presentations/dc2018/faq-stackoverflow-lightning.html#29
On Windows and Linux : Ctrl + Shift + F
On Mac : ? + ? + F
(Alternatively you can press Format
in Main Menu > Source)
Let said our backend looks like this:
public async Task<IActionResult> Post([FromBody] IList<UserRol> roles, string notes) {
}
We have a HttpService like this:
post<T>(url: string, body: any, headers?: HttpHeaders, params?: HttpParams): Observable<T> {
return this.http.post<T>(url, body, { headers: headers, params});
}
Following is how we can pass the body and the notes as parameter: // how to call it
const headers: HttpHeaders = new HttpHeaders({
'Authorization': `Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXX`
});
const bodyData = this.getBodyData(); // get whatever we want to send as body
let params: HttpParams = new HttpParams();
params = params.set('notes', 'Some notes to send');
this.httpService.post<any>(url, bodyData, headers, params);
It worked for me (using angular 7^), I hope is useful for somebody.
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?
To get value you can use now different ways:
console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?
While I agree that in general inline-block
is better, there's one extra thing to take into account if you're using percentage widths to create a responsive grid (or if you want pixel-perfect widths):
If you're using inline-block
for grids that total 100% or near to 100% width, you need to make sure your HTML markup contains no white space between columns.
With floats, this is not something you need to worry about - the columns float over any whitespace or other content between columns. This question's answers have some good tips on ways to remove HTML whitespace without making your code ugly.
If for any reason you can't control the HTML markup (e.g. a restrictive CMS), you can try the tricks described here, or you might need to compromise and use floats instead of inline-block. There are also ugly CSS tricks that should only be used in extreme circumstances, like font-size:0;
on the column container then reapply font size within each column.
For example:
float: left
. It "just works" (but for the wrapper needing to be cleared).inline-block
. The whitespace between blocks creates a fixed-width space which pushes the total width beyond 100%, breaking the layout and causing the last column to drop down a line.inline-block
and no whitespace between columns in the HTML. It "just works" again - but the HTML is uglier and your CMS might force some kind of prettification or indenting to its HTML output making this difficult to achieve in reality.Considering we have the following post
and post_comment
tables:
The post
has the following records:
| id | title |
|----|-----------|
| 1 | Java |
| 2 | Hibernate |
| 3 | JPA |
and the post_comment
has the following three rows:
| id | review | post_id |
|----|-----------|---------|
| 1 | Good | 1 |
| 2 | Excellent | 1 |
| 3 | Awesome | 2 |
The SQL JOIN clause allows you to associate rows that belong to different tables. For instance, a CROSS JOIN will create a Cartesian Product containing all possible combinations of rows between the two joining tables.
While the CROSS JOIN is useful in certain scenarios, most of the time, you want to join tables based on a specific condition. And, that's where INNER JOIN comes into play.
The SQL INNER JOIN allows us to filter the Cartesian Product of joining two tables based on a condition that is specified via the ON clause.
If you provide an "always true" condition, the INNER JOIN will not filter the joined records, and the result set will contain the Cartesian Product of the two joining tables.
For instance, if we execute the following SQL INNER JOIN query:
SELECT
p.id AS "p.id",
pc.id AS "pc.id"
FROM post p
INNER JOIN post_comment pc ON 1 = 1
We will get all combinations of post
and post_comment
records:
| p.id | pc.id |
|---------|------------|
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
So, if the ON clause condition is "always true", the INNER JOIN is simply equivalent to a CROSS JOIN query:
SELECT
p.id AS "p.id",
pc.id AS "pc.id"
FROM post p
CROSS JOIN post_comment
WHERE 1 = 1
ORDER BY p.id, pc.id
On the other hand, if the ON clause condition is "always false", then all the joined records are going to be filtered out and the result set will be empty.
So, if we execute the following SQL INNER JOIN query:
SELECT
p.id AS "p.id",
pc.id AS "pc.id"
FROM post p
INNER JOIN post_comment pc ON 1 = 0
ORDER BY p.id, pc.id
We won't get any result back:
| p.id | pc.id |
|---------|------------|
That's because the query above is equivalent to the following CROSS JOIN query:
SELECT
p.id AS "p.id",
pc.id AS "pc.id"
FROM post p
CROSS JOIN post_comment
WHERE 1 = 0
ORDER BY p.id, pc.id
The most common ON clause condition is the one that matches the Foreign Key column in the child table with the Primary Key column in the parent table, as illustrated by the following query:
SELECT
p.id AS "p.id",
pc.post_id AS "pc.post_id",
pc.id AS "pc.id",
p.title AS "p.title",
pc.review AS "pc.review"
FROM post p
INNER JOIN post_comment pc ON pc.post_id = p.id
ORDER BY p.id, pc.id
When executing the above SQL INNER JOIN query, we get the following result set:
| p.id | pc.post_id | pc.id | p.title | pc.review |
|---------|------------|------------|------------|-----------|
| 1 | 1 | 1 | Java | Good |
| 1 | 1 | 2 | Java | Excellent |
| 2 | 2 | 3 | Hibernate | Awesome |
So, only the records that match the ON clause condition are included in the query result set. In our case, the result set contains all the post
along with their post_comment
records. The post
rows that have no associated post_comment
are excluded since they can not satisfy the ON Clause condition.
Again, the above SQL INNER JOIN query is equivalent to the following CROSS JOIN query:
SELECT
p.id AS "p.id",
pc.post_id AS "pc.post_id",
pc.id AS "pc.id",
p.title AS "p.title",
pc.review AS "pc.review"
FROM post p, post_comment pc
WHERE pc.post_id = p.id
The non-struck rows are the ones that satisfy the WHERE clause, and only these records are going to be included in the result set. That's the best way to visualize how the INNER JOIN clause works.
| p.id | pc.post_id | pc.id | p.title | pc.review | |------|------------|-------|-----------|-----------| | 1 | 1 | 1 | Java | Good | | 1 | 1 | 2 | Java | Excellent || 1 | 2 | 3 | Java | Awesome || 2 | 1 | 1 | Hibernate | Good || 2 | 1 | 2 | Hibernate | Excellent || 2 | 2 | 3 | Hibernate | Awesome || 3 | 1 | 1 | JPA | Good || 3 | 1 | 2 | JPA | Excellent || 3 | 2 | 3 | JPA | Awesome |
An INNER JOIN statement can be rewritten as a CROSS JOIN with a WHERE clause matching the same condition you used in the ON clause of the INNER JOIN query.
Not that this only applies to INNER JOIN, not for OUTER JOIN.
document.location.constructor === window.location.constructor
is true
.
It's because it's exactly the same object as you can see from document.location===window.location
.
So there's no need to compare the constructor or any other property.
With Jetpack Compose, it's really easy:
AmbientClipboardManager.current.setText(AnnotatedString("Copied Text"))
Make sure the PORTS ARE ON
var app = express();
app.set('port', (process.env.PORT || 5000));
BLAL BLA BLA AND AT THE END YOU HAVE THIS
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
});
Still a newbee in node js but this caused more of this.
You can use Microsoft Office Web Apps to embed PowerPoint and Excel Files. See Say more in your blog with embedded PowerPoint and Excel files.
Here is the crisp answer:
public String sendSMS(String phone, String token) {
WebClient webClient = WebClient.create(smsServiceUrl);
SMSRequest smsRequest = new SMSRequest();
smsRequest.setMessage(token);
smsRequest.setPhoneNo(phone);
smsRequest.setTokenId(smsServiceTokenId);
Mono<String> response = webClient.post()
.uri(smsServiceEndpoint)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(Mono.just(smsRequest), SMSRequest.class)
.retrieve().bodyToMono(String.class);
String deliveryResponse = response.block();
if (deliveryResponse.equalsIgnoreCase("success")) {
return deliveryResponse;
}
return null;
}
Good news: hg 2.2 just added git like --amend
option.
and in tortoiseHg, you can use "Amend current revision" by select black arrow on the right of commit button
I think you're looking for;
string[] skus = myLines.Select(x => x.Sku).ToArray();
However, if you're going to iterate over the sku's in subsequent code I recommend not using the ToArray()
bit as it forces the queries execution prematurely and makes the applications performance worse. Instead you can just do;
var skus = myLines.Select(x => x.Sku); // produce IEnumerable<string>
foreach (string sku in skus) // forces execution of the query
I had to replace new lines with br
string newString = oldString.Replace("\n", "<br />");
or if you use xml
<asp:Label ID="Label1" runat="server" Text='<%# ShowLineBreaks(Eval("Comments")) %>'></asp:Label>
Then in code behind
public string ShowLineBreaks(object text)
{
return (text.ToString().Replace("\n", "<br/>"));
}
That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.
Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.
Although there are already few answers to this questions but I think some people still may have doubt in actually visualising the differece b/w throughput and bandwidth just like I had ;) until I read this analogy on quora(full credits to that) which proved really helpful
Consider
A highway which has a capacity of moving ,say, 200 vehicles at a time
but
at a random time someone notices only , say, 150 vehicles moving through it..
say due to some traffic-jam in between...
i.e.
capacity is 200 but not all the time it is fully utilised, actual traffic is only 150 out of a max of 200.
i.e. the bandwidth is 200 per unit time but still actual throughput is 150 ...
I thought it might help someone...
You can have multiple CTE
s in one query, as well as reuse a CTE
:
WITH cte1 AS
(
SELECT 1 AS id
),
cte2 AS
(
SELECT 2 AS id
)
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
UNION ALL
SELECT *
FROM cte1
Note, however, that SQL Server
may reevaluate the CTE
each time it is accessed, so if you are using values like RAND()
, NEWID()
etc., they may change between the CTE
calls.
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++)
{
for (var j = 0; j < cols; j++)
{
if(j <= c && i <= r) {
myArray[i][j] = 1;
} else {
myArray[i][j] = 0;
}
}
}
<select name="FakeName" id="Fake-ID" aria-required="true" required> <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options); foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>"; } ?> </select>
Extract the element:
var buttonMatcherRegExp=/<a[\s\S]*?>[\s\S]*?<\/a>/;
htmlStr=string.match( buttonMatcherRegExp )[0]
Then use jQuery to parse and extract the bit you want:
$(htmlStr).attr('style')
I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest
module. So a simple apt install python-pytest
fixed it for me.
'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.