Try the following
download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.
Unzip the file and Run intelhaxm-android.exe.
Run silent_install.bat.
In my computer Win10 x64 - VS2015 it worked
Since most modern CPUs support virtualization natively, the reason you received such message can be because virtualization is turned off on your machine. For example, that was the case on my HP laptop - the factory setting for hardware virtualization was "Disabled". So, go to your machine's BIOS and enable virtualization.
For IntelHAXM to install you have to activate Intel Virtual Technology.
To activate it, you have to restart your PC and go to BIOS. There is an option called Intel Virtual Technology that you have to enable to activate it.
After enabling it, reinstall IntelHAXM. That should solve the problem.
The way I solved it is by setting the AVD memory limit and HAXM memory to be equal in size which is 1 GB = 1024 MB. The AVD cannot have higher memory limit than the HAXM.
1. Setting the HAXM memory to be 1024 M
The only way to change the HAXM memory is by installing it again. I did it using the terminal. Locate Hardware_Accelerated_Execution_Manager in your machine. Then change directory that folder to run the installation script.
cd ~/Library/Android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager
-OR-
cd ~/Library/Developer/Xamarin/android-sdk-macosx/extras/intel/Hardware_Accelerated_Execution_Manager
May need to change permissions:
sudo chmod 755 "HAXM installation"
Then:
./HAXM\ installation -m 1024
-OR-
sudo ./"HAXM installation" -m 1024
2. Setting the virtual device the same size with HAXM memory limit
This works for me. Good luck!
I ran into this problem while building a program that requires a huge amount of stack space (over 2 GiB). The solution was to add the flag -mcmodel=medium
, which is supported by both GCC and Intel compilers.
If you met the problem after upgrading php-fpm like me, try this: open /etc/php5/fpm/pool.d/www.conf uncomment the following lines:
listen.owner = www-data
listen.group = www-data
listen.mode = 0666
then restart php-fpm.
I tested eAccelerator and XCache with Apache, Lighttp and Nginx with a Wordpress site. eAccelerator wins every time. The bad thing is only the missing packages for Debian and Ubuntu. After a PHP update often the server doesn't work anymore if the eAccelerator modules are not recompiled.
eAccelerator last RC is from 2009/07/15 (0.9.6 rc1) with support for PHP 5.3
On Fedora, this works:
sudo yum install -y python-pip
sudo yum install -y lapack lapack-devel blas blas-devel
sudo yum install -y blas-static lapack-static
sudo pip install numpy
sudo pip install scipy
If you get any public key
errors while downloading, add --nogpgcheck
as parameter to yum
, for example:
yum --nogpgcheck install blas-devel
On Fedora 23 onwards, use dnf
instead of yum
.
The quick and dirty way would be to simple bind to the keyup
event.
$('#mytxt').keyup(function(){_x000D_
$('#divlen').text('you typed ' + this.value.length + ' characters');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type=text id=mytxt >_x000D_
<div id=divlen></div>
_x000D_
But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup
)
I've created a "lazy load" plugin which might help. Here is the a possible way to get the job done with it in your case:
$('img').lazyloadanything({
'onLoad': function(e, LLobj) {
var $img = LLobj.$element;
var src = $img.attr('data-src');
$img.css('background-image', 'url("'+src+'")');
}
});
It is simple like maosmurf's example but still gives you the "lazy load" functionality of event firing when the element comes into view.
As of Apache POI 3.17 you will have to check if the cell is empty using enumerations:
import org.apache.poi.ss.usermodel.CellType;
if(cell == null || cell.getCellTypeEnum() == CellType.BLANK) { ... }
You can solve this error by running cmd as admin than
Do the same as in picture for windows 32 bit
Just make changes in 64 bit as framework64 instead of framework only
Than go to iis and refresh the site
If u still got some error make changes in application pool
Why not just add Labels to the top of the Listbox and if changes are needed, the only thing you need to programmatically change are the labels.
Directly from the node.js tag wiki, make sure watch some of the talk videos linked there to get a better idea.
Node.js is an event based, asynchronous I/O framework that uses Google's V8 JavaScript Engine.
Node.js - or just Node as it's commonly called - is used for developing applications that make heavy use of the ability to run JavaScript both on the client, as well as on server side and therefore benefit from the re-usability of code and the lack of context switching.
It's also possible to use matured JavaScript frameworks like YUI and jQuery for server side DOM manipulation.
To ease the development of complex JavaScript further, Node.js supports the CommonJS standard that allows for modularized development and the distribution of software in packages via the Node Package Manager.
I agree that it's counterintuitive at first, but there's a good reason. Join can't be a method of a list because:
There are actually two join methods (Python 3.0):
>>> b"".join
<built-in method join of bytes object at 0x00A46800>
>>> "".join
<built-in method join of str object at 0x00A28D40>
If join was a method of a list, then it would have to inspect its arguments to decide which one of them to call. And you can't join byte and str together, so the way they have it now makes sense.
<anything> | sort | uniq -c | sort -n
will give you a count of all the different occurrences of <anything>.
Often, awk, sed, or cut help with the parsing of data in <anything>.
next() is read until the space of the encounter, and the nextLine() is read to the end of the line.
Scanner scan = new Scanner(System.in);
String address = scan.next();
s += scan.nextLine();
An alternative approach may be to embed images in the email using the cid
method. (Basically including the image as an attachment, and then embedding it). In my experience, this approach seems to be well supported these days.
Source: https://www.campaignmonitor.com/blog/how-to/2008/08/embedding-images-revisited/
You can use JSTL tags together with EL expressions to avoid intermixing Java and HTML code:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
</head>
<body>
<c:out value="${x + 1}" />
<c:out value="${param.name}" />
// and so on
</body>
</html>
You need to re-add that certificate to your machine or chose another certificate.
To choose another certificate or to recreate one, head over to the Project's properties page, click on Signing tab and either
Once either of these is done, you should be able to build it again.
I found this:
<embed type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2" width="100%"
height="100%" id="vlc" loop="yes"autoplay="yes" target="http://10.1.2.201:8000/"></embed>
I don't see that in your code anywhere.... I think that's all you need and the target would be the location of your video...
and here is more info on the vlc plugin:
http://wiki.videolan.org/Documentation%3aWebPlugin#Input_object
Another thing to check is that the address for the video file is correct....
Your data is poorly formed. The value fields in particular have numerous spaces and new lines. Automated formatters won't work on this, as they will not modify the actual data. As you generate the data for output, filter it as needed to avoid the spaces.
To remove an item from a text file, first move all the text to a list and remove whichever item you want. Then write the text stored in the list into a text file:
List<string> quotelist=File.ReadAllLines(filename).ToList();
string firstItem= quotelist[0];
quotelist.RemoveAt(0);
File.WriteAllLines(filename, quotelist.ToArray());
return firstItem;
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.
Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.
You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.
To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.
A typical C++ code will be:
hVaultLib = LoadLibrary(L"vaultcli.dll");
if (hVaultLib != NULL)
{
pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");
bStatus = (pVaultEnumerateVaults != NULL)
&& (pVaultFree != NULL)
&& (pVaultGetItemW7 != NULL)
&& (pVaultGetItemW8 != NULL)
&& (pVaultOpenVault != NULL)
&& (pVaultCloseVault != NULL)
&& (pVaultEnumerateItems != NULL);
}
Then you enumerate all stored credentials by calling
VaultEnumerateVaults
Then you go over the results.
CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class "saved"
and you define how it looks when it doesn't have the class "saved"
(it's normal look). When you remove the class "saved"
, it will transition to the other state according to the transition settings in place for the object without the "saved"
class.
If the CSS transition settings apply to the object (without the "saved"
class), then they will apply to both transitions.
We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided.
My guess from looking at your HTML is that your transition CSS settings only apply to .saved
and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class ".fade"
that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect.
I also had problem with refused connection on port 80. I didn't use localhost.
curl --data-binary "@/textfile.txt" "http://www.myserver.com/123.php"
Problem was that I had umlauts äåö in my textfile.txt.
To write a newline use \n
not /n
the latter is just a slash and a n
yegor256 has found a nice solution using Apache Commons IO:
import org.apache.commons.io.IOUtils;
String text = IOUtils.toString(this.getClass().getResourceAsStream("foo.xml"),
"UTF-8");
try
String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
HashMap<String,Integer> hm =new HashMap<String,Integer>();
for(String s1:s.split(",")){
String[] s2 = s1.split(":");
hm.put(s2[0], Integer.parseInt(s2[1]));
}
If you are using Java, you can actually use commons-codec library
import org.apache.commons.codec.binary.Base64;
String stringToBeChecked = "...";
boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());
[UPDATE 1] Deprecation Notice Use instead
Base64.isBase64(value);
/**
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
* method treats whitespace as valid.
*
* @param arrayOctet
* byte array to test
* @return {@code true} if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
* {@code false}, otherwise
* @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
*/
@Deprecated
public static boolean isArrayByteBase64(final byte[] arrayOctet) {
return isBase64(arrayOctet);
}
Use modulo:
$hours = $time_in_seconds / 3600;
$minutes = ($time_in_seconds / 60) % 60;
You can do it pretty easy in Interface Builder. Just create a view with a table and drop another view onto the table. This will become the table header view. Add your labels and image to that view. See the pic below for the view hierarchy.
I use [^\t\r\n\x20-\x7E]+
and that seems to be working fine.
To select rows whose column value equals a scalar, some_value
, use ==
:
df.loc[df['column_name'] == some_value]
To select rows whose column value is in an iterable, some_values
, use isin
:
df.loc[df['column_name'].isin(some_values)]
Combine multiple conditions with &
:
df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]
Note the parentheses. Due to Python's operator precedence rules, &
binds more tightly than <=
and >=
. Thus, the parentheses in the last example are necessary. Without the parentheses
df['column_name'] >= A & df['column_name'] <= B
is parsed as
df['column_name'] >= (A & df['column_name']) <= B
which results in a Truth value of a Series is ambiguous error.
To select rows whose column value does not equal some_value
, use !=
:
df.loc[df['column_name'] != some_value]
isin
returns a boolean Series, so to select rows whose value is not in some_values
, negate the boolean Series using ~
:
df.loc[~df['column_name'].isin(some_values)]
For example,
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
print(df.loc[df['A'] == 'foo'])
yields
A B C D
0 foo one 0 0
2 foo two 2 4
4 foo two 4 8
6 foo one 6 12
7 foo three 7 14
If you have multiple values you want to include, put them in a
list (or more generally, any iterable) and use isin
:
print(df.loc[df['B'].isin(['one','three'])])
yields
A B C D
0 foo one 0 0
1 bar one 1 2
3 bar three 3 6
6 foo one 6 12
7 foo three 7 14
Note, however, that if you wish to do this many times, it is more efficient to
make an index first, and then use df.loc
:
df = df.set_index(['B'])
print(df.loc['one'])
yields
A C D
B
one foo 0 0
one bar 1 2
one foo 6 12
or, to include multiple values from the index use df.index.isin
:
df.loc[df.index.isin(['one','two'])]
yields
A C D
B
one foo 0 0
one bar 1 2
two foo 2 4
two foo 4 8
two bar 5 10
one foo 6 12
Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set on an existing file with setPosixFilePermissions()
, or atomically at file creation with methods like createFile()
or newByteChannel()
.
You can create a set of permissions using EnumSet.of()
, but the helper method PosixFilePermissions.fromString()
will uses a conventional format that will be more readable to many developers. For APIs that accept a FileAttribute
, you can wrap the set of permissions with with PosixFilePermissions.asFileAttribute()
.
Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);
In earlier versions of Java, using native code of your own, or exec
-ing command-line utilities are common approaches.
While looking at the same problem, I found an example
<style type="text/css">
#topright {
position: absolute;
right: 0;
top: 0;
display: block;
height: 125px;
width: 125px;
background: url(TRbanner.gif) no-repeat;
text-indent: -999em;
text-decoration: none;
}
</style>
<a id="topright" href="#" title="TopRight">Top Right Link Text</a>
The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)
Yes, you can. But if you have non-unique entries on your table, it will fail. Here is the how to add unique constraint on your table. If you're using PostgreSQL 9.x you can follow below instruction.
CREATE UNIQUE INDEX constraint_name ON table_name (columns);
Hmmm... would it be much different if you just had non-static classes filled with static methods..?
You can do this:
$('.searchbychar').click(function () {
var divID = '#' + this.id;
$('html, body').animate({
scrollTop: $(divID).offset().top
}, 2000);
});
F.Y.I.
.
(dot) like in your first line of code.$( 'searchbychar' ).click(function() {
$('.searchbychar').attr('id')
will return a string ID not a jQuery object. Hence, you can not apply .offset()
method to it.Question 1:
vectorOfGamers.push_back(Player)
This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:
vectorOfGamers.push_back(Player(name, id))
//^^assuming name and id are parameters to the vector, call Player constructor
//^^In other words, push `instance` of Player class into vector
Question 2:
These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?
Yes you can. You can create a vector of pointers that points to the base class Gamer
.
A good choice is to use a vector of smart_pointer
, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer
, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?
Inside styles.xml...
<!-- No action bar -->
<style name="NoActonBar" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Theme customization. -->
<item name="colorPrimary">#000</item>
<item name="colorPrimaryDark">#444</item>
<item name="colorAccent">#999</item>
<item name="android:windowFullscreen">true</item>
</style>
This worked for me. Hope it'll help you.
Well, found a solution to my problem; Updating all rows using a SQL query and a SQL Task in SSIS Like Below. May help others if they face same challenge in future.
update Original
set Original.Vaal= t.vaal
from Original join (select * from staging1 union select * from staging2) t
on Original.id=t.id
Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.
intresult = None
while intresult is None:
input = raw_input()
try: intresult = int(input)
except ValueError: pass
It's possible to compile and use tmux within Cgywin. http://sourceforge.net/mailarchive/message.php?msg_id=30850840
I've added a number of helper methods to the O2 Platform (Open Source project) which allow you easily script an interaction with another process via the console output and input (see http://code.google.com/p/o2platform/source/browse/trunk/O2_Scripts/APIs/Windows/CmdExe/CmdExeAPI.cs)
Also useful for you might be the API that allows the viewing of the console output of the current process (in an existing control or popup window). See this blog post for more details: http://o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/ (this blog also contains details of how to consume the console output of new processes)
If you're not set on rolling your own solution, check out this jQuery plugin:
malsup.com/jquery/form/
It will do that and more for you. It's highly recommended.
There is no bound checking in array in C programming. If you declare array as
int arr[50];
Then you can even write as
arr[51] = 10;
The compiler would not throw an error. Hope this answers your question.
A complete example which leaves the fields as NULL-terminated strings in the original input buffer and provides access to them via an array of char pointers. The CSV processor has been confirmed to work with fields enclosed in "double quotes", ignoring any delimiter chars within them.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// adjust BUFFER_SIZE to suit longest line
#define BUFFER_SIZE 1024 * 1024
#define NUM_FIELDS 10
#define MAXERRS 5
#define RET_OK 0
#define RET_FAIL 1
#define FALSE 0
#define TRUE 1
// char* array will point to fields
char *pFields[NUM_FIELDS];
// field offsets into pFields array:
#define LP 0
#define IMIE 1
#define NAZWISKo 2
#define ULICA 3
#define NUMER 4
#define KOD 5
#define MIEJSCOw 6
#define TELEFON 7
#define EMAIL 8
#define DATA_UR 9
long loadFile(FILE *pFile, long *errcount);
static int loadValues(char *line, long lineno);
static char delim;
long loadFile(FILE *pFile, long *errcount){
char sInputBuf [BUFFER_SIZE];
long lineno = 0L;
if(pFile == NULL)
return RET_FAIL;
while (!feof(pFile)) {
// load line into static buffer
if(fgets(sInputBuf, BUFFER_SIZE-1, pFile)==NULL)
break;
// skip first line (headers)
if(++lineno==1)
continue;
// jump over empty lines
if(strlen(sInputBuf)==0)
continue;
// set pFields array pointers to null-terminated string fields in sInputBuf
if(loadValues(sInputBuf,lineno)==RET_FAIL){
(*errcount)++;
if(*errcount > MAXERRS)
break;
} else {
// On return pFields array pointers point to loaded fields ready for load into DB or whatever
// Fields can be accessed via pFields, e.g.
printf("lp=%s, imie=%s, data_ur=%s\n", pFields[LP], pFields[IMIE], pFields[DATA_UR]);
}
}
return lineno;
}
static int loadValues(char *line, long lineno){
if(line == NULL)
return RET_FAIL;
// chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.)
// can be removed if sure fgets has removed both CR and LF from end of line
if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1) == '\n')
*(line + strlen(line)-1) = '\0';
if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1 )== '\n')
*(line + strlen(line)-1) = '\0';
char *cptr = line;
int fld = 0;
int inquote = FALSE;
char ch;
pFields[fld]=cptr;
while((ch=*cptr) != '\0' && fld < NUM_FIELDS){
if(ch == '"') {
if(! inquote)
pFields[fld]=cptr+1;
else {
*cptr = '\0'; // zero out " and jump over it
}
inquote = ! inquote;
} else if(ch == delim && ! inquote){
*cptr = '\0'; // end of field, null terminate it
pFields[++fld]=cptr+1;
}
cptr++;
}
if(fld > NUM_FIELDS-1){
fprintf(stderr, "Expected field count (%d) exceeded on line %ld\n", NUM_FIELDS, lineno);
return RET_FAIL;
} else if (fld < NUM_FIELDS-1){
fprintf(stderr, "Expected field count (%d) not reached on line %ld\n", NUM_FIELDS, lineno);
return RET_FAIL;
}
return RET_OK;
}
int main(int argc, char **argv)
{
FILE *fp;
long errcount = 0L;
long lines = 0L;
if(argc!=3){
printf("Usage: %s csvfilepath delimiter\n", basename(argv[0]));
return (RET_FAIL);
}
if((delim=argv[2][0])=='\0'){
fprintf(stderr,"delimiter must be specified\n");
return (RET_FAIL);
}
fp = fopen(argv[1] , "r");
if(fp == NULL) {
fprintf(stderr,"Error opening file: %d\n",errno);
return(RET_FAIL);
}
lines=loadFile(fp,&errcount);
fclose(fp);
printf("Processed %ld lines, encountered %ld error(s)\n", lines, errcount);
if(errcount>0)
return(RET_FAIL);
return(RET_OK);
}
I had some problems with pending request for mp3 files. I had a list of mp3 files and one player to play them. If I picked a file that had already been downloaded, Chrome would block the request and show "pending request" in the network tab of the developer tools.
All versions of Chrome seem to be affected.
Here is a solution I found:
player[0].setAttribute('src','video.webm?dummy=' + Date.now());
You just add a dummy query string to the end of each url. This forces Chrome to download the file again.
Another example with popcorn player (using jquery) :
url = $(this).find('.url_song').attr('url');
pop = Popcorn.smart( "#player_", url + '?i=' + Date.now());
This works for me. In fact, the resource is not stored in the cache system. This should also work in the same way for .csv files.
The following code works with multiple types of archives (jar, war) and multiple types of classloaders (jar, url, vfs, ...)
public static Manifest getManifest(Class<?> clz) {
String resource = "/" + clz.getName().replace(".", "/") + ".class";
String fullPath = clz.getResource(resource).toString();
String archivePath = fullPath.substring(0, fullPath.length() - resource.length());
if (archivePath.endsWith("\\WEB-INF\\classes") || archivePath.endsWith("/WEB-INF/classes")) {
archivePath = archivePath.substring(0, archivePath.length() - "/WEB-INF/classes".length()); // Required for wars
}
try (InputStream input = new URL(archivePath + "/META-INF/MANIFEST.MF").openStream()) {
return new Manifest(input);
} catch (Exception e) {
throw new RuntimeException("Loading MANIFEST for class " + clz + " failed!", e);
}
}
check the curl_error after the curl_getinfo to find out the hidden errors.
if(curl_errno($ch)){
echo 'Curl error: ' . curl_error($ch);
}
You can simply give it an empty hash:
anchor.href = "#";
or if that's not good enough of a "disable", use an event handler:
anchor.href = "javascript:void(0)";
Are you simply appending string literals? Or are you going to be appending various data types (ints, floats, etc.)?
It might be easier to abstract this out into its own function (the following assumes C99):
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
int appendToStr(char *target, size_t targetSize, const char * restrict format, ...)
{
va_list args;
char temp[targetSize];
int result;
va_start(args, format);
result = vsnprintf(temp, targetSize, format, args);
if (result != EOF)
{
if (strlen(temp) + strlen(target) > targetSize)
{
fprintf(stderr, "appendToStr: target buffer not large enough to hold additional string");
return 0;
}
strcat(target, temp);
}
va_end(args);
return result;
}
And you would use it like so:
char target[100] = {0};
...
appendToStr(target, sizeof target, "%s %d %f\n", "This is a test", 42, 3.14159);
appendToStr(target, sizeof target, "blah blah blah");
etc.
The function returns the value from vsprintf
, which in most implementations is the number of bytes written to the destination. There are a few holes in this implementation, but it should give you some ideas.
Have been edited in 2020-06-15
public class Outer {
public Inner getInner(){
return new Inner(this);
}
static class Inner {
public final Outer Outer;
public Inner(Outer outer) {
this.Outer=outer;
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Inner inner = outer.getInner();
Outer anotherOuter=inner.Outer;
if(anotherOuter == outer) {
System.out.println("Was able to reach out to the outer object via inner !!");
} else {
System.out.println("No luck :-( ");
}
}
}
In NoSQL: If Only It Was That Easy, the author writes about MongoDB:
MongoDB is not a key/value store, it’s quite a bit more. It’s definitely not a RDBMS either. I haven’t used MongoDB in production, but I have used it a little building a test app and it is a very cool piece of kit. It seems to be very performant and either has, or will have soon, fault tolerance and auto-sharding (aka it will scale). I think Mongo might be the closest thing to a RDBMS replacement that I’ve seen so far. It won’t work for all data sets and access patterns, but it’s built for your typical CRUD stuff. Storing what is essentially a huge hash, and being able to select on any of those keys, is what most people use a relational database for. If your DB is 3NF and you don’t do any joins (you’re just selecting a bunch of tables and putting all the objects together, AKA what most people do in a web app), MongoDB would probably kick ass for you.
Then, in the conclusion:
The real thing to point out is that if you are being held back from making something super awesome because you can’t choose a database, you are doing it wrong. If you know mysql, just use it. Optimize when you actually need to. Use it like a k/v store, use it like a rdbms, but for god sake, build your killer app! None of this will matter to most apps. Facebook still uses MySQL, a lot. Wikipedia uses MySQL, a lot. FriendFeed uses MySQL, a lot. NoSQL is a great tool, but it’s certainly not going to be your competitive edge, it’s not going to make your app hot, and most of all, your users won’t care about any of this.
What am I going to build my next app on? Probably Postgres. Will I use NoSQL? Maybe. I might also use Hadoop and Hive. I might keep everything in flat files. Maybe I’ll start hacking on Maglev. I’ll use whatever is best for the job. If I need reporting, I won’t be using any NoSQL. If I need caching, I’ll probably use Tokyo Tyrant. If I need ACIDity, I won’t use NoSQL. If I need a ton of counters, I’ll use Redis. If I need transactions, I’ll use Postgres. If I have a ton of a single type of documents, I’ll probably use Mongo. If I need to write 1 billion objects a day, I’d probably use Voldemort. If I need full text search, I’d probably use Solr. If I need full text search of volatile data, I’d probably use Sphinx.
I like this article, I find it very informative, it gives a good overview of the NoSQL landscape and hype. But, and that's the most important part, it really helps to ask yourself the right questions when it comes to choose between RDBMS and NoSQL. Worth the read IMHO.
go test -v -timeout 30s <path_to_package> -run ^(TestFuncRegEx)
go
test file in that package-run TestCaseFunc
If you’re using TortoiseSVN…
From your commit window in the “Changes Made” section you can select all the offending files, then right-click and select delete. Finish the commit and the files will be removed from the scheduled additions.
You should be able to perform a select on the orders table, using a raw WHERE to find the max(id
) in a subquery, like this:
\DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();
If you want to use Eloquent (for example, so you can convert your response to an object) you will want to use whereRaw, because some functions such as toJSON
or toArray
will not work without using Eloquent models.
$order = Order::whereRaw('id = (select max(`id`) from orders)')->get();
That, of course, requires that you have a model that extends Eloquent.
class Order extends Eloquent {}
As mentioned in the comments, you don't need to use whereRaw
, you can do the entire query using the query builder without raw SQL.
// Using the Query Builder
\DB::table('orders')->find(\DB::table('orders')->max('id'));
// Using Eloquent
$order = Order::find(\DB::table('orders')->max('id'));
(Note that if the id
field is not unique, you will only get one row back - this is because find()
will only return the first result from the SQL server.).
Try with subprocess
CurlUrl="curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache-
Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding:
gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' --
compressed"
Use getstatusoutput
to store the results
status, output = subprocess.getstatusoutput(CurlUrl)
Update your
<li>
<a href="#about">About</a>
</li>
to
<li>
<a data-toggle="collapse" data-target=".nav-collapse" href="#about">About</a>
</li>
This simple change worked for me.
The syntax to modify a column in an existing table in SQL Server (Transact-SQL) is:
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
For example:
ALTER TABLE employees
ALTER COLUMN last_name VARCHAR(75) NOT NULL;
This SQL Server ALTER TABLE
example will modify the column called last_name
to be a data type of VARCHAR(75)
and force the column to not allow null values.
see here
First check if mingw32-make is installed on your system. Use mingw32-make.exe command in windows terminal or cmd to check, else install the package mingw32-make-bin.
then go to bin directory default ( C:\MinGW\bin) create new file make.bat
@echo off
"%~dp0mingw32-make.exe" %*
add the above content and save it
set the env variable in powershell
$Env:CC="gcc"
then compile the file
make hello
where hello.c is the name of source code
2^8 = 256 Characters. A character in binary is a series of 8 ( 0 or 1).
|----------------------------------------------------------|
| |
| Type | Storage | Minimum Value | Maximum Value |
| | (Bytes) | (Signed/Unsigned) | (Signed/Unsigned)|
| | | | |
|---------|---------|-------------------|------------------|
| | | | |
| | | | |
| TINYINT | 1 | -128 - 0 | 127 - 255 |
| | | | |
|----------------------------------------------------------|
you can do something like this
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
Reference is https://laravel.com/docs/5.1/collections#method-toarray
Originally from Laracasts website https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array
Swift 5.0
func makeTransform(horizontalDegree: CGFloat, verticalDegree: CGFloat, maxVertical: CGFloat,rotateDegree: CGFloat, maxHorizontal: CGFloat) -> CATransform3D {
var transform = CATransform3DIdentity
transform.m34 = 1 / -500
let xAnchor = (horizontalDegree / (2 * maxHorizontal)) + 0.5
let yAnchor = (verticalDegree / (-2 * maxVertical)) + 0.5
let anchor = CGPoint(x: xAnchor, y: yAnchor)
setAnchorPoint(anchorPoint: anchor, forView: self.imgView)
let hDegree = (CGFloat(horizontalDegree) * .pi) / 180
let vDegree = (CGFloat(verticalDegree) * .pi) / 180
let rDegree = (CGFloat(rotateDegree) * .pi) / 180
transform = CATransform3DRotate(transform, vDegree , 1, 0, 0)
transform = CATransform3DRotate(transform, hDegree , 0, 1, 0)
transform = CATransform3DRotate(transform, rDegree , 0, 0, 1)
return transform
}
func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = newPoint.applying(view.transform)
oldPoint = oldPoint.applying(view.transform)
var position = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
print("Anchor: \(anchorPoint)")
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
you only need to call the function with your degree. for example:
var transform = makeTransform(horizontalDegree: 20.0 , verticalDegree: 25.0, maxVertical: 25, rotateDegree: 20, maxHorizontal: 25)
imgView.layer.transform = transform
It worked using PSCP. Instructions:
set PATH=<path to the pscp.exe file>
pscp
use the following command to copy file form remote server to the local system
pscp [options] [user@]host:source target
So to copy the file /etc/hosts
from the server example.com
as user fred
to the file
c:\temp\example-hosts.txt
, you would type:
pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt
Thank you for planting a seed, Cel! I've been struggling with this for hours, finally got it. I was counting a text field, oops, calculation failed.
Created 2 helper columns in my raw data, each resulting in 1 if condition met, 0 if not. Then pulled each into a pivot column, mine are called, "Inbd" (for Inbound), "Back", where "Back" is a return to sending facility, so in reality the total is one trip, not 2 trips, i.e., back is a subset of inbound and not every inbd has a back (obviously). Trying to calculate in the pivot table so I can sort on the field the rate of back to inbound for each sending facility.
For my calculated field I used: =IFERROR(IF(Pvt_Back>0,Pvt_Back/Pvt_Inbd,0),0)
So: if we sent back to sending some number of times greater than 0, divide Back/Inbd to give me a rate; if equal to 0, then 0; if Inbd = 0, then 0 to avoid Div/0 error.
Thanks again!! :)
map[key] = value
is provided for easier syntax. It is easier to read and write.
The reason for which you need to have default constructor is that map[key]
is evaluated before assignment. If key wasn't present in map, new one is created (with default constructor) and reference to it is returned from operator[]
.
Use .net:
[System.IO.Path]::GetFileName("c:\foo.txt")
returns foo.txt
.
[System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt")
returns foo
If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10
, is good enough.
But if you want, say, a list of ten dict
s, do not use [{}]*10
-- that would give you a list with the same initially-empty dict
ten times, not ten distinct ones. Rather, use [{} for i in range(10)]
or similar constructs, to construct ten separate dict
s to make up your list.
Use array_walk_recursive function for multi-denominational array.
array_walk_recursive($data, function (&$v, $k) {
if($k == 'transaction_date'){
$v = date('d/m/Y',$v);
}
});
You can use this code for generating has code for a given string.
int hash = 7;
for (int i = 0; i < strlen; i++) {
hash = hash*31 + charAt(i);
}
This a old question, but this can useful for someone In my case i can't using a sub query because i have a big query and i need using min() on my result, if i use sub query the db need reexecute my big query. i'm using Mysql
select t.*
from (select m.*, @g := 0
from MyTable m --here i have a big query
order by id, record_date) t
where (1 = case when @g = 0 or @g <> id then 1 else 0 end )
and (@g := id) IS NOT NULL
Basically I ordered the result and then put a variable in order to get only the first record in each group.
Somehow I got it to work by using margin-right, and setting it to move from right to left. http://jsfiddle.net/gXdMc/
Don't know why for this case, margin-right 100% doesn't go off the screen. :D (tested on chrome 18)
EDIT: now left to right works too http://jsfiddle.net/6LhvL/
you should load jquery first because bootstrap use jquery features. like this:
<!doctype html>
<html>
<head>
<link type="text/css" rel="stylesheet" src="css/animate.css">
<link type="text/css" rel="stylesheet" src="css/bootstrap-theme.min.css">
<link type="text/css" rel="stylesheet" src="css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="css/custom.css">
<!-- Shuffle your scripts HERE -->
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/wow.min.js"></script>
<!-- End -->
<title>pyMeLy Interface</title>
</head>
<body>
<p class="title1"><strong>pyMeLy</strong></p>
<p class="title2"><em> A stylish way to view your media</em></p>
<div style="text-align:center;">
<button type="button" class="btn btn-primary">Movies</button>
<button type="button" class="btn btn-primary btn-lg">Large button</button>
</div>
</body>
</html>
Normally you'd just stick the code in Page_Load
in your .aspx
page's code-behind.
if (someVar) {
Item1.Visible = true;
Item2.Visible = false;
} else {
Item1.Visible = false;
Item2.Visible = true;
}
This assumes you've got Item1
and Item2
laid out on the page already.
Yes, a table row can slide up and down, but it's ugly, since it changes the shape of the table and makes everything jump. Instead, put and element in each td
... something that makes sense like a p
or h2
etc.
For how to implement a table slide toggle...
It's probably simplest to put the click handler on the entire table, .stopPropagation()
and check what was clicked.
If a td in a row with a colspan is clicked, close the p
in it. If it's not a td in a row with a colspan, then close then toggle the following row's p
.
It is essentially to wrap all your written content in an element inside the td
s, since you never want to slideUp
a td
or tr
or table shape will change!
Something like:
$(function() {
// Initially hide toggleable content
$("td[colspan=3]").find("p").hide();
// Click handler on entire table
$("table").click(function(event) {
// No bubbling up
event.stopPropagation();
var $target = $(event.target);
// Open and close the appropriate thing
if ( $target.closest("td").attr("colspan") > 1 ) {
$target.slideUp();
} else {
$target.closest("tr").next().find("p").slideToggle();
}
});
});?
... and try out this jsFiddle showing implementation of a +
- -
toggle.
The HTML just has to have alternating rows of several td
s and then a row with a td
of a colspan greater than 1. You can obviously adjust the specifics quite easily.
The HTML would look something like:
<table>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
</table>?
This looks like a Bootstrap issue...
Currently, here's a workaround : add .col-xs-12
to your responsive image.
You may do:
a= [1,1,1,2,2,3]
delete_list = [1,3]
delete_list.each do |del|
a.delete_at(a.index(del))
end
result : [1, 1, 2, 2]
User Pumbaa80's answer is great if you have an object you want pretty printed. If you're starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first:
var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);
This builds a JSON object from the string, and then converts it back to a string using JSON stringify's pretty print.
Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.
In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:
Google Maps API error: MissingKeyMapError [SOLVED]
Also, remember to replace YOUR_API_KEY with your actual API key!
Target with hash string 'android-18' is corresponding to the SDK level 18. You need to install SDK 18 from SDK manager.
Change padding-bottom , i.e may be the simplest possible way .
As you can state you need to have a mutable object, but let me suggest you to check over the global variables as they can help you or even solve this kind of issue!
example:
>>> def x(y):
... global z
... z = y
...
>>> x
<function x at 0x00000000020E1730>
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> z
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'z' is not defined
>>> x(2)
>>> x
<function x at 0x00000000020E1730>
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> z
2
Maybe the most intuitive solution is probably to use the stringr
function str_remove
which is even easier than str_replace
as it has only 1 argument instead of 2.
The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern)
.
See example:
strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")
[1] "_1121" "_1432" "_1121"
Another alternative, if you already have an instance of the object created and you want to add it as an @autowired dependency to initialize all the internal @autowired variables, could be the following:
@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
public void doStuff() {
YourObject obj = new YourObject("Value X", "etc");
autowireCapableBeanFactory.autowireBean(obj);
}
Do the following:
Dim dataTable1 As New DataTable
dataTable1.Columns.Add("FECHA")
dataTable1.Columns.Add("TT")
dataTable1.Columns.Add("DESCRIPCION")
dataTable1.Columns.Add("No. DOC")
dataTable1.Columns.Add("DEBE")
dataTable1.Columns.Add("HABER")
dataTable1.Columns.Add("SALDO")
For Each line As String In System.IO.File.ReadAllLines(objetos.url)
dataTable1.Rows.Add(line.Split(","))
Next
do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.
You can also wait on a Task that returns from your void async
The DDMS tool included in the Android SDK includes a tool for monitoring network traffic. It does not provide the kind of detail you get from tcpdump and similar low level tools, but it is still very useful.
Oficial documentation: http://developer.android.com/tools/debugging/ddms.html#network
Use the "not" selector.
For example, instead of:
$(".thumbs").hover()
try:
$(".thumbs:not(.selected)").hover()
I found another way to take a input value of a UITextField and cast it to a float:
var tempString:String?
var myFloat:Float?
@IBAction func ButtonWasClicked(_ sender: Any) {
tempString = myUITextField.text
myFloat = Float(tempString!)!
}
Il the library is not installed you should give boost libraries folder:
example:
g++ -L/usr/lib/x86_64-linux-gnu -lboost_system -lboost_filesystem prog.cpp -o prog
C:\java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
prepend in front of bootstrap class path
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xloggc:<file> log GC status to a file with time stamps
-Xbatch disable background compilation
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
-Xprof output cpu profiling data
-Xfuture enable strictest checks, anticipating future default
-Xrs reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni perform additional checks for JNI functions
-Xshare:off do not attempt to use shared class data
-Xshare:auto use shared class data if possible (default)
-Xshare:on require using shared class data, otherwise fail.
The -X options are non-standard and subject to change without notice.
Did you try du -ks | awk '{print $1*1024}'. That might just work.
What worked for was uninstalling jdk 9 and reinstalling jkd 8.x
On Mac in order to uninstall go to the terminal and follow this steps:
cd /Library/Java/JavaVirtualMachines
sudo rm -rf jdk-9.0.1.jdk
Then install the jdk 8.x by downloading the .dmg package from Oracle.
In Konsole (KDE terminal) is the same, Ctrl + Shift + V
$('.button1').click(function() {
window.location = "www.example.com/index.php?id=" + this.id;
});
First of all using window.location
is better as according to specification document.location
value was read-only and might cause you headaches in older/different browsers. Check notes @MDC DOM document.location page
And for the second - using attr
jQuery method to get id is a bad practice - you should use direct native DOM accessor this.id
as the value assigned to this
is normal DOM element.
Just to add more information to what Zain Abbas said:
Load the controller that way, and use it like he said:
$this->load->library('../controllers/instructor');
$this->instructor->functioname();
Or you can create an object and use it this way:
$this->load->library('../controllers/your_controller');
$obj = new $this->your_controller();
$obj->your_function();
Hope this can help.
You shouldn't have to make any changes to the certificate. Are you sure you are running the right import command?
The following works for me:
keytool -import -alias joe -file mycert.cer -keystore mycerts -storepass changeit
where mycert.cer contains:
-----BEGIN CERTIFICATE-----
MIIFUTCCBDmgAwIBAgIHK4FgDiVqczANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE
BhMCVVMxEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAY
...
RLJKd+SjxhLMD2pznKxC/Ztkkcoxaw9u0zVPOPrUtsE/X68Vmv6AEHJ+lWnUaWlf
zLpfMEvelFPYH4NT9mV5wuQ1Pgurf/ydBhPizc0uOCvd6UddJS5rPfVWnuFkgQOk
WmD+yvuojwsL38LPbtrC8SZgPKT3grnLwKu18nm3UN2isuciKPF2spNEFnmCUWDc
MMicbud3twMSO6Zbm3lx6CToNFzP
-----END CERTIFICATE-----
This not only works with cmake
, but also with ./configure
and make
:
./configure CC=/usr/local/bin/gcc CXX=/usr/local/bin/g++
Which is resulting in:
checking for gcc... /usr/local/bin/gcc
checking whether the C compiler works... yes
I made this for another project using random and time. I used a general format from time you can view the documentation here for the first argument in strftime(). The second part is a random.randrange function. It returns an integer between the arguments. Change it to the ranges that match the strings you would like. You must have nice arguments in the tuple of the second arugment.
import time
import random
def get_random_date():
return strftime("%Y-%m-%d %H:%M:%S",(random.randrange(2000,2016),random.randrange(1,12),
random.randrange(1,28),random.randrange(1,24),random.randrange(1,60),random.randrange(1,60),random.randrange(1,7),random.randrange(0,366),1))
In my code I use DATETIME DEFAULT CURRENT_TIMESTAMP
as the type and constraint of the column.
In your case your table definition would be
create table notes (
_id integer primary key autoincrement,
created_date date default CURRENT_DATE
)
As strings in C can not dynamically grow inplace substitution will generally not work. Therefore you need to allocate space for a new string that has enough room for your substitution and then copy the parts from the original plus the substitution into the new string. To copy the parts you would use strncpy.
Try RGBA, e.g.
div { background-color: rgba(255, 255, 255, 0.5); }
As always, this won't work in every single browser ever written.
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
$personCount=1;
while ($personCount < 10) {
$result=0;
$result.= $personCount . "person ";
$personCount++;
echo $result;
}
Check below method is working awesome also Oreo 8.1 ..
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO ManualMT-generated method stub
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
try {
FilePath = data.getData().getPath();
Uri selectedImageUri = data.getData();
if (selectedImageUri.toString().contains("storage/emulated")){
String[] split = selectedImageUri.toString().split("storage/");
FilePath = "storage/"+split[1];
} else {
FilePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
}
recyclerview.setVisibility(View.VISIBLE);
if (FilePath == null) {
FilePath = "";
}
File file = new File(FilePath);
reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
image_list.add(FilePath);
composeImageAdapter.notifyDataSetChanged();
} catch (Exception e){
Toast.makeText(ClusterCreateNote.this , e.toString(),Toast.LENGTH_SHORT).show();
}
}
break;
}
}
URI path Class:
public static class ImageFilePath {
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
public static String getPath(final Context context, final Uri uri) {
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.wifAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Log.e("typetype",type);
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{
split[1]
};
Log.e("gddhjf",getDataColumn(context, contentUri, selection, selectionArgs));
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return
"com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return
"com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
When you want start a new activity and finish the current activity you can do this:
API 11 or greater
Intent intent = new Intent(OldActivity.this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
API 10 or lower
Intent intent = new Intent(OldActivity.this, NewActivity.class);
intent.setFlags(IntentCompat.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
I hope this can help somebody =)
Put all the commands on to a script and it can be run like
ssh <remote-user>@<remote-host> "bash -s" <./remote-commands.sh
Second approach lets the compiler produce more optimized code, because when address of a variable is passed to a function, the compiler cannot keep its value in register(s) during subsequent calls to other functions. The completion code usually is used only once, just after the call, whereas "real" data returned from the call may be used more often
I'm using the /Console
parameter in the Visual Studio project Debug ? Start Options ? Command line arguments:
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
var runMode = args.Contains(@"/Console")
? WindowsService.RunMode.Console
: WindowsService.RunMode.WindowsService;
new WinodwsService().Run(runMode);
}
}
public class WindowsService : ServiceBase
{
public enum RunMode
{
Console,
WindowsService
}
public void Run(RunMode runMode)
{
if (runMode.Equals(RunMode.Console))
{
this.StartService();
Console.WriteLine("Press <ENTER> to stop service...");
Console.ReadLine();
this.StopService();
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
}
else if (runMode.Equals(RunMode.WindowsService))
{
ServiceBase.Run(new[] { this });
}
}
protected override void OnStart(string[] args)
{
StartService(args);
}
protected override void OnStop()
{
StopService();
}
/// <summary>
/// Logic to Start Service
/// Public accessibility for running as a console application in Visual Studio debugging experience
/// </summary>
public virtual void StartService(params string[] args){ ... }
/// <summary>
/// Logic to Stop Service
/// Public accessibility for running as a console application in Visual Studio debugging experience
/// </summary>
public virtual void StopService() {....}
}
Integer.valueOf()
returns an Integer object, while Integer.parseInt()
returns an int
primitive.
I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).
Adding to existing answers, it can be done like,
You can use System.Linq.
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
private IEnumerable<string> Tables
{
get {
yield return "Foo";
yield return "Bar";
}
}
static void Main()
{
var x = new Test();
Console.WriteLine(x.Tables.Count());
}
}
You'll get the result '2'.
In my experience, using the cross-join-with-a-where-clause syntax often produces a brain damaged execution plan, especially if you are using a Microsoft SQL product. The way that SQL Server attempts to estimate table row counts, for instance, is savagely horrible. Using the inner join syntax gives you some control over how the query is executed. So from a practical point of view, given the atavistic nature of current database technology, you have to go with the inner join.
In addition, you can use it to check if the dynamic allocation was successful.
Code example:
int ** p;
p = new int * [5]; // Dynamic array (size 5) of pointers to int
for (int i = 0; i < 5; ++i) {
p[i] = new int[3]; // Each i(ptr) is now pointing to a dynamic
// array (size 3) of actual int values
}
assert (p); // Check the dynamic allocation.
Similar to:
if (p == NULL) {
cout << "dynamic allocation failed" << endl;
exit(1);
}
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
I like to think of branches as where you're going, tags as where you've been.
A tag feels like a bookmark of a particular important point in the past, such as a version release.
Whereas a branch is a particular path the project is going down, and thus the branch marker advances with you. When you're done you merge/delete the branch (i.e. the marker). Of course, at that point you could choose to tag that commit.
You need to pass --whitelisted-ips=
into chrome driver (not chrome!). If you use ChromeDriver locally/directly (not using RemoteWebDriver) from code, it shouldn't be your problem.
If you use it remotely (eg. selenium hub/grid) you need to set system property when node starts, like in command:
java -Dwebdriver.chrome.whitelistedIps= testClass etc...
or docker by passing JAVA_OPTS
env
chrome:
image: selenium/node-chrome:3.141.59
container_name: chrome
depends_on:
- selenium-hub
environment:
- HUB_HOST=selenium-hub
- HUB_PORT=4444
- JAVA_OPTS=-Dwebdriver.chrome.whitelistedIps=
You can add one
public static boolean isNullOrBlank(String param) {
return param == null || param.trim().length() == 0;
}
I have
public static boolean isSet(String param) {
// doesn't ignore spaces, but does save an object creation.
return param != null && param.length() != 0;
}
This a much more elegant way to get the end of the month:
$thedate = Date('m/d/Y');
$lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate))));
This answer assumes that you have python3.6
installed. For python3.7
, replace 3.6
with 3.7
. For python3.8
, replace 3.6
with 3.8
, but it may also first require the python3.8-distutils
package.
With regard to installing pip
, using curl
(instead of wget
) avoids writing the file to disk.
curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6
The -H
flag is evidently necessary with sudo
in order to prevent errors such as the following when installing pip for an updated python interpreter:
The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user
This may sometimes give a warning such as:
WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
After this, pip
, pip3
, and pip3.6
can all be expected to point to the same target:
$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Of course you can alternatively use python3.6 -m pip
as well.
$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
A little late to the game here, but I was running into some performance issues with HYRY's solution, so I had to come up with another one.
It works by finding the frequency of each key-value, and then, for each key, only keeping the value that appears with it most often.
There's also an additional solution that supports multiple modes.
On a scale test that's representative of the data I'm working with, this reduced runtime from 37.4s to 0.5s!
Here's the code for the solution, some example usage, and the scale test:
import numpy as np
import pandas as pd
import random
import time
test_input = pd.DataFrame(columns=[ 'key', 'value'],
data= [[ 1, 'A' ],
[ 1, 'B' ],
[ 1, 'B' ],
[ 1, np.nan ],
[ 2, np.nan ],
[ 3, 'C' ],
[ 3, 'C' ],
[ 3, 'D' ],
[ 3, 'D' ]])
def mode(df, key_cols, value_col, count_col):
'''
Pandas does not provide a `mode` aggregation function
for its `GroupBy` objects. This function is meant to fill
that gap, though the semantics are not exactly the same.
The input is a DataFrame with the columns `key_cols`
that you would like to group on, and the column
`value_col` for which you would like to obtain the mode.
The output is a DataFrame with a record per group that has at least one mode
(null values are not counted). The `key_cols` are included as columns, `value_col`
contains a mode (ties are broken arbitrarily and deterministically) for each
group, and `count_col` indicates how many times each mode appeared in its group.
'''
return df.groupby(key_cols + [value_col]).size() \
.to_frame(count_col).reset_index() \
.sort_values(count_col, ascending=False) \
.drop_duplicates(subset=key_cols)
def modes(df, key_cols, value_col, count_col):
'''
Pandas does not provide a `mode` aggregation function
for its `GroupBy` objects. This function is meant to fill
that gap, though the semantics are not exactly the same.
The input is a DataFrame with the columns `key_cols`
that you would like to group on, and the column
`value_col` for which you would like to obtain the modes.
The output is a DataFrame with a record per group that has at least
one mode (null values are not counted). The `key_cols` are included as
columns, `value_col` contains lists indicating the modes for each group,
and `count_col` indicates how many times each mode appeared in its group.
'''
return df.groupby(key_cols + [value_col]).size() \
.to_frame(count_col).reset_index() \
.groupby(key_cols + [count_col])[value_col].unique() \
.to_frame().reset_index() \
.sort_values(count_col, ascending=False) \
.drop_duplicates(subset=key_cols)
print test_input
print mode(test_input, ['key'], 'value', 'count')
print modes(test_input, ['key'], 'value', 'count')
scale_test_data = [[random.randint(1, 100000),
str(random.randint(123456789001, 123456789100))] for i in range(1000000)]
scale_test_input = pd.DataFrame(columns=['key', 'value'],
data=scale_test_data)
start = time.time()
mode(scale_test_input, ['key'], 'value', 'count')
print time.time() - start
start = time.time()
modes(scale_test_input, ['key'], 'value', 'count')
print time.time() - start
start = time.time()
scale_test_input.groupby(['key']).agg(lambda x: x.value_counts().index[0])
print time.time() - start
Running this code will print something like:
key value
0 1 A
1 1 B
2 1 B
3 1 NaN
4 2 NaN
5 3 C
6 3 C
7 3 D
8 3 D
key value count
1 1 B 2
2 3 C 2
key count value
1 1 2 [B]
2 3 2 [C, D]
0.489614009857
9.19386196136
37.4375009537
Hope this helps!
You could use the static StartupPath property of the Application class.
From the bash manpage:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the
--login
option, it first reads and executes commands from the file/etc/profile
, if that file exists. After reading that file, it looks for~/.bash_profile
,~/.bash_login
, and~/.profile
, in that order, and reads and executes commands from the first one that exists and is readable. The--noprofile
option may be used when the shell is started to inhibit this behavior.When a login shell exits, bash reads and executes commands from the file
~/.bash_logout
, if it exists.When an interactive shell that is not a login shell is started, bash reads and executes commands from
~/.bashrc
, if that file exists. This may be inhibited by using the--norc
option. The--rcfile
file option will force bash to read and execute commands from file instead of~/.bashrc
.
Thus, if you want to get the same behavior for both login shells and interactive non-login shells, you should put all of your commands in either .bashrc
or .bash_profile
, and then have the other file source the first one.
<?php
// sample array
$fruits3 = [
"iron",
1,
"ascorbic",
"potassium",
"ascorbic",
2,
"2",
"1",
];
// Let's say we are looking for the item "ascorbic", in the above array
//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"
// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
return array_search($needle, array_reverse($arr, true), true);
}
echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"
// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()
When entered as the reference of a Named range
, it refers to range on the sheet the named range is used on.
For example, create a named range MyName
refering to =SUM(!B1:!K1)
Place a formula on Sheet1
=MyName
. This will sum Sheet1!B1:K1
Now place the same formula (=MyName
) on Sheet2
. That formula will sum Sheet2!B1:K1
Note: (as pnuts commented) this and the regular SheetName!B1:K1
format are relative, so reference different cells as the =MyName
formula is entered into different cells.
Try the following:
java -cp jar1:jar2:jar3:dir1:. HelloWorld
The default classpath (unless there is a CLASSPATH environment variable) is the current directory so if you redefine it, make sure you're adding the current directory (.) to the classpath as I have done.
I was doing this inside a virtualenv on Oracle Linux 6.4 using python-2.6 so the apt-based solutions weren't an option for me, nor were the python-2.7 ideas. My fix was to upgrade my version of setuptools that had been installed by virtualenv:
pip install --upgrade setuptools
After that, I was able to install packages into the virtualenv. I know this question has already had an answer selected but I hope this answer will help others in my situation.
You can explicitly call onBackPressed
is the easiest way
Refer Go back to previous activity for details
RunOnce is an option and have a few keys that can be used for pointing a command to start on startup (depending if it concerns a user or the whole system):
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
setting the value:
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v MyBat /D "!C:\mybat.bat"
With setting and exclamation mark at the beginning and if the script exist with a value different than 0 the registry key wont be deleted and the script will be executed every time on startup
You can use SCHTASKS and a triggering event:
SCHTASKS /Create /SC ONEVENT /MO ONLOGON /TN ON_LOGON /tr "c:\some.bat"
or
SCHTASKS /Create /SC ONEVENT /MO ONSTART/TN ON_START /tr "c:\some.bat"
You also have two startup folders - one for the current user and one global. There you can copy your scripts (or shortcuts) in order to start a file on startup
::the global one
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
::for the current user
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Change setInterval("func",10000)
to either setInterval(funcName, 10000)
or setInterval("funcName()",10000)
. The former is the recommended method.
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps
You can try this:
$(".myclass").mouseover(function() {
$(this).find(" > div").css("background-color","red");
}).mouseout(function() {
$(this).find(" > div").css("background-color","transparent");
});
I have tested the performance of three methods:
# Method 1: `del`
for key in remove_keys:
if key in d:
del d[key]
# Method 2: `pop()`
for key in remove_keys:
d.pop(key, None)
# Method 3: comprehension
{key: v for key, v in d.items() if key not in remove_keys}
Here are the results of 1M iterations:
del
: 2.03s 2.0 ns/iter (100%)pop()
: 2.38s 2.4 ns/iter (117%)So both del
and pop()
are the fastest. Comprehensions are 2x slower.
But anyway, we speak nanoseconds here :) Dicts in Python are ridiculously fast.
Javascript has a random()
available. Take a look at Math.random().
If you have a valid integer value and your requirement is to compare values, you can simply go ahead with the comparison as seen below.
Sub t()
Dim i As Integer
Dim s As String
' pass
i = 65
s = "65"
If i = s Then
MsgBox i
End If
' fail - Type Mismatch
i = 65
s = "A"
If i = s Then
MsgBox i
End If
End Sub
%S
seems to conform to The Single Unix Specification v2 and is also part of the current (2008) POSIX specification.
Equivalent C99 conforming format specifiers would be %s
and %ls
.
Create hash as:
h = Hash.new
=> {}
Now insert into hash as:
h = Hash["one" => 1]
<?php
$username = "the_username_here";
$password = "the_password_here";
$nonsense = "supercalifragilisticexpialidocious";
if (isset($_COOKIE['PrivatePageLogin'])) {
if ($_COOKIE['PrivatePageLogin'] == md5($password.$nonsense)) {
?>
<!-- LOGGED IN CONTENT HERE -->
<?php
exit;
} else {
echo "Bad Cookie.";
exit;
}
}
if (isset($_GET['p']) && $_GET['p'] == "login") {
if ($_POST['user'] != $username) {
echo "Sorry, that username does not match.";
exit;
} else if ($_POST['keypass'] != $password) {
echo "Sorry, that password does not match.";
exit;
} else if ($_POST['user'] == $username && $_POST['keypass'] == $password) {
setcookie('PrivatePageLogin', md5($_POST['keypass'].$nonsense));
header("Location: $_SERVER[PHP_SELF]");
} else {
echo "Sorry, you could not be logged in at this time.";
}
}
?>
And the login form on the page...
(On the same page, right below the above^ posted code)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<label><input type="text" name="user" id="user" /> Name</label><br />
<label><input type="password" name="keypass" id="keypass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</form>
Something else you can use is isnull
:
isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)
There is a tool localfont.com to help you download all font variants. It as well generates the corresponding CSS for implementation. deprecated
localfont is down. Instead, as Damir suggests, you can use google-webfonts-helper
You can also take a look at x-ray: https://github.com/lapwinglabs/x-ray
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
I hate answering my own question, but @Matt Bodily put me on the right track.
The @Html.Action
method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" })
does indeed return the URL, but I finally discovered an overload of Html.ActionLink
that provided a better solution for my case:
@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
Note: , null
is significant in this case, to match the right signature.
Documentation: @Html.ActionLink (LinkExtensions.ActionLink)
Documentation for this particular overload:
LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)
It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.
Still marking Matt's response as the answer.
Edit: Found yet another HTML helper to solve this:
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
This member fn returns an array of 0-based positions, if any, of the input word inside the String object
String.prototype.matching_positions = function( _word, _case_sensitive, _whole_words, _multiline )
{
/*besides '_word' param, others are flags (0|1)*/
var _match_pattern = "g"+(_case_sensitive?"i":"")+(_multiline?"m":"") ;
var _bound = _whole_words ? "\\b" : "" ;
var _re = new RegExp( _bound+_word+_bound, _match_pattern );
var _pos = [], _chunk, _index = 0 ;
while( true )
{
_chunk = _re.exec( this ) ;
if ( _chunk == null ) break ;
_pos.push( _chunk['index'] ) ;
_re.lastIndex = _chunk['index']+1 ;
}
return _pos ;
}
Now try
var _sentence = "What do doers want ? What do doers need ?" ;
var _word = "do" ;
console.log( _sentence.matching_positions( _word, 1, 0, 0 ) );
console.log( _sentence.matching_positions( _word, 1, 1, 0 ) );
You can also input regular expressions:
var _second = "z^2+2z-1" ;
console.log( _second.matching_positions( "[0-9]\z+", 0, 0, 0 ) );
Here one gets the position index of linear term.
Resolved it in 2 minutes downtime :)
Just move your folder, add symlink, then tune permissions.
sudo service mongod stop
sudo mv mongodb /new/disk/mongodb/
sudo ln -s /new/disk/mongodb/ /var/lib/mongodb
sudo chown mongodb:mongodb /new/disk/mongodb/
sudo service mongod start
# test if mongodb user can access new location:
sudo -u mongodb -s cd /new/disk/mongodb/
# resolve other permissions issues if necessary
sudo usermod -a -G <newdisk_grp> mongodb
The answer is to place the root dir to the location directives:
root /srv/www/ducklington.org/public_html;
If you face this issue directly after a complete new installation on Windows:
It seems like the setup program already starts the http.exe process and blocks the initial port 80 but does not reflect this state in the control panel.
To verify, just test for a running server in your browser. Type into your browser address bar:
localhost
If this displays the XAMPP dashboard, you're fine. Alternatively, check the Task Manager for a running 'Apache HTTP Server' (httpd.exe) process.
You could stop the apache process with the xampp_stop.exe in your xampp base folder. Then, the XAMPP control panel should work as expected.
Here's an option if you need to escape multiple %'s in a string with some already escaped.
(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])
To sanitise the message before passing it to String.format, you can use the following
Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);
StringBuffer buf = new StringBuffer();
while (m1.find())
m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));
// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();
This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.
It will leave any already escaped characters alone (e.g. %%, %%%% etc.)
How to drop rows of Pandas DataFrame whose value in a certain column is NaN
This is an old question which has been beaten to death but I do believe there is some more useful information to be surfaced on this thread. Read on if you're looking for the answer to any of the following questions:
DataFrame.dropna
: Usage, and ExamplesIt's already been said that df.dropna
is the canonical method to drop NaNs from DataFrames, but there's nothing like a few visual cues to help along the way.
# Setup
df = pd.DataFrame({
'A': [np.nan, 2, 3, 4],
'B': [np.nan, np.nan, 2, 3],
'C': [np.nan]*3 + [3]})
df
A B C
0 NaN NaN NaN
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
Below is a detail of the most important arguments and how they work, arranged in an FAQ format.
This is where the how=...
argument comes in handy. It can be one of
'any'
(default) - drops rows if at least one column has NaN'all'
- drops rows only if all of its columns have NaNs<!_ ->
# Removes all but the last row since there are no NaNs
df.dropna()
A B C
3 4.0 3.0 3.0
# Removes the first row only
df.dropna(how='all')
A B C
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
Note
If you just want to see which rows are null (IOW, if you want a boolean mask of rows), useisna
:df.isna() A B C 0 True True True 1 False True True 2 False False True 3 False False False df.isna().any(axis=1) 0 True 1 True 2 True 3 False dtype: bool
To get the inversion of this result, use
notna
instead.
This is a use case for the subset=[...]
argument.
Specify a list of columns (or indexes with axis=1
) to tells pandas you only want to look at these columns (or rows with axis=1
) when dropping rows (or columns with axis=1
.
# Drop all rows with NaNs in A
df.dropna(subset=['A'])
A B C
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
# Drop all rows with NaNs in A OR B
df.dropna(subset=['A', 'B'])
A B C
2 3.0 2.0 NaN
3 4.0 3.0 3.0
This is a use case for the thresh=...
argument. Specify the minimum number of NON-NULL values as an integer.
df.dropna(thresh=1)
A B C
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
df.dropna(thresh=2)
A B C
2 3.0 2.0 NaN
3 4.0 3.0 3.0
df.dropna(thresh=3)
A B C
3 4.0 3.0 3.0
The thing to note here is you need to specify how many NON-NULL values you want to keep, rather than how many NULL values you want to drop. This is a pain point for new users.
Luckily the fix is easy: if you have a count of NULL values, simply subtract it from the column size to get the correct thresh argument for the function.
required_min_null_values_to_drop = 2 # drop rows with at least 2 NaN
df.dropna(thresh=df.shape[1] - required_min_null_values_to_drop + 1)
A B C
2 3.0 2.0 NaN
3 4.0 3.0 3.0
Use the axis=...
argument, it can be axis=0
or axis=1
.
Tells the function whether you want to drop rows (axis=0
) or drop columns (axis=1
).
df.dropna()
A B C
3 4.0 3.0 3.0
# All columns have rows, so the result is empty.
df.dropna(axis=1)
Empty DataFrame
Columns: []
Index: [0, 1, 2, 3]
# Here's a different example requiring the column to have all NaN rows
# to be dropped. In this case no columns satisfy the condition.
df.dropna(axis=1, how='all')
A B C
0 NaN NaN NaN
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
# Here's a different example requiring a column to have at least 2 NON-NULL
# values. Column C has less than 2 NON-NULL values, so it should be dropped.
df.dropna(axis=1, thresh=2)
A B
0 NaN NaN
1 2.0 NaN
2 3.0 2.0
3 4.0 3.0
dropna
, like most other functions in the pandas API returns a new DataFrame (a copy of the original with changes) as the result, so you should assign it back if you want to see changes.
df.dropna(...) # wrong
df.dropna(..., inplace=True) # right, but not recommended
df = df.dropna(...) # right
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html
DataFrame.dropna( self, axis=0, how='any', thresh=None, subset=None, inplace=False)
The problems were:
The solution based on omerkirk's answer involves:
autoOpen: false, width: "auto", height: "auto"
Here is a rough outline of code:
<div class="thumb">
<a href="http://jsfiddle.net/yBNVr/show/" data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
<a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>
$(function () {
var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
autoOpen: false,
modal: true,
resizable: false,
width: "auto",
height: "auto",
close: function () {
iframe.attr("src", "");
}
});
$(".thumb a").on("click", function (e) {
e.preventDefault();
var src = $(this).attr("href");
var title = $(this).attr("data-title");
var width = $(this).attr("data-width");
var height = $(this).attr("data-height");
iframe.attr({
width: +width,
height: +height,
src: src
});
dialog.dialog("option", "title", title).dialog("open");
});
});
Demo here and code here. And another example along similar lines
Manually add it when you build the query:
SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2
UNION ALL
...
EXAMPLE:
DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))
INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'
INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'
SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2
RESULT:
SiteName column1 column2
Site1 1 a
Site1 2 b
Site2 3 c
Site2 4 d
No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.
Newer kernels (e.g. the latest Ubuntu kernels) come with the new 'perf' tools (apt-get install linux-tools
) AKA perf_events.
These come with classic sampling profilers (man-page) as well as the awesome timechart!
The important thing is that these tools can be system profiling and not just process profiling - they can show the interaction between threads, processes and the kernel and let you understand the scheduling and I/O dependencies between processes.
what you are doing here is reading one character at a time from the input stream and assume that all the characters between " " represent a word. BUT it's unlikely to be a " " after the last word, so that's probably why it does not work:
"word1 word2 word2EOF"
With the upcoming Python 3.10
release schedule
, the new pairwise
function provides a way to slide through pairs of consecutive elements, and thus find if all of these pairs satisfy the same predicate of ordering:
from itertools import pairwise
all(x <= y for x, y in pairwise([1, 2, 3, 5, 6, 7]))
# True
The intermediate result of pairwise
:
pairwise([1, 2, 3, 5, 6, 7])
# [(1, 2), (2, 3), (3, 5), (5, 6), (6, 7)]
In config.inc.php
in the top-level directory, set
$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users
If Lang
isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.
I have solved this if you are using array called for 2 tables. Example you have,
$tableA['yellow']
and $tableA['blue']
. You are getting these 2 values and you want to add another element inside them to separate them by their type
.
foreach ($tableA['yellow'] as $value) {
$value->type = 'YELLOW'; //you are adding new element named 'type'
}
foreach ($tableA['blue'] as $value) {
$value->type = 'BLUE'; //you are adding new element named 'type'
}
So, both of the tables value will have new element called type
.
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
For Angular 2, use this
<div [ngClass]="{'active': dashboardComponent.selected_menu == 'mapview'}">Content</div>
if else condition can be covered with ternary operator
@item.rigged? ? 'Yes' : 'No'
For those of you interested in PySpark version (actually it's same in Scala - see comment below) :
merchants_df_renamed = merchants_df.toDF(
'merchant_id', 'category', 'subcategory', 'merchant')
merchants_df_renamed.printSchema()
Result:
root
|-- merchant_id: integer (nullable = true)
|-- category: string (nullable = true)
|-- subcategory: string (nullable = true)
|-- merchant: string (nullable = true)
According to composer's manual:
require-dev (root-only)
Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both
install
orupdate
support the--no-dev
option that prevents dev dependencies from being installed.
So running composer install
will also download the development dependencies.
The reason is actually quite simple. When contributing to a specific library you may want to run test suites or other develop tools (e.g. symfony). But if you install this library to a project, those development dependencies may not be required: not every project requires a test runner.
It is a batch terminator, you can however change it to whatever you want
what about changing the position: relative on your #content #text div to position: absolute
#content #text {
position:absolute;
width:950px;
height:215px;
color:red;
}
then you can use the css properties left and top to position within the #content div
if (pathname.substring(0, 6) == "/sub/1") {
// ...
}
Pasting my code here, this should help. It shows the package which can be used.
import org.json.JSONException;
import org.json.JSONObject;
public class extractingJSON {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"}}";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
System.out.println(name);
String first = jsonObj.getJSONObject("arr").getString("a");
System.out.println(first);
}
}
Your sql is incorrect.
$sql = mysql_query("UPDATE anstalld....
only
$sql = "UPDATE anstalld...
You can reset the padding (and I think everything else) with initial
to the default.
p {
padding: initial;
}
Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:
<textarea name="comentarii" cols="36" rows="5" placeholder="Message>
OK, I'll take a stab at this. Python passes by object reference, which is different from what you'd normally think of as "by reference" or "by value". Take this example:
def foo(x):
print x
bar = 'some value'
foo(bar)
So you're creating a string object with value 'some value' and "binding" it to a variable named bar
. In C, that would be similar to bar
being a pointer to 'some value'.
When you call foo(bar)
, you're not passing in bar
itself. You're passing in bar
's value: a pointer to 'some value'. At that point, there are two "pointers" to the same string object.
Now compare that to:
def foo(x):
x = 'another value'
print x
bar = 'some value'
foo(bar)
Here's where the difference lies. In the line:
x = 'another value'
you're not actually altering the contents of x
. In fact, that's not even possible. Instead, you're creating a new string object with value 'another value'. That assignment operator? It isn't saying "overwrite the thing x
is pointing at with the new value". It's saying "update x
to point at the new object instead". After that line, there are two string objects: 'some value' (with bar
pointing at it) and 'another value' (with x
pointing at it).
This isn't clumsy. When you understand how it works, it's a beautifully elegant, efficient system.
Instead of:
void addStudent(person)
{
return;
}
try this:
void addStudent(student person)
{
return;
}
Since you have already declared a structure called 'student' you don't necessarily have to specify so in the function implementation as in:
void addStudent(struct student person)
{
return;
}
select COUNT(*)
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5
in express there may be application-scoped JSON formatters.
after looking at express\lib\response.js, I'm using this routine:
function writeJsonPToRes(app, req, res, obj) {
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
res.set('Content-Type', 'application/json');
var partOfResponse = JSON.stringify(obj, replacer, spaces)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
var callback = req.query[app.get('jsonp callback name')];
if (callback) {
if (Array.isArray(callback)) callback = callback[0];
res.set('Content-Type', 'text/javascript');
var cb = callback.replace(/[^\[\]\w$.]/g, '');
partOfResponse = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + partOfResponse + ');\n';
}
res.write(partOfResponse);
}
You could use numpy.arange
.
EDIT: The docs prefer numpy.linspace
. Thanks @Droogans for noticing =)
<%:
Html.DropDownListFor(
model => model.Color,
new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"}
},
"value",
"text",
Model.Color
)
)
%>
or you can write no classes, put something like this directly to the view.
I guess you should add android:centerColor
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#FFFFFF"
android:centerColor="#000000"
android:endColor="#FFFFFF"
android:angle="0" />
</shape>
This example displays a horizontal gradient from white to black to white.
From datetime.datetime you already can export to timestamps with method strftime. Following your function example:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return int(now.strftime("%s"))
If you want microseconds, you need to change the export string and cast to float like: return float(now.strftime("%s.%f"))
OS X 10.8.x with Homebrew:
brew install curl-ca-bundle
brew list curl-ca-bundle
cp /usr/local/Cellar/curl-ca-bundle/1.87/share/ca-bundle.crt /usr/local/etc/openssl/cert.pem
I do not feel there is anything wrong with using JQuery with angular and bootstrap, since it is included when adding bootstrap.
import {.......
declare var $: any;
@component.....
<div id="errorModal" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" ..............
showErrorModal() {
$("#errorModal").modal('show');
}
I believe you should escape the dot. Try:
String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];
Otherwise dot is interpreted as any character in regular expressions.
The python-shell
module by extrabacon
is a simple way to run Python scripts from Node.js with basic, but efficient inter-process communication and better error handling.
Installation: npm install python-shell
.
var PythonShell = require('python-shell');
PythonShell.run('my_script.py', function (err) {
if (err) throw err;
console.log('finished');
});
var PythonShell = require('python-shell');
var options = {
mode: 'text',
pythonPath: 'path/to/python',
pythonOptions: ['-u'],
scriptPath: 'path/to/my/scripts',
args: ['value1', 'value2', 'value3']
};
PythonShell.run('my_script.py', options, function (err, results) {
if (err)
throw err;
// Results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
For the full documentation and source code, check out https://github.com/extrabacon/python-shell
The browser is connected to the proxy so the data that the proxy gets from the web server is just sent via the same connection that the browser initiated to the proxy.
try this
/^(\+{0,})(\d{0,})([(]{1}\d{1,3}[)]{0,}){0,}(\s?\d+|\+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}(\s){0,}$/gm
valid formats
You can do like:
a="""xyz"""
g="abcd " & a
Or:
a=chr(34) & "xyz" & chr(34)
g="abcd " & a
In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":
find / -name index.html -print
Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:
/var/www/*
Or type:
find /var/www -name index.html -print
replace:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
with:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
if (isset($_POST['newsletter'])) {
$checkBoxValue = "yes";
} else {
$checkBoxValue = "no";
}
then replace this line of code:
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter"
with:
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter";
>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]
Or for integers:
>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]
Or for later versions of ruby (>= 1.9 - as pointed out by Alex):
>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]
Specifically, I want to mention one situation, by which you may confuse.
What is the difference between "\0" and ""?
The answer is that "\0"
represents in array is {0 0}
and ""
is {0}
.
Because "\0"
is still a string literal and it will also add "\0"
at the end of it. And ""
is empty but also add "\0"
.
Understanding of this will help you understand "\0"
deeply.
from django.http import QueryDict
def search(request):
if request.GET.\__contains__("q"):
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
return HttpResponse(message)
Use this way, django offical document recommended __contains__ method. See https://docs.djangoproject.com/en/1.9/ref/request-response/
rm -rf /var/log/jenkins too big the log
You could also try nextBoolean()
-Method
Here is an example: http://www.tutorialspoint.com/java/util/random_nextboolean.htm
This can be done by cloning to a new directory, then moving the .git
directory into your existing directory.
If your existing directory is named "code".
git clone https://myrepo.com/git.git temp
mv temp/.git code/.git
rm -rf temp
This can also be done without doing a checkout during the clone command; more information can be found here.
Yes you can. You can even test it:
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
console.log(++i);_x000D_
if (i === 5) clearInterval(timer);_x000D_
console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
In this example, this timer clears when i
reaches 5.
/* Microsoft Edge Browser 12-18 (All versions before Chromium) */
This one should work:
@supports (-ms-ime-align:auto) {
.selector {
property: value;
}
}
For more see: Browser Strangeness
This will do the trick :-
new Date().valueOf()
Using official HTML without adding extra CSS styles and classes, it's like native support.
Just add the following code:
$.fn.dropdown = (function() {
var $bsDropdown = $.fn.dropdown;
return function(config) {
if (typeof config === 'string' && config === 'toggle') { // dropdown toggle trigged
$('.has-child-dropdown-show').removeClass('has-child-dropdown-show');
$(this).closest('.dropdown').parents('.dropdown').addClass('has-child-dropdown-show');
}
var ret = $bsDropdown.call($(this), config);
$(this).off('click.bs.dropdown'); // Turn off dropdown.js click event, it will call 'this.toggle()' internal
return ret;
}
})();
$(function() {
$('.dropdown [data-toggle="dropdown"]').on('click', function(e) {
$(this).dropdown('toggle');
e.stopPropagation();
});
$('.dropdown').on('hide.bs.dropdown', function(e) {
if ($(this).is('.has-child-dropdown-show')) {
$(this).removeClass('has-child-dropdown-show');
e.preventDefault();
}
e.stopPropagation();
});
});
Dropdown of bootstrap can be easily changed to infinite level. It's a pity that they didn't do it.
BTW, a hover version: https://github.com/dallaslu/bootstrap-4-multi-level-dropdown
Here is a perfect demo: https://jsfiddle.net/dallaslu/adky6jvs/ (works well with Bootstrap v4.4.1)
Use:
<nav class="navbar navbar-inverse" role="navigation"></nav>
navbar-inverse {
background-color: #F8F8F8;
border-color: #E7E7E7;
}
Use a subquery:
SELECT * FROM
(
SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name
The inner query selects 20 users at random and the outer query orders the selected users by name.
So I had this same problem with WSUS and it turned out that IIS 8.5 was not binding to my ipv4 ip address, but was binding to ipv6 address. when I accessed it via localhost:8580 it would translate it to the ipv6 localhost address, and thus would work. Accessing it via ip was a no go. I had to manually bind the address using netsh, then it worked right away. bloody annoying.
Steps:
netsh http add iplisten ipaddress (IPADDRESSOFYOURSERVER)
that's it. You should get:
IP address successfully added
I found the commands here https://serverfault.com/questions/123796/get-iis-7-5-to-listen-on-ipv6
My solution combines the target and before selectors for our CMS. Other techniques don't account for text in the anchor. Adjust the height and the negative margin to the offset you need...
:target::before {
content: '';
display: block;
height: 180px;
margin-top: -180px;
}