The simplest way to do this is to use MATLAB's system function.
So basically, you would execute a Python function on MATLAB as you would do on the command prompt (Windows), or shell (Linux):
system('python pythonfile.py')
The above is for simply running a Python file. If you wanted to run a Python function (and give it some arguments), then you would need something like:
system('python pythonfile.py argument')
For a concrete example, take the Python code in Adrian's answer to this question, and save it to a Python file, that is test.py
. Then place this file in your MATLAB directory and run the following command on MATLAB:
system('python test.py 2')
And you will get as your output 4 or 2^2.
Note: MATLAB looks in the current MATLAB directory for whatever Python file you specify with the system
command.
This is probably the simplest way to solve your problem, as you simply use an existing function in MATLAB to do your bidding.
I also want to contribute to this answer. I was looking for something similar in jQuery and this what I eventually ended up using.
I got my loading spinner from http://ajaxload.info/. My solution is based on this simple answer at http://christierney.com/2011/03/23/global-ajax-loading-spinners/.
Basically your HTML markup and CSS would look like this:
<style>
#ajaxSpinnerImage {
display: none;
}
</style>
<div id="ajaxSpinnerContainer">
<img src="~/Content/ajax-loader.gif" id="ajaxSpinnerImage" title="working..." />
</div>
And then you code for jQuery would look something like this:
<script>
$(document).ready(function () {
$(document)
.ajaxStart(function () {
$("#ajaxSpinnerImage").show();
})
.ajaxStop(function () {
$("#ajaxSpinnerImage").hide();
});
var owmAPI = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID";
$.getJSON(owmAPI)
.done(function (data) {
alert(data.coord.lon);
})
.fail(function () {
alert('error');
});
});
</script>
It is as simple as that :)
The reason IMHO is because they are/were too lazy to implement/correct that mistake. Suggesting that C/C++ programmers does not understand unsigned, structure, union, bit flag... Is just preposterous.
Ether you were talking with a basic/bash/java programmer on the verge of beginning programming a la C, without any real knowledge this language or you are just talking out of your own mind. ;)
when you deal every day on format either from file or hardware you begin to question, what in the hell they were thinking.
A good example here would be trying to use an unsigned byte as a self rotating loop. For those of you who do not understand the last sentence, how on earth you call yourself a programmer.
DC
You can use Notepad++ to evaluate a file's encoding without needing to write code. The evaluated encoding of the open file will display on the bottom bar, far right side. The encodings supported can be seen by going to Settings -> Preferences -> New Document/Default Directory
and looking in the drop down.
Take a look at this http://benalman.com/code/projects/jquery-resize/examples/resize/
It has various examples. Try resizing your window and see how elements inside container elements adjusted.
Example with js fiddle to explain how to get it work.
Take a look at this fiddle http://jsfiddle.net/sgsqJ/4/
In that resize() event is bound to an elements having class "test" and also to the window object and in resize callback of window object $('.test').resize() is called.
e.g.
$('#test_div').bind('resize', function(){
console.log('resized');
});
$(window).resize(function(){
$('#test_div').resize();
});
import { readFileSync } from 'fs';
const file = readFileSync('./filename.txt', 'utf-8');
This worked for me.
You may need to wrap the second command in any function or you may need to declare inside a class without keyword const
.
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
I recommend you to read more about the this keyword.
You cannot expect "this" to select the "select" tag in this case.
What you want to do in this case is use obj.id
to get the id of select tag.
You should be able to do something like this:
http://maps.google.com/maps?q=24.197611,120.780512
Some more info on the query parameters available at this location
Here's another link to an SO thread
I think it is the autoboxing that is throwing you off.
This part of your code:
public static Integer inc(Integer i) {
i = i+1; // I think that this must be **sneakally** creating a new integer...
System.out.println("Inc: "+i);
return i;
}
Really boils down to code that looks like:
public static Integer inc(Integer i) {
i = new Integer(i) + new Integer(1);
System.out.println("Inc: "+i);
return i;
}
Which of course.. will not changes the reference passed in.
You could fix it with something like this
public static void main(String[] args) {
Integer integer = new Integer(0);
for (int i =0; i<10; i++){
integer = inc(integer);
System.out.println("main: "+integer);
}
}
You can use the SpringBoot plugin:
plugins {
id "org.springframework.boot" version "2.2.2.RELEASE"
}
Create the jar
gradle assemble
And then run it
java -jar build/libs/*.jar
Note: your project does NOT need to be a SpringBoot project to use this plugin.
I met similar problem. the log is like below
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to 0.0.0.0:443 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: bind() to [::]:80 failed (98: Address already in use)
2018/10/31 12:54:20 [emerg] 128005#128005: still could not bind()
2018/10/31 12:54:23 [alert] 127997#127997: unlink() "/run/nginx.pid" failed (2: No such file or directory)
2018/10/31 22:40:48 [info] 36948#36948: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:68
2018/10/31 22:50:40 [emerg] 37638#37638: duplicate listen options for [::]:80 in /etc/nginx/sites-enabled/default:18
2018/10/31 22:51:33 [info] 37787#37787: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:68
The last [emerg]
shows that duplicate listen options for [::]:80
which means that there are more than one nginx block file containing [::]:80
.
My solution is to remove one of the [::]:80
setting
P.S. you probably have default block file. My advice is to keep this file as default server for port 80. and remove [::]:80
from other block files
If you've just got the iterator then that's what you'll have to do - it doesn't know how many items it's got left to iterate over, so you can't query it for that result. There are utility methods that will seem to do this efficiently (such as Iterators.size()
in Guava), but underneath they're just consuming the iterator and counting as they go, the same as in your example.
However, many iterators come from collections, which you can often query for their size. And if it's a user made class you're getting the iterator for, you could look to provide a size() method on that class.
In short, in the situation where you only have the iterator then there's no better way, but much more often than not you have access to the underlying collection or object from which you may be able to get the size directly.
Adding .dockerignore works for me. One additional point Those who are trying this solution on Windows , windows will not let you create .dockerignore file (as it doesn't by default allows creating file starting with .)
To create such file starting with . on Windows, include an ending dot also, like : .dockerignore.
and hit enter ( provided you have enabled view extension options from folder options )
A. Grab file data from the file field
The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
This saves the file data to a file variable for later use.
B. Handle the file upload on submit
When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:
C. Upload the files
Quick and dirty php script to upload the files and pass back some info:
<?php // You need to add server side validation and better error handling here
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = './uploads/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
IMP: Don't use this, write your own.
D. Handle the form submit
The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
Final note
This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.
Thanks for above answer , here is my jQuery code that is working now:
$(".header-login-li").click(function(){
activaTab('pane_login');
});
$(".header-register-li").click(function(){
activaTab('pane_reg');
$("#reg_log_modal_header_text").css()
});
function activaTab(tab){
$('.nav-tabs a[href="#' + tab + '"]').tab('show');
};
The way I load static images
and fonts
:
module: {
rules: [
....
{
test: /\.(jpe?g|png|gif|svg)$/i,
/* Exclude fonts while working with images, e.g. .svg can be both image or font. */
exclude: path.resolve(__dirname, '../src/assets/fonts'),
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}]
},
{
test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=\d+\.\d+\.\d+)?$/,
/* Exclude images while working with fonts, e.g. .svg can be both image or font. */
exclude: path.resolve(__dirname, '../src/assets/images'),
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
},
}
]
}
Don't forget to install file-loader
to have that working.
I had this issue when I forgot to add the new .h/.c file I created to the meson recipe so this is just a friendly reminder.
I hope following code will give you more information.
select * from information_schema.triggers where
information_schema.triggers.trigger_schema like '%your_db_name%'
This will give you total 22 Columns in MySQL version: 5.5.27 and Above
TRIGGER_CATALOG
TRIGGER_SCHEMA
TRIGGER_NAME
EVENT_MANIPULATION
EVENT_OBJECT_CATALOG
EVENT_OBJECT_SCHEMA
EVENT_OBJECT_TABLE
ACTION_ORDER
ACTION_CONDITION
ACTION_STATEMENT
ACTION_ORIENTATION
ACTION_TIMING
ACTION_REFERENCE_OLD_TABLE
ACTION_REFERENCE_NEW_TABLE
ACTION_REFERENCE_OLD_ROW
ACTION_REFERENCE_NEW_ROW
CREATED
SQL_MODE
DEFINER
CHARACTER_SET_CLIENT
COLLATION_CONNECTION
DATABASE_COLLATION
I just did this in v5.9.1. Just go to the Macro Menu, click "Start Recording", perform your 3 replace all commands, then stop recording. You can then select "Save Current Recorded Macro", and play it back as often as you like, and it will perform the replaces as you expect.
Ensure you have the maven.google.com repository declared in your module-level build.gradle file
repositories {
maven {
url 'https://maven.google.com'
}
}
2.Add the library as a dependency in the same build.gradle file:
dependencies {
compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
RelativeLayout relativeLayout; //declare this globally
now, inside any function like onCreate, onResume
relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is
setContentView(relativeLayout); //you might be forgetting this
If youR data was in A1:C100
then:
Excel - all versions
=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))
Excel - 2007 onwards
=COUNTIFS(A1:A100,"M",C1:C100,"Yes")
Running JMeter in command line mode:
1.Navigate to JMeter’s bin directory
Now enter following command,
jmeter -n –t test.jmx
-n: specifies JMeter is to run in non-gui mode
-t: specifies name of JMX file that contains the Test Plan
add -e
key for passing environment variables to container.
example:
$ MYSQLHOSTIP=$(sudo docker inspect -format="{{ .NetworkSettings.IPAddress }}" $MYSQL_CONRAINER_ID)
$ sudo docker run -e DBIP=$MYSQLHOSTIP -i -t myimage /bin/bash
root@87f235949a13:/# echo $DBIP
172.17.0.2
$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Recurse
This will delete old folders and it content.
I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear:
And trying to move a not-too-long basename to a too-long-pathname is also very clear:
The pathname error is deceptive, though. Quite unhelpful:
This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.
Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.
public class Parent {
public int add(int m, int n){
return m+n;
}
}
public class Child extends Parent{
public int add(int m,int n,int o){
return super.add(super.add(m, n),0);
}
}
public class SimpleInheritanceTest {
public static void main(String[] a){
Child child = new Child();
child.add(10, 11);
}
}
The add
method in the Child class calls super.add
to reuse the addition logic.
If the user has not generated a ssh public/private key pair set before
This info is working on theChaw but can be applied to all other git repositories which support SSH pubkey authentications. (See gitolite, gitlab or github for example.)
First start by setting up your own public/private key pair set. This can use either DSA or RSA, so basically any key you setup will work. On most systems you can use ssh-keygen.
- First you'll want to cd into your .ssh directory. Open up the terminal and run:
cd ~/.ssh && ssh-keygen
- Next you need to copy this to your clipboard.
- On OS X run:
cat id_rsa.pub | pbcopy
- On Linux run:
cat id_rsa.pub | xclip
- On Windows (via Cygwin/Git Bash) run:
cat id_rsa.pub | clip
- Add your key to your account via the website.
- Finally setup your .gitconfig.
git config --global user.name "bob"
git config --global user.email bob@...
(don't forget to restart your command line to make sure the config is reloaded)That's it you should be good to clone and checkout.
Further information can be found at https://help.github.com/articles/generating-ssh-keys (thanks to @Lee Whitney) -
If the user has generated a ssh public/private key pair set before
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I would just use a value in the querystring to pass the required information to the next page.
I had the same problem. It works perfectly fine when you add this:
android:inputType="textFilter"
to your EditText
.
Be sure to check out the VS 2010 Beta that was just released. The new editor should have this.
Your function shouldn't take vector<int>*
; it should take vector<int>::iterator
or vector<int>::const_iterator
as appropriate. Then, just pass in foo.begin() + 1
.
In Swift:
import UIKit
extension UIView {
/**
Removes all constrains for this view
*/
func removeConstraints() {
let constraints = self.superview?.constraints.filter{
$0.firstItem as? UIView == self || $0.secondItem as? UIView == self
} ?? []
self.superview?.removeConstraints(constraints)
self.removeConstraints(self.constraints)
}
}
You can use
DispatchQueue.main.asyncAfter(deadline: .now() + .microseconds(100)) {
// Code
}
You could also try string addition:
print " "+'"'+'a word that needs quotation marks'+'"'
If you are looking to create an instant messenger for Android, this code should get you started somewhere.
Excerpt from the source :
This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.
EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.
There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!
*UPDATE : * Scringo services will be closed down on 15 February, 2015.
You can also do this,
<?php
if ( ($cart->count_product) > 0) {
$print .= "<div class='my_class'>"
$print .= $cart->count_product;
$print .= "</div>"
} else {
$print = '';
}
echo $print;
?>
You can also find a copy of the nuspec.xsd here as it seems to no longer be available:
This can be done using the tag <ScrollView>
. For ScrollView, one thing you have to remind that, ScrollView must have a single child.
If you want your full layout to be scrollable then add <ScrollView>
at the top. Check the example given below.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Content here -->
</LinearLayout>
</ScrollView>
But if you want some part of your layout to be scrollable then add <ScrollView>
within that part. Check the example given below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="400dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Content here -->
</LinearLayout>
</ScrollView>
</LinearLayout>
If you used the auth scaffolding in 5.5 simply direct your href
to:
{{ route('logout') }}
There is no need to alter any routes or controllers.
I had this issue, and after doing some debugging, and searching I realized that the SERVER (Godaddy) can have issues.
I recommend you contact your Web hosting Provider and talk to them about Quota Restrictions
on the mail function (They do this to prevent people doing spam bots or mass emailing (spam) ).
They may be able to advise you of their limits, and if you're exceeding them. You can also possibly upgrade limit by going to private server.
After talking with GoDaddy for 15 minutes the tech support was able to resolve this within 20 minutes.
This helped me out a lot, and I wanted to share it so if someone else comes across this they can try this method if all fails, or before they try anything else.
This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.
You can include dependent jars using plugin.
Add below snippet into your pom's plugins section
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
Here's a simple, pure-Python implementation. It should be used when performance is not critical (included for future Googlers).
import string
allowed = set(string.ascii_lowercase + string.digits + '.')
def check(test_str):
set(test_str) <= allowed
Regarding performance, iteration will probably be the fastest method. Regexes have to iterate through a state machine, and the set equality solution has to build a temporary set. However, the difference is unlikely to matter much. If performance of this function is very important, write it as a C extension module with a switch statement (which will be compiled to a jump table).
Here's a C implementation, which uses if statements due to space constraints. If you absolutely need the tiny bit of extra speed, write out the switch-case. In my tests, it performs very well (2 seconds vs 9 seconds in benchmarks against the regex).
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *check(PyObject *self, PyObject *args)
{
const char *s;
Py_ssize_t count, ii;
char c;
if (0 == PyArg_ParseTuple (args, "s#", &s, &count)) {
return NULL;
}
for (ii = 0; ii < count; ii++) {
c = s[ii];
if ((c < '0' && c != '.') || c > 'z') {
Py_RETURN_FALSE;
}
if (c > '9' && c < 'a') {
Py_RETURN_FALSE;
}
}
Py_RETURN_TRUE;
}
PyDoc_STRVAR (DOC, "Fast stringcheck");
static PyMethodDef PROCEDURES[] = {
{"check", (PyCFunction) (check), METH_VARARGS, NULL},
{NULL, NULL}
};
PyMODINIT_FUNC
initstringcheck (void) {
Py_InitModule3 ("stringcheck", PROCEDURES, DOC);
}
Include it in your setup.py:
from distutils.core import setup, Extension
ext_modules = [
Extension ('stringcheck', ['stringcheck.c']),
],
Use as:
>>> from stringcheck import check
>>> check("abc")
True
>>> check("ABC")
False
Try this in input field:
[readonly]="true"
Hope, this will work.
How are you calling split
? It works like this:
def values = '1182-2'.split('-')
assert values[0] == '1182'
assert values[1] == '2'
Shelving is like your changes have been stored in the source control without affecting the existing changes. Means if you check in a file in source control it will modify the existing file but shelving is like storing your changes in source control but without modifying the actual changes.
If you really just want a random value from the available key range, use random.choice
on the dictionary's values (converted to list form, if Python 3).
>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))
To copy whole datatable just do this:
DataGridView sourceGrid = this.dataGridView1;
DataGridView targetGrid = this.dataGridView2;
targetGrid.DataSource = sourceGrid.DataSource;
It is because display:inline-block
takes into account white-space in the html. If you remove the white-space between the div
's it works as expected. Live Example: http://jsfiddle.net/XCDsu/4/
<div id="col1">content</div><div id="col2">content</div>
I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.
I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.
There are two examples illustrates difference
int a , b , c = 0 ;
a = ++c ;
b = c++ ;
printf (" %d %d %d " , a , b , c++);
a = 1
and value of c = 1
next statement assiagn value of c = 1
to b then increment c by 1 so
value of b = 1
and value of c = 2
in printf
statement we have c++
this mean that orginal value of c
which is 2 will printed then increment c by 1 so printf
statement
will print 1 1 2
and value of c now is 3
you can use http://pythontutor.com/c.html
int a , b , c = 0 ;
a = ++c ;
b = c++ ;
printf (" %d %d %d " , a , b , ++c);
printf
statement ++c
will increment value of c by 1 first then
assign new value 3 to c so printf
statement will print 1 1 3
read
Here's an example that uses read
to get the password and store it in the variable pass
. Then, 7z
uses the password to create an encrypted archive:
read -s -p "Enter password: " pass && 7z a archive.zip a_file -p"$pass"; unset pass
But be aware that the password can easily be sniffed.
I had the same issue when I clone my project from Git and directly build the solution first time. Instead of that go to the local repository in file explorer and double click the solution file (.sln) solved my issue.
It works for me, use iframe to ignore browsers show GET error message
var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
if ($(imgFrame).find('img').attr('width') > 0) {
// do something
} else {
// do something
}
Description:
there are 3 steps to run PHP code inside post or page.
In functions.php
file (in your theme) add new function
In functions.php
file (in your theme) register new shortcode which call your function:
add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
Example #1: just display text.
In functions:
function simple_function_1() {
return "Hello World!";
}
add_shortcode( 'own_shortcode1', 'simple_function_1' );
In post/page:
[own_shortcode1]
Effect:
Hello World!
Example #2: use for loop.
In functions:
function simple_function_2() {
$output = "";
for ($number = 1; $number < 10; $number++) {
// Append numbers to the string
$output .= "$number<br>";
}
return "$output";
}
add_shortcode( 'own_shortcode2', 'simple_function_2' );
In post/page:
[own_shortcode2]
Effect:
1
2
3
4
5
6
7
8
9
Example #3: use shortcode with arguments
In functions:
function simple_function_3($name) {
return "Hello $name";
}
add_shortcode( 'own_shortcode3', 'simple_function_3' );
In post/page:
[own_shortcode3 name="John"]
Effect:
Hello John
Example #3 - without passing arguments
In post/page:
[own_shortcode3]
Effect:
Hello
Small performance test comparision for three solutions:
$(".link").prop('href',"https://example.com")
$(".link").attr('href',"https://example.com")
document.querySelector(".link").href="https://example.com";
Here you can perform test by yourself https://jsperf.com/a-href-js-change
We can read href values in following ways
let href = $(selector).prop('href');
let href = $(selector).attr('href');
let href = document.querySelector(".link").href;
Here you can perform test by yourself https://jsperf.com/a-href-js-read
the style is:
<style type="text/css">
.topcorner{
position:absolute;
top:0;
right:0;
}
</style>
hope it will work. Thanks
You can put the values as the table's keys. For example:
function addToSet(set, key)
set[key] = true
end
function removeFromSet(set, key)
set[key] = nil
end
function setContains(set, key)
return set[key] ~= nil
end
There's a more fully-featured example here.
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
Employer employer = context.Employers.First(x => x.EmployerId == 1);
context.Customers.DeleteObject(employer);
context.SaveChanges();
You just need to change directories to your app, THEN run bundle install
:)
Change the <td>
to be split to look like this:
<td><table><tr><td>split 1</td><td>split 2</td></tr></table></td>
It means node is not able to listen on defined port. Change it to something like 1234 or 2000 or 3000 and restart your server.
The &nKByte
creates a temporary value, which cannot be bound to a reference to non-const.
You could change void test(float *&x)
to void test(float * const &x)
or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);
.
I don't know JavaScript, but isn't it possible using regex?
Something like [^\w\d\s]
will match anything but digits, characters and whitespaces. It would be just a question to find the syntax in JavaScript.
If you are converting it to string, you can easily do it like this.
I'm taking date as your DateTime object.
date.ToString("d");
This will give you only the date.
This is an ugly but fast solution: use JDK 6 instead of 7.
After read Chloe's answer, I uninstalled my JDK 7 (don't need it currently anyways) and installed JDK 6. That fixed it. A better solution would make ant uses JDK 6 (without uninstalling 7). Maybe possible changing / setting this property:
java.library.path
in local.properties file. It's in the project directory (root).
Android doesn't work with JDK 7 anyways (only 6 or 5), so make that the ant script also uses JDK 6 or 5 is probably a good solution.
/revive
ES6 Version using Class-y syntactic sugar
(slightly-modified: added start())
class Timer {_x000D_
constructor(callback, delay) {_x000D_
this.callback = callback_x000D_
this.remainingTime = delay_x000D_
this.startTime_x000D_
this.timerId_x000D_
}_x000D_
_x000D_
pause() {_x000D_
clearTimeout(this.timerId)_x000D_
this.remainingTime -= new Date() - this.startTime_x000D_
}_x000D_
_x000D_
resume() {_x000D_
this.startTime = new Date()_x000D_
clearTimeout(this.timerId)_x000D_
this.timerId = setTimeout(this.callback, this.remainingTime)_x000D_
}_x000D_
_x000D_
start() {_x000D_
this.timerId = setTimeout(this.callback, this.remainingTime)_x000D_
}_x000D_
}_x000D_
_x000D_
// supporting code_x000D_
const pauseButton = document.getElementById('timer-pause')_x000D_
const resumeButton = document.getElementById('timer-resume')_x000D_
const startButton = document.getElementById('timer-start')_x000D_
_x000D_
const timer = new Timer(() => {_x000D_
console.log('called');_x000D_
document.getElementById('change-me').classList.add('wow')_x000D_
}, 3000)_x000D_
_x000D_
pauseButton.addEventListener('click', timer.pause.bind(timer))_x000D_
resumeButton.addEventListener('click', timer.resume.bind(timer))_x000D_
startButton.addEventListener('click', timer.start.bind(timer))
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Traditional HTML Document. ZZz...</title>_x000D_
<style type="text/css">_x000D_
.wow { color: blue; font-family: Tahoma, sans-serif; font-size: 1em; }_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<h1>DOM & JavaScript</h1>_x000D_
_x000D_
<div id="change-me">I'm going to repaint my life, wait and see.</div>_x000D_
_x000D_
<button id="timer-start">Start!</button>_x000D_
<button id="timer-pause">Pause!</button>_x000D_
<button id="timer-resume">Resume!</button>_x000D_
</body>_x000D_
</html>
_x000D_
The following javascript will fade in an element from opacity 0 to whatever the opacity value was at the time of calling fade in. You can also set the duration of the animation which is nice:
function fadeIn(element) {
var duration = 0.5;
var interval = 10;//ms
var op = 0.0;
var iop = element.style.opacity;
var timer = setInterval(function () {
if (op >= iop) {
op = iop;
clearInterval(timer);
}
element.style.opacity = op;
op += iop/((1000/interval)*duration);
}, interval);
}
*Based on IBUs answer but modified to account for previous opacity value and ability to set duration, also removed irrelevant CSS changes it was making
Here is how I did this, somewhat similar to the solutions above. Just make sure you call the loadDots() method after all images are downloaded.
private int dotsCount;
private TextView dotsTextView[];
private void setupAdapter() {
adapter = new SomeAdapter(getContext(), images);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
private final ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++)
dotsTextView[i].setTextColor(Color.GRAY);
dotsTextView[position].setTextColor(Color.WHITE);
}
@Override
public void onPageScrollStateChanged(int state) {}
};
protected void loadDots() {
dotsCount = adapter.getCount();
dotsTextView = new TextView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dotsTextView[i] = new TextView(getContext());
dotsTextView[i].setText(R.string.dot);
dotsTextView[i].setTextSize(45);
dotsTextView[i].setTypeface(null, Typeface.BOLD);
dotsTextView[i].setTextColor(android.graphics.Color.GRAY);
mDotsLayout.addView(dotsTextView[i]);
}
dotsTextView[0].setTextColor(Color.WHITE);
}
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#00000000"/>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/introImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:id="@+id/image_count"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000"
android:gravity="center|bottom"
android:orientation="horizontal"/>
</FrameLayout>
That is not an nginx
configuration file. It is part of an nginx
configuration file.
The nginx
configuration file (usually called nginx.conf
) will look like:
events {
...
}
http {
...
server {
...
}
}
The server
block is enclosed within an http
block.
Often the configuration is distributed across multiple files, by using the include
directives to pull in additional fragments (for example from the sites-enabled
directory).
Use sudo nginx -t
to test the complete configuration file, which starts at nginx.conf
and pulls in additional fragments using the include
directive. See this document for more.
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
This happens when accessing a package scoped method of a class that is in the same package but is in a different jar and classloader.
This was my source, but the link is now broken. Following is full text from google cache:
Packages (as in package access) are scoped per ClassLoader.
You state that the parent ClassLoader loads the interface and the child ClassLoader loads the implementation. This won't work because of the ClassLoader-specific nature of package scoping. The interface isn't visible to the implementation class because, even though it's the same package name, they're in different ClassLoaders.
I only skimmed the posts in this thread, but I think you've already discovered that this will work if you declare the interface to be public. It would also work to have both interface and implementation loaded by the same ClassLoader.
Really, if you expect arbitrary folks to implement the interface (which you apparently do if the implementation is being loaded by a different ClassLoader), then you should make the interface public.
The ClassLoader-scoping of package scope (which applies to accessing package methods, variables, etc.) is similar to the general ClassLoader-scoping of class names. For example, I can define two classes, both named com.foo.Bar, with entirely different implementation code if I define them in separate ClassLoaders.
Joel
You can use a node.js extension to provide bindings for your C++ code. Here is one tutorial that covers that:
http://syskall.com/how-to-write-your-own-native-nodejs-extension
for disable sorting on any column in datatable use the following
aoColumnDefs: [{ "aTargets": [ 0 ], "bSortable": false}],
it means "aTargets": [ 0 ]
is the column id starting from 0
so in your case it becomes:
$(".tableSort").dataTable({
aaSorting: [[0, 'asc']],
aoColumnDefs: [
{ "aTargets": [ -1 ], "bSortable": false},
]
});
For anyone looking for a UI option using IIS Manager.
Get a decent text editor like Notepad++ or Vim (if you're already proficient with it). Search for the table name and you should be able to highlight just the CREATE, ALTER, and INSERT commands for that table. It may be easier to navigate with your keyboard rather than a mouse. And I would make sure you're on a machine with plenty or RAM so that it will not have a problem loading the entire file at once. Once you've highlighted and copied the rows you need, it would be a good idea to back up just the copied part into it's own backup file and then import it into MySQL.
Check your dao class. It must be like this:
Session session = getCurrentSession();
Query query = session.createQuery(GET_ALL);
And annotations:
@Transactional
@Repository
The -H 'Cache-Control: no-cache'
argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.
curl "http://www.example.com?foo123"
You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s
, which will return the seconds since epoch.
curl "http://www.example.com?$(date +%s)"
You can also configure directly on the file ..sqldeveloper\ide\bin\ide.conf
:
Just add the JVM Option:
AddVMOption -Duser.language=en
The file will be like this:
Just for clarification, CorFlags.exe is part of the .NET Framework SDK. I have the development tools on my machine, and the simplest way for me determine whether a DLL is 32-bit only is to:
Open the Visual Studio Command Prompt (In Windows: menu Start/Programs/Microsoft Visual Studio/Visual Studio Tools/Visual Studio 2008 Command Prompt)
CD to the directory containing the DLL in question
Run corflags like this:
corflags MyAssembly.dll
You will get output something like this:
Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Version : v2.0.50727
CLR Header: 2.5
PE : PE32
CorFlags : 3
ILONLY : 1
32BIT : 1
Signed : 0
As per comments the flags above are to be read as following:
If you are using C# you should use Environment.NewLine
, which accordingly to MSDN it is:
A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.
In fact, this is a retro-gradation of Python3 as compared to Python2. Certainly, Python2 which uses range() and xrange() is more convenient than Python3 which uses list(range()) and range() respectively. The reason is because the original designer of Python3 is not very experienced, they only considered the use of the range function by many beginners to iterate over a large number of elements where it is both memory and CPU inefficient; but they neglected the use of the range function to produce a number list. Now, it is too late for them to change back already.
If I was to be the designer of Python3, I will:
That should be optimal.
There are two options that I can think of, but without more details, I can't be sure which is the better:
#elementId {
display: block;
}
This will force the element to a 'new line' if it's not on the same line as a floated element.
#elementId {
clear: both;
}
This will force the element to clear the floats, and move to a 'new line.'
In the case of the element being on the same line as another that has position
of fixed
or absolute
nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.
Just an update, Feb 1, 2019: cmd+shift+n
on Mac now opens a new window where you can drag over tabs. I didn't find that out until I when through KyleMit's response and saw his key mapping suggestion was already mapped to the correct action.
Don't define variables in headers. Put declarations in header and definitions in one of the .c files.
In config.h
extern const char *names[];
In some .c file:
const char *names[] =
{
"brian", "stefan", "steve"
};
If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.
EventLog.Log should be set as "Application"
This is a likely a linker error.
Add the -lm
switch to specify that you want to link against the standard C math library (libm
) which has the definition for those functions (the header just has the declaration for them - worth looking up the difference.)
For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.
For me it was the "breakOnLoad": true
line in VS Code launch.json
config.
I applied CSS styling to an anchored HREF attribute fully emulating the push button behaviors I needed (hover, active, background-color, etc., etc.). HTML markup is much simpler a-n-d eliminates the get/post complexity associated with using a form-based approach.
<a class="GYM" href="http://www.spufalcons.com/index.aspx?tab=gymnastics&path=gym">Gymnastics</a>
None of the previous answers efficiently provide the required output, which is a tuple of lists, rather than a list of tuples. For the former, you can use tuple
with map
. Here's the difference:
res1 = list(zip(*original)) # [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
res2 = tuple(map(list, zip(*original))) # (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
In addition, most of the previous solutions assume Python 2.7, where zip
returns a list rather than an iterator.
For Python 3.x, you will need to pass the result to a function such as list
or tuple
to exhaust the iterator. For memory-efficient iterators, you can omit the outer list
and tuple
calls for the respective solutions.
try using the after()
method:
$('#bla').after('<div id="space"></div>');
you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"')
,if you want to know more detail, please refer to $sce
For Objects
try this:
function sortBy(field) {
return function(a, b) {
if (a[field] > b[field]) {
return -1;
} else if (a[field] < b[field]) {
return 1;
}
return 0;
};
}
Just set targetSdkVersion to 19. The notification icon will be colored. Then wait for Firebase to fix this issue.
The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary.
You can test this yourself, e.g. in Chrome's console:
new Object().toString()
// "[object Object]"
JSON.parse(new Object())
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse("[object Object]")
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse()
converts the input into a string. The toString()
method of JavaScript objects by default returns [object Object]
, resulting in the observed behavior.
Try the following instead:
var newData = userData.data.userList;
To force enable TLSv1.2 in JRE7u_80 I had to use following code snippet before creating JDBC connection.
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import javax.net.ssl.SSLContextSpi;
import sun.security.jca.GetInstance;
import sun.security.jca.ProviderList;
import sun.security.jca.Providers;
public static void enableTLSv12ForMssqlJdbc() throws NoSuchAlgorithmException
{
ProviderList providerList = Providers.getProviderList();
GetInstance.Instance instance = GetInstance.getInstance("SSLContext", SSLContextSpi.class, "TLS");
for (Provider provider : providerList.providers())
{
if (provider == instance.provider)
{
provider.put("Alg.Alias.SSLContext.TLS", "TLSv1.2");
}
}
}
Able to connect to Windows 10 with SQL server 2017 & TLSv1.2 enabled OS.
Learned a lot from Jamiec's answer.
If the only need is to generate CSV string, you may try this.
var csv3 = string.Join(",",chars);
Here is a test with 1 million strings
0.28 seconds = Aggregate w/ String Builder
0.30 seconds = String.Join
Source code is here
IF
is used to select the field, then the LIKE
clause is placed after it:
SELECT `id` , `naam`
FROM `klanten`
WHERE IF(`email` != '', `email`, `email2`) LIKE '%@domain.nl%'
In comments debiasej wrote the mentioned below article explains more about design patterns (based on interfaces, classes):
http://loredanacirstea.github.io/es6-design-patterns/
Design patterns book in javascript may also be useful for you:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
Design pattern = classes + interface or multiple inheritance
An example of the factory pattern in ES6 JS (to run: node example.js):
"use strict";
// Types.js - Constructors used behind the scenes
// A constructor for defining new cars
class Car {
constructor(options){
console.log("Creating Car...\n");
// some defaults
this.doors = options.doors || 4;
this.state = options.state || "brand new";
this.color = options.color || "silver";
}
}
// A constructor for defining new trucks
class Truck {
constructor(options){
console.log("Creating Truck...\n");
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
}
}
// FactoryExample.js
// Define a skeleton vehicle factory
class VehicleFactory {}
// Define the prototypes and utilities for this factory
// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;
// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {
switch(options.vehicleType){
case "car":
this.vehicleClass = Car;
break;
case "truck":
this.vehicleClass = Truck;
break;
//defaults to VehicleFactory.prototype.vehicleClass (Car)
}
return new this.vehicleClass( options );
};
// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
vehicleType: "car",
color: "yellow",
doors: 6 } );
// Test to confirm our car was created using the vehicleClass/prototype Car
// Outputs: true
console.log( car instanceof Car );
// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );
var movingTruck = carFactory.createVehicle( {
vehicleType: "truck",
state: "like new",
color: "red",
wheelSize: "small" } );
// Test to confirm our truck was created with the vehicleClass/prototype Truck
// Outputs: true
console.log( movingTruck instanceof Truck );
// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );
Intent videoClient = new Intent(Intent.ACTION_VIEW);
videoClient.setData(Uri.parse("http://m.youtube.com/watch?v="+videoId));
startActivityForResult(videoClient, 1234);
Where videoId
is the video id of the youtube video that has to be played. This code works fine on Motorola Milestone.
But basically what we can do is to check for what activity is loaded when you start the Youtube app and accordingly substitute for the packageName and the className.
In SQL Server , cast text as datetime
select cast('5/21/2013 9:45:48' as datetime)
I have looked at the above answers and have mixed together this version which works for me:
function getFilesFromPath(path, extension) {
let files = fs.readdirSync( path );
return files.filter( file => file.match(new RegExp(`.*\.(${extension})`, 'ig')));
}
console.log(getFilesFromPath("./testdata", ".txt"));
This test will return an array of filenames from the files found in the folder at the path ./testdata
. Working on node version 8.11.3.
Most states are in exactly one time zone (though there are a few exceptions). Most zip codes do not cross state boundaries (though there are a few exceptions).
You could quickly come up with your own list of time zones per zip by combining those facts.
Here's a list of zip code ranges per state, and a list of states per time zone.
You can see the boundaries of zip codes and compare to the timezone map using this link, or Google Earth, to map zips to time zones for the states that are split by a time zone line.
The majority of non-US countries you are dealing with are probably in exactly one time zone (again, there are exceptions). Depending on your needs, you may want to look at where your top-N non-US visitors come from and just lookup their time zone.
As I have noticed this error occurs under two circumstances,
so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)
Hope this helps.
A cleaner way instead of the
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
method is to use
textView.getPaint().setUnderlineText(true);
And if you need to later turn off underlining for that view, such as in a reused view in a RecyclerView, textView.getPaint().setUnderlineText(false);
When something happens in my view I fire off an event that my activity is listening for:
// DECLARED IN (CUSTOM) VIEW
private OnScoreSavedListener onScoreSavedListener;
public interface OnScoreSavedListener {
public void onScoreSaved();
}
// ALLOWS YOU TO SET LISTENER && INVOKE THE OVERIDING METHOD
// FROM WITHIN ACTIVITY
public void setOnScoreSavedListener(OnScoreSavedListener listener) {
onScoreSavedListener = listener;
}
// DECLARED IN ACTIVITY
MyCustomView slider = (MyCustomView) view.findViewById(R.id.slider)
slider.setOnScoreSavedListener(new OnScoreSavedListener() {
@Override
public void onScoreSaved() {
Log.v("","EVENT FIRED");
}
});
If you want to know more about communication (callbacks) between fragments see here: http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
Remove everything after first digit (was adequate for my use case): LEFT(field,PATINDEX('%[0-9]%',field+'0')-1)
Remove trailing digits: LEFT(field,len(field)+1-PATINDEX('%[^0-9]%',reverse('0'+field))
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.
char *ptr = "Hello";
printf("%40s\n", ptr);
That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).
If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf
statements like the one above, or do it in a loop, changing the value of ptr
each time.
The for-in statement iterates over the enumerable properties of an object, in arbitrary order.
The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype
You can think of it as "for in" basically iterates and list out all the keys.
var str = 'abc';
var arrForOf = [];
var arrForIn = [];
for(value of str){
arrForOf.push(value);
}
for(value in str){
arrForIn.push(value);
}
console.log(arrForOf);
// ["a", "b", "c"]
console.log(arrForIn);
// ["0", "1", "2", "formatUnicorn", "truncate", "splitOnLast", "contains"]
SAP is just a company name and Abap or Abap/4 is a language programming. SAP company has a lot of products: ERP(material, sales, costs, financial), CRM, SRM, SCM and all of them are customizing and programmed with ABAP and Java. Basically is it.
In lieu of a python goto equivalent I use the break statement in the following fashion for quick tests of my code. This assumes you have structured code base. The test variable is initialized at the start of your function and I just move the "If test: break" block to the end of the nested if-then block or loop I want to test, modifying the return variable at the end of the code to reflect the block or loop variable I'm testing.
def x:
test = True
If y:
# some code
If test:
break
return something
Wow, I update/submit apps about every 6 months. Every time I do this I have to learn the "new" way to do it...
Same problems as described above when running iOS 5.1, and Xcode 4.3.2
Thanks for the posts! I spent a while updating all of the project settings to armv6, armv7, but no joy. When I set "build active architecture only" to No I got a build error about putting both objects in the same directory.
Fortunately, I noticed you guys were modifying the target build settings instead. This is what finally worked (armv6, armv7, and setting "build active architecture only" to No under the Target build Settings). As a disclaimer, I had already set all of the architectures to armv6, armv7 in the project settings too.
Anyway, thanks for the help, Brent
Lot's of sort-of-answers, so I just wrote the function so you can copy/paste.
rename <- function(x, old_names, new_names) {
stopifnot(length(old_names) == length(new_names))
# pull out the names that are actually in x
old_nms <- old_names[old_names %in% names(x)]
new_nms <- new_names[old_names %in% names(x)]
# call out the column names that don't exist
not_nms <- setdiff(old_names, old_nms)
if(length(not_nms) > 0) {
msg <- paste(paste(not_nms, collapse = ", "),
"are not columns in the dataframe, so won't be renamed.")
warning(msg)
}
# rename
names(x)[names(x) %in% old_nms] <- new_nms
x
}
x = data.frame(q = 1, w = 2, e = 3)
rename(x, c("q", "e"), c("Q", "E"))
Q w E
1 1 2 3
In C++17, use std::to_chars
as:
std::array<char, 10> str;
std::to_chars(str.data(), str.data() + str.size(), 42);
In C++11, use std::to_string
as:
std::string s = std::to_string(number);
char const *pchar = s.c_str(); //use char const* as target type
And in C++03, what you're doing is just fine, except use const
as:
char const* pchar = temp_str.c_str(); //dont use cast
Solution is just simple.
If you are trying to access server using your local IP address and you are getting error saying like Forbidden You don't have permission to access / on this server
Just open your httpd.conf file from (in my case C:/wamp/bin/apache/apache2.2.21/conf/httpd.conf
)
Search for
<Directory "D:/wamp/www/">
....
.....
</Directory>
Replace Allow from 127.0.0.1
to
Allow from all
Save changes and restart your server.
Now you can access your server using your IP address
Consider Prism.js: https://prismjs.com/#examples
It makes <pre><code>
work and is attractive.
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add
option:
client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");
According to the Wordpress documentation, you should use wp_localize_script()
in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.
See Codex
Example:
<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>
To access this variable within in Javascript, you would simply do:
<script type="text/javascript">
var url = WPURLS.siteurl;
</script>
The below java solution which will print the different combinations as well. Easy to understand. Idea is
for sum 5
The solution is
5 - 5(i) times 1 = 0
if(sum = 0)
print i times 1
5 - 4(i) times 1 = 1
5 - 3 times 1 = 2
2 - 1(j) times 2 = 0
if(sum = 0)
print i times 1 and j times 2
and so on......
If the remaining sum in each loop is lesser than the denomination ie if remaining sum 1 is lesser than 2, then just break the loop
The complete code below
Please correct me in case of any mistakes
public class CoinCombinbationSimple {
public static void main(String[] args) {
int sum = 100000;
printCombination(sum);
}
static void printCombination(int sum) {
for (int i = sum; i >= 0; i--) {
int sumCopy1 = sum - i * 1;
if (sumCopy1 == 0) {
System.out.println(i + " 1 coins");
}
for (int j = sumCopy1 / 2; j >= 0; j--) {
int sumCopy2 = sumCopy1;
if (sumCopy2 < 2) {
break;
}
sumCopy2 = sumCopy1 - 2 * j;
if (sumCopy2 == 0) {
System.out.println(i + " 1 coins " + j + " 2 coins ");
}
for (int k = sumCopy2 / 5; k >= 0; k--) {
int sumCopy3 = sumCopy2;
if (sumCopy2 < 5) {
break;
}
sumCopy3 = sumCopy2 - 5 * k;
if (sumCopy3 == 0) {
System.out.println(i + " 1 coins " + j + " 2 coins "
+ k + " 5 coins");
}
}
}
}
}
}
I was running a PowerShell script into the task scheduller but i forgot to enable the execution-policy to unrestricted, in an elevated PowerShell console:
Set-ExecutionPolicy Unrestricted
After that, the error disappeared (0x1).
It is what you do inside the loop that affects perfomance, not the actual looping construct (assuming your case is non-trivial).
You can not delete the directory if it has subdirectories or files in Java. Try this two-line simple solution. This will delete the directory and contests inside the directory.
File dirName = new File("directory path");
FileUtils.deleteDirectory(dirName);
Add this line in gradle file and sync the project
compile 'org.apache.commons:commons-io:1.3.2'
Alternative way with substring and regexpr:
substring(name, 1) <- toupper(substring(name, 1, 1))
pos <- regexpr(" ", name, perl=TRUE) + 1
substring(name, pos) <- toupper(substring(name, pos, pos))
Adapted from Timmmm to PYQT5
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel
class Label(QLabel):
def __init__(self):
super(Label, self).__init__()
self.pixmap_width: int = 1
self.pixmapHeight: int = 1
def setPixmap(self, pm: QPixmap) -> None:
self.pixmap_width = pm.width()
self.pixmapHeight = pm.height()
self.updateMargins()
super(Label, self).setPixmap(pm)
def resizeEvent(self, a0: QResizeEvent) -> None:
self.updateMargins()
super(Label, self).resizeEvent(a0)
def updateMargins(self):
if self.pixmap() is None:
return
pixmapWidth = self.pixmap().width()
pixmapHeight = self.pixmap().height()
if pixmapWidth <= 0 or pixmapHeight <= 0:
return
w, h = self.width(), self.height()
if w <= 0 or h <= 0:
return
if w * pixmapHeight > h * pixmapWidth:
m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
self.setContentsMargins(m, 0, m, 0)
else:
m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
self.setContentsMargins(0, m, 0, m)
Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.
As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:
To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash
and the command to export
. You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources. Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.
The result is this incredibly helpful listing of current environment variables used for building:
Use getName()
as the key and Choice
itself as the value of the map:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));
Use the download
attribute, but take into account that it only works for files hosted in the same origin that your code. It means that users can only download files that are from the origin site, same host.
Download with original filename:
<a href="file link" download target="_blank">Click here to download</a>
Download with 'some_name' as filename:
<a href="file link" download="some_name" target="_blank">Click here to download</a>
Adding target="_blank"
we will use a new Tab instead of the actual one, and also it will contribute to the proper behavior of the download
attribute in some scenarios.
It follows the same rules as same-origin policy. You can learn more about this policy on the MDN Web Doc same-origin policy page
You can lern more about this download HTML5 attribute on the MDN Web Doc anchor's attributes page.
I had this issue start happening when debugging from one web project to a web service in the same solution. The web service was returning responses that the web project couldnt understand. It would kind of work again at some points, then stop again.
It was because there was not an explicit reference between these projects, so the web service was not getting built when hitting F5 to start debugging. Once I added that, the errors went away.
For ASP.NET try this:
<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>
This appears to work on page load and on update panel load
Please find the full discussion here.
BEGIN
FOR r IN (select sid,serial# from v$session where username='user')
LOOP
EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid || ','
|| r.serial# || ''' immediate';
END LOOP;
END;
This should work - I just changed your script to add the immediate
keyword. As the previous answers pointed out, the kill session
only marks the sessions for killing; it does not do so immediately but later when convenient.
From your question, it seemed you are expecting to see the result immediately. So immediate
keyword is used to force this.
notice, that code is:
std::abs((x - y)/x) <= epsilon
you are requiring that the "relative error" on the var is <= epsilon, not that the absolute difference is
function removeParam(parameter)
{
var url=document.location.href;
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift();
var queryString=urlparts.join("?");
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1)
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .
}
return url;
}
This will resolve your problem
This will work perfectly
db.collection.find({ song_Name: { '$regex': searchParam, $options: 'i' } })
Just have to add in your regex $options: 'i'
where i is case-insensitive.
You should
$ brew install bash bash-completion git
Then source "$(brew --prefix)/etc/bash_completion" in your .bashrc.
All of the answers posted so far are correct, an endpoint is simply one end of a communication channel. In the case of OAuth, there are three endpoints you need to be concerned with:
Hope that helps clear things up. Have fun learning about OAuth! Post more questions if you run into any difficulties implementing an OAuth client.
This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).
Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).
Here is an illustrative example:
Sub RunSomeMacros()
Call FirstPart
Call SecondPart
'the below code will not be executed if user clicks yes during SecondPart.
Call ThirdPart
MsgBox "All of the macros have been run."
End Sub
Private Sub FirstPart()
MsgBox "This is the first macro"
End Sub
Private Sub SecondPart()
Dim answer As Long
answer = MsgBox("Do you want to stop the macros?", vbYesNo)
If answer = vbYes Then
'Stops All macros!
End
End If
MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub
Private Sub ThirdPart()
MsgBox "Final Macro was run."
End Sub
The right thing would be to use a "if defined" statement, which is used to test for the existence of a variable. For example:
IF DEFINED somevariable echo Value exists
In this particular case, the negative form should be used:
IF NOT DEFINED somevariable echo Value missing
PS: the variable name should be used without "%" caracters.
I've used in my project and works perfectly for me
var returnObjName= JSON.parse(localStorage.getItem('ObjName'));
if(returnObjName && Object.keys(returnObjName).length > 0){
//Exist data in local storage
}else{
//Non Exist data block
}
Check if a MySQL connection is open
ConnectionState state = connection.State;
if (state == ConnectionState.Open)
{
return true;
}
else
{
connection.Open();
return true;
}
There should be a line in your postgresql.conf
file that says:
port = 1486
Change that.
The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/
On Windows it is C:\Program Files\PostgreSQL\9.3\data
Don't forget to sudo service postgresql restart
for changes to take effect.
Like this:
{{ form_widget(form.description, { 'attr': {'class': 'form-control', 'rows': '5', 'style': 'resize:none;'} }) }}
Notice the cool thing in S.Lott's comment - you can also call functions with *mylist
and **mydict
to unpack positional and keyword arguments:
def foo(a, b, c, d):
print a, b, c, d
l = [0, 1]
d = {"d":3, "c":2}
foo(*l, **d)
Will print: 0 1 2 3
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
Create a wrapper module project/bin/lib
, which contains this:
import sys, os
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib'))
import mylib
del sys.path[0], sys, os
Then you can replace all the cruft at the top of your scripts with:
#!/usr/bin/python
from lib import mylib
You can't have a switch in render. The psuedo-switch approach of placing an object-literal that accesses one element isn't ideal because it causes all views to process and that can result in dependency errors of props that don't exist in that state.
Here's a nice clean way to do it that doesn't require each view to render in advance:
render () {
const viewState = this.getViewState();
return (
<div>
{viewState === ViewState.NO_RESULTS && this.renderNoResults()}
{viewState === ViewState.LIST_RESULTS && this.renderResults()}
{viewState === ViewState.SUCCESS_DONE && this.renderCompleted()}
</div>
)
If your conditions for which view state are based on more than a simple property – like multiple conditions per line, then an enum and a getViewState
function to encapsulate the conditions is a nice way to separate this conditional logic and cleanup your render.
Here's a more interesting implementation of multi line lambdas. It's not possible to achieve because of how python use indents as a way to structure code.
But luckily for us, indent formatting can be disabled using arrays and parenthesis.
As some already pointed out, you can write your code as such:
lambda args: (expr1, expr2,... exprN)
In theory if you're guaranteed to have evaluation from left to right it would work but you still lose values being passed from one expression to an other.
One way to achieve that which is a bit more verbose is to have
lambda args: [lambda1, lambda2, ..., lambdaN]
Where each lambda receives arguments from the previous one.
def let(*funcs):
def wrap(args):
result = args
for func in funcs:
if not isinstance(result, tuple):
result = (result,)
result = func(*result)
return result
return wrap
This method let you write something that is a bit lisp/scheme like.
So you can write things like this:
let(lambda x, y: x+y)((1, 2))
A more complex method could be use to compute the hypotenuse
lst = [(1,2), (2,3)]
result = map(let(
lambda x, y: (x**2, y**2),
lambda x, y: (x + y) ** (1/2)
), lst)
This will return a list of scalar numbers so it can be used to reduce multiple values to one.
Having that many lambda is certainly not going to be very efficient but if you're constrained it can be a good way to get something done quickly then rewrite it as an actual function later.
I wrote a custom hook that will run a function once before first render.
useBeforeFirstRender.js
import { useState, useEffect } from 'react'
export default (fun) => {
const [hasRendered, setHasRendered] = useState(false)
useEffect(() => setHasRendered(true), [hasRendered])
if (!hasRendered) {
fun()
}
}
Usage:
import React, { useEffect } from 'react'
import useBeforeFirstRender from '../hooks/useBeforeFirstRender'
export default () => {
useBeforeFirstRender(() => {
console.log('Do stuff here')
})
return (
<div>
My component
</div>
)
}
A cleaner alternative would be to use a Dictionary
to handle parameters. They are key-value pairs after all.
private static readonly HttpClient httpclient;
static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}
var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);
var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
Also dont forget to Dispose()
httpclient, if you dont use the keyword using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
Edit:
You may want to look into response.EnsureSuccessStatusCode();
instead of if (response.StatusCode == HttpStatusCode.OK)
.
You may want to keep your httpclient and dont Dispose()
it. See: Do HttpClient and HttpClientHandler have to be disposed?
Edit:
Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
I couldn't get this to work no matter which environment variables I set. So I simply put a copy of the JDK into my Android Studio installation folder.
Copy the contents of the JDK installation (for example, C:\Program Files (x86)\Java\jdk1.7.0_21
)
Paste them into the installation directory of the Android Studio (for example, C:\Program Files (x86)\Android\android-studio
)
I somewhat assumed that the issue was caused by having the x64 version of the JDK installed. But what was especially confusing was the fact that I could start Android Studio just fine when I started the studio.bat
as an Administrator (even though the environment variables were set for my personal user account).
studio.bat
will look for several valid options when determining which JDK to use.
:: Locate a JDK installation directory which will be used to run the IDE.
:: Try (in order): ANDROID_STUDIO_JDK, ..\jre, JDK_HOME, JAVA_HOME.
As explained above, I picked the ..\jre
option.
butangDonload.php
$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;
Try this,
<?php
$name=$_SESSION['name'];
download($name);
function download($name){
$file = $nama_fail;
?>
If you are working in node.js with lusca try also this:
$.ajax({
url: "http://test.com",
type:"post"
headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}
})
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
On Windows, I had this issue with static files cropping up under pydev/eclipse with python 2.7, due to an instance of django (1.8.7) that had been installed under cygwin. This caused a conflict between windows style paths and cygwin style paths. So, unfindable static files despite all the above fixes. I removed the extra distribution (so that all packages were installed by pip under windows) and this fixed the issue.
For me this works perfectly:
let font = UIFont.systemFont(ofSize: 12, weight: .medium)
let text = "text"
let attString = NSMutableAttributedString(string: "exemple text :)")
attString.addAttributes([.font: font], range:(attString.string as NSString).range(of: text))
label.attributedText = attString
If you want to access redis
from the host (127.0.0.1), you have to use the ports
command.
redis:
build:
context: .
dockerfile: Dockerfile-redis
ports:
- "6379:6379"
You can use regular expressions like this:
SELECT * FROM pet WHERE name REGEXP 'Bob|Smith';
If you are using Theme then you can the below Syntax
Yii::app()->theme->baseUrl
include CSS File :
<link href="<?php echo Yii::app()->theme->baseUrl;?>/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
Include JS File
<script src="<?php echo Yii::app()->theme->baseUrl;?>/js/jquery-2.2.3.min.js"></script>
If you are not using theme
Yii::app()->request->baseUrl
Use Like this
<link href="<?php echo Yii::app()->request->baseUrl; ?>/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery-2.2.3.min.js"></script>
Another solution would be dictdiffer
(https://github.com/inveniosoftware/dictdiffer).
import dictdiffer
a_dict = {
'a': 'foo',
'b': 'bar',
'd': 'barfoo'
}
b_dict = {
'a': 'foo',
'b': 'BAR',
'c': 'foobar'
}
for diff in list(dictdiffer.diff(a_dict, b_dict)):
print diff
A diff is a tuple with the type of change, the changed value, and the path to the entry.
('change', 'b', ('bar', 'BAR'))
('add', '', [('c', 'foobar')])
('remove', '', [('d', 'barfoo')])
Isn't simply android:saveEnabled="true"
in the ListView xml declaration enough?
To stop or start mysql on most linux systems the following should work:
/etc/init.d/mysqld stop
/etc/init.d/mysqld start
The other answers look good for accessing the mysql client from the command line.
Good luck!
gdb -ex=r --args myprogram arg1 arg2
-ex=r
is short for -ex=run
and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args
says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.
Just add this at start: image = cv2.imread(image)
For me with iexplorer 11 and Angular 2 I fixed all those above issues by doing 2 things:
in index.html add:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
in src\polyfills.ts uncomment:
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
It simply means that when git inspects the actual content of the file (it doesn't know that any given extension is not a binary file - you can use the attributes file if you want to tell it explicitly - see the man pages).
Having inspected the file's contents it has seen stuff that isn't in basic ascii characters. Being UTF16 I expect that it will have 'funny' characters so it thinks it's binary.
There are ways of telling git if you have internationalisation (i18n) or extended character formats for the file. I'm not sufficiently up on the exact method for setting that - you may need to RT[Full]M ;-)
Edit: a quick search of SO found can-i-make-git-recognize-a-utf-16-file-as-text which should give you a few clues.
In Kotlin:
myButton.setOnClickListener { doSomething((it as Button).text) }
Note: This gets the button text as a CharSequence
, which more places in code can likely use. If you really want a String from there, then you can use .toString()
.
The quickest method is:
df.sort_index(axis=1)
Be aware that this creates a new instance. Therefore you need to store the result in a new variable:
sortedDf=df.sort_index(axis=1)
If you use jquery, it can be done by using $(window).height();
<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>
<script type="text/javascript" language="javascript">
$('.myIframe').css('height', $(window).height()+'px');
</script>
Instead of using Key_press event you may use Key_down event. You can find this as below
after double clicking here it will automatically this code
private void textbox1_KeyDown(object sender, KeyEventArgs e)
{
}
Problem solved now use as you want.
private void textbox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show(" Enter pressed ");
}
}
If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).
threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).
Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).
Suppose we want one thread to process one pixel (i,j).
We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)
It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.
dim3 threadsPerBlock(8, 8); // 64 threads
and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.
dim3 numBlocks(imageWidth/threadsPerBlock.x, /* for instance 512/8 = 64*/
imageHeight/threadsPerBlock.y);
The kernel is launched like this:
myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );
Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.
In the kernel the pixel (i,j) to be processed by a thread is calculated this way:
uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;
OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.
OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.
OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.
So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.
I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK
There is no super() in C++. You have to call the Base Constructor explicitly by name.
Open xCode can be exhausting if you do it everytime, so you need to add this flag :
OR if you have build.json file at the root of your project, you must add this lines:
{
"ios": {
"debug": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
},
"release": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
}
}
}
Hope this will help in the future
No. Looking at the syntax from the man page for GNU make
make [ -f makefile ] [ options ] ... [ targets ] ...
you can specify multiple targets, hence 'no' (at least no in the exact way you specified).
This is my working example of our simple Vue component.
<template functional>
<div v-html="require('!!html-loader!./../svg/logo.svg')"></div>
</template>
<strong>
and <em>
- unlike <b>
and <i>
- have clear purpose for web browsers for the blind.
A blind person doesn't browse the web visually, but by sound such as text readers. <strong>
and <em>
, in addition to encouraging something to be bold or italic, also convey loudness or stressing syllables respectively (OH MY! & Ooooooh Myyyyyyy!). Audio-only browsers are unpredictable when it comes to <b>
and <i>
... they may make them loud or stress them or they may not... you never can be sure unless you use <strong>
and <em>
.
Use the Find method if item_manuf_id
is a primary key:
var result = dtPs.Rows.Find("some value");
If you only want to know if the value is in there then use the Contains method.
if (dtPs.Rows.Contains("some value"))
{
...
}
Primary key restriction applies to Contains
aswell.
The na.omit
function is what a lot of the regression routines use internally:
vec <- 1:1000
vec[runif(200, 1, 1000)] <- NA
max(vec)
#[1] NA
max( na.omit(vec) )
#[1] 1000
Declare this in your CSS and you should be good:
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
This solution can be implemented without using additional wrappers.
This will force the browser to calculate the width according to the "outer"-width of the div, it means the padding will be subtracted from the width.
Given a data setup like this:
The formula in cell D2 and copied down is:
=INDEX($B$2:$B$28,MATCH(1,INDEX(($A$2:$A$28=LARGE($A$2:$A$28,ROWS(D$1:D1)))*(COUNTIF(D$1:D1,$B$2:$B$28)=0),),0))
This formula will work even if there are tied OPS scores among players.
If you are reading that text from a file or from the network.
You can achieve it by adding HTML tags to your text like mentioned
This text is <i>italic</i> and <b>bold</b>
and <u>underlined</u> <b><i><u>bolditalicunderlined</u></b></i>
and then you can use the HTML class that processes HTML strings into displayable styled text.
// textString is the String after you retrieve it from the file
textView.setText(Html.fromHtml(textString));
I know its already accepted, but for thoses like me who look for "remove ALL whitespaces" (not just at the begining and endingof the string):
select SUBSTRING_INDEX('1234 243', ' ', 1);
// returns '1234'
EDIT 2019/6/20 : Yeah, that's not good. The function returns the part of the string since "when the character space occured for the first time". So, I guess that saying this remove the leading and trailling whitespaces and returns the first word :
select SUBSTRING_INDEX(TRIM(' 1234 243'), ' ', 1);
If you put the declaration in a header file, and the definition in a separate .cpp
file, and #include
the header from a different .cpp
file, you will be able to see the difference.
Specifically, suppose:
int Add(int a, int b);
int Add(int a, int b = 3) {
...
}
#include "lib.h"
int main() {
Add(4);
}
The compilation of test.cpp
will not see the default parameter declaration, and will fail with an error.
For this reason, the default parameter definition is usually specified in the function declaration:
int Add(int a, int b = 3);
Is there any particular reason that you need to use find
? You can just use ls
to find files that match a pattern in a directory.
ls /dev/abc-*
If you do need to use find
, you can use the -maxdepth 1
switch to only apply to the specified directory.
The easiest way is to use Math library.
Use Math.pow(a, b)
and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
The main reason you use the default queue over the main queue is to run tasks in the background.
For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
You can use react-html-id to generate uniq id easely : https://www.npmjs.com/package/react-html-id
This should do the trick
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
dow <- function(x) format(as.Date(x), "%A")
df$day <- dow(df$date)
df
#Returns:
date day
1 2012-02-01 Wednesday
2 2012-02-01 Wednesday
3 2012-02-02 Thursday
They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:
#include <signal.h>
kill(pid, SIGUSR1);
where pid
is the process id of the receiving process. At the receiving end, you can register a signal handler for them:
#include <signal.h>
void my_handler(int signum)
{
if (signum == SIGUSR1)
{
printf("Received SIGUSR1!\n");
}
}
signal(SIGUSR1, my_handler);
I don't think that notation is available because—unlike say PHP or C—everything in Ruby is an object.
Sure you could use $var=0; $var++
in PHP, but that's because it's a variable and not an object. Therefore, $var = new stdClass(); $var++
would probably throw an error.
I'm not a Ruby or RoR programmer, so I'm sure someone can verify the above or rectify it if it's inaccurate.
I would seriously consider making a CLR UDF instead and using regular expressions (both the string and the pattern can be passed in as parameters) to do a complete search and replace for a range of characters. It should easily outperform this SQL UDF.
I had the same issue but when i deleted the cached items from Temp folder the build failed.
In order to make the build work again I had to close the project and reopen it.
SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2®ion=0&page=1', LEN(URL))
Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx
It tells the browser to read the css file as UTF-8. This is handy if your CSS contains unicode characters and not only ASCII.
Using it in the meta tag is fine, but only for pages that include that meta tag.
Read about the rules for character set resolution of CSS files at the w3c spec for CSS 2.
if (!a) {
// is emtpy
}
To ignore white space for strings:
if (!a.trim()) {
// is empty or whitespace
}
If you need legacy support (IE8-) for trim()
, use $.trim
or a polyfill.
Each deployed webapp has a context.xml
file that lives in
$CATALINA_BASE/conf/[enginename]/[hostname]
(conf/Catalina/localhost by default)
and has the same name as the webapp (manager.xml
in this case). If no file is present, default values are used.
So, you need to create a file conf/Catalina/localhost/manager.xml
and specify the rule you want to allow remote access. For example, the following content of manager.xml
will allow access from all machines:
<Context privileged="true" antiResourceLocking="false"
docBase="${catalina.home}/webapps/manager">
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>
Note that the allow attribute of the Valve
element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).
Other Valve
classes cater for other rules (e.g. RemoteHostValve
for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.
Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml
you should have access to the Manager.