This looks like an old thread but there is one more variant of how we can set an environment variable in the Gradle task.
task runSomeRandomTask(type: NpmTask, dependsOn: [npmInstall]) {
environment = [ 'NODE_ENV': 'development', BASE_URL: '3000' ]
args = ['run']
}
The above Gradle task integrates the Gradle and npm tasks.
This way we can pass multiple environment variables. Hope this helps to broaden the understanding which the answers above have already provided. Cheers!!
OK. I've triple-tested this and I am 100% sure that it is being caused by my anti-virus (ESET NOD32 ANTIVIRUS 5).
Whenever I disable the Real-Time protection, the issue disappears. Today, I left the Real-Time protection off for 6-7 hours and the issue never occurred.
A few moments ago, I switched it back on, only for the problem to surface within a minute.
Over the course of the last 24 hours, I have switched the Real-Time protection on and off again, just to be sure. Each time - the result has been the same.
Update: I have come across another developer who had the exact same problem with the Real-Time protection on his Kaspersky anti-virus. He disabled it and the problem went away. i.e. This issue doesn't seem to be limited to ESET.
Step 1) C:\WINDOWS\system32\drivers\etc\ Open the "hosts" file :
127.0.0.1 localhost
127.0.0.1 test.com
127.0.0.1 example.com
Step 2) xampp\apache\conf\extra\httpd-vhosts.conf
<VirtualHost *:80>
DocumentRoot C:/xampp/htdocs/test/
ServerName www.test.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot C:/xampp/htdocs/example/
ServerName www.example.com
</VirtualHost>
Step 3) C:\xampp\apache\conf\httpd.conf. Scroll down to the Supplemental configuration section at the end, and locate the following section (around line 500), Remove the # from the beginning of the second line so the section now looks like this:
#Virtual hosts
Include conf/extra/httpd-vhosts.conf
Step 4) Restart XAMPP and now run in your browser :
www.example.com or www.test.com
A reason for this could be Skype as well! If you use the default XAMPP settings, they both would run on the same port (80). You can:
This exception come due to you are providing listener ContextLoaderListener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
but you are not providing context-param
for your spring configuration file. like applicationContext.xml
You must provide below snippet for your configuration
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>applicationContext.xml</param-value>
</context-param>
If You are providing the java based spring configuration , means you are not using xml file for spring configuration at that time you must provide below code:
<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified @Configuration classes. Fully-qualified packages may also
be specified for component-scanning -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.nirav.modi.config.SpringAppConfig</param-value>
</context-param>
The default execution policy, "Restricted", prevents all scripts from running, including scripts that you write on the local computer.
The execution policy is saved in the registry, so you need to change it only once on each computer.
To change the execution policy, use the following procedure:
Start Windows PowerShell with the "Run as administrator" option.
At the command prompt, type:
Set-ExecutionPolicy AllSigned
-or-
Set-ExecutionPolicy RemoteSigned
The change is effective immediately.
To run a script, type the full name and the full path to the script file.
For example, to run the Get-ServiceLog.ps1
script in the C:\Scripts
directory, type:
C:\Scripts\Get-ServiceLog.ps1
And to the Python file, you have two points. Try to add your Python folder to your PATH and the extension .py
.
To PATHEXT from go properties of computer. Then click on advanced system protection. Then environment variable. Here you will find the two points.
Changing "Managed Pipeline Mode" from "Classic" to "Integrated" worked for me. It can be changed at Application Pools -> Basic Settings
In my situation it was matter of the permissions:
sudo chmod -R +777 <your_folder_path>
It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.
I like a combination of Gaurav's and user2550946's answer best, but would like to add two more aspects:
Don't use JAVA_OPTS
, instead use CATALINA_OPTS
. This will be used solely for starting tomcat, not for shutting it down. Typically you want more memory when starting tomcat, but the shutdown process (which just spins up, tells tomcat to shut down and then ends again) doesn't need any specifically tuned resources. In fact, shutdown can even fail if some ridiculous amount of memory is not available from the OS anymore.
On production systems, my recommentation is to claim the maximum allowed memory immediately. Because if you anticipate that the memory will be required sooner or later, you don't want to discover it not being available at 3am in the night - rather when you start up the server. Thus, set -Xmx
and -Xms
to the same value in production systems. (This makes my aspect 1 even more relevant)
Or, in one line, here's my recommendation:
set "CATALINA_OPTS=%CATALINA_OPTS% -Xms1024M -Xmx1024M"
There is a trusted answer on the Wordpress website:
Where's my .htaccess file?
WordPress's index.php and .htaccess files should be together in the directory indicated by the Site address (URL) setting on your General Options page. Since the name of the file begins with a dot, the file may not be visible through an FTP client unless you change the preferences of the FTP tool to show all files, including the hidden files. Some hosts (e.g. Godaddy) may not show or allow you to edit .htaccess if you install WordPress through the Godaddy Hosting Connection installation.
Creating and editing (.htaccess)
If you do not already have a .htaccess file, create one. If you have shell or ssh access to the server, a simple touch .htaccess command will create the file. If you are using FTP to transfer files, create a file on your local computer, call it 1.htaccess, upload it to the root of your WordPress folder, and then rename it to .htaccess.
You can edit the .htaccess file by FTP, shell, or (possibly) your host's control panel.
The following permalink rewrite code should be included in your .htaccess file (since WordPress 3.0):
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
*Taken from here.
Ran into this problem using the same .htaccess configuration. I realized that my server was serving javascript files as text/javascript
instead of application/javascript
. Once I added text/javascript
to the AddOutputFilterByType
declaration, gzip started working.
As to why javascript was being served as text/javascript
: there was an AddType 'text/javascript' js
declaration at the top of my root .htaccess file. After removing it (it had been added in error), javascript starting serving as application/javascript
.
For a permanent solution I found the following worked:
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python 3.5")
I just want to change my public directory www, and access it from my PC, and mobile connected by Wifi. I've Ubuntu 16.04.
So, first, I modified /etc/apache2/sites-enabled/000-default.conf and I changed the line DocumentRoot /var/www/html for my new public directory DocumentRoot "/media/data/XAMPP/htdocs"
Then I modified /etc/apache2/apache2.conf, and I put the permissions for localhost, and my mobile, this time I used the IP address, I know it is not completely safe, but it's OK for my purposes.
<Directory/>
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from localhost 10.42.0.11
</Directory>
A bit late to the party but might be valuable to someone with this error..
I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.
The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.
One possibility: Turn on "Dead code stripping" in the Xcode 4 build settings.
Another possibility: It could be that you switched to using LLVM for some framework that was previously using GCC. Moving back to GCC (or LLVM GCC) may get rid of those warnings.
I had used a CLGeocoder without adding a Core.Location Framework. Basically this error can mean multiple things. I hope this helps someone else.
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
FOO = $PATH all: @echo $(FOO) @echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
Your change may well be working. Does your application need a lot of memory - the stack trace shows some Image related features.
I'm guessing that the error either happens right away, with a large file, or happens later after several requests.
If the error happens right away, then you can increase memory still further, or investigate find out why so much memory is needed for one file.
If the error happens after several requests, then you could have a memory leak - where objects are not being reclaimed by the garbage collector. Using a tool like JProfiler can help you monitor how much memory is being used by your VM and can help you see what is using that memory and why objects are not being reclaimed by the garbage collector.
You're not going to be able to modify the caller's shell because it's in a different process context. When child processes inherit your shell's variables, they're inheriting copies themselves.
One thing you can do is to write a script that emits the correct commands for tcsh or sh based how it's invoked. If you're script is "setit" then do:
ln -s setit setit-sh
and
ln -s setit setit-csh
Now either directly or in an alias, you do this from sh
eval `setit-sh`
or this from csh
eval `setit-csh`
setit uses $0 to determine its output style.
This is reminescent of how people use to get the TERM environment variable set.
The advantage here is that setit is just written in whichever shell you like as in:
#!/bin/bash
arg0=$0
arg0=${arg0##*/}
for nv in \
NAME1=VALUE1 \
NAME2=VALUE2
do
if [ x$arg0 = xsetit-sh ]; then
echo 'export '$nv' ;'
elif [ x$arg0 = xsetit-csh ]; then
echo 'setenv '${nv%%=*}' '${nv##*=}' ;'
fi
done
with the symbolic links given above, and the eval of the backquoted expression, this has the desired result.
To simplify invocation for csh, tcsh, or similar shells:
alias dosetit 'eval `setit-csh`'
or for sh, bash, and the like:
alias dosetit='eval `setit-sh`'
One nice thing about this is that you only have to maintain the list in one place.
In theory you could even stick the list in a file and put cat nvpairfilename
between "in" and "do".
This is pretty much how login shell terminal settings used to be done: a script would output statments to be executed in the login shell. An alias would generally be used to make invocation simple, as in "tset vt100". As mentioned in another answer, there is also similar functionality in the INN UseNet news server.
Poking around online, it looks like it might be possible to do this with JNI. You'd then have to make a call to putenv() from C, and you'd (presumably) have to do it in a way that worked on both Windows and UNIX.
If all that can be done, it surely wouldn't be too hard for Java itself to support this instead of putting me in a straight jacket.
A Perl-speaking friend elsewhere suggests that this is because environment variables are process global and Java is striving for good isolation for good design.
VAR=value
sets VAR to value.
After that export VAR
will give it to child processes too.
export VAR=value
is a shorthand doing both.
Use re.sub
directly, this allows you to specify a count
:
regex.sub('', url, 1)
(Note that the order of arguments is replacement
, original
not the opposite, as might be suspected.)
Decode it.
>>> b'a string'.decode('ascii')
'a string'
To get bytes from string, encode it.
>>> 'a string'.encode('ascii')
b'a string'
I've managed to achieve it with minimal effort (just as simple as with ASP.NET Core).
For that I use OWIN Startup.cs
file and Microsoft.Owin.Security.Jwt
library.
In order for the app to hit Startup.cs
we need to amend Web.config
:
<configuration>
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
...
Here's how Startup.cs
should look:
using MyApp.Helpers;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;
[assembly: OwinStartup(typeof(MyApp.App_Start.Startup))]
namespace MyApp.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = ConfigHelper.GetAudience(),
ValidIssuer = ConfigHelper.GetIssuer(),
IssuerSigningKey = ConfigHelper.GetSymmetricSecurityKey(),
ValidateLifetime = true,
ValidateIssuerSigningKey = true
}
});
}
}
}
Many of you guys use ASP.NET Core nowadays, so as you can see it doesn't differ a lot from what we have there.
It really got me perplexed first, I was trying to implement custom providers, etc. But I didn't expect it to be so simple. OWIN
just rocks!
Just one thing to mention - after I enabled OWIN Startup NSWag
library stopped working for me (e.g. some of you might want to auto-generate typescript HTTP proxies for Angular app).
The solution was also very simple - I replaced NSWag
with Swashbuckle
and didn't have any further issues.
Ok, now sharing ConfigHelper
code:
public class ConfigHelper
{
public static string GetIssuer()
{
string result = System.Configuration.ConfigurationManager.AppSettings["Issuer"];
return result;
}
public static string GetAudience()
{
string result = System.Configuration.ConfigurationManager.AppSettings["Audience"];
return result;
}
public static SigningCredentials GetSigningCredentials()
{
var result = new SigningCredentials(GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256);
return result;
}
public static string GetSecurityKey()
{
string result = System.Configuration.ConfigurationManager.AppSettings["SecurityKey"];
return result;
}
public static byte[] GetSymmetricSecurityKeyAsBytes()
{
var issuerSigningKey = GetSecurityKey();
byte[] data = Encoding.UTF8.GetBytes(issuerSigningKey);
return data;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey()
{
byte[] data = GetSymmetricSecurityKeyAsBytes();
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins()
{
string result = System.Configuration.ConfigurationManager.AppSettings["CorsOrigins"];
return result;
}
}
Another important aspect - I sent JWT Token via Authorization header, so typescript code looks for me as follows:
(the code below is generated by NSWag)
@Injectable()
export class TeamsServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "https://localhost:44384";
}
add(input: TeamDto | null): Observable<boolean> {
let url_ = this.baseUrl + "/api/Teams/Add";
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(input);
let options_ : any = {
body: content_,
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + localStorage.getItem('token')
})
};
See headers part - "Authorization": "Bearer " + localStorage.getItem('token')
In general, stack allocation is faster than heap allocation as mentioned by almost every answer above. A stack push or pop is O(1), whereas allocating or freeing from a heap could require a walk of previous allocations. However you shouldn't usually be allocating in tight, performance-intensive loops, so the choice will usually come down to other factors.
It might be good to make this distinction: you can use a "stack allocator" on the heap. Strictly speaking, I take stack allocation to mean the actual method of allocation rather than the location of the allocation. If you're allocating a lot of stuff on the actual program stack, that could be bad for a variety of reasons. On the other hand, using a stack method to allocate on the heap when possible is the best choice you can make for an allocation method.
Since you mentioned Metrowerks and PPC, I'm guessing you mean Wii. In this case memory is at a premium, and using a stack allocation method wherever possible guarantees that you don't waste memory on fragments. Of course, doing this requires a lot more care than "normal" heap allocation methods. It's wise to evaluate the tradeoffs for each situation.
This adds custom text at the beginning of your file:
echo 'your_custom_escaped_content' > temp_file.csv
cat testfile.csv >> temp_file.csv
mv temp_file.csv testfile.csv
Since recently, navigator.onLine
shows the same on all major browsers, and is thus useable.
if (navigator.onLine) {
// do things that need connection
} else {
// do things that don't need connection
}
The oldest versions that support this in the right way are: Firefox 41, IE 9, Chrome 14 and Safari 5.
Currently this will represent almost the whole spectrum of users, but you should always check what the users of your page have of capabilities.
Previous to FF 41, it would only show false
if the user put the browser manually in offline mode. In IE 8, the property was on the body
, instead of window
.
source: caniuse
document.getElementsByName("iframe_name")[0].contentWindow.document.body.focus();
You just CAST()
this way
SELECT cast(yourNumber as varchar(10))
FROM yourTable
Then if you want to JOIN
based on it, you can use:
SELECT *
FROM yourTable t1
INNER JOIN yourOtherTable t2
on cast(t1.yourNumber as varchar(10)) = t2.yourString
Try this instead
SELECT MAX(shoppername), COUNT(*) AS cnt
FROM dbo.sales
GROUP BY CHECKSUM(*)
HAVING COUNT(*) > 1
Read about the CHECKSUM function first, as there can be duplicates.
The answer by Steve Jessop explains well, why you can't use std::map::operator[]
on a const std::map
. Gabe Rainbow's answer suggests a nice alternative. I'd just like to provide some example code on how to use map::at()
. So, here is an enhanced example of your function()
:
void function(const MAP &map, const std::string &findMe) {
try {
const std::string& value = map.at(findMe);
std::cout << "Value of key \"" << findMe.c_str() << "\": " << value.c_str() << std::endl;
// TODO: Handle the element found.
}
catch (const std::out_of_range&) {
std::cout << "Key \"" << findMe.c_str() << "\" not found" << std::endl;
// TODO: Deal with the missing element.
}
}
And here is an example main()
function:
int main() {
MAP valueMap;
valueMap["string"] = "abc";
function(valueMap, "string");
function(valueMap, "strong");
return 0;
}
Output:
Value of key "string": abc
Key "strong" not found
Look at how Runtime.getRuntime().exec()
passes the String command to the ProcessBuilder
. It uses a tokenizer and explodes the command into individual tokens, then invokes exec(String[] cmdarray, ......)
which constructs a ProcessBuilder
.
If you construct the ProcessBuilder
with an array of strings instead of a single one, you'll get to the same result.
The ProcessBuilder
constructor takes a String...
vararg, so passing the whole command as a single String has the same effect as invoking that command in quotes in a terminal:
shell$ "command with args"
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx
name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);
Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.
OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.
You can invoke onNewIntent always by putting it into onCreate method like
@Override
public void onCreate(Bundle savedState){
super.onCreate(savedState);
onNewIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//code
}
TYPE string_aa IS TABLE OF VARCHAR2(32767) INDEX BY PLS_INTEGER;
FUNCTION string_to_list(p_string_in IN VARCHAR2)
RETURN string_aa
IS
TYPE ref_cursor IS ref cursor;
l_cur ref_cursor;
l_strlist string_aa;
l_x PLS_INTEGER;
BEGIN
IF p_string_in IS NOT NULL THEN
OPEN l_cur FOR
SELECT regexp_substr(p_string_in,'[^,]+', 1, level) FROM dual
CONNECT BY regexp_substr(p_string_in, '[^,]+', 1, level) IS NOT NULL;
l_x := 1;
LOOP
FETCH l_cur INTO l_strlist(l_x);
EXIT WHEN l_cur%notfound;
-- excludes NULL items e.g. 1,2,,,,5,6,7
l_x := l_x + 1;
END LOOP;
END IF;
RETURN l_strlist;
END string_to_list;
<style>
#div1, #div2 {
float: left; /* or right */
}
</style>
This was a quick script I found that worked... .Result is assigned to a label.
$(".Result").html($("option:selected").text());
You can't specify the width of an element with display inline. You could put something in it like a non-breaking space ( ) and then set the padding to give it some more width but you can't control it directly.
You could use display inline-block but that isn't widely supported.
A real hack would be to put an image inside and then set the width of that. Something like a transparent 1 pixel GIF. Not the recommended approach however.
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
C#
using System.Text.RegularExpressions;
...
Regex.Match(
input: "Check This String",
pattern: "Regex Pattern",
options: RegexOptions.IgnoreCase)
specifically: options: RegexOptions.IgnoreCase
Assuming xmlDoc is an XmlDocument object whats wrong with xmlDoc.OuterXml?
return xmlDoc.OuterXml;
The OuterXml property returns a string version of the xml.
Using Array's reduce
and findIndex
methods, this can be achieved.
var myArray = [{_x000D_
group: "one",_x000D_
color: "red"_x000D_
}, {_x000D_
group: "two",_x000D_
color: "blue"_x000D_
}, {_x000D_
group: "one",_x000D_
color: "green"_x000D_
}, {_x000D_
group: "one",_x000D_
color: "black"_x000D_
}];_x000D_
_x000D_
var transformedArray = myArray.reduce((acc, arr) => {_x000D_
var index = acc.findIndex(function(element) {_x000D_
return element.group === arr.group;_x000D_
});_x000D_
if (index === -1) {_x000D_
return acc.push({_x000D_
group: arr.group,_x000D_
color: [arr.color]_x000D_
});_x000D_
}_x000D_
_x000D_
acc[index].color.push(arr.color);_x000D_
return acc;_x000D_
}, []);_x000D_
_x000D_
console.log(transformedArray);
_x000D_
By using reduce
function, array is iterator and the new values are stored in acc (accumulating)
parameter. To check if the object with given group
already exists we can use findIndex
function.
If findIndex()
return -1, the value does not exist, so add the array in the acc
parameter.
If findIndex()
return index, then update the index
with the arr
values.
If your drive letter is C, you should be able to use
scp -r \desktop\myfolder\deployments\ user@host:/path/to/whereyouwant/thefile
without drive letter and backslashes instead of forward slashes.
You are using putty, so you can use pscp. It is better adapted to Windows.
If you want to stay with underscore so your predicate function can be more flexible, here are 2 ideas.
Since the predicate for _.find
receives both the value and index of an element, you can use side effect to retrieve the index, like this:
var idx;
_.find(tv, function(voteItem, voteIdx){
if(voteItem.id == voteID){ idx = voteIdx; return true;};
});
Looking at underscore source, this is how _.find
is implemented:
_.find = _.detect = function(obj, predicate, context) {
var result;
any(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
To make this a findIndex
function, simply replace the line result = value;
with result = index;
This is the same idea as the first method. I included it to point out that underscore uses side effect to implement _.find
as well.
private void clearRecyclerView() {
CustomListViewValuesArr.clear();
customRecyclerViewAdapter.notifyDataSetChanged();
}
use this func
for "THIS IS" not to be bold -
add <span></span>
around the text
<h1>><span>THIS IS</span> A HEADLINE</h1>
and in style
h1 span{font-weight:normal}
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
The easiest way so far. Hope this helps.
Say you want Comic Sans for the title and Helvetica for the x label.
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
Try umount -f /mnt/share. Works OK with NFS, never tried with cifs.
Also, take a look at autofs, it will mount the share only when accessed, and will unmount it afterworlds.
There is a good tutorial at www.howtoforge.net
Simply write one line in the constructor:
setResizable(false);
This will make it impossible to resize the frame.
Try with this code, you will get the image preview while uploading
<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />
function readURL(input){
var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg"))
var reader = new FileReader();
reader.onload = function (e) {
$('#img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}else{
$('#img').attr('src', '/assets/no_preview.png');
}
}
gacutil comes with Visual Studio, not with VSTS. It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en . This installation will have gacutil.exe
included. But first check it here
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
you might have it installed.
As @devi mentioned
If you decide to grab gacutil files from existing installation, note that from .NET 4.0 is three files: gacutil.exe gacutil.exe.config and 1033/gacutlrc.dll
To switch to another branch, discarding all uncommitted changes (e.g. resulting from Git's strange handling of line endings):
git checkout -f <branchname>
I had a working copy with hundreds of changed files (but empty git diff --ignore-space-at-eol
) which I couldn't get rid off with any of the commands I read here, and git checkout <branchname>
won't work, either - unless given the -f
(or --force
) option.
+
means a space only in application/x-www-form-urlencoded
content, such as the query part of a URL:
http://www.example.com/path/foo+bar/path?query+name=query+value
In this URL, the parameter name is query name
with a space and the value is query value
with a space, but the folder name in the path is literally foo+bar
, not foo bar
.
%20
is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with %20
and pluses with %2B
. This is what eg. encodeURIComponent()
does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer).
See Also HTML 4.01 Specification application/x-www-form-urlencoded
The author of this post (now deleted post) suggests checking your C:\Windows\System32
folder to make sure that the oci.dll
exists there. Copying in the file from the Oracle home directory solved this problem for me.
The following code gives you the answer. It essentially implements MAX(COUNT(*)) by using ALL. It has the advantage that it uses very basic commands and operations.
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr HAVING COUNT(title) >= ALL
(SELECT COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr)
In C++03, aggregate initialization only applies with syntax similar as below, which must be a separate statement and doesn't fit in a ctor initializer.
T var = {...};
The amount of capacity which is to be exhausted for the HashMap to increase its capacity ?
Load factor is by default 0.75 of the initial capacity (16) therefore 25% of the buckets will be free before there is an increase in the capacity & this makes many new buckets with new hashcodes pointing to them to exist just after the increase in the number of buckets.
If you set the loading factor to say 1.0 then something very interesting might happen.
Say you are adding an object x to your hashmap whose hashCode is 888 & in your hashmap the bucket representing the hashcode is free , so the object x gets added to the bucket, but now again say if you are adding another object y whose hashCode is also 888 then your object y will get added for sure BUT at the end of the bucket (because the buckets are nothing but linkedList implementation storing key,value & next) now this has a performance impact ! Since your object y is no longer present in the head of the bucket if you perform a lookup the time taken is not going to be O(1) this time it depends on how many items are there in the same bucket. This is called hash collision by the way & this even happens when your loading factor is less than 1.
Lower load factor = more free buckets = less chances of collision = high performance = high space requirement.
Correct me if i am wrong somewhere.
datePicker's onSelect equivalent is the dateSelected event.
$(function() {
$('.date-pick').datePicker( {
selectWeek: true,
inline: true,
startDate: '01/01/2000',
firstDay: 1,
}).bind('dateSelected', function(e, selectedDate, $td) {
alert(selectedDate);
});
});
This page has a good example showing the dateSelected event and other events being bound.
It's also possible that you have included /bin in your JAVA_HOME setting, and Ant is adding /bin to it - thereby not finding any exe's. It's happened to me :}
For me, the only way to reset the failed cherry-pick-attempt was
git reset --hard HEAD
Ran into this similar issue while using iframe to logout of sub sites with different domains. The solution I used was to load the iframe first, then update the source after the frame is loaded.
var frame = document.createElement('iframe');_x000D_
frame.style.display = 'none';_x000D_
frame.setAttribute('src', 'about:blank');_x000D_
document.body.appendChild(frame);_x000D_
frame.addEventListener('load', () => {_x000D_
frame.setAttribute('src', url);_x000D_
});
_x000D_
.tpl shows there is a smarty! Smarty is a template language to split out PHP code from HTML code. Which gives us to the ability to do design stuff on a page which has not included PHP code.
What this message from the glibc dynamic linker actually means is that the library mentioned (/lib/libpam.so.0
in your case) doesn't have the VERDEF
ELF section while the binary (authpam
in your case) has some version definitions in VERNEED
section for this library (presumably, libpam.so.0
). You can easily see it with readelf
, just look at .gnu.version_d
and .gnu.version_r
sections (or lack thereof).
So it's not a symbol version mismatch, because if the binary wanted to get some specific version via VERNEED
and the library didn't provide it in its actual VERDEF
, that would be a hard linker error and the binary wouldn't run at all (like this compared to this or that). It's that the binary wants some versions, but the library doesn't provide any information about its versions.
What does it mean in practice? Usually, exactly what is seen in this example — nothing, things just work ignoring versioning. Could things break? Of course, yes, so the other answers are correct in the fact that one should use the same libraries at runtime as the ones the binary was linked to at build time.
More information could be found in Ulrich Dreppers "ELF Symbol Versioning".
You can use HTTP Requests that are described in the Requests: HTTP for Humans user guide.
It depends on what type of machine/encoding generated your import file.
If you're getting it from an English or Western European version of Windows, your best bet is probably setting it to 'WIN1252'. If you are getting it from a different source, consult the list of character encodings here:
http://www.postgresql.org/docs/8.3/static/multibyte.html
If you're getting it from a Mac, you may have to run it through the "iconv" utility first to convert it from MacRoman to UTF-8.
Use the following import statement to import java.util.List
:
<%@ page import="java.util.List" %>
BTW, to import more than one class, use the following format:
<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>
After installing the gems, if you want to know where a particular gem is. Try typing:
gem list
You will be able to see the list of gems you have installed. Now use bundle show
and name the gem you want to know the path for, like this:
bundle show <gemName>
Or (as of younger versions of bundler):
bundle info <gemName>
AFAIK you cannot use VBA Excel to create custom tab in the Excel ribbon. You can however hide/make visible a ribbon component using VBA. Additionally, the link that you mentioned above is for MS Project and not MS Excel.
I create tabs for my Excel Applications/Add-Ins using this free utility called Custom UI Editor.
Edit: To accommodate new request by OP
Here is a short tutorial as promised:
After you have installed the Custom UI Editor (CUIE), open it and then click on File | Open and select the relevant Excel File. Please ensure that the Excel File is closed before you open it via CUIE. I am using a brand new worksheet as an example.
Right click as shown in the image below and click on "Office 2007 Custom UI Part". It will insert the "customUI.xml"
Next Click on menu Insert | Sample XML | Custom Tab. You will notice that the basic code is automatically generated. Now you are all set to edit it as per your requirements.
Let's inspect the code
label="Custom Tab"
: Replace "Custom Tab" with the name which you want to give your tab. For the time being let's call it "Jerome".
The below part adds a custom button.
<button id="customButton" label="Custom Button" imageMso="HappyFace" size="large" onAction="Callback" />
imageMso
: This is the image that will display on the button. "HappyFace" is what you will see at the moment. You can download more image ID's here.
onAction="Callback"
: "Callback" is the name of the procedure which runs when you click on the button.
With that, let's create 2 buttons and call them "JG Button 1" and "JG Button 2". Let's keep happy face as the image of the first one and let's keep the "Sun" for the second. The amended code now looks like this:
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<ribbon startFromScratch="false">
<tabs>
<tab id="MyCustomTab" label="Jerome" insertAfterMso="TabView">
<group id="customGroup1" label="First Tab">
<button id="customButton1" label="JG Button 1" imageMso="HappyFace" size="large" onAction="Callback1" />
<button id="customButton2" label="JG Button 2" imageMso="PictureBrightnessGallery" size="large" onAction="Callback2" />
</group>
</tab>
</tabs>
</ribbon>
</customUI>
Delete all the code which was generated in CUIE and then paste the above code in lieu of that. Save and close CUIE. Now when you open the Excel File it will look like this:
Now the code part. Open VBA Editor, insert a module, and paste this code:
Public Sub Callback1(control As IRibbonControl)
MsgBox "You pressed Happy Face"
End Sub
Public Sub Callback2(control As IRibbonControl)
MsgBox "You pressed the Sun"
End Sub
Save the Excel file as a macro enabled file. Now when you click on the Smiley or the Sun you will see the relevant message box:
Hope this helps!
i have a solution for dynamically created variable value and combined all value in a variable.
if($_SERVER['REQUEST_METHOD']=='POST'){
$r=0;
for($i=1; $i<=4; $i++){
$a = $_POST['a'.$i];
$r .= $a;
}
echo $r;
}
SELECT TOP 1 column_name, LEN(column_name) AS Lenght FROM table_name ORDER BY LEN(column_name) DESC
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
Make sure you are using volumes for all the persistent data (configuration, logs, or application data) which you store on the containers related to the state of the processes inside that container. Update your Dockerfile and rebuild the image with the changes you wanted, and restart the containers with your volumes mounted at their appropriate place.
I asked in the discussion:
does
ssh -T [email protected]
ouput the same username (in Hi [My Username]!
) as in the one used for the ssh url of your repo ([email protected]:username/repo.git
)?Sorry It not showing same name
That means somehow the credentials have changed.
One solution would be to at least copy %HOME%\.ssh\id_rsa.pub
in the SSH keys section of the right GitHub account
The OP adds:
I am working on private repo. So In [email protected]:username/repo.git,
I replied:
If you were able to clone/push to that repo whose username is not your own GitHub account, that must be because you had your previous public ssh key added as a contributor to that repo by the repo's owner.
What next is to ask that same repo owner to add your current public ssh key
%HOME%\.ssh\id_rsa.pub
to the repo contributor list.
So check with the owner that you (meaning your public ssh key) are declared as a contributor.
You probably haven't added a reference to Microsoft XML
(any version) for Dim objHTTP As New MSXML2.XMLHTTP
in the VBA window's Tools/References... dialog.
Also, it's a good idea to avoid using late binding (CreateObject
...); better to use early binding (Dim objHTTP As New MSXML2.XMLHTTP
), as early binding allows you to use Intellisense to list the members and do all sorts of design-time validation.
Something like:
var min = dates.reduce(function (a, b) { return a < b ? a : b; });
var max = dates.reduce(function (a, b) { return a > b ? a : b; });
Tested on Chrome 15.0.854.0 dev
PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options
The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values
Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String
Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True
End Sub
import sys
sys.argv[1:]
will give you a list of arguments (not including the name of the python file)
The below code expands upon the top answer chosen for this thread, to get rid of the bottom border and set text color:
The last two coded lines of this code set transparency. I borrowed that code from this thread and it worked perfectly!
The "clipsToBounds" property was code I found which got rid of the bottom border line with OR without transparency set (so if you decide to go with a solid white/black/etc. background instead, there will still be no border line).
The "tintColor" line (2nd coded line) set my back button to a light grey
I kept barTintColor as a backup. I don't know why transparency would not work, but if it doesn't, I want my bg white as I used to have it
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.tintColor = UIColor.lightGray
navigationBarAppearace.barTintColor = UIColor.white
navigationBarAppearace.clipsToBounds = true
navigationBarAppearace.isTranslucent = true
navigationBarAppearace.setBackgroundImage(UIImage(), for: .default)
navigationBarAppearace.shadowImage = UIImage()
Directly parsing a date string that is not in yyyy-mm-dd format, like in the accepted answer does not work. The answer by vitran does work but has some JQuery mixed in so I reworked it a bit.
// Takes two strings as input, format is dd/mm/yyyy
// returns true if d1 is smaller than or equal to d2
function compareDates(d1, d2){
var parts =d1.split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts = d2.split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 <= d2;
}
P.S. would have commented directly to vitran's post but I don't have the rep to do that.
If you look at the output you receive from print()
and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b
):
b'{\n "note":"This file .....
If you fetch the URL using a tool such as curl -v
, you will see that the content type is
Content-Type: application/json; charset=utf-8
So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.
Change the last line of code to this:
info = json.loads(js.decode("utf-8"))
use
=VLOOKUP(D4,F4:G9,2)
with the range F4:G9:
0 0.1
1 0.15
5 0.2
15 0.3
30 1
100 1.3
and D4
being the value in question, e.g. 18.75
-> result: 0.3
I came across this post searching how to add an extra directory for resources. I found a solution that may be useful to someone. Here is my final configuration to get that:
sourceSets {
main {
resources {
srcDirs "src/main/resources", "src/main/configs"
}
}
}
In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> sum(l)
6
>>> sum = 0 # oops! shadowed a builtin!
>>> sum(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> import sys
>>> sum = sys.modules['__builtin__'].sum # -- fixing sum
>>> sum(l)
6
This also comes in handy if you happened to assign a value to any other builtin, like dict
or list
Task method worked for me, except Browser.Task.IsCompleted has to be changed to PageLoaded.Task.IsCompleted.
Sorry I didnt add comment, that is because I need higher reputation to add comments.
i don't know of a simple css(2.1 standard)-only solution for circles, but for squares you can do easily:
.squared {
border: 2x solid black;
}
then, use the following html code:
<img src="…" alt="an image " class="squared" />
I can see that the accepted answer uses position: absolute;
instead of float: left
. In case you want to use float: left
with the following structure,
<div class="parent">
<div class="child-left floatLeft"></div>
<div class="child-right floatLeft"></div>
</div>
Give position: auto;
to the parent so that it will contain its children height.
.parent {
position: auto;
}
.floatLeft {
float: left
}
In code level also, you could add your lib to the project using the compiler directives #pragma.
example:
#pragma comment( lib, "yourLibrary.lib" )
Search within file content
and Search External Files
remove all lines of codes referencing the missing entity. They will look like this:
public virtual DbSet< Entity1> Entity1 { get; set; }
This error is common to tables deleted from the database.
When one drops a table in the database, or one just changes the web.config.connectionStrings
for the EF Mapped database, to point to a new one and not the one used to generate the original mappings is the problem.
It is this new db these entities with the 3027 error aren't present.
MacOS: composer is available on brew now (Tested on Php7+):
brew install composer
Install instructions on the Composer Docs page are quite to the point otherwise.
There is no command based text editors in windows (at least from Windows 7). But you can try the vi windows clone available here : http://www.vim.org/
Those GCD functions provided by Commons-Math and Guava have some differences.
ArithematicException.class
only for Integer.MIN_VALUE
or Long.MIN_VALUE
.
IllegalArgumentException.class
for any negative values.public class AesCryptoService
{
private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");
public static string EncryptStringToBytes_Aes(string plainText)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
public static string DecryptStringFromBytes_Aes(string Text)
{
if (Text == null || Text.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
string plaintext = null;
byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
another way, will also work on MySQL and PostgreSQL
select TABLE_NAME from INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = 'BASE TABLE'
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
<p>31<sup>st</sup> March 2015</p>
_x000D_
You can use
1<sup>st</sup>
2<sup>nd</sup>
3<sup>rd</sup>
4<sup>th</sup>
for positioning the suffix
Spring-boot allows us several methods to provide externalized configurations , you can try using application.yml or yaml files instead of the property file and provide different property files setup according to different environments.
We can separate out the properties for each environment into separate yml files under separate spring profiles.Then during deployment you can use :
java -jar -Drun.profiles=SpringProfileName
to specify which spring profile to use.Note that the yml files should be name like
application-{environmentName}.yml
for them to be automatically taken up by springboot.
To read from the application.yml or property file :
The easiest way to read a value from the property file or yml is to use the spring @value annotation.Spring automatically loads all values from the yml to the spring environment , so we can directly use those values from the environment like :
@Component
public class MySampleBean {
@Value("${name}")
private String sampleName;
// ...
}
Or another method that spring provides to read strongly typed beans is as follows:
YML
ymca:
remote-address: 192.168.1.1
security:
username: admin
Corresponding POJO to read the yml :
@ConfigurationProperties("ymca")
public class YmcaProperties {
private InetAddress remoteAddress;
private final Security security = new Security();
public boolean isEnabled() { ... }
public void setEnabled(boolean enabled) { ... }
public InetAddress getRemoteAddress() { ... }
public void setRemoteAddress(InetAddress remoteAddress) { ... }
public Security getSecurity() { ... }
public static class Security {
private String username;
private String password;
public String getUsername() { ... }
public void setUsername(String username) { ... }
public String getPassword() { ... }
public void setPassword(String password) { ... }
}
}
The above method works well with yml files.
Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
EDIT Ignore this answer. There are now better answers. See the comments. Use + theme_classic()
EDIT
This is a better version. The bug mentioned below in the original post remains (I think). But the axis line is drawn under the panel. Therefore, remove both the panel.border
and panel.background
to see the axis lines.
library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
ggplot(df, aes(x = a, y = b)) + geom_point() +
theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Original post
This gets close. There was a bug with axis.line
not working on the y-axis (see here), that appears not to be fixed yet. Therefore, after removing the panel border, the y-axis has to be drawn in separately using geom_vline
.
library(ggplot2)
library(grid)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
p = ggplot(df, aes(x = a, y = b)) + geom_point() +
scale_y_continuous(expand = c(0,0)) +
scale_x_continuous(expand = c(0,0)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
p
The extreme points are clipped, but the clipping can be undone using code by baptiste.
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Or use limits
to move the boundaries of the panel.
ggplot(df, aes(x = a, y = b)) + geom_point() +
xlim(0,22) + ylim(.95, 2.1) +
scale_x_continuous(expand = c(0,0), limits = c(0,22)) +
scale_y_continuous(expand = c(0,0), limits = c(.95, 2.2)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List
; it's an immutable data structure, like a Java String.
What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List. (Source)
Instead of using lists for such use cases, I suggest to either use an ArrayBuffer
or a ListBuffer
. Those datastructures are designed to have new elements added.
Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:
scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer
scala> var fruits = new ListBuffer[String]()
fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()
scala> fruits += "Apple"
res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)
scala> fruits += "Banana"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)
scala> fruits += "Orange"
res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)
scala> val fruitsList = fruits.toList
fruitsList: List[String] = List(Apple, Banana, Orange)
you need to wrap your text inside div and float it left while wrapper div should have height, and I've also added line height for vertical alignment
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray;height:30px;">
<div style="float:left;line-height:30px;">Contact Details</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
</div>
also js fiddle here =) http://jsfiddle.net/xQgSm/
I figured it out!
With almost 2 hours worth of trial and error, i figured it out.
This WORKS and is what you do to pass variables to remote job:
def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2=${env.param2}")
Use \n to separate two parameters, no spaces..
As opposed to parameters: '''someparams'''
we use paramters: "someparams"
the " ... " is what gets us the values of the desired variables. (These are double quotes, not two single quotes)
the ''' ... ''' or ' ... ' will not get us those values. (Three single quotes or just single quotes)
All parameters here are defined in environment{} block at the start of the pipeline and are modified in stages>steps>scripts wherever necessary.
I also tested and found that when you use " ... " you cannot use something like ''' ... "..." ''' or "... '..'..." or any combination of it...
The catch here is that when you are using "..." in parameters section, you cannot pass a string parameter; for example This WILL NOT WORK:
def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2='param2'")
if you want to pass something like the one above, you will need to set an environment variable param2='param2' and then use ${env.param2} in the parameters section of remote trigger plugin step
Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.
mongoexport -d <database> -c <collection_name>
Also helpful:
-o
: write the output to file, otherwise standard output is used (docs)
--jsonArray
: generates a valid json document, instead of one json object per line (docs)
--pretty
: outputs formatted json (docs)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
I have searched a lot for a solution in which I can compare two array of objects with different attribute names (something like a left outer join). I came up with this solution. Here I used Lodash. I hope this will help you.
var Obj1 = [
{id:1, name:'Sandra'},
{id:2, name:'John'},
];
var Obj2 = [
{_id:2, name:'John'},
{_id:4, name:'Bobby'}
];
var Obj3 = lodash.differenceWith(Obj1, Obj2, function (o1, o2) {
return o1['id'] === o2['_id']
});
console.log(Obj3);
// {id:1, name:'Sandra'}
you can easily search for a line like "@Test" and then use the quickfix "add junit 4 library to the build path" at this line. i think this is faster than adding junit manually to the project.
When you provide a path, it can be absolute/rooted, or relative. If you provide a relative path, it will be resolved by taking the working directory of the running process.
Example:
string text = File.ReadAllText("Some\\Path.txt"); // relative path
The above code has the same effect as the following:
string text = File.ReadAllText(
Path.Combine(Environment.CurrentDirectory, "Some\\Path.txt"));
If you have files that are always going to be in the same location relative to your application, just include a relative path to them, and they should resolve correctly on different computers.
Tried the answer from @kta but didn't work for me.
I am using MySQL 8.0
This worked for me:
mysql> SET PASSWORD FOR 'root'@'localhost' = 'yourpassword'
For anyone stumbling upon this question, there are now two projects that create exes out of your node projects, Pkg and Electron.atom.io , they differ slightly:
Use Arrays.asList()
to wrap the array in a List<String>
, which does have a contains()
method:
Arrays.asList(dan).contains(say.getText())
One cheeky solution :
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
HTML :
<form id="form1" runat="server">
<div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
Print me I am in 1st Div
</div>
<div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
I am not going to print
</div>
<input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>
In my case i just went through following steps in windows 10.
OracelServeceXE
, OracleXEClrAgeng
, OracleXETNSListener
Start
/Restart
You can do some thing like this,
Initialize with empty array and assign the values later
String importRt = "23:43 43:34";
if(null != importRt) {
importArray = Arrays.stream(importRt.split(" "))
.map(String::trim)
.toArray(String[]::new);
}
System.out.println(Arrays.toString(exportImportArray));
Hope it helps..
AFAIK, there is no a interactive option for output to file, there is a previous SO question related with this: Printing mongodb shell output to File
However, you can log all the shell session if you invoked the shell with tee command:
$ mongo | tee file.txt
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye
Then you'll get a file with this content:
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye
To remove all the commands and keep only the json output, you can use a command similar to:
tail -n +3 file.txt | egrep -v "^>|^bye" > output.json
Then you'll get:
{ "this" : "is a test" }
{ "this" : "is another test" }
I've discovered that if the filename has 300
in it, AdBlock blocks the page and throws a ERR_BLOCKED_BY_CLIENT
error.
Are you using virtualenv
? If yes, deactivate the virtualenv. If you are not using, it is already installed widely (system level). Try to upgrade package.
pip install flake8 --upgrade
Adding to @pranay-rana's list:
Third way is:
function passFromValue(){
var x = 15;
return x;
}
function passToValue() {
var y = passFromValue();
console.log(y);//15
}
passToValue();
You cannot add style to an SVG <g>
element. Its only purpose is to group children. That means, too, that style attributes you give to it are given down to its children, so a fill="green"
on the <g>
means an automatic fill="green"
on its child <rect>
(as long as it has no own fill
specification).
Your only option is to add a new <rect>
to the SVG and place it accordingly to match the <g>
children's dimensions.
Here's a SCSS version of @Patrick's mixin.
$mqIterations: 19;
@mixin fontResize($iterations)
{
$i: 1;
@while $i <= $iterations
{
@media all and (min-width: 100px * $i) {
body { font-size:0.2em * $i; }
}
$i: $i + 1;
}
}
@include fontResize($mqIterations);
In typescript, the declaration is something like this:
const regex : RegExp = /.+\*.+/;
using RegExp constructor:
const regex = new RegExp('.+\\*.+');
What I found helpful is this condition that is below.
String tempEmail = "";
JTextField tf1 = new JTextField();
tf1.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent evt){
tempEmail = ((JTextField)evt.getSource()).getText() + String.valueOf(evt.getKeyChar());
}
});
Not an answer, but just some food for thought.
If class is having overloaded index/subscript operator, the expression 0[x]
will not work:
class Sub
{
public:
int operator [](size_t nIndex)
{
return 0;
}
};
int main()
{
Sub s;
s[0];
0[s]; // ERROR
}
Since we dont have access to int class, this cannot be done:
class int
{
int operator[](const Sub&);
};
FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color
, fill
, etc.
I did eventually figure out that some filter
properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
background: transparent;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
<input type="date" />_x000D_
</body>
_x000D_
Hopefully this helps some people as for the most part chrome even directly says this is impossible.
Don't mess with the visibility flags of the container - FragmentTransaction.hide/show does that internally for you.
So the correct way to do this is:
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(somefrag)
.commit();
OR if you are using android.support.v4.app.Fragment
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.show(somefrag)
.commit();
There is no do-while loop in Python.
This is a similar construct, taken from the link above.
while True:
do_something()
if condition():
break
You should get the array like in $_POST['id']. So you should be able to do this:
foreach ($_POST['id'] as $key => $value) {
echo $value . "<br />";
}
Input names should be same:
<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...
First, open the terminal.
Then, type
cd ~
touch .sure
chmod 700 .sure
Next, open .sure and paste this inside.
#!/bin/bash --init-file
PS1='> '
alias y='
$1
exit
'
alias n='Taskkill /IM %Terminal% /f'
echo ''
echo 'Are you sure? Answer y or n.'
echo ''
After that, close the file.
~/.sure ; ENTER COMMAND HERE
This will give you a prompt of are you sure before continuing the command.
int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
var nonRepeats = (from n in numbers select n).Distinct();
foreach (var d in nonRepeats)
{
Response.Write(d);
}
OUTPUT
1234567890
In C++ copying the object means cloning. There is no any special cloning in the language.
As the standard suggests, after copying you should have 2 identical copies of the same object.
There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.
this is a version problem change version > 2.4 to 1.9 solve it
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-xml-provider</artifactId>
<version>2.4.1</version>
to
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
Question content may have changed, so I'll try to answer thoroughly.
Destructuring allows you to pull values out of anything with properties. You can also define default values when null/undefined and name aliases.
const options = {
filters : {
firstName : "abc"
}
}
const {filters: {firstName = "John", lastName = "Smith"}} = options
// firstName = "abc"
// lastName = "Smith"
NOTE: Capitalization matters
If working with an array, here is how you do it.
In this case, name is extracted from each object in the array, and given its own alias. Since the object might not exist = {}
was also added.
const options = {
filters: [{
name: "abc",
value: "lots"
}]
}
const {filters:[{name : filter1 = "John"} = {}, {name : filter2 = "Smith"} = {}]} = options
// filter1 = "abc"
// filter2 = "Smith"
Browser Support 92% July 2020
This expression will force the first letter to be alphabetic and the remaining characters to be alphanumeric or any of the following special characters: @,#,%,&,*
^[A-Za-z][A-Za-z0-9@#%&*]*$
If at all anyone is looking to convert data in 1 variable that lies in 2 or 3 different lines like below
'Data1
Data2'
And you want to display data as 'Data1 Data2' then use below
select TRANSLATE ('Data1
Data2', ''||CHR(10), ' ') from dual;
it took me hrs to get the right output. Thanks to me I just saved you 1 or 2 hrs :)
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
To read one byte:
file.read(1)
8 bits is one byte.
Sounds like you need to round to the nearest 0.5. I see no version of round
in the C# API that does this (one version takes a number of decimal digits to round to, which isn't the same thing).
Assuming you only have to deal with integer numbers of tenths, it's sufficient to calculate round (num * 2) / 2
. If you're using arbitrarily precise decimals, it gets trickier. Let's hope you don't.
I've had good luck with XLConnect
: http://cran.r-project.org/web/packages/XLConnect/index.html
I was getting the following errors:
Failed to decode downloaded font: [...]/fonts/glyphicons-halflings-regular.woff2
OTS parsing error: invalid version tag
which was fixed after downloading the raw file directly from:
https://github.com/twbs/bootstrap/blob/master/fonts/glyphicons-halflings-regular.woff2
The problem was that there was a proxy error when downloading the file (it contained the HTML error message).
You have to deal with the exception at commit time and repeat the transaction.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x=54.999999999999943157;
int y=ceil(x);//The ceil() function returns the smallest integer no less than x
return 0;
}
I have used this way lots time ...
@Component({_x000D_
selector: "data",_x000D_
template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
this.http.get(path).subscribe({_x000D_
DataComponent.setSubscribeData(res);_x000D_
})_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
DataComponent.subscribeData=data;_x000D_
return data;_x000D_
}
_x000D_
use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...
Next time, from the Take Offline dialog, remember to check the 'Drop All Active Connections' checkbox. I was also on SQL_EXPRESS on local machine with no connections, but this slowdown happened for me unless I checked that checkbox.
To avoid caching of output you might wanna try pexpect,
child = pexpect.spawn(launchcmd,args,timeout=None)
while True:
try:
child.expect('\n')
print(child.before)
except pexpect.EOF:
break
PS : I know this question is pretty old, still providing the solution which worked for me.
PPS: got this answer from another question
And do not forget the "new" service type (from the k8s docu):
ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value. No proxying of any kind is set up.
Note: You need either kube-dns version 1.7 or CoreDNS version 0.0.8 or higher to use the ExternalName type.
if (@available(iOS 13.0, *)) {
_window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
}
let my_u8: u8 = "42".parse::<u8>().unwrap();
let my_u32: u32 = "42".parse::<u32>().unwrap();
// or, to be safe, match the `Err`
match "foobar".parse::<i32>() {
Ok(n) => do_something_with(n),
Err(e) => weep_and_moan(),
}
str::parse::<u32>
returns a Result<u32, core::num::ParseIntError>
and Result::unwrap
"Unwraps a result, yielding the content of an Ok
[or] panics if the value is an Err
, with a panic message provided by the Err
's value."
str::parse
is a generic function, hence the type in angle brackets.
Just call moment as a function without any arguments:
moment()
For timezone information with moment, look at the moment-timezone
package: http://momentjs.com/timezone/
Try this ( also corrected check for upper case and lower case, it had a bug since you grouped them as [a-zA-Z] it only looks for atleast one lower or upper. So separated them out ):
(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)^(.{8,15})$
Update: I found that the regex doesn't really work as expected and this is not how it is supposed to be written too!
Try something like this:
(?=^.{8,15}$)(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?!.*\s).*$
(Between 8 and 15 inclusive, contains atleast one digit, atleast one upper case and atleast one lower case and no whitespace.)
And I think this is easier to understand as well.
Yess, possible with conditions:
If you have your app installed in the user phone and a server app communicating with this app, and there at last one of location service providers activated in the user phone, and some horrible android permissions!
In most of android phones there 3 location providers that can give exact location (GPS_PROVIDER 1m) or estimated (NETWORK_PROVIDER around 2-20m) and PASSIVE_PROVIDER (more in LocationManager official documentation).
1* App sends SMS to user's phone
Yess, can be server app or you create an android app if you want something automated, so you can do it manually by sending SMS from your default SMS app! I use Kannel: Open Source WAP and SMS Gateway and here (lot of APIs to send SMS )
2* App receives SMS at user's phone from the SMS sender
Yess, you can get all received SMS, and you can filter them by sender phone number! and do some actions when your specified sms received, basic tuto here (i do some actions according to the content of my SMS)
3* App gets location coordinates of the user's phone
Yess, you can get actual user coordinates easily if one of location providers is activated, so you can get last known location when the user have activated one of location providers, if those disabled or the phone don't have GPS hardware you can use Open Cell Id api to get the nearest cell coordinates(10m-10Km) or Loc8 api but those not available in all around the world, and some apps use IP location apis to get the country, city and province, here the simplest way to get current user location.
4* App sends location coordinates to the SMS sender via SMS
Yess, you can get sender phone number and send user location, immediately when SMS received or at specified times in the day.
(Those 4 yesses for you :) )
Viber and other apps that access to users locations, identify there users by there phone numbers by obligating them to send SMS to the server app to create an account and activate the free service (Ex:VOIP) , and lunch a service that can:
And your application users must accept all of that when installing it, of corse i don't gonna install apps like this because i read permissions before installing :) and permissions maybe something like that:
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<-- and more if you wanna more -->
The final user will accept for something like that (those permissions of an android app u asked about):
This app has access to these permissions:
Your accounts -create accounts and set passwords -find accounts on the device -add or remove accounts -use accounts on the device -read Google service configuration
Your location -approximate location (network-based) -precise location (GPS and network-based)
Your messages -receive text messages (SMS) -send SMS messages -edit your text messages (SMS or MMS) -read your text messages (SMS or MMS)
Network communication -receive data from Internet -full network access -view Wi-Fi connections -view network connections -change network connectivity
Phone calls -read phone status and identity -directly call phone numbers
Storage -modify or delete the contents of your USB storage
Your applications information -retrieve running apps -close other apps -run at startup
Bluetooth -pair with Bluetooth devices -access Bluetooth settings
Camera -take pictures and videos
Other Application UI -draw over other apps
Microphone -record audio
Lock screen -disable your screen lock
Your social information -read your contacts -modify your contacts -read call log -write call log -read your social stream -write to your social stream
Development tools -read sensitive log data
System tools -modify system settings -send sticky broadcast -test access to protected storage
Affects battery -control vibration -prevent device from sleeping
Audio settings -change your audio settings
Sync Settings -read sync settings -toggle sync on and off -read sync statistics
Wallpaper -set wallpaper
You'll need to join twice:
SELECT home.*, away.*, g.network, g.date_start
FROM game AS g
INNER JOIN team AS home
ON home.importid = g.home
INNER JOIN team AS away
ON away.importid = g.away
ORDER BY g.date_start DESC
LIMIT 7
To add multiples params or headers you can do the following:
constructor(private _http: HttpClient) {}
//....
const url = `${environment.APP_API}/api/request`;
let headers = new HttpHeaders().set('header1', hvalue1); // create header object
headers = headers.append('header2', hvalue2); // add a new header, creating a new object
headers = headers.append('header3', hvalue3); // add another header
let params = new HttpParams().set('param1', value1); // create params object
params = params.append('param2', value2); // add a new param, creating a new object
params = params.append('param3', value3); // add another param
return this._http.get<any[]>(url, { headers: headers, params: params })
And here is a quick benchmark for both #sample
and #rand
:
irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1* x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1> x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
user system total real
sample 3.870000 0.020000 3.890000 ( 3.888147)
rand 0.150000 0.000000 0.150000 ( 0.153557)
So, doing rand(a..b)
is the right thing
its because of Headerfiles define what the class contains (Members, data-structures) and cpp files implement it.
And of course, the main reason for this is that you could include one .h File multiple times in other .h files, but this would result in multiple definitions of a class, which is invalid.
Angular: "9.0.0"
Angular CLI: 9.0.1
Node: 13.10.1
OS: linux x64
.html file
<input [(ngModel)]="userConsent" id="userConsent" required type="checkbox"/> " I Accept"
.ts file
userConsent: boolean = false;
For a more flexible and faster approach to data aggregation, check out the collap
function in the collapse R package available on CRAN:
library(collapse)
# Simple aggregation with one function
head(collap(df1, x1 + x2 ~ year + month, fmean))
year month x1 x2
1 2000 1 -1.217984 4.008534
2 2000 2 -1.117777 11.460301
3 2000 3 5.552706 8.621904
4 2000 4 4.238889 22.382953
5 2000 5 3.124566 39.982799
6 2000 6 -1.415203 48.252283
# Customized: Aggregate columns with different functions
head(collap(df1, x1 + x2 ~ year + month,
custom = list(fmean = c("x1", "x2"), fmedian = "x2")))
year month fmean.x1 fmean.x2 fmedian.x2
1 2000 1 -1.217984 4.008534 3.266968
2 2000 2 -1.117777 11.460301 11.563387
3 2000 3 5.552706 8.621904 8.506329
4 2000 4 4.238889 22.382953 20.796205
5 2000 5 3.124566 39.982799 39.919145
6 2000 6 -1.415203 48.252283 48.653926
# You can also apply multiple functions to all columns
head(collap(df1, x1 + x2 ~ year + month, list(fmean, fmin, fmax)))
year month fmean.x1 fmin.x1 fmax.x1 fmean.x2 fmin.x2 fmax.x2
1 2000 1 -1.217984 -4.2460775 1.245649 4.008534 -1.720181 10.47825
2 2000 2 -1.117777 -5.0081858 3.330872 11.460301 9.111287 13.86184
3 2000 3 5.552706 0.1193369 9.464760 8.621904 6.807443 11.54485
4 2000 4 4.238889 0.8723805 8.627637 22.382953 11.515753 31.66365
5 2000 5 3.124566 -1.5985090 7.341478 39.982799 31.957653 46.13732
6 2000 6 -1.415203 -4.6072295 2.655084 48.252283 42.809211 52.31309
# When you do that, you can also return the data in a long format
head(collap(df1, x1 + x2 ~ year + month, list(fmean, fmin, fmax), return = "long"))
Function year month x1 x2
1 fmean 2000 1 -1.217984 4.008534
2 fmean 2000 2 -1.117777 11.460301
3 fmean 2000 3 5.552706 8.621904
4 fmean 2000 4 4.238889 22.382953
5 fmean 2000 5 3.124566 39.982799
6 fmean 2000 6 -1.415203 48.252283
Note: You can use base functions like mean, max
etc. with collap
, but fmean, fmax
etc. are C++ based grouped functions offered in the collapse package which are significantly faster (i.e. the performance on large data aggregations is the same as data.table while providing greater flexibility, and these fast grouped functions can also be used without collap
).
Note2: collap
also supports flexible multitype data aggregation, which you can of course do using the custom
argument, but you can also apply functions to numeric and non-numeric columns in a semi-automated way:
# wlddev is a data set of World Bank Indicators provided in the collapse package
head(wlddev)
country iso3c date year decade region income OECD PCGDP LIFEEX GINI ODA
1 Afghanistan AFG 1961-01-01 1960 1960 South Asia Low income FALSE NA 32.292 NA 114440000
2 Afghanistan AFG 1962-01-01 1961 1960 South Asia Low income FALSE NA 32.742 NA 233350000
3 Afghanistan AFG 1963-01-01 1962 1960 South Asia Low income FALSE NA 33.185 NA 114880000
4 Afghanistan AFG 1964-01-01 1963 1960 South Asia Low income FALSE NA 33.624 NA 236450000
5 Afghanistan AFG 1965-01-01 1964 1960 South Asia Low income FALSE NA 34.060 NA 302480000
6 Afghanistan AFG 1966-01-01 1965 1960 South Asia Low income FALSE NA 34.495 NA 370250000
# This aggregates the data, applying the mean to numeric and the statistical mode to categorical columns
head(collap(wlddev, ~ iso3c + decade, FUN = fmean, catFUN = fmode))
country iso3c date year decade region income OECD PCGDP LIFEEX GINI ODA
1 Aruba ABW 1961-01-01 1962.5 1960 Latin America & Caribbean High income FALSE NA 66.58583 NA NA
2 Aruba ABW 1967-01-01 1970.0 1970 Latin America & Caribbean High income FALSE NA 69.14178 NA NA
3 Aruba ABW 1976-01-01 1980.0 1980 Latin America & Caribbean High income FALSE NA 72.17600 NA 33630000
4 Aruba ABW 1987-01-01 1990.0 1990 Latin America & Caribbean High income FALSE 23677.09 73.45356 NA 41563333
5 Aruba ABW 1996-01-01 2000.0 2000 Latin America & Caribbean High income FALSE 26766.93 73.85773 NA 19857000
6 Aruba ABW 2007-01-01 2010.0 2010 Latin America & Caribbean High income FALSE 25238.80 75.01078 NA NA
# Note that by default (argument keep.col.order = TRUE) the column order is also preserved
This should cover you:
String lines[] = string.split("\\r?\\n");
There's only really two newlines (UNIX and Windows) that you need to worry about.
Working for me (remember to change 3 things in code):
previousWidth (original size of image)
map_ID (id of your image map)
img_ID (id of your image)
HTML:
<div style="width:100%;">
<img id="img_ID" src="http://www.gravatar.com/avatar/0865e7bad648eab23c7d4a843144de48?s=128&d=identicon&r=PG" usemap="#map" border="0" width="100%" alt="" />
</div>
<map id="map_ID" name="map">
<area shape="poly" coords="48,10,80,10,65,42" href="javascript:;" alt="Bandcamp" title="Bandcamp" />
<area shape="poly" coords="30,50,62,50,46,82" href="javascript:;" alt="Facebook" title="Facebook" />
<area shape="poly" coords="66,50,98,50,82,82" href="javascript:;" alt="Soundcloud" title="Soundcloud" />
</map>
Javascript:
window.onload = function () {
var ImageMap = function (map, img) {
var n,
areas = map.getElementsByTagName('area'),
len = areas.length,
coords = [],
previousWidth = 128;
for (n = 0; n < len; n++) {
coords[n] = areas[n].coords.split(',');
}
this.resize = function () {
var n, m, clen,
x = img.offsetWidth / previousWidth;
for (n = 0; n < len; n++) {
clen = coords[n].length;
for (m = 0; m < clen; m++) {
coords[n][m] *= x;
}
areas[n].coords = coords[n].join(',');
}
previousWidth = img.offsetWidth;
return true;
};
window.onresize = this.resize;
},
imageMap = new ImageMap(document.getElementById('map_ID'), document.getElementById('img_ID'));
imageMap.resize();
return;
}
JSFiddle: http://jsfiddle.net/p7EyT/154/
There could be a perceptible difference.
String.format
is quite complex and uses a regular expression underneath, so don't make it a habit to use it everywhere, but only where you need it.
StringBuilder
would be an order of magnitude faster (as someone here already pointed out).
You can use the DOMSubtreeModified event
$(something).bind('DOMSubtreeModified' ...
But this will fire even if the dimensions don't change, and reassigning the position whenever it fires can take a performance hit. In my experience using this method, checking whether the dimensions have changed is less expensive and so you might consider combining the two.
Or if you are directly altering the div (rather than the div being altered by user input in unpredictable ways, like if it is contentEditable), you can simply fire a custom event whenever you do so.
Downside: IE and Opera don't implement this event.
Hm, combining LEFT and RIGHT JOIN with UNION could do this:
SELECT p.LastName, p.FirstName, o.OrderNo
FROM persons AS p
LEFT JOIN
orders AS o
ON p.P_Id = Orders.P_Id
UNION ALL
SELECT p.LastName, p.FirstName, o.OrderNo
FROM persons AS p
RIGHT JOIN
orders AS o
ON p.P_Id = Orders.P_Id
WHERE p.P_Id IS NULL
Use org.springframework.web.servlet.config.annotation.WebMvcConfigurer
With Spring Boot 2.1.4.RELEASE (Spring Framework 5.1.6.RELEASE), do like this
package vn.bkit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // Deprecated.
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {
@Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".html");
return resolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
No, you can't do it by using an actual <select>
, but there are techniques that allow you to "replace" them with javascript solutions that look better.
Here's a good article on the topic: <select> Something New
You're looking for the function strcmp
, or strncmp
from string.h
.
Since strings are just arrays, you need to compare each character, so this function will do that for you:
if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
Further reading: strcmp at cplusplus.com
You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.
For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.
If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp
. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.
For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.
If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.
With the new version of React Router (using 2.0.1 now), you can use an asterisk as a path to route all 'other paths'.
So it would look like this:
<Route route="/" component={App}>
<Route path=":area" component={Area}>
<Route path=":city" component={City} />
<Route path=":more-stuff" component={MoreStuff} />
</Route>
<Route path="*" component={NotFoundRoute} />
</Route>
I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :
function buildOptions (object) {
var validTypes = ['string', 'number', 'boolean'];
var value;
var key;
for (key in object) {
value = object[key];
if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
object[key + '=' + value] = true;
}
}
return object;
}
With this hack, an object like this:
var contact = {
"id": 1364,
"author_name": "Mr Nobody",
"notified_type": "friendship",
"action": "create"
};
Will look like this before transformation:
var contact = {
"id": 1364,
"id=1364": true,
"author_name": "Mr Nobody",
"author_name=Mr Nobody": true,
"notified_type": "friendship",
"notified_type=friendship": true,
"action": "create",
"action=create": true
};
And your mustache template will look like this:
{{#notified_type=friendship}}
friendship…
{{/notified_type=friendship}}
{{#notified_type=invite}}
invite…
{{/notified_type=invite}}
Note: Commenting out bind_ip can make your system vulnerable to security flaws. Please see Security Checklist. It is a better idea to add more IP addresses than to open up your system to everything.
You need to edit your /etc/mongod.conf file's bind_ip variable to include the IP of the computer you're using, or eliminate it altogether.
I was able to connect using the following mongod.conf file. I commented out bind_ip and uncommented port.
# mongod.conf
# Where to store the data.
# Note: if you run MongoDB as a non-root user (recommended) you may
# need to create and set permissions for this directory manually.
# E.g., if the parent directory isn't mutable by the MongoDB user.
dbpath=/var/lib/mongodb
# Where to log
logpath=/var/log/mongodb/mongod.log
logappend=true
port = 27017
# Listen to local interface only. Comment out to listen on all
interfaces.
#bind_ip = 127.0.0.1
# Disables write-ahead journaling
# nojournal = true
# Enables periodic logging of CPU utilization and I/O wait
#cpu = true
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
# Verbose logging output.
#verbose = true
# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true
# Enable db quota management
#quota = true
# Set oplogging level where n is
# 0=off (default)
# 1=W
# 2=R
# 3=both
# 7=W+some reads
#diaglog = 0
# Ignore query hints
#nohints = true
# Enable the HTTP interface (Defaults to port 28017).
#httpinterface = true
# Turns off server-side scripting. This will result in greatly limited
# functionality
#noscripting = true
# Turns off table scans. Any query that would do a table scan fails.
#notablescan = true
# Disable data file preallocation.
#noprealloc = true
# Specify .ns file size for new databases.
# nssize = <size>
# Replication Options
# In replicated MongoDB databases, specify the replica set name here
#replSet=setname
# Maximum size in megabytes for replication operation log
#oplogSize=1024
# Path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile
Don't forget to restart the mongod service before trying to connect:
service mongod restart
From Robomongo, I used the following connection settings:
Connection Tab:
SSH Tab:
SSH Address: [VPS IP] : 22
SSH User Name: [Username for sudo enabled user]
SSH Auth Method: Password
User Password: Supersecret
You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):
SELECT DISTINCT Left(LastName, 1)
FROM Authors;
SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
Use double quotation marks.
string foo = @"this ""word"" is escaped";
The response from Marco is the BEST solution. I needed to control my error handling, and I mean really CONTROL it. Of course, I have extended the solution a little and created a full error management system that manages everything. I have also read about this solution in other blogs and it seems very acceptable by most of the advanced developers.
Here is the final code that I am using:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "ErrorManager";
routeData.Values["action"] = "Fire404Error";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 404:
routeData.Values["action"] = "Fire404Error";
break;
}
}
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
IController errormanagerController = new ErrorManagerController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new RequestContext(wrapper, routeData);
errormanagerController.Execute(rc);
}
}
and inside my ErrorManagerController :
public void Fire404Error(HttpException exception)
{
//you can place any other error handling code here
throw new PageNotFoundException("page or resource");
}
Now, in my Action, I am throwing a Custom Exception that I have created. And my Controller is inheriting from a custom Controller Based class that I have created. The Custom Base Controller was created to override error handling. Here is my custom Base Controller class:
public class MyBasePageController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
filterContext.GetType();
filterContext.ExceptionHandled = true;
this.View("ErrorManager", filterContext).ExecuteResult(this.ControllerContext);
base.OnException(filterContext);
}
}
The "ErrorManager" in the above code is just a view that is using a Model based on ExceptionContext
My solution works perfectly and I am able to handle ANY error on my website and display different messages based on ANY exception type.
I was using localhost during unit testing when my recaptcha key was registered to 127.0.0.1. So I changed my browser to point to 127.0.0.1 and it started working. Although I was able to add "localhost" to the list of domains in my ReCaptcha Key Settings, I am still unable to unit test using localhost. I have to use the loopback IP address 127.0.0.1.
Here is another way to view your app's memory usage:
adb shell dumpsys meminfo <com.package.name> -d
Sample output:
Applications Memory Usage (kB):
Uptime: 2896577 Realtime: 2896577
** MEMINFO in pid 2094 [com.package.name] **
Pss Private Private Swapped Heap Heap Heap
Total Dirty Clean Dirty Size Alloc Free
------ ------ ------ ------ ------ ------ ------
Native Heap 3472 3444 0 0 5348 4605 102
Dalvik Heap 2349 2188 0 0 4640 4486 154
Dalvik Other 1560 1392 0 0
Stack 772 772 0 0
Other dev 4 0 4 0
.so mmap 2749 1040 1220 0
.jar mmap 1 0 0 0
.apk mmap 218 0 32 0
.ttf mmap 38 0 4 0
.dex mmap 3161 80 2564 0
Other mmap 9 4 0 0
Unknown 76 76 0 0
TOTAL 14409 8996 3824 0 9988 9091 256
Objects
Views: 30 ViewRootImpl: 2
AppContexts: 4 Activities: 2
Assets: 2 AssetManagers: 2
Local Binders: 17 Proxy Binders: 21
Death Recipients: 7
OpenSSL Sockets: 0
SQL
MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
For overall memory usage:
adb shell dumpsys meminfo
https://developer.android.com/studio/command-line/dumpsys#meminfo
The problem is that Chrome needs to have must-revalidate
in the Cache-Control` header in order to re-check files to see if they need to be re-fetched.
You can always SHIFT-F5 and force Chrome to refresh, but if you want to fix this problem on the server, include this response header:
Cache-Control: must-revalidate
This tells Chrome to check with the server, and see if there is a newer file. IF there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.
If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.
Here is a blog post that discusses the issue further.
You can use jQuery's css
function to test the CSS properties, eg. if ($('node').css('display') == 'block')
.
Colin is right, that there is no explicit event that gets fired when a specific CSS property gets changed. But you may be able to flip it around, and trigger an event that sets the display, and whatever else.
Also consider using adding CSS classes to get the behavior you want. Often you can add a class to a containing element, and use CSS to affect all elements. I often slap a class onto the body element to indicate that an AJAX response is pending. Then I can use CSS selectors to get the display I want.
Not sure if this is what you're looking for.
Had the same problem where I specified data
but the browser was sending requests to URL ending with [Object object]
.
You should have processData
set to true
.
processData: true, // You should comment this out if is false or set to true
When you define your function using this syntax:
def someFunc(*args):
for x in args
print x
You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:
def someFunc(myList = [], *args):
for x in myList:
print x
Then you can call it with this:
items = [1,2,3,4,5]
someFunc(items)
You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:
def someFunc(arg1, arg2, arg3, *args, **kwargs):
for x in args
print x
Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.
SyntaxError: missing ) after argument list.
the issue also may occur if you pass string directly without a single or double quote.
$('#contentData').append("<div class='media'><div class='media-body'><a class='btn' href='" + type + "' onclick=\"(canLaunch(' + v.LibraryItemName + '))\">View »</a></div></div>").
so always keep the habit to pass in a quote like
onclick=\"(canLaunch(\'' + v.LibraryItemName + '\'))"\
You want to use an App.Config.
When you add a new item to a project there is something called Applications Configuration file. Add that.
Then you add keys in the configuration/appsettings section
Like:
<configuration>
<appSettings>
<add key="MyKey" value="false"/>
Access the members by doing
System.Configuration.ConfigurationSettings.AppSettings["MyKey"];
This works in .NET 2 and above.
There's this short command line script in python: https://github.com/rgrp/csv2ascii/blob/master/csv2ascii.py
Just download and place in your path. Usage is like
csv2ascii.py [options] csv-file-path
Convert csv file at csv-file-path
to ascii form returning the result on
stdout. If csv-file-path
= '-' then read from stdin.
Options:
-h, --help show this help message and exit -w WIDTH, --width=WIDTH Width of ascii output -c COLUMNS, --columns=COLUMNS Only display this number of columns
You can get the maximum like this:
>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]]
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]].max(axis=1)
0 1
1 8
2 3
and so:
>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If you know that "A" and "B" are the only columns, you could even get away with
>>> df["C"] = df.max(axis=1)
And you could use .apply(max, axis=1)
too, I guess.
Did you try:
$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;
DiffUtil can the best choice for updating the data in the RecyclerView Adapter which you can find in the android framework. DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.
Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!
One more note, for our web application, I found that we had huge performance issues due to contention between threads over locks... so the moral was to think over the locking scheme very carefully. We ended up having worker threads to throttle too many requests using an asynchronous http handler, otherwise the application would just get overwhelmed and crash and burn. It meant a huge backlog could pile up, but at least the site would stay up.
The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).
For this example, let's draw a RED pixel at position 100x50.
Mat foo;
int x=100, y=50;
Solution 1:
Create a macro function that obtains the pixel from the array.
#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
Solution 2:
Get's the pixel using the method ptr.
unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
For me it's not important to play audio in the background like for others here, my problem was that I had some animations and they acted like crazy when you were in other tabs and coming back to them. My solution was putting these animations inside if that is preventing inactive tab:
if (!document.hidden){ //your animation code here }
thanks to that my animation was running only if tab was active. I hope this will help someone with my case.
David Thomas’s answer describes a way to use $('#elem').attr('style', …)
, but warns that using it will delete previously-set styles in the style
attribute. Here is a way of using attr()
without that problem:
var $elem = $('#elem');
$elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');
As a function:
function addStyleAttribute($element, styleAttribute) {
$element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
addStyleAttribute($('#elem'), 'width: 100px !important');
Here is a JS Bin demo.
By loading the .js
file first and then calling the function via onclick, there's less coding and it's fairly obvious what's going on. We'll call the JS file zipcodehelp.js
.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Button to call JS function.</title>
</head>
<body>
<h1>Use Button to execute function in '.js' file.</h1>
<script type="text/javascript" src="zipcodehelp.js"></script>
<button onclick="ZipcodeHelp();">Get Zip Help!</button>
</body>
</html>
And the contents of zipcodehelp.js
is :
function ZipcodeHelp() {
alert("If Zipcode is missing in list at left, do: \n\n\
1. Enter any zipcode and click Create Client. \n\
2. Goto Zipcodes and create new zip code. \n\
3. Edit this new client from the client list.\n\
4. Select the new zipcode." );
}
Hope that helps! Cheers!
–Ken
.phtml
was the standard file extension for PHP 2 programs. .php3
took over for PHP 3. When PHP 4 came out they switched to a straight .php
.
The older file extensions are still sometimes used, but aren't so common.
In case you are using axios and trying via a service call.
URL: https://react-16-demo.firebaseio.com/
Schema Name: todos
Key: -Lhu8a0uoSRixdmECYPE
axios.delete(`https://react-16-demo.firebaseio.com/todos/-Lhu8a0uoSRixdmECYPE.json`). then();
can help.
If you want a free simple location map showing a single marked location, for your website, Then
Let me know If this would help..
The other answers are all good approaches. However, there are a few other options in R that haven't been mentioned, including lowess
and approx
, which may give better fits or faster performance.
The advantages are more easily demonstrated with an alternate dataset:
sigmoid <- function(x)
{
y<-1/(1+exp(-.15*(x-100)))
return(y)
}
dat<-data.frame(x=rnorm(5000)*30+100)
dat$y<-as.numeric(as.logical(round(sigmoid(dat$x)+rnorm(5000)*.3,0)))
Here is the data overlaid with the sigmoid curve that generated it:
This sort of data is common when looking at a binary behavior among a population. For example, this might be a plot of whether or not a customer purchased something (a binary 1/0 on the y-axis) versus the amount of time they spent on the site (x-axis).
A large number of points are used to better demonstrate the performance differences of these functions.
Smooth
, spline
, and smooth.spline
all produce gibberish on a dataset like this with any set of parameters I have tried, perhaps due to their tendency to map to every point, which does not work for noisy data.
The loess
, lowess
, and approx
functions all produce usable results, although just barely for approx
. This is the code for each using lightly optimized parameters:
loessFit <- loess(y~x, dat, span = 0.6)
loessFit <- data.frame(x=loessFit$x,y=loessFit$fitted)
loessFit <- loessFit[order(loessFit$x),]
approxFit <- approx(dat,n = 15)
lowessFit <-data.frame(lowess(dat,f = .6,iter=1))
And the results:
plot(dat,col='gray')
curve(sigmoid,0,200,add=TRUE,col='blue',)
lines(lowessFit,col='red')
lines(loessFit,col='green')
lines(approxFit,col='purple')
legend(150,.6,
legend=c("Sigmoid","Loess","Lowess",'Approx'),
lty=c(1,1),
lwd=c(2.5,2.5),col=c("blue","green","red","purple"))
As you can see, lowess
produces a near perfect fit to the original generating curve. Loess
is close, but experiences a strange deviation at both tails.
Although your dataset will be very different, I have found that other datasets perform similarly, with both loess
and lowess
capable of producing good results. The differences become more significant when you look at benchmarks:
> microbenchmark::microbenchmark(loess(y~x, dat, span = 0.6),approx(dat,n = 20),lowess(dat,f = .6,iter=1),times=20)
Unit: milliseconds
expr min lq mean median uq max neval cld
loess(y ~ x, dat, span = 0.6) 153.034810 154.450750 156.794257 156.004357 159.23183 163.117746 20 c
approx(dat, n = 20) 1.297685 1.346773 1.689133 1.441823 1.86018 4.281735 20 a
lowess(dat, f = 0.6, iter = 1) 9.637583 10.085613 11.270911 11.350722 12.33046 12.495343 20 b
Loess
is extremely slow, taking 100x as long as approx
. Lowess
produces better results than approx
, while still running fairly quickly (15x faster than loess).
Loess
also becomes increasingly bogged down as the number of points increases, becoming unusable around 50,000.
EDIT: Additional research shows that loess
gives better fits for certain datasets. If you are dealing with a small dataset or performance is not a consideration, try both functions and compare the results.
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
I found this article that provided a solution for me. It pertains to Xcode 7 where the default for No Common Blocks is Yes rather than No in previous versions.
This is a quote from the article:
The problem seems to be that the "No common blocks" in the "Apple LLVM 6.1 - Code Generation" section in the Build settings pane is set to Yes, in the latest version of Xcode.
This caused what I will describe as circular references where a class that was included in my Compile Sources was referenced via a #import in another source file (appDelegate.m). This caused duplicate blocks for variables that were declared in the original base class.
Changing the value to No immediately enabled my app to compile and resolved my problem.
You're looking for axhline
(a horizontal axis line). For example, the following will give you a horizontal line at y = 0.5
:
import matplotlib.pyplot as plt
plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()
This error message appears if the Windows service launcher has quit immediately after being started. This problem usually happens because the license key has not been correctly deployed(license.txt file in the license folder). If service is not strtign with correct key, just put incorrect key and try to start. Once started, place the correct key, it will work.
Two choices:
1/ From the project:
2/ If you have already other jar imported, from the directory "References Libraries":
Both will lead you to this screen where you can mange your libraries:
You must use a more recent version of tomcat which has support for JDK 8.
I can confirm that apache-tomcat-7.0.35 does NOT have support for JDK8, I can also confirm that apache-tomcat-7.0.50 DOES have support for JDK8.
This answers is for command needed for undoing local changes which are in multiple specific files in same or multiple folders (or directories). This answers specifically addresses question where a user has more than one file but the user doesn't want to undo all local changes:
if you have one or more files you could apply the same command (
git checkout -- file
) to each of those files by listing each of their location separated by space as in:
git checkout -- name1/name2/fileOne.ext nameA/subFolder/fileTwo.ext
mind the space above between name1/name2/fileOne.ext nameA/subFolder/fileTwo.ext
For multiple files in the same folder:
If you happen to need to discard changes for all of the files in a certain directory, use the git checkout as follows:
git checkout -- name1/name2/*
The asterisk in the above does the trick of undoing all files at that location under name1/name2.
And, similarly the following can undo changes in all files for multiple folders:
git checkout -- name1/name2/* nameA/subFolder/*
again mind the space between name1/name2/* nameA/subFolder/* in the above.
Note: name1, name2, nameA, subFolder - all of these example folder names indicate the folder or package where the file(s) in question may be residing.
I saw a review of Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools on a blog talking also about XI-Factory, I read it and I must say this book is a must read. Altough not specifically targetted to programmers, it explains very clearly what is happening in the programming world right now with Model-Driven Architecture and so on..
The permanent fix if one wants to create a new branch on the remote to mirror and track your local branch(or, vice-versa) is:
git config --global push.default current
I always configure my local git with this command after I do git clone. Although it can be applied anytime when the local-remote branch "Git fatal: The current branch has no upstream branch" error occurs.
Hope this helps. Much peace. :)
I can think of 2 options
background-color
for the column on the container <div/>
instead (<div class="separator"/>
) with repeat-y
Just remove the (
and the )
on your SELECT statement:
insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;
This error means that, while linking, compiler is not able to find the definition of main()
function anywhere.
In your makefile, the main
rule will expand to something like this.
main: producer.o consumer.o AddRemove.o
gcc -pthread -Wall -o producer.o consumer.o AddRemove.o
As per the gcc
manual page, the use of -o
switch is as below
-o file Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If
-o
is not specified, the default is to put an executable file ina.out
.
It means, gcc will put the output in the filename provided immediate next to -o
switch. So, here instead of linking all the .o
files together and creating the binary [main
, in your case], its creating the binary as producer.o
, linking the other .o
files. Please correct that.
If I understand correctly, you wish to have everything in one page and execute it from the same page.
You can use the following code to send mail from a single page, for example index.php
or contact.php
The only difference between this one and my original answer is the <form action="" method="post">
where the action has been left blank.
It is better to use header('Location: thank_you.php');
instead of echo
in the PHP handler to redirect the user to another page afterwards.
<?php
if(isset($_POST['submit'])){
$to = "[email protected]"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.
Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail()
function.
The PHP handler will also send a copy of the message to the person who filled in the form.
You can use two forward slashes //
in front of a line of code if you're not going to use it.
For example: // $subject2 = "Copy of your form submission";
will not execute.
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
(Uses info from HTML form and sends the Email)
<?php
if(isset($_POST['submit'])){
$to = "[email protected]"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
// You cannot use header and echo together. It's one or the other.
}
?>
To send as HTML:
If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.
Read the manual on mail()
to learn how to send emails as HTML:
Footnotes:
You have to specify the URL of the service that will handle the submitted data, using the action attribute.
As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.
Therefore, action=""
will not work in HTML5.
The proper syntax would be:
action="handler.xxx"
or action="http://www.example.com/handler.xxx"
.Note that xxx
will be the extension of the type of file used to handle the process. This could be a .php
, .cgi
, .pl
, .jsp
file extension etc.
Consult the following Q&A on Stack if sending mail fails:
assert
will terminate the program (usually with a message quoting the assert statement) if its argument turns out to be false. It's commonly used during debugging to make the program fail more obviously if an unexpected condition occurs.
For example:
assert(length >= 0); // die if length is negative.
You can also add a more informative message to be displayed if it fails like so:
assert(length >= 0 && "Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith");
Or else like this:
assert(("Length can't possibly be negative! Tell jsmith", length >= 0));
When you're doing a release (non-debug) build, you can also remove the overhead of evaluating assert
statements by defining the NDEBUG
macro, usually with a compiler switch. The corollary of this is that your program should never rely on the assert macro running.
// BAD
assert(x++);
// GOOD
assert(x);
x++;
// Watch out! Depends on the function:
assert(foo());
// Here's a safer way:
int ret = foo();
assert(ret);
From the combination of the program calling abort() and not being guaranteed to do anything, asserts should only be used to test things that the developer has assumed rather than, for example, the user entering a number rather than a letter (which should be handled by other means).
We were trying to avoid using the IE specific
$window[0].document.body.clientHeight
And found that the following jQuery will not consistently yield the same value but eventually does at some point in our page load scenario which worked for us and maintained cross-browser support:
$(document).height()
Simple. Use splitlines()
L = open("myFile.txt", "r").read().splitlines();
for line in L:
process(line) # this 'line' will not have '\n' character at the end
Improving axiac's solution to avoid selecting multiple rows per group while also allowing for use of indexes
SELECT o.*
FROM `Persons` o
LEFT JOIN `Persons` b
ON o.Group = b.Group AND o.Age < b.Age
LEFT JOIN `Persons` c
ON o.Group = c.Group AND o.Age = c.Age and o.id < c.id
WHERE b.Age is NULL and c.id is null
From Java 8 API
It could be easier to take actual implementation from API doc https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#longs-long-long-long- they are using it to generate longs stream. And your origin can be "0" like in the question.
long nextLong(long origin, long bound) {
long r = nextLong();
long n = bound - origin, m = n - 1;
if ((n & m) == 0L) // power of two
r = (r & m) + origin;
else if (n > 0L) { // reject over-represented candidates
for (long u = r >>> 1; // ensure nonnegative
u + m - (r = u % n) < 0L; // rejection check
u = nextLong() >>> 1) // retry
;
r += origin;
}
else { // range not representable as long
while (r < origin || r >= bound)
r = nextLong();
}
return r;
}
I adopted the answer from @Darkwaltz4 for its brevity and would like to share how I adapted the solution to situations where the array may contain different keys for each iteration like so:
Array[0] ...
['dob'] = '12/08/1986';
['some_key'] = 'some value';
Array[1] ...
['dob'] = '12/08/1986';
Array[2] ...
['dob'] = '12/08/1986';
['some_key'] = 'some other value';
and maintained a "master key" like so:
$master_key = array( 'dob' => ' ' , 'some_key' => ' ' );
array_merge would have executed the merge in the Array[1] iteration based on $master_key and produced ['some_key'] = '', an empty value, for that iteration. Hence, array_intersect_key was used to modify $master_key in each iterations like so:
foreach ($customer as $customer) {
$modified_key = array_intersect_key($master_key, $unordered_array);
$properOrderedArray = array_merge($modified_key, $customer);
}
The best bet is to start off with tel: which works on all mobiles
Then put in this code, which will only run when on a desktop, and only when a link is clicked.
I'm using http://detectmobilebrowsers.com/ to detect mobile browsers, you can use whatever method you prefer
if (!jQuery.browser.mobile) {
jQuery('body').on('click', 'a[href^="tel:"]', function() {
jQuery(this).attr('href',
jQuery(this).attr('href').replace(/^tel:/, 'callto:'));
});
}
So basically you cover all your bases.
tel: works on all phones to open the dialer with the number
callto: works on your computer to connect to skype from firefox, chrome
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
You cannot check window.history.length
as it contains the amount of pages in you visited in total in a given session:
window.history.length
(Integer)Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1
Lets say a user visits your page, clicks on some links and goes back:
www.mysite.com/index.html <-- first page and now current page <----+ www.mysite.com/about.html | www.mysite.com/about.html#privacy | www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back
Now window.history.length
is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.
You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:
window.goBack = function (e){
var defaultLocation = "http://www.mysite.com";
var oldHash = window.location.hash;
history.back(); // Try to go back
var newHash = window.location.hash;
/* If the previous page hasn't been loaded in a given time (in this case
* 1000ms) the user is redirected to the default location given above.
* This enables you to redirect the user to another page.
*
* However, you should check whether there was a referrer to the current
* site. This is a good indicator for a previous entry in the history
* session.
*
* Also you should check whether the old location differs only in the hash,
* e.g. /index.html#top --> /index.html# shouldn't redirect to the default
* location.
*/
if(
newHash === oldHash &&
(typeof(document.referrer) !== "string" || document.referrer === "")
){
window.setTimeout(function(){
// redirect to default location
window.location.href = defaultLocation;
},1000); // set timeout in ms
}
if(e){
if(e.preventDefault)
e.preventDefault();
if(e.preventPropagation)
e.preventPropagation();
}
return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>
Note that typeof(document.referrer) !== "string"
is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.
EDIT: Don't use <a href='#'>...</a>
, as this will add another entry to the session history. It's better to use a <span>
or some other element. Note that typeof document.referrer
is always "string"
and not empty if your page is inside of a (i)frame.
See also:
I would checkout the remote file from the "master" (the remote/origin repository) like this:
git checkout master <FileWithPath>
Example: git checkout master components/indexTest.html
A div is a block element, and will span the width of the container unless a width is set. A span is an inline element, and will have the width of the text inside it. Currently, you are trying to set align as a CSS property. Align is an attribute.
<span align="center" style="border:1px solid red;">
This is some text in a div element!
</span>
However, the align attribute is deprecated. You should use the CSS text-align
property on the container.
<div style="text-align: center;">
<span style="border:1px solid red;">
This is some text in a div element!
</span>
</div>
With the unobtrusive way:
Jquery Validate Example:
<input type="text" name="email" class="required">
<script>
$(function () {
$("form").validate();
});
</script>
Jquery Validate Unobtrusive Example:
<input type="text" name="email" data-val="true"
data-val-required="This field is required.">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
Adding to bobble bubble's answer, there are other regex flavors where recursive constructs are supported.
Lua
Use %b()
(%b{}
/ %b[]
for curly braces / square brackets):
for s in string.gmatch("Extract (a(b)c) and ((d)f(g))", "%b()") do print(s) end
(see demo)Raku (former Perl6):
Non-overlapping multiple balanced parentheses matches:
my regex paren_any { '(' ~ ')' [ <-[()]>+ || <&paren_any> ]* }
say "Extract (a(b)c) and ((d)f(g))" ~~ m:g/<&paren_any>/;
# => (?(a(b)c)? ?((d)f(g))?)
Overlapping multiple balanced parentheses matches:
say "Extract (a(b)c) and ((d)f(g))" ~~ m:ov:g/<&paren_any>/;
# => (?(a(b)c)? ?(b)? ?((d)f(g))? ?(d)? ?(g)?)
See demo.
Python re
non-regex solution
See poke's answer for How to get an expression between balanced parentheses.
Java customizable non-regex solution
Here is a customizable solution allowing single character literal delimiters in Java:
public static List<String> getBalancedSubstrings(String s, Character markStart,
Character markEnd, Boolean includeMarkers)
{
List<String> subTreeList = new ArrayList<String>();
int level = 0;
int lastOpenDelimiter = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == markStart) {
level++;
if (level == 1) {
lastOpenDelimiter = (includeMarkers ? i : i + 1);
}
}
else if (c == markEnd) {
if (level == 1) {
subTreeList.add(s.substring(lastOpenDelimiter, (includeMarkers ? i + 1 : i)));
}
if (level > 0) level--;
}
}
return subTreeList;
}
}
Sample usage:
String s = "some text(text here(possible text)text(possible text(more text)))end text";
List<String> balanced = getBalancedSubstrings(s, '(', ')', true);
System.out.println("Balanced substrings:\n" + balanced);
// => [(text here(possible text)text(possible text(more text)))]
distcp command use for copying from one cluster to another cluster in parallel. You have to set the path for namenode of src and path for namenode of dst, internally it use mapper.
Example:
$ hadoop distcp <src> <dst>
there few options you can set for distcp
-m for no. of mapper for copying data this will increase speed of copying.
-atomic for auto commit the data.
-update will only update data that is in old version.
There are generic command for copying files in hadoop are -cp and -put but they are use only when the data volume is less.
Let's say you have 25 objects and want one process to handle any one objects click event. You could write 25 delegates or use a loop to handle the click event.
public form1()
{
foreach (Panel pl in Container.Components)
{
pl.Click += Panel_Click;
}
}
private void Panel_Click(object sender, EventArgs e)
{
// Process the panel clicks here
int index = Panels.FindIndex(a => a == sender);
...
}