The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
You can pass multiple arrays as arguments using something like this:
takes_ary_as_arg()
{
declare -a argAry1=("${!1}")
echo "${argAry1[@]}"
declare -a argAry2=("${!2}")
echo "${argAry2[@]}"
}
try_with_local_arys()
{
# array variables could have local scope
local descTable=(
"sli4-iread"
"sli4-iwrite"
"sli3-iread"
"sli3-iwrite"
)
local optsTable=(
"--msix --iread"
"--msix --iwrite"
"--msi --iread"
"--msi --iwrite"
)
takes_ary_as_arg descTable[@] optsTable[@]
}
try_with_local_arys
sli4-iread sli4-iwrite sli3-iread sli3-iwrite
--msix --iread --msix --iwrite --msi --iread --msi --iwrite
Edit/notes: (from comments below)
descTable
and optsTable
are passed as names and are expanded in the function. Thus no $
is needed when given as parameters.descTable
etc being defined with local
, because locals are visible to the functions they call.!
in ${!1}
expands the arg 1 variable.declare -a
just makes the indexed array explicit, it is not strictly necessary.Others have pointed out that a get_FOO_display method is what you need. I'm using this:
def get_type(self):
return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]
which iterates over all of the choices that a particular item has until it finds the one that matches the items type
Very simply, a delegate provides functionality for how a function pointer SHOULD work. There are many limitations of function pointers in C++. A delegate uses some behind-the-scenes template nastyness to create a template-class function-pointer-type-thing that works in the way you might want it to.
ie - you can set them to point at a given function and you can pass them around and call them whenever and wherever you like.
There are some very good examples here:
String s1="[a,b,c,d]";
String replace = s1.replace("[","");
System.out.println(replace);
String replace1 = replace.replace("]","");
System.out.println(replace1);
List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
System.out.println(myList.toString());
After enabling these two lines, it started working:
; Determines the size of the realpath cache to be used by PHP. This value should
; be increased on systems where PHP opens many files to reflect the quantity of
; the file operations performed.
; http://php.net/realpath-cache-size
realpath_cache_size = 16k
; Duration of time, in seconds for which to cache realpath information for a given
; file or directory. For systems with rarely changing files, consider increasing this
; value.
; http://php.net/realpath-cache-ttl
realpath_cache_ttl = 120
That can be caused by unicode or other charset mismatch. Try changing charset in your browser, in of the settings the text will look OK. Then it's question of how to convert your database contents to charset you use for displaying. (Which can actually be just adding utf-8 charset statement to your output.)
To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:
make -p
For instance:
%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
which expands
COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
This will also print # environment
data. Here, you will find GCC's include path among other useful info.
C_INCLUDE_PATH=/usr/include
In make, when it comes to search, the paths are many, the light is one... or something to that effect.
C_INCLUDE_PATH
is system-wide, set it in your shell's *.rc
.$(CPPFLAGS)
is for the preprocessor include path.VPATH = my_dir_to_search
... or even more specific
vpath %.c src
vpath %.h include
make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.
Process p = Runtime.getRuntime().exec("ping google.com");
p.getInputStream().transferTo(System.out);
p.getErrorStream().transferTo(System.out);
I typically make this function apart of all my projects. Quick and easy.
unfactorize <- function(df){
for(i in which(sapply(df, class) == "factor")) df[[i]] = as.character(df[[i]])
return(df)
}
Here is the simple arraylist example for insertion at specific index
ArrayList<Integer> str=new ArrayList<Integer>();
str.add(0);
str.add(1);
str.add(2);
str.add(3);
//Result = [0, 1, 2, 3]
str.add(1, 11);
str.add(2, 12);
//Result = [0, 11, 12, 1, 2, 3]
//K.I.S.S. method
//(the setup/comments is/are longer than the code)
//cards is a two dimensional array object
// has an array object with 4 elements at each first dimensional index
//var cards = new Array()
//cards[cards.length] = new Array(name, colors, cost, type)
//Can be constructed with Associated arrays, modify code as needed.
//my test array has 60 'cards' in it
// 15 'cards' repeated 4 times each
// groups were not sorted prior to execution
// (I had 4 groups starting with 'U' before the first 'A')
//Should work with any dimensionality as long as first
//index controls sort order
//sort and remove duplicates
//Algorithm:
// While same name side by side, remove higher entry;
// assumes 'cards' with same name have same other data
// (otherwise use cards[i-1] === cards[i] to compare array objects).
//Tested on IE9 and FireFox (multiple version #s from 31 up).
//Also tested by importing array data from 5MB text file.
//Quick execution
cards.sort()
for (i=1; i<cards.length-1; i++){
while (cards[i-1][0] == cards[i][0]){
cards.splice(i,1)
}
}
Is what I used. It is easily installed from the repository:
Name: ObjectAid UML Explorer
Location: http://www.objectaid.com/update/current
And produces quite nice UML diagrams:
The ObjectAid UML Explorer is different from other UML tools. It uses the UML notation to show a graphical representation of existing code that is as accurate and up-to-date as your text editor, while being very easy to use. Several unique features make this possible:
- Your source code and libraries are the model that is displayed, they are not reverse engineered into a different format.
- If you update your code in Eclipse, your diagram is updated as well; there is no need to reverse engineer source code.
- Refactoring updates your diagram as well as your source code. When you rename a field or move a class, your diagram simply reflects the changes without going out of sync.
- All diagrams in your Eclipse workspace are updated with refactoring changes as appropriate. If necessary, they are checked out of your version control system.
- Diagrams are fully integrated into the Eclipse IDE. You can drag Java classes from any other view onto the diagram, and diagram-related information is shown in other views wherever applicable.
Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.
import pickle
class MyUser(object):
def __init__(self,name):
self.name = name
user = MyUser('Peter')
print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'
with open(filename,'wb') as file_object:
file_object.write(serialized)
with open(filename,'rb') as file_object:
raw_data = file_object.read()
deserialized = pickle.loads(raw_data)
print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
Just develop a normal app and then add a couple of lines to the app's manifest file.
First you need to add the following attribute to your activity:
android:launchMode="singleTask"
Then add two categories to the intent filter :
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
The result could look something like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dummy.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.dummy.app.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</activity>
</application>
</manifest>
It's that simple!
Following code worked for me:
public function jsonSerialize()
{
return get_object_vars($this);
}
Using inline-block
allows for white-space in your HTML, This usually equates to .25em (or 4px).
You can either comment out the white-space or, a more commons solution, is to set the parent's font-size
to 0 and the reset it back to the required size on the inline-block elements.
Refer Below code which give the date in String form.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
public static void main(String[] args) {
long val = 1346524199000l;
Date date=new Date(val);
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
String dateText = df2.format(date);
System.out.println(dateText);
}
}
There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.
Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4
Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220
The previous answers are all correct. I go one step further and make C# work for me by defining an extension method on String:
public static class Extensions
{
public static string[] Split(this string toSplit, string splitOn) {
return toSplit.Split(new string[] { splitOn }, StringSplitOptions.None);
}
}
That way I can call it on any string in the simple way I naively expected the first time I tried to accomplish this:
"a big long string with stuff to split on".Split("g str");
This code works for me with IE8 and Firefox
<td>
<textarea style="width:100%" rows=3 name="abc">Modify width:% accordingly</textarea>
</td>
For Google chrome it is not Ctrl+F5. It's Shift+F5 to clear the current cache! It works for me !
I've spent half a day on this problem. It's best to import using SQL Server Import & Export data wizard. There is a setting in that wizard which solves this problem. Detailed screenshots here: https://www.mssqltips.com/sqlservertip/1316/strip-double-quotes-from-an-import-file-in-integration-services-ssis/ Thanks
You don't need javascript for doing so. Just delete the onClick and write the php Admin.php
file like this:
<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
{
$new = '{';
$new .= '"fullname":"' . $_GET['fullname'] . '",';
$new .= '"email":"' . $_GET['email'] . '",';
$new .= '"phone":"' . $_GET['phone'] . '",';
$new .= '}';
return $new;
}
function saveContact()
{
$datafile = fopen ("data/data.json", "a+");
if(!$datafile){
echo "<script>alert('Data not existed!')</script>";
}
else{
$contact_list = $contact_list . addNewContact();
file_put_contents("data/data.json", $contact_list);
}
fclose($datafile);
}
// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled
{ ?>
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="[email protected]" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact"/>
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->
Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...
Other thought, IE doesn't support placeholder.
You can install Kafkacat tool on your machine
For example on Ubuntu You can install it using
apt-get install kafkacat
once kafkacat is installed then you can use following command to connect it
kafkacat -b <your-ip-address>:<kafka-port> -t test-topic
once you run the above command and if kafkacat is able to make the connection then it means that kafka is up and running
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:
angular.module('myApp').directive('conversation', function() {
return {
restrict: 'E',
replace: true,
compile: function(tElement, attr) {
attr.$observe('typeId', function(data) {
console.log("Updated data ", data);
}, true);
}
};
});
Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.
If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:
<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>
And in the directive:
angular.module('myApp').directive('conversation', function() {
return {
scope: {
typeId: '=',
},
link: function(scope, elm, attr) {
scope.$watch('typeId', function(newValue, oldValue) {
if (newValue !== oldValue) {
// You actions here
console.log("I got the new value! ", newValue);
}
}, true);
}
};
});
var word = " testWord "; //add here word or space and test
var x = $.trim(word);
if(x.length > 0)
alert('word');
else
alert('spaces');
Minimal runnable example
glOrtho
: 2D games, objects close and far appear the same size:
glFrustrum
: more real-life like 3D, identical objects further away appear smaller:
main.c
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
static int ortho = 0;
static void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
if (ortho) {
} else {
/* This only rotates and translates the world around to look like the camera moved. */
gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
glColor3f(1.0f, 1.0f, 1.0f);
glutWireCube(2);
glFlush();
}
static void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (ortho) {
glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
} else {
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
}
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
if (argc > 1) {
ortho = 1;
}
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return EXIT_SUCCESS;
}
Compile:
gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut
Run with glOrtho
:
./main 1
Run with glFrustrum
:
./main
Tested on Ubuntu 18.10.
Schema
Ortho: camera is a plane, visible volume a rectangle:
Frustrum: camera is a point,visible volume a slice of a pyramid:
Parameters
We are always looking from +z to -z with +y upwards:
glOrtho(left, right, bottom, top, near, far)
left
: minimum x
we seeright
: maximum x
we seebottom
: minimum y
we seetop
: maximum y
we see-near
: minimum z
we see. Yes, this is -1
times near
. So a negative input means positive z
.-far
: maximum z
we see. Also negative.Schema:
How it works under the hood
In the end, OpenGL always "uses":
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
If we use neither glOrtho
nor glFrustrum
, that is what we get.
glOrtho
and glFrustrum
are just linear transformations (AKA matrix multiplication) such that:
glOrtho
: takes a given 3D rectangle into the default cubeglFrustrum
: takes a given pyramid section into the default cubeThis transformation is then applied to all vertexes. This is what I mean in 2D:
The final step after transformation is simple:
x
, y
and z
are in [-1, +1]
z
component and take only x
and y
, which now can be put into a 2D screenWith glOrtho
, z
is ignored, so you might as well always use 0
.
One reason you might want to use z != 0
is to make sprites hide the background with the depth buffer.
Deprecation
glOrtho
is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.
So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.
Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.
Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.
Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245
With an explicit GLfloat transform[]
it would look something like this:
glfw_transform.c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
"#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"layout (location = 1) in vec3 color;\n"
"out vec3 ourColor;\n"
"uniform mat4 transform;\n"
"void main() {\n"
" gl_Position = transform * vec4(position, 1.0f);\n"
" ourColor = color;\n"
"}\n";
static const GLchar* fragment_shader_source =
"#version 330 core\n"
"in vec3 ourColor;\n"
"out vec4 color;\n"
"void main() {\n"
" color = vec4(ourColor, 1.0f);\n"
"}\n";
static GLfloat vertices[] = {
/* Positions Colors */
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
const char *vertex_shader_source,
const char *fragment_shader_source
) {
GLchar *log = NULL;
GLint log_length, success;
GLuint fragment_shader, program, vertex_shader;
/* Vertex shader */
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
glCompileShader(vertex_shader);
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
log = malloc(log_length);
if (log_length > 0) {
glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
printf("vertex shader log:\n\n%s\n", log);
}
if (!success) {
printf("vertex shader compile error\n");
exit(EXIT_FAILURE);
}
/* Fragment shader */
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
glCompileShader(fragment_shader);
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0) {
log = realloc(log, log_length);
glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
printf("fragment shader log:\n\n%s\n", log);
}
if (!success) {
printf("fragment shader compile error\n");
exit(EXIT_FAILURE);
}
/* Link shaders */
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success);
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0) {
log = realloc(log, log_length);
glGetProgramInfoLog(program, log_length, NULL, log);
printf("shader link log:\n\n%s\n", log);
}
if (!success) {
printf("shader link error");
exit(EXIT_FAILURE);
}
/* Cleanup. */
free(log);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return program;
}
int main(void) {
GLint shader_program;
GLint transform_location;
GLuint vbo;
GLuint vao;
GLFWwindow* window;
double time;
glfwInit();
window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
glewInit();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glViewport(0, 0, WIDTH, HEIGHT);
shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
/* Position attribute */
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
/* Color attribute */
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shader_program);
transform_location = glGetUniformLocation(shader_program, "transform");
/* THIS is just a dummy transform. */
GLfloat transform[] = {
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
};
time = glfwGetTime();
transform[0] = 2.0f * sin(time);
transform[5] = 2.0f * cos(time);
glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glfwTerminate();
return EXIT_SUCCESS;
}
Compile and run:
gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out
Output:
The matrix for glOrtho
is really simple, composed only of scaling and translation:
scalex, 0, 0, translatex,
0, scaley, 0, translatey,
0, 0, scalez, translatez,
0, 0, 0, 1
as mentioned in the OpenGL 2 docs.
The glFrustum
matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho
, more info at: https://gamedev.stackexchange.com/a/118848/25171
The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho
and frustum
operations.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
var checkJSON = function(m) {
if (typeof m == 'object') {
try{ m = JSON.stringify(m); }
catch(err) { return false; } }
if (typeof m == 'string') {
try{ m = JSON.parse(m); }
catch (err) { return false; } }
if (typeof m != 'object') { return false; }
return true;
};
checkJSON(JSON.parse('{}')); //true
checkJSON(JSON.parse('{"a":0}')); //true
checkJSON('{}'); //true
checkJSON('{"a":0}'); //true
checkJSON('x'); //false
checkJSON(''); //false
checkJSON(); //false
You can use the following if you want to specify tricky formats:
df['date_col'] = pd.to_datetime(df['date_col'], format='%d/%m/%Y')
More details on format
here:
I just set outline transparent.
input[type=text] {
outline: rgba(0, 0, 0, 0);
border-radius: 10px;
}
input[type=text]:focus {
border-color: #0079ff;
}
I'm running SQL Server 2014 64 bit
on Windows 10. I tried everything, the thing that made it work was:
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 0
I don't know why the AllowInProcess turned off makes it work but that was the key in my case. Thank you for the suggestion of turning all the options off on the linkserver.
To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).
At startup, we do:
TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
And set the desired timezone to the DateFormat:
fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))
Check the jQuery .scrollTop()
function here
It would look something like
$(document).load().scrollTop(0);
Similar answers:
Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview
app.directive("myDir", function($compile) {
return {
priority:1001, // compiles first
terminal:true, // prevent lower priority directives to compile after it
compile: function(el) {
el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
el.attr('ng-click', 'fxn()');
var fn = $compile(el);
return function(scope){
fn(scope);
};
}
};
});
ngClick
at all:A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview
app.directive("myDir", function($parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('fxn()');
return function (scope,elm){
elm.bind('click',function(){
exp(scope);
});
};
}
};
});
To read both the first and final line of a file you could...
readline()
, ...def readlastline(f):
f.seek(-2, 2) # Jump to the second last byte.
while f.read(1) != b"\n": # Until EOL is found ...
f.seek(-2, 1) # ... jump back, over the read byte plus one more.
return f.read() # Read all data from this point on.
with open(file, "rb") as f:
first = f.readline()
last = readlastline(f)
Jump to the second last byte directly to prevent trailing newline characters to cause empty lines to be returned*.
The current offset is pushed ahead by one every time a byte is read so the stepping backwards is done two bytes at a time, past the recently read byte and the byte to read next.
The whence
parameter passed to fseek(offset, whence=0)
indicates that fseek
should seek to a position offset
bytes relative to...
0
or os.SEEK_SET
= The beginning of the file.1
or os.SEEK_CUR
= The current position.2
or os.SEEK_END
= The end of the file.* As would be expected as the default behavior of most applications, including print
and echo
, is to append one to every line written and has no effect on lines missing trailing newline character.
1-2 million lines each and I have to do this for several hundred files.
I timed this method and compared it against against the top answer.
10k iterations processing a file of 6k lines totalling 200kB: 1.62s vs 6.92s.
100 iterations processing a file of 6k lines totalling 1.3GB: 8.93s vs 86.95.
Millions of lines would increase the difference a lot more.
Exakt code used for timing:
with open(file, "rb") as f:
first = f.readline() # Read and store the first line.
for last in f: pass # Read all lines, keep final value.
A more complex, and harder to read, variation to address comments and issues raised since.
Also adds support for multibyte delimiters, readlast(b'X<br>Y', b'<br>', fixed=False)
.
Please note that this variation is really slow for large files because of the non-relative offsets needed in text mode. Modify to your need, or do not use it at all as you're probably better off using f.readlines()[-1]
with files opened in text mode.
#!/bin/python3
from os import SEEK_END
def readlast(f, sep, fixed=True):
r"""Read the last segment from a file-like object.
:param f: File to read last line from.
:type f: file-like object
:param sep: Segment separator (delimiter).
:type sep: bytes, str
:param fixed: Treat data in ``f`` as a chain of fixed size blocks.
:type fixed: bool
:returns: Last line of file.
:rtype: bytes, str
"""
bs = len(sep)
step = bs if fixed else 1
if not bs:
raise ValueError("Zero-length separator.")
try:
o = f.seek(0, SEEK_END)
o = f.seek(o-bs-step) # - Ignore trailing delimiter 'sep'.
while f.read(bs) != sep: # - Until reaching 'sep': Read sep-sized block
o = f.seek(o-step) # and then seek to the block to read next.
except (OSError,ValueError): # - Beginning of file reached.
f.seek(0)
return f.read()
def test_readlast():
from io import BytesIO, StringIO
# Text mode.
f = StringIO("first\nlast\n")
assert readlast(f, "\n") == "last\n"
# Bytes.
f = BytesIO(b'first|last')
assert readlast(f, b'|') == b'last'
# Bytes, UTF-8.
f = BytesIO("X\nY\n".encode("utf-8"))
assert readlast(f, b'\n').decode() == "Y\n"
# Bytes, UTF-16.
f = BytesIO("X\nY\n".encode("utf-16"))
assert readlast(f, b'\n\x00').decode('utf-16') == "Y\n"
# Bytes, UTF-32.
f = BytesIO("X\nY\n".encode("utf-32"))
assert readlast(f, b'\n\x00\x00\x00').decode('utf-32') == "Y\n"
# Multichar delimiter.
f = StringIO("X<br>Y")
assert readlast(f, "<br>", fixed=False) == "Y"
# Make sure you use the correct delimiters.
seps = { 'utf8': b'\n', 'utf16': b'\n\x00', 'utf32': b'\n\x00\x00\x00' }
assert "\n".encode('utf8' ) == seps['utf8']
assert "\n".encode('utf16')[2:] == seps['utf16']
assert "\n".encode('utf32')[4:] == seps['utf32']
# Edge cases.
edges = (
# Text , Match
("" , "" ), # Empty file, empty string.
("X" , "X" ), # No delimiter, full content.
("\n" , "\n"),
("\n\n", "\n"),
# UTF16/32 encoded U+270A (b"\n\x00\n'\n\x00"/utf16)
(b'\n\xe2\x9c\x8a\n'.decode(), b'\xe2\x9c\x8a\n'.decode()),
)
for txt, match in edges:
for enc,sep in seps.items():
assert readlast(BytesIO(txt.encode(enc)), sep).decode(enc) == match
if __name__ == "__main__":
import sys
for path in sys.argv[1:]:
with open(path) as f:
print(f.readline() , end="")
print(readlast(f,"\n"), end="")
For me:
<input id="color" value="Blue"/>
This can be fetched by below snippet.
page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(color['value'])
Well, I spent a lot of time on this issue. To get an answer working with Chrome AND IE, I had to change my approach. The idea is to avoid removing the selected option (because cannot remove it properly with IE). => this implies to select option not by adding or setting the selected attribute on the option, but to choose an option at the "select" level using the selectedIndex prop.
Before :
$('#myselect option:contains("value")').attr('selected','selected');
$('#myselect option:contains("value")').removeAttr('selected'); => KO with IE
After :
$('#myselect').prop('selectedIndex', $('#myselect option:contains("value")').index());
$('#myselect').prop('selectedIndex','-1'); => OK with all browsers
Hope it will help
EOF
is a constant in C. You are not checking the actual file for EOF. You need to do something like this
while(!feof(stdin))
Here is the documentation to feof. You can also check the return value of scanf. It returns the number of successfully converted items, or EOF
if it reaches the end of the file.
Despite that the other answers are correct and thoroughly explained, I found some difficulties understanding them. Here is the method I used (Taken from here):
openssl pkcs12 -in filename.pfx -out cert.pem -nodes
Extracts the private key form a PFX to a PEM file:
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
Exports the certificate (includes the public key only):
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
Removes the password (paraphrase) from the extracted private key (optional):
openssl rsa -in key.pem -out server.key
I'm thinking something like, just give an idea, to convert the column to string, and work with string is easier. however this does not work with strings containing numbers, like bad123
. and ~
is taking the complement of selection.
df['a'] = df['a'].astype(str)
df[~df['a'].str.contains('0|1|2|3|4|5|6|7|8|9')]
df['a'] = df['a'].astype(object)
and using '|'.join([str(i) for i in range(10)])
to generate '0|1|...|8|9'
or using np.isreal()
function, just like the most voted answer
df[~df['a'].apply(lambda x: np.isreal(x))]
Note in 2018: readAsBinaryString
is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer
(or in some cases, readAsDataURL
) instead.
readAsBinaryString
says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText
and readAsBinaryString
, but with readAsBinaryString
you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText
, because readAsText
will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
showResult(fr, "Text");
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsBinaryString(file);
}
function receivedBinary() {
showResult(fr, "Binary");
}
}
function showResult(fr, label) {
var markup, result, n, aByte, byteStr;
markup = [];
result = fr.result;
for (n = 0; n < result.length; ++n) {
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2) {
byteStr = "0" + byteStr;
}
markup.push(byteStr);
}
bodyAppend("p", label + " (" + result.length + "):");
bodyAppend("pre", markup.join(" "));
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText
interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString
didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with responseType = "arraybuffer"
is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.
Answering the old question, but this answer has not been provided previously, and hopefully this will be useful for someone finding this results through a search engine.
With SQL Server 2008, a new function has been introduced, CRYPT_GEN_RANDOM(8)
, which uses CryptoAPI to produce a cryptographically strong random number, returned as VARBINARY(8000)
. Here's the documentation page: https://docs.microsoft.com/en-us/sql/t-sql/functions/crypt-gen-random-transact-sql
So to get a random number, you can simply call the function and cast it to the necessary type:
select CAST(CRYPT_GEN_RANDOM(8) AS bigint)
or to get a float
between -1 and +1, you could do something like this:
select CAST(CRYPT_GEN_RANDOM(8) AS bigint) % 1000000000 / 1000000000.0
Bash can get the last part of a path without having to call the external basename
:
subdir="/path/to/whatever/${1##*/}"
select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}
To return the queryset you retrieved with queryset = Users.objects.all(),
you first need to serialize them.
Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.
from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View
class JSONListView(View):
def get(self, request, *args, **kwargs):
qs = User.objects.all()
data = serialize("json", qs)
return JsonResponse(data)
This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.
I was stumped by this. Once I got passed the 255 problem... I ended up with a mysterious error code 1. This is the foo to get that resolved:
pssh -x '-tt' -h HOSTFILELIST -P "sudo yum -y install glibc"
-P means write the output out as you go and is optional. But the -x '-tt' trick is what forces a psuedo tty to be allocated.
You can get a clue what the error code 1 means this if you try:
ssh AHOST "sudo yum -y install glibc"
You may see:
[slc@bastion-ci ~]$ ssh MYHOST "sudo yum -y install glibc"
sudo: sorry, you must have a tty to run sudo
[slc@bastion-ci ~]$ echo $?
1
Notice the return code for this is 1, which is what pssh is reporting to you.
I found this -x -tt trick here. Also note that turning on verbose mode (pssh --verbose) for these cases does nothing to help you.
in my case the issue was in the EOL Conversion. (End Of Line).
i created the file on windows and only after i converted the EOL from windows(CR LF) to unix(LF), everything went well.
I did the conversion with Notepad++ very easily from: Edit -> EOL Conversion -> Unix(LF)
Add &autoplay=1 to your syntax, like this
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&autoplay=1" frameborder="0" allowfullscreen></iframe>
My way is simple like this:
static id instanceOfXXX = nil;
+ (id) sharedXXX
{
static volatile BOOL initialized = NO;
if (!initialized)
{
@synchronized([XXX class])
{
if (!initialized)
{
instanceOfXXX = [[XXX alloc] init];
initialized = YES;
}
}
}
return instanceOfXXX;
}
If the singleton is initialized already, the LOCK block will not be entered. The second check if(!initialized) is to make sure it is not initialized yet when the current thread acquires the LOCK.
Button inputs don't have a submit event. Try attaching the event handler to the form instead:
<script type="text/javascript">
$('#login_form').submit(function() {
$('#gif').show();
return true;
});
</script>
In this Eclipse Preferences panel you can change the compiler compatibility from 1.7 to 1.6. This solved the similar message I was getting. For Eclipse, it is under: Preferences -> Java -> Compiler: 'Compiler compliance level'
You are getting the error because $ret
is not an array.
To get rid of the error, at the start of your function, define it with this line: $ret = array();
It appears that the get_tags() call is returning nothing, so the foreach is not run, which means that $ret isn't defined.
I am one of the engineers on the Fresco project. So obviously I'm biased.
But you don't have to take my word for it. We've released a sample app that allows you to compare the performance of five libraries - Fresco, Picasso, UIL, Glide, and Volley Image Loader - side by side. You can get it at our GitHub repo.
I should also point out that Fresco is available on Maven Central, as com.facebook.fresco:fresco
.
Fresco offers features that Picasso, UIL, and Glide do not yet have:
There are many others (see our documentation), but these are the most important.
Your form should look like this :
<form action="myprocessingscript.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
and the PHP
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
I wrote to /tmp/mydata.txt
because this way I know exactly where it is. using data.txt
writes to that file in the current working directory which I know nothing of in your example.
file_put_contents
opens, writes and closes files for you. Don't mess with it.
Further reading: file_put_contents
For i = 0 To dt.Rows.Count - 1
ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)
Next
Since the question was asking how to do this with JS I'm providing a vanilla JS implementation.
var element = document.querySelector(".your-element-class-goes-here");
// it's a good idea to check whether the element exists
if (element != null && element != undefined) {
element.disabled = "disabled";
}
_x000D_
<?php
$value = "Hello world";
$tokens = explode(" ", $value);
echo $tokens[0];
?>
Just use explode to get every word of the input and output the first element of the resulting array.
I always use:
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
The join()
call prepends the current working directory, but the documentation says that if some path is absolute, all other paths left of it are dropped. Therefore, getcwd()
is dropped when dirname(__file__)
returns an absolute path.
Also, the realpath
call resolves symbolic links if any are found. This avoids troubles when deploying with setuptools on Linux systems (scripts are symlinked to /usr/bin/
-- at least on Debian).
You may the use the following to open up files in the same folder:
f = open(os.path.join(__location__, 'bundled-resource.jpg'))
# ...
I use this to bundle resources with several Django application on both Windows and Linux and it works like a charm!
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
The above options do not work for maps created with sf
and geom_sf()
. Hence, I want to add the relevant ndiscr
parameter here. This will create a nice clean map showing only the features.
library(sf)
library(ggplot2)
ggplot() +
geom_sf(data = some_shp) +
theme_minimal() + # white background
theme(axis.text = element_blank(), # remove geographic coordinates
axis.ticks = element_blank()) + # remove ticks
coord_sf(ndiscr = 0) # remove grid in the background
To return the whole table at once you could change the SELECT to:
SELECT ...
BULK COLLECT INTO T
FROM ...
This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.
(new Date()).toLocaleString()
Will output the date and time using your local format. For example: "5/1/2020, 10:35:41 AM"
Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:
class Base
{
// some virtual methods
};
class Derived : public Base
{
~Derived()
{
// Do some important cleanup
}
};
Here, you'll notice that I didn't declare Base's destructor to be virtual
. Now, let's have a look at the following snippet:
Base *b = new Derived();
// use b
delete b; // Here's the problem!
Since Base's destructor is not virtual
and b
is a Base*
pointing to a Derived
object, delete b
has undefined behaviour:
[In
delete b
], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.
In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.
To sum up, always make base classes' destructors virtual
when they're meant to be manipulated polymorphically.
If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete
on a base class pointer.
You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.
You can discover those things easily by yourself:
def hello(*args, **kwargs):
print kwargs
print type(kwargs)
print dir(kwargs)
hello(what="world")
Use fileOrBlob.text()
as follows:
<input type="file" onchange="this.files[0].text().then(t => console.log(t))">
When user uploads a text file via that input, it will be logged to the console. Here's a working jsbin demo.
Here's a more verbose version:
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await file.text();
console.log(text);
}
</script>
Currently (January 2020) this only works in Chrome and Firefox, check here for compatibility if you're reading this in the future: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
On older browsers, this should work:
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await (new Response(file)).text();
console.log(text);
}
</script>
Related: As of September 2020 the new Native File System API available in Chrome and Edge in case you want permanent read-access (and even write access) to the user-selected file.
Use the following,
echo "<script type='text/javascript'> window.location.href = '$file_name'; </script>";
You can solve it be running on Google API emulator.
To run on Google API emulator, open your Android SDK & AVD Manager > Available packages > Google Repos > select those Google API levels that you need to test on.
After installing them, add them as virtual device and run.
You can use System.setOut() at the start of your program to redirect all output via System.out
to your own PrintStream
.
I think this is a good structure. And it is a nicely written blog explaining the mindset of these choices.
This question, although rather old, needs some benchmarks, as it asks for not the most idiomatic way, or the way that can be written in the fewest number of lines, but the fastest way. And it is silly to answer that question without some actual testing. So I compared four solutions, memset vs. std::fill vs. ZERO of AnT's answer vs a solution I made using AVX intrinsics.
Note that this solution is not generic, it only works on data of 32 or 64 bits. Please comment if this code is doing something incorrect.
#include<immintrin.h>
#define intrin_ZERO(a,n){\
size_t x = 0;\
const size_t inc = 32 / sizeof(*(a));/*size of 256 bit register over size of variable*/\
for (;x < n-inc;x+=inc)\
_mm256_storeu_ps((float *)((a)+x),_mm256_setzero_ps());\
if(4 == sizeof(*(a))){\
switch(n-x){\
case 3:\
(a)[x] = 0;x++;\
case 2:\
_mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
case 1:\
(a)[x] = 0;\
break;\
case 0:\
break;\
};\
}\
else if(8 == sizeof(*(a))){\
switch(n-x){\
case 7:\
(a)[x] = 0;x++;\
case 6:\
(a)[x] = 0;x++;\
case 5:\
(a)[x] = 0;x++;\
case 4:\
_mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
case 3:\
(a)[x] = 0;x++;\
case 2:\
((long long *)(a))[x] = 0;break;\
case 1:\
(a)[x] = 0;\
break;\
case 0:\
break;\
};\
}\
}
I will not claim that this is the fastest method, since I am not a low level optimization expert. Rather it is an example of a correct architecture dependent implementation that is faster than memset.
Now, onto the results. I calculated performance for size 100 int and long long arrays, both statically and dynamically allocated, but with the exception of msvc, which did a dead code elimination on static arrays, the results were extremely comparable, so I will show only dynamic array performance. Time markings are ms for 1 million iterations, using time.h's low precision clock function.
clang 3.8 (Using the clang-cl frontend, optimization flags= /OX /arch:AVX /Oi /Ot)
int:
memset: 99
fill: 97
ZERO: 98
intrin_ZERO: 90
long long:
memset: 285
fill: 286
ZERO: 285
intrin_ZERO: 188
gcc 5.1.0 (optimization flags: -O3 -march=native -mtune=native -mavx):
int:
memset: 268
fill: 268
ZERO: 268
intrin_ZERO: 91
long long:
memset: 402
fill: 399
ZERO: 400
intrin_ZERO: 185
msvc 2015 (optimization flags: /OX /arch:AVX /Oi /Ot):
int
memset: 196
fill: 613
ZERO: 221
intrin_ZERO: 95
long long:
memset: 273
fill: 559
ZERO: 376
intrin_ZERO: 188
There is a lot interesting going on here: llvm killing gcc, MSVC's typical spotty optimizations (it does an impressive dead code elimination on static arrays and then has awful performance for fill). Although my implementation is significantly faster, this may only be because it recognizes that bit clearing has much less overhead than any other setting operation.
Clang's implementation merits more looking at, as it is significantly faster. Some additional testing shows that its memset is in fact specialized for zero--non zero memsets for 400 byte array are much slower (~220ms) and are comparable to gcc's. However, the nonzero memsetting with an 800 byte array makes no speed difference, which is probably why in that case, their memset has worse performance than my implementation--the specialization is only for small arrays, and the cuttoff is right around 800 bytes. Also note that gcc 'fill' and 'ZERO' are not optimizing to memset (looking at generated code), gcc is simply generating code with identical performance characteristics.
Conclusion: memset is not really optimized for this task as well as people would pretend it is (otherwise gcc and msvc and llvm's memset would have the same performance). If performance matters then memset should not be a final solution, especially for these awkward medium sized arrays, because it is not specialized for bit clearing, and it is not hand optimized any better than the compiler can do on its own.
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)re.search('<title>(.*)</title>', s, re.IGNORECASE).group(1)
My solution was to avoid using NOW()
when writing sql with your programming language, and substitute with a string. The problem with NOW()
as you indicate is it includes current time. So to capture from the beginning of the query day (0 hour and minute) instead of:
r.date <= DATE_SUB(NOW(), INTERVAL 99 DAY)
I did (php):
$current_sql_date = date('Y-m-d 00:00:00');
in the sql:
$sql_x = "r.date <= DATE_SUB('$current_sql_date', INTERVAL 99 DAY)"
With that, you will be retrieving data from midnight of the given day
Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if
construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).
The top answer by @808sound did not work for me. I wanted to resize
So instead I opened up Inkscape, then went to File
, Export as PNG file
and a GUI box popped up that allowed me to set the exact dimensions I needed.
Version on Ubuntu 16.04 Linux
:
Inkscape 0.91 (September 2016)
(This image is from Kenney.nl's asset packs by the way)
There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);
BOOST_FOREACH(std::string const& token, tokens)
{
std::cout << "<" << *tok_iter << "> " << "\n";
}
I'm using ReactJs and used import 'core-js/es6/string';
at the start of index.js
to solve my problem.
I'm also using import 'react-app-polyfill/ie11';
to support running React in IE11.
react-app-polyfill
This package includes polyfills for various browsers. It includes minimum requirements and commonly used language features used by Create React App projects.
https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md
echo off
setlocal
SET AREYOUSURE = N
:PROMPT
set /P AREYOUSURE=Update Release Files (Y/N)?
if /I %AREYOUSURE% NEQ Y GOTO END
set /P AREYOUSURE=Are You Sure you want to Update Release Files (Y/N)?
if /I %AREYOUSURE% NEQ Y GOTO END
echo Copying New Files
:END
This is code I use regularly. I have noticed in the examples in this blog that quotes are used. If the test line is changed to use quotes the test is invalid.
if /I %AREYOUSURE% NEQ "Y" GOTO END
I have tested on XP, Vista, Win7 and Win8. All fail when quotes are used.
I ended her with the same problem and I could not use the the solution with onEditorAction or onFocusChange and did not want to try the timer. A timer is too dangerous for may taste, because of all the threads and too unpredictable, as you do not know when you code is executed.
The onEditorAction do not catch when the user leave without using a button and if you use it please notice that KeyEvent can be null. The focus is unreliable at both ends the user can get focus and leave without enter any text or selecting the field and the user do not need to leave the last EditText field.
My solution use onFocusChange and a flag set when the user starts editing text and a function to get the text from the last focused view, which I call when need.
I just clear the focus on all my text fields to tricker the leave text view code, The clearFocus code is only executed if the field has focus. I call the function in onSaveInstanceState so I do not have to save the flag (mEditing) as a state of the EditText view and when important buttons is clicked and when the activity is closed.
Be careful with TexWatcher as it is call often I use the condition on focus to not react when the onRestoreInstanceState code entering text. I
final EditText mEditTextView = (EditText) getView();
mEditTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!mEditing && mEditTextView.hasFocus()) {
mEditing = true;
}
}
});
mEditTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus && mEditing) {
mEditing = false;
///Do the thing
}
}
});
protected void saveLastOpenField(){
for (EditText view:getFields()){
view.clearFocus();
}
}
If you look at the javadoc for the class SyndFeed
(I guess you are referring to the class com.sun.syndication.feed.synd.SyndFeed
), the method getEntries() doesn't return java.util.List<SyndEntry>
, but returns just java.util.List
.
So you need an explicit cast for this.
Some permissions issue for default sample.
I wanted to see how it works, I am creating the first extension, so I downloaded a simpler one.
Downloaded 'Typed URL History' sample from
https://developer.chrome.com/extensions/examples/api/history/showHistory.zip
which can be found at
https://developer.chrome.com/extensions/samples
this worked great, hope it helps
git cherry-pick C
where C is the commit hash for C. This applies the old commit on top of the newest one.
I was able to fix this by downgrading RubyGems to 1.5.3, since it happens with RubyGems 1.6.0+ and Rails < 2.3.11:
gem update --system 1.5.3
If you had previously downgraded to an even earlier version and want to update to 1.5.3, you might get the following when trying to run that:
Updating RubyGems
ERROR: While executing gem ... (RuntimeError)
No gem names are allowed with the --system option
If you get that error, then update, so that it lets you specify the version, and then downgrade again:
gem update --system
gem update --system 1.5.3
Build ---> Build APK(s) and be sure it works
I personally don't see the need for a library for this. Looking at http://caniuse.com/#feat=clipboard it's pretty widely supported now, however you can still do things like checking to see if the functionality exists in the current client and simply hide the copy button if it doesn't.
import React from 'react';
class CopyExample extends React.Component {
constructor(props) {
super(props);
this.state = { copySuccess: '' }
}
copyToClipboard = (e) => {
this.textArea.select();
document.execCommand('copy');
// This is just personal preference.
// I prefer to not show the whole text area selected.
e.target.focus();
this.setState({ copySuccess: 'Copied!' });
};
render() {
return (
<div>
{
/* Logical shortcut for only displaying the
button if the copy command exists */
document.queryCommandSupported('copy') &&
<div>
<button onClick={this.copyToClipboard}>Copy</button>
{this.state.copySuccess}
</div>
}
<form>
<textarea
ref={(textarea) => this.textArea = textarea}
value='Some text to copy'
/>
</form>
</div>
);
}
}
export default CopyExample;
Update: Rewritten using React Hooks in React 16.7.0-alpha.0
import React, { useRef, useState } from 'react';
export default function CopyExample() {
const [copySuccess, setCopySuccess] = useState('');
const textAreaRef = useRef(null);
function copyToClipboard(e) {
textAreaRef.current.select();
document.execCommand('copy');
// This is just personal preference.
// I prefer to not show the whole text area selected.
e.target.focus();
setCopySuccess('Copied!');
};
return (
<div>
{
/* Logical shortcut for only displaying the
button if the copy command exists */
document.queryCommandSupported('copy') &&
<div>
<button onClick={copyToClipboard}>Copy</button>
{copySuccess}
</div>
}
<form>
<textarea
ref={textAreaRef}
value='Some text to copy'
/>
</form>
</div>
);
}
I had the same problem. I decided in a very unexpected way. Just opened the command line as an administrator. And then typed:
pip install numpy
This functionality is now supported by Python 3.8+ :)
https://github.com/python/cpython/commit/4959c33d2555b89b494c678d99be81a65ee864b0
String[][] shades = new String[intSize][intSize];
// print array in rectangular form
for (int r=0; r<shades.length; r++) {
for (int c=0; c<shades[r].length; c++) {
shades[r][c]="hello";//your value
}
}
I have also faced this exact problem. But I have got a solution and it worked perfectly. I have needed to pass the parameters which are already produced by javascript function. So below code is working for me. I used ColdFusion for the backend. I just directly used the parameters as a variable.
$.ajax({
url: "https://myexampleurl.com/myactionfile.cfm",
type: "POST",
data : {paramert1: variable1,parameter2: variable2},
success: function(data){
console.log(data);
} )};
Load testing :- Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.
Stress Testing :- Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.
The basic difference is as under
Go to the Window menu and choose "Web Publish Activity" There will be a cancel button. Cancel button on "Web Publish Activity" tab
You can just return a Boolean like this:
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.query.Param;
@QueryHints(@QueryHint(name = org.hibernate.jpa.QueryHints.HINT_FETCH_SIZE, value = "1"))
@Query(value = "SELECT (1=1) FROM MyEntity WHERE ...... :id ....")
Boolean existsIfBlaBla(@Param("id") String id);
Boolean.TRUE.equals(existsIfBlaBla("0815"))
could be a solution
It's better to try to simulate a webbrowser by yourself.You don't have to stick with Chrome or IE or else thing.
If you're using Python,you can try package pyQt4 which helps you to simulate a webbrowser. By doing this,there will not be any security reasons and you can set the webbrowser to show in full screen mode automatically.
I use the following to remove the slashes
echo json_decode($mystring, JSON_UNESCAPED_SLASHES);
The easiest way to determine the size and position of an element is to call its getBoundingClientRect() method. This method returns element positions in viewport coordinates. It expects no arguments and returns an object with properties left, right, top, and bottom. The left and top properties give the X and Y coordinates of the upper-left corner of the element and the right and bottom properties give the coordinates of the lower-right corner.
element.getBoundingClientRect(); // Get position in viewport coordinates
Supported everywhere.
You could take it out of the flow with position:absolute. But the helper_panel will oberlap with other stuff. (I added orders, to see the divs)
<div id="container" style="width: 960px; border:1px solid #f00;">
Text before<br>
<div id="help_panel" style="width: 100%; position:absolute; margin: 0 auto; border:1px solid #0f0;">
Content goes here.
</div>
This is behind the help_penal
</div>
use RewriteBase /{your folder}/ on your .htaccess
Since Spring Boot v2+
I have verified with Spring Boot v2.3.5.RELEASE
With Spring Boot Maven Plugin
You can provide commandline argument like this:
mvn spring-boot:run -Dspring-boot.run.arguments="--spring.profiles.active=dev"
You can provide JVM argument like this:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dspring.profiles.active=dev"
java -jar
java -Dspring.profiles.active=dev -jar app.jar
(Note order)
or
java -jar app.jar --spring.profiles.active=dev
(Note order)
Write a file
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your
app's temporary cache files.
Be sure to delete each file once it is no longer needed and implement a reasonable
size limit for the amount of memory you use at any given time, such as 1MB.
Caution: If the system runs low on storage, it may delete your cache files without warning.
@Sparr is right, but I guess you expected byte array like byte[]
in C#. It's the same solution as Sparr did but instead of HEX you expected int
presentation (range from 0 to 255) of each char
. You can do as follows:
$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array); // $byte_array should be int[] which can be converted
// to byte[] in C# since values are range of 0 - 255
By using var_dump
you can see that elements are int
(not string
).
array(44) { [1]=> int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32)
[5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107)
[10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32)
[15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101)
[20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101)
[25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101)
[30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121)
[35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119)
[40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) }
Be careful: the output array is of 1-based index (as it was pointed out in the comment)
Its work fine to me,You can try it.
protected void displayNotification() {
Log.i("Start", "notification");
// Invoking the default notification service //
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setAutoCancel(true);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
mBuilder.setTicker("New message from PayMe..");
mBuilder.setSmallIcon(R.drawable.icon2);
// Increase notification number every time a new notification arrives //
mBuilder.setNumber(unMber_unRead_sms);
// Creates an explicit intent for an Activity in your app //
Intent resultIntent = new Intent(this, FreesmsLog.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(FreesmsLog.class);
// Adds the Intent that starts the Activity to the top of the stack //
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// mBuilder.setOngoing(true);
Notification note = mBuilder.build();
note.defaults |= Notification.DEFAULT_VIBRATE;
note.defaults |= Notification.DEFAULT_SOUND;
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on. //
mNotificationManager.notify(notificationID, mBuilder.build());
}
Below worked for me.
Height & width are taken to show that, if you 2 such children, it will scroll horizontally, since height of child is greater than height of parent scroll vertically.
Parent CSS:
.divParentClass {
width: 200px;
height: 100px;
overflow: scroll;
white-space: nowrap;
}
Children CSS:
.divChildClass {
width: 110px;
height: 200px;
display: inline-block;
}
To scroll horizontally only:
overflow-x: scroll;
overflow-y: hidden;
To scroll vertically only:
overflow-x: hidden;
overflow-y: scroll;
you could connect all the data you need from the file to a single string, and in the excel sheet seperate it with text to column. here is an example i did for same issue, enjoy:
Sub CP()
Dim ToolFile As String
Cells(3, 2).Select
For i = 0 To 5
r = ActiveCell.Row
ToolFile = Cells(r, 7).Value
On Error Resume Next
ActiveCell.Value = CP_getdatta(ToolFile)
'seperate data by "-"
Selection.TextToColumns Destination:=Range("C3"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Cells(r + 1, 2).Select
Next
End Sub
Function CP_getdatta(ToolFile As String) As String
Workbooks.Open Filename:=ToolFile, UpdateLinks:=False, ReadOnly:=True
Range("A56000").Select
Selection.End(xlUp).Select
x = CStr(ActiveCell.Value)
ActiveCell.Offset(0, 20).Select
Selection.End(xlToLeft).Select
While IsNumeric(ActiveCell.Value) = False
ActiveCell.Offset(0, -1).Select
Wend
' combine data to 1 string
CP_getdatta = CStr(x & "-" & ActiveCell.Value)
ActiveWindow.Close False
End Function
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
Another reason for slow loading is if you have disabled "Enable Just My Code" in Debugging options. To enable this go to:
Tools -> Options -> Debugging -> General -> Enable Just My Code (Managed Only)
Make sure this is checked.
Description
Setting a server's X-Content-Type-Options
HTTP response header to nosniff
instructs browsers to disable content or MIME sniffing which is used to override response Content-Type
headers to guess and process the data using an implicit content type. While this can be convenient in some scenarios, it can also lead to some attacks listed below. Configuring your server to return the X-Content-Type-Options
HTTP response header set to nosniff
will instruct browsers that support MIME sniffing to use the server-provided Content-Type
and not interpret the content as a different content type.
Browser Support
The X-Content-Type-Options
HTTP response header is supported in Chrome, Firefox and Edge as well as other browsers. The latest browser support is available on the Mozilla Developer Network (MDN) Browser Compatibility Table for X-Content-Type-Options:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
Attacks Countered
MIME Confusion Attack enables attacks via user generated content sites by allowing users uploading malicious code that is then executed by browsers which will interpret the files using alternate content types, e.g. implicit application/javascript
vs. explicit text/plain
. This can result in a "drive-by download" attack which is a common attack vector for phishing. Sites that host user generated content should use this header to protect their users. This is mentioned by VeraCode and OWASP which says the following:
This reduces exposure to drive-by download attacks and sites serving user uploaded content that, by clever naming, could be treated by MSIE as executable or dynamic HTML files.
Unauthorized Hotlinking can also be enabled by Content-Type
sniffing. By hotlinking to sites with resources for one purpose, e.g. viewing, apps can rely on content-type sniffing and generate a lot of traffic on sites for another purpose where it may be against their terms of service, e.g. GitHub displays JavaScript code for viewing, but not for execution:
Some pesky non-human users (namely computers) have taken to "hotlinking" assets via the raw view feature -- using the raw URL as the
src
for a<script>
or<img>
tag. The problem is that these are not static assets. The raw file view, like any other view in a Rails app, must be rendered before being returned to the user. This quickly adds up to a big toll on performance. In the past we've been forced to block popular content served this way because it put excessive strain on our servers.
This makes a difference on Windows, at least. See that link for details.
use admin
db.createUser(
{
user: "admin",
pwd: "admin123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
mongod --auth
in case of linux you can edit the /etc/mongod.conf
file to add security.authorization : enabled
and then restart the mongd servicemongo -u "admin" -p "admin123" --authenticationDatabase "admin"
. That's itYou can check out this post to go into more details and to learn connecting to it using mongoose.
@fooMonster article worked for me
# git ls-tree HEAD
100644 blob 55c0287d4ef21f15b97eb1f107451b88b479bffe script.sh
As you can see the file has 644 permission (ignoring the 100). We would like to change it to 755:
# git update-index --chmod=+x script.sh
commit the changes
# git commit -m "Changing file permissions"
[master 77b171e] Changing file permissions
0 files changed, 0 insertions(+), 0 deletions(-)
mode change 100644 => 100755 script.sh
I know this question has been answered 3 years ago, but this may be what your were looking for.
Google has released a couple of weeks ago a library allowing easy and flexible dynamic object allocations. Here it is: http://google-opensource.blogspot.fr/2014/01/introducing-infact-library.html
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
Query syntax:
var count = (from o in context.MyContainer
where o.ID == '1'
from t in o.MyTable
select t).Count();
Method syntax:
var count = context.MyContainer
.Where(o => o.ID == '1')
.SelectMany(o => o.MyTable)
.Count()
Both generate the same SQL query.
This is a sample simplelogger.properties
which you can place on the classpath (uncomment the properties you wish to use):
# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info
# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=
# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false
# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true
# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true
# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false
Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.
So, I would use what Justin is suggesting:
>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'
No. We cannot alter the constraint, only thing we can do is drop and recreate it
ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]
Foreign Key Constraint
Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade
Primary Key constraint
Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)
you may try like this using jquery
var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];
var uniqueVals = [];
$.each(arr, function(i, el){
if($.inArray(el, uniqueVals) === -1) uniqueVals.push(el);
});
IP Version 4 Only ...
Imports System.Net
Module MainLine
Sub Main()
Dim hostName As String = Dns.GetHostName
Console.WriteLine("Host Name: " & hostName & vbNewLine)
Console.WriteLine("IP Version 4 Address(es):")
For Each address In Dns.GetHostEntry(hostName).AddressList().
Where(Function(p) p.AddressFamily = Sockets.AddressFamily.InterNetwork)
Console.WriteLine(vbTab & address.ToString)
Next
Console.ReadKey()
End Sub
End Module
HI. This is (for me) the best solution to run both Python (Python 2.7 and Python 3.x) directly from Git Bash on Win 10 => adding aliases into the aliases file that Git Bash uses for.
Git Bash aliases file is aliases.sh. It is located in:
C:\path where you installed Git\etc\profile.d\aliases.sh
for ex: in my case the file is in C:\Software\Develop\Git\etc\profile.d\aliases.sh
In my case the python.exe are installed in:
C:\Networking\Network Automation\Python 2.7\python.exe
C:\Networking\Network Automation\Python 3.7\python.exe
So you must create 2 aliases, one for Python 2 (I named python2) and the other for Python 3 (I named just python) Git Bash uses linux file structure so you need to change the "\" for "/" and if you have a path like my example Network Automation you put it with " "
"Network Automation", for ex.
winpty is the magic command that will call the executable.
So add these lines at the beginning of aliases.sh
alias python2='winpty C/Networking/"Network Automation"/"Python 2.7"/python.exe'
alias python='winpty C/Networking/"Network Automation"/"Python 3.7"/python.exe'
I modified also the ll alias to show all the files and in a human readable list:
alias ll='ls -lah'
Now, permanently you could launch both Python directly from Git shell just writting
$ python
-> launch Python 3
$ python2
-> launch Python 2
$ ll
-> enters a ls -lah to quickly show your detailed file list
Cheers, Harry
May be the private key itself is not present in the file.I was also faced the same issue but the problem is that there is no private key present in the file.
import sys
for a in sys.path:
a.replace('\\\\','\\')
print(a)
It will give all the paths ready for place in the Windows.
I think you'll get what you want with the -maxdepth 1
option, based on your current command structure. If not, you can try looking at the man page for find
.
Relevant entry (for convenience's sake):
-maxdepth levels
Descend at most levels (a non-negative integer) levels of direc-
tories below the command line arguments. `-maxdepth 0' means
only apply the tests and actions to the command line arguments.
Your options basically are:
# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f
Or:
# DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f
We can use npm view any-promise(your module name) -v
I have a function next()
which will maybe inspire you.
function queue(target) {
var array = Array.prototype;
var queueing = [];
target.queue = queue;
target.queued = queued;
return target;
function queued(action) {
return function () {
var self = this;
var args = arguments;
queue(function (next) {
action.apply(self, array.concat.apply(next, args));
});
};
}
function queue(action) {
if (!action) {
return;
}
queueing.push(action);
if (queueing.length === 1) {
next();
}
}
function next() {
queueing[0](function (err) {
if (err) {
throw err;
}
queueing = queueing.slice(1);
if (queueing.length) {
next();
}
});
}
}
You can use:
function encodeHTML(str){
var aStr = str.split(''),
i = aStr.length,
aRet = [];
while (i--) {
var iC = aStr[i].charCodeAt();
if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
aRet.push('&#'+iC+';');
} else {
aRet.push(aStr[i]);
}
}
return aRet.reverse().join('');
}
This function HTMLEncodes everything that is not a-z/A-Z.
[Edit] A rather old answer. Let's add a simpler String extension to encode all extended characters:
String.prototype.encodeHTML = function () {
return this.replace(/[\u0080-\u024F]/g,
function (v) {return '&#'+v.charCodeAt()+';';}
);
}
// usage
log('Übergroße Äpfel mit Würmern'.encodeHTML());
//=> 'Übergroße Äpfel mit Würmern'
Just add this section to server, just before the location / {
location /your/folder/to/browse/ {
autoindex on;
}
What you should do, is put CallFunction
into *.cpp file, where you include B.h.
After edit, files will look like:
#pragma once //or other specific to compiler...
using namespace std;
class A
{
public:
void CallFunction ();
};
class B: public A
{
public:
virtual void bFunction()
{
//stuff done here
}
};
#include "B.h"
void A::CallFunction(){
//use B object here...
}
Referencing to your explanation, that you have tried to change B b; into pointer- it would be okay, if you wouldn't use it in that same place. You can use pointer of undefined class(but declared), because ALL pointers have fixed byte size(4), so compiler doesn't have problems with that. But it knows nothing about the object they are pointing to(simply: knows the size/boundary, not the content).
So as long as you are using the knowledge, that all pointers are same size, you can use them anywhere. But if you want to use the object, they are pointing to, the class of this object must be already defined and known by compiler.
And last clarification: objects may differ in size, unlike pointers. Pointer is a number/index, which indicates the place in RAM, where something is stored(for example index: 0xf6a7b1).
You had it nearly right in the last line. You want
str(bytes_string, 'utf-8')
because the type of bytes_string
is bytes
, the same as the type of b'abc'
.
Context means Android get to know in which activity I should go for or act in.
1 - Toast.makeText(context, "Enter All Details", Toast.LENGTH_SHORT).show();
it used in this.
Context context = ActivityName.this;
2 -startActivity(new Intent(context,LoginActivity.class));
in this context means from which activity you wanna go to other activity. context or ActivityName.this is faster then , getContext and getApplicatinContext.
From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.
To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.
In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.
You have to use <Integer>
instead of <int>
:
int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
arl.add(i);
System.out.println("Arraylist contains:" + arl.get(0));
}
Change this line:
Aboutme.Text = String.Format("{0}", reader.GetString(0));
You are calling the function before the page loads jQuery. It is always advisable to use jQuery inside
$(document).ready(function(){ //Your code here });
In your case:
$(document).ready(function(){
$(function(){
$( "#searcharea" ).autocomplete({
source: "suggestions.php"
});
$( "#searchcat" ).autocomplete({
source: "suggestions1.php"
});
});
});
You can do either…
$qb->where('e.fecha BETWEEN :monday AND :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
or…
$qb->where('e.fecha > :monday')
->andWhere('e.fecha < :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
Use the flex-grow
property to make a flex item consume free space on the main axis.
This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.
A common example is flex-grow: 1
or, using the shorthand property, flex: 1
.
Hence, instead of width: 96%
on your div, use flex: 1
.
You wrote:
So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.
The squashing of the fixed-width div is related to another flex property: flex-shrink
By default, flex items are set to flex-shrink: 1
which enables them to shrink in order to prevent overflow of the container.
To disable this feature use flex-shrink: 0
.
For more details see The flex-shrink
factor section in the answer here:
Learn more about flex alignment along the main axis here:
Learn more about flex alignment along the cross axis here:
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
>>> from dis import dis
>>> dis(compile('not 10 == 20', '', 'exec'))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 1 (20)
6 COMPARE_OP 2 (==)
9 UNARY_NOT
10 POP_TOP
11 LOAD_CONST 2 (None)
14 RETURN_VALUE
>>> dis(compile('10 != 20', '', 'exec'))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 1 (20)
6 COMPARE_OP 3 (!=)
9 POP_TOP
10 LOAD_CONST 2 (None)
13 RETURN_VALUE
Here you can see that not x == y
has one more instruction than x != y
. So the performance difference will be very small in most cases unless you are doing millions of comparisons and even then this will likely not be the cause of a bottleneck.
You can leverage the streams API of Java 8.
public class ListToMap {
public static void main(String[] args) {
List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));
Map<String, User> map = createHashMap(items);
for(String key : map.keySet()) {
System.out.println(key +" : "+map.get(key));
}
}
public static Map<String, User> createHashMap(List<User> items) {
Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
return map;
}
}
For more details visit: http://codecramp.com/java-8-streams-api-convert-list-map/
Use the below snippet to convert the text from Latin to English
import unicodedata
def strip_accents(text):
return "".join(char for char in
unicodedata.normalize('NFKD', text)
if unicodedata.category(char) != 'Mn')
strip_accents('áéíñóúü')
output:
'aeinouu'
Ideone is the best site for the online code running, debugging and it provides extra performance stats also.
Without Sign Up, you can run code upto of maximum 5 sec, and for signup, upto a max of 15 sec. And for Signup, the code management and history is also too good.
However, it has some maximum amount of submissions per month for registered users.
www.ideone.com
It supports more than 40 languages, and is integrated with SPOJ and RecruitCoders.
while(choice!=99)
{
cin>>choice;
if (choice==99)
exit(0);
cin>>gNum;
}
Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
This worked for me. In your config file
$cfg['Servers']['$i']['password'] = 'yourpassword';
In your mysql shell, login as root
mysql -u root
change your password or update if you've forgotten the old one
UPDATE mysql.user SET Password=PASSWORD('yourpassword') WHERE User='root';
stop and restart your mysql server from the xampp control panel. phpmyadmin can login to see your databases
After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.
Don't forget to hit Do Refactor afterwards.
Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 405 && Context.Request.HttpMethod == "OPTIONS" )
{
Response.Clear();
Response.StatusCode = 200;
Response.End();
}
}
For any number validation you have to use different different range validation as per your requirements :
For Integer
[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")]
for float
[Range(0, float.MaxValue, ErrorMessage = "Please enter valid float Number")]
for double
[Range(0, double.MaxValue, ErrorMessage = "Please enter valid doubleNumber")]
The :before
pseudo element isn't needed for the clearfix hack itself.
It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.
display:table
is being used because display:block
doesn't do the trick. Using display:block
margins will collapse even with a :before
element.
There is one caveat: if vertical-align:baseline
is used in table cells with clearfixed <div>
elements, Firefox won't align well. Then you might prefer using display:block
despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.
Don't write tests to get full coverage of your code. Write tests that guarantee your requirements. You may discover codepaths that are unnecessary. Conversely, if they are necessary, they are there to fulfill some kind of requirement; find it what it is and test the requirement (not the path).
Keep your tests small: one test per requirement.
Later, when you need to make a change (or write new code), try writing one test first. Just one. Then you'll have taken the first step in test-driven development.
Stick this in your ~/.vimrc and be happy:
" enables :Paste to just do what you want
command Paste execute 'set noai | insert | set ai'
Edit: on reflection, :r !cat
is a far better approach since it's short, semantic, and requires no custom vimrc. Use that instead!
I tried in many different ways, but the one which worked for me was. Use Seekbar inside FrameLayout
<FrameLayout
android:id="@+id/VolumeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/MuteButton"
android:layout_below="@id/volumeText"
android:layout_centerInParent="true">
<SeekBar
android:id="@+id/volume"
android:layout_width="500dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:progress="50"
android:secondaryProgress="40"
android:progressDrawable="@drawable/seekbar_volume"
android:secondaryProgressTint="@color/tint_neutral"
android:thumbTint="@color/tint_neutral"
/>
And in Code.
Setup Pre Draw callback on Seekbar, Where you can change the Width and height of the Seekbar I did this part in c#, so Code i used was
var volumeSlider = view.FindViewById<SeekBar>(Resource.Id.home_link_volume);
var volumeFrameLayout = view.FindViewById<FrameLayout>(Resource.Id.linkVolumeFrameLayout);
void OnPreDrawVolume(object sender, ViewTreeObserver.PreDrawEventArgs e)
{
volumeSlider.ViewTreeObserver.PreDraw -= OnPreDrawVolume;
var h = volumeFrameLayout.Height;
volumeSlider.Rotation = 270.0f;
volumeSlider.LayoutParameters.Width = h;
volumeSlider.RequestLayout();
}
volumeSlider.ViewTreeObserver.PreDraw += OnPreDrawVolume;
Here i Add listener to PreDraw Event and when its triggered, I remove the PreDraw so that it doesnt go into Infinite loop.
So when Pre Draw gets executed, I fetch the Height of FrameLayout and assign it to Seekbar. And set the rotation of seekbar to 270. As my seekbar is inside frame Layout and its Gravity is set as Center. I dont need to worry about the Translation. As Seekbar always stay in middle of Frame Layout.
Reason i remove EventHandler is because seekbar.RequestLayout(); Will make this event to be executed again.
I wanted to add this to @marczking's answer (Option 1) as a comment, but my lowly status on StackOverflow is preventing that.
I did a port of @marczking's answer to Objective C. Works like charm, thanks @marczking!
UIView+Border.h:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface UIView (Border)
-(void)setBorderColor:(UIColor *)color;
-(void)setBorderWidth:(CGFloat)width;
-(void)setCornerRadius:(CGFloat)radius;
@end
UIView+Border.m:
#import "UIView+Border.h"
@implementation UIView (Border)
// Note: cannot use synthesize in a Category
-(void)setBorderColor:(UIColor *)color
{
self.layer.borderColor = color.CGColor;
}
-(void)setBorderWidth:(CGFloat)width
{
self.layer.borderWidth = width;
}
-(void)setCornerRadius:(CGFloat)radius
{
self.layer.cornerRadius = radius;
self.layer.masksToBounds = radius > 0;
}
@end
Reading app/config/mailphp
Supported : "smtp", "mail", "sendmail"
Depending on your mail utilities installed on your machine, fill in the value of the driver key. I would do
'driver' => 'sendmail',
Print a [large] tree by lines.
output example:
z
+-- c
¦ +-- a
¦ +-- b
+-- d
+-- e
¦ +-- asdf
+-- f
code:
public class TreeNode {
final String name;
final List<TreeNode> children;
public TreeNode(String name, List<TreeNode> children) {
this.name = name;
this.children = children;
}
public String toString() {
StringBuilder buffer = new StringBuilder(50);
print(buffer, "", "");
return buffer.toString();
}
private void print(StringBuilder buffer, String prefix, String childrenPrefix) {
buffer.append(prefix);
buffer.append(name);
buffer.append('\n');
for (Iterator<TreeNode> it = children.iterator(); it.hasNext();) {
TreeNode next = it.next();
if (it.hasNext()) {
next.print(buffer, childrenPrefix + "+-- ", childrenPrefix + "¦ ");
} else {
next.print(buffer, childrenPrefix + "+-- ", childrenPrefix + " ");
}
}
}
}
P.S. This answer doesn't exactly focus on "binary" trees -- instead, it prints all kinds of trees. Solution is inspired by the "tree" command in linux.
The error you're getting is that self.adj
doesn't already have a key 0
. You're trying to append to a list that doesn't exist yet.
Consider using a defaultdict
instead, replacing this line (in __init__
):
self.adj = {}
with this:
self.adj = defaultdict(list)
You'll need to import at the top:
from collections import defaultdict
Now rather than raise a KeyError
, self.adj[0].append(edge)
will create a list automatically to append to.
In Three.js R66, this is what I use (CoffeeScript version):
THREE.Object3D.prototype.rotateAroundWorldAxis = (axis, radians) ->
rotWorldMatrix = new THREE.Matrix4()
rotWorldMatrix.makeRotationAxis axis.normalize(), radians
rotWorldMatrix.multiply this.matrix
this.matrix = rotWorldMatrix
this.rotation.setFromRotationMatrix this.matrix
I would suggest the method presented on the Gradle forum:
def createMinifyCssTask(def brand, def sourceFile, def destFile) {
return tasks.create("minify${brand}Css", com.eriwen.gradle.css.tasks.MinifyCssTask) {
source = sourceFile
dest = destFile
}
}
I have used this method myself to create custom tasks, and it works very well.
You'll do it the same way you would apply a css selector. For instanse you can do
$("#mydiv > .myclass")
or
$("#mydiv .myclass")
The last one will match every myclass inside myDiv, including myclass inside myclass.
(at least) for Django 1.8:
If you use
if settings.DEBUG:
urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:
if settings.DEBUG:
urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
urlpatterns.append(url(r'$', 'views.home', name='home')),
I just created my own version using CSS. As I need to disabled, then when document is ready use jQuery to make active. So that way a user cannot click on a button until after the document is ready. So i can substitute with AJAX instead. The way I came up with, was to add a class to the anchor tag itself and remove the class when document is ready. Could re-purpose this for your needs.
CSS:
a.disabled{
pointer-events: none;
cursor: default;
}
HTML:
<a class="btn btn-info disabled">Link Text</a>
JS:
$(function(){
$('a.disabled').on('click',function(event){
event.preventDefault();
}).removeClass('disabled');
});
It is solved by adding the following code in app.js file
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render("index");
});
Here is example of using separated parallel
and for
here. In short it can be used for dynamic allocation of OpenMP thread-private arrays before executing for
cycle in several threads.
It is impossible to do the same initializing in parallel for
case.
UPD: In the question example there is no difference between single pragma and two pragmas. But in practice you can make more thread aware behavior with separated parallel and for directives. Some code for example:
#pragma omp parallel
{
double *data = (double*)malloc(...); // this data is thread private
#pragma omp for
for(1...100) // first parallelized cycle
{
}
#pragma omp single
{} // make some single thread processing
#pragma omp for // second parallelized cycle
for(1...100)
{
}
#pragma omp single
{} // make some single thread processing again
free(data); // free thread private data
}
In my case:
PHImageRequestOptions *requestOptions = [PHImageRequestOptions new];
requestOptions.synchronous = NO;
Was trying to do this with dispatch_group
Simple function for splitting a vector by simply using indexes - no need to over complicate this
vsplit <- function(v, n) {
l = length(v)
r = l/n
return(lapply(1:n, function(i) {
s = max(1, round(r*(i-1))+1)
e = min(l, round(r*i))
return(v[s:e])
}))
}
Quick Easy Process in Visual Studio
Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..
/// <reference path="../../components/someclass.ts"/>
A short solution:
use Dotenv;
with(new Dotenv(app()->environmentPath(), app()->environmentFile()))->overload();
with(new LoadConfiguration())->bootstrap(app());
In my case I needed to re-establish database connection after altering .env programmatically, but it didn't work , If you get into this trouble try this
app('db')->purge($connection->getName());
after reloading .env , that's because Laravel App could have accessed the default connection before and the \Illuminate\Database\DatabaseManager
needs to re-read config parameters.
I don't know about best (simplest? fastest? most readable?), but one way would be:
dict(zip([1, 2, 3, 4], [a, b, c, d]))
It may be very simple, but couldn't you just round it up then minus 1? For example:
number=1.5
round(number)-1
> 1
You can use a css selector combination a well
driver.find_element_by_css_selector("#fruits01 [value='1']").click()
Change the 1 in the attribute = value css selector to the value corresponding with the desired fruit.
Something I did for showing gifs in apps. I extended ImageView so people can use its attributes freely. It can show gifs from url or from the assets directory. The library also makes it easy for extending classes to inherit from it and extend it to support different methods to initialize the gif.
https://github.com/Gavras/GIFView
There's a little guide on the github page.
It was also published on Android Arsenal:
https://android-arsenal.com/details/1/4947
Use example:
From XML:
<com.whygraphics.gifview.gif.GIFView xmlns:gif_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_activity_gif_vie"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="center"
gif_view:gif_src="url:http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif" />
In the activity:
GIFView mGifView = (GIFView) findViewById(R.id.main_activity_gif_vie);
mGifView.setOnSettingGifListener(new GIFView.OnSettingGifListener() {
@Override
public void onSuccess(GIFView view, Exception e) {
Toast.makeText(MainActivity.this, "onSuccess()", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(GIFView view, Exception e) {
}
});
Setting the gif programmatically:
mGifView.setGifResource("asset:gif1");
If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shown this is what is required:
$('#myModal').on('shown.bs.modal', function () {
$('#textareaID').focus();
})
From your shell run:
pip2 install unicodecsv
And (unlike the original question) presuming you're using Python's built in csv
module, turn
import csv
into
import unicodecsv as csv
in your code.
You need to set the error_reporting value in a .htaccess file. Since there is a parse error, it never runs the error_reporting() function in your PHP code.
Try this in a .htaccess file (assuming you can use one):
php_flag display_errors 1
php_value error_reporting 30719
I think 30719 corresponds to E_ALL but I may be wrong.
Edit Update: http://php.net/manual/en/errorfunc.constants.php
int error_reporting ([ int $level ] )
---
32767 E_ALL (integer)
All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0. 32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously
Maybe you are trying to set it in Apache's php.ini
, but your CLI (Command Line Interface) php.ini
is not good.
Find your php.ini
file with the following command:
php -i | grep php.ini
And then search for date.timezone
and set it to "Europe/Amsterdam"
. all valid timezone will be found here http://php.net/manual/en/timezones.php
Another way (if the other does not work), search for the file AppKernel.php
, which should be under the folder app
of your Symfony project directory. Overwrite the __construct
function below in the class AppKernel
:
<?php
class AppKernel extends Kernel
{
// Other methods and variables
// Append this init function below
public function __construct($environment, $debug)
{
date_default_timezone_set( 'Europe/Paris' );
parent::__construct($environment, $debug);
}
}
Accessing the files directly on your phone is difficult, but you may be able to copy them to your computer where you can do anything you want with it. Without rooting you have 2 options:
If the application is debuggable you can use the run-as
command in adb shell
adb shell
run-as com.your.packagename
cp /data/data/com.your.packagename/
Alternatively you can use Android's backup function.
adb backup -noapk com.your.packagename
You will now be prompted to 'unlock your device and confirm the backup operation'. It's best NOT to provide a password, otherwise it becomes more difficult to read the data. Just click on 'backup my data'. The resulting 'backup.ab' file on your computer contains all application data in android backup format. Basically it's a compressed tar file. This page explains how you can use OpenSSL's zlib command to uncompress it.
You can use the adb restore backup.db
command to restore the backup.
if(/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())){
alert('I am chrome');
}
Someone pointed me to args4j lately which is annotation based. I really like it!
It is possible to use the old Excel 2003 XML format (before OpenXML) to create a string that contains your desired XML, then on the client side you could use a data URI to open the file using the XSL mime type, or send the file to the client using the Excel mimetype "Content-Type: application/vnd.ms-excel" from the server side.
<script type="text/javascript">
var worksheet_template = '<?xml version="1.0"?><ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'+
'<ss:Styles><ss:Style ss:ID="1"><ss:Font ss:Bold="1"/></ss:Style></ss:Styles><ss:Worksheet ss:Name="Sheet1">'+
'<ss:Table>{{ROWS}}</ss:Table></ss:Worksheet></ss:Workbook>';
var row_template = '<ss:Row ss:StyleID="1"><ss:Cell><ss:Data ss:Type="String">{{name}}</ss:Data></ss:Cell></ss:Row>';
</script>
<script type="text/javascript">
var rows = document.getElementById("my-table").getElementsByTagName('tr'),
row_data = '';
for (var i = 0, length = rows.length; i < length; ++i) {
row_data += row_template.replace('{{name}}', rows[i].getElementsByTagName('td')[0].innerHTML);
}
</script>
Once you have the information collected, create the final string and open a new window using the data URI
<script type="text/javascript">
var worksheet = worksheet_template.replace('{{ROWS}}', row_data);
window.open('data:application/vnd.ms-excel,'+worksheet);
</script>
It is worth noting that older browsers do not support the data URI scheme, so you may need to produce the file server side for those browser that do not support it.
You may also need to perform base64 encoding on the data URI content, which may require a js library, as well as adding the string ';base64' after the mime type in the data URI.
Add below properties to the Edittext controller in the layout file
<Edittext
android:focusableInTouchMode="true"
android:cursorVisible="false"
android:focusable="false" />
I have been using this solution for while and it works fine for me.
None of the above solutions resolved this error for me. I had to set the following in web.config:
system.servicemodel > bindings > webHttpBinding > binding:
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
I would like to take this opportunity to CURSE Microsoft once again for creating such a huge mess with the .NET Framework and making developer lives so miserable for so long!
You may not need to do with group by , using sort_values
+ drop_duplicates
df.sort_values('count').drop_duplicates(['Sp','Mt'],keep='last')
Out[190]:
Sp Mt Value count
0 MM1 S1 a 3
2 MM1 S3 cb 5
8 MM4 S2 uyi 7
3 MM2 S3 mk 8
4 MM2 S4 bg 10
Also almost same logic by using tail
df.sort_values('count').groupby(['Sp', 'Mt']).tail(1)
Out[52]:
Sp Mt Value count
0 MM1 S1 a 3
2 MM1 S3 cb 5
8 MM4 S2 uyi 7
3 MM2 S3 mk 8
4 MM2 S4 bg 10
it is possible to remove leading and trailing zeros in TSQL
Convert it to string using STR TSQL function if not string, Then
Remove both leading & trailing zeros
SELECT REPLACE(RTRIM(LTRIM(REPLACE(AccNo,'0',' '))),' ','0') AccNo FROM @BankAccount
More info on forum.
You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.
You can however have cells span multiple columns, such as:
<table>
<tr>
<td>25</td>
<td>50</td>
<td>25</td>
</tr>
<tr>
<td colspan="2">75</td>
<td>20</td>
</tr>
</table>
As an aside, you should avoid using style attributes like border
and bgcolor
and prefer CSS for those.
I just learned from a website:
Get-ChildItem *.txt | ForEach-Object { (get-Content $_) | Where-Object {(1) -notcontains $_.ReadCount } | Set-Content -path $_ }
Or you can use the aliases to make it short, like:
gci *.txt | % { (gc $_) | ? { (1) -notcontains $_.ReadCount } | sc -path $_ }
The most simple solution is to use LINQ and then transform the result to a DataTable
//data is a DataTable that you want to change
DataTable result = data.AsEnumerable().Distinct().CopyToDataTable < DataRow > ();
This is valid only for asp.net 4.0 ^ Framework and it needs the reference to System.Data.DataSetExtensions as Ivan Ferrer Villa pointed out
I suspect the problem is that you've put the "-D" after the -jar
. Try this:
java -Dtest="true" -jar myApplication.jar
From the command line help:
java [-options] -jar jarfile [args...]
In other words, the way you've got it at the moment will treat -Dtest="true"
as one of the arguments to pass to main
instead of as a JVM argument.
(You should probably also drop the quotes, but it may well work anyway - it probably depends on your shell.)
If you have saved the excel file in the same folder as your python program (relative paths) then you just need to mention sheet number along with file name.
Example:
data = pd.read_excel("wt_vs_ht.xlsx", "Sheet2")
print(data)
x = data.Height
y = data.Weight
plt.plot(x,y,'x')
plt.show()
Easy way to do it without annotations is to use Gson library
Simple as that:
Gson gson = new Gson();
String json = gson.toJson(listaDePontos);
I am using on the client side socket.disconnect();
client.emit('disconnect') didnt work for me
The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>
</tomcat-users>
It works for me very well
I guess this will help you.
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj.length();
for(int i=0; i<length; i++) {
JSONObject jsonObj = ja_data.getJSONObject(i);
Toast.makeText(this, jsonObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jsonObj.getJSONArray("Ingredients");
int len = ja.length();
ArrayList<String> Ingredients_names = new ArrayList<>();
for(int j=0; j<len; j++) {
JSONObject json = ja.getJSONObject(j);
Ingredients_names.add(json.getString("name"));
}
}
Go to Anaconda Naviagator, find spyder,click settings in the top right corner of the spyder app.click update tab
I'm not sure if this is available on OS X, but on linux I would make use of the module
command. See here.
Set up the modulefile correctly, then add something like this to your rc file (e.g. ~/.bashrc):
module load python3.3
This will make it so that your paths get switched around as required when you log in without impacting any system defaults.
if((number%1)!=0)
{
System.out.println("not a integer");
}
else
{
System.out.println("integer");
}
I could also just add that I knew everything about the syntax change between Python2.7
and Python3
, and my code was correctly written as print("string")
and even
print(f"string")
...
But after some time of debugging I realized that my bash script was calling python like:
python file_name.py
which had the effect of calling my python script by default using python2.7
which gave the error. So I changed my bash script to:
python3 file_name.py
which of coarse uses python3 to run the script which fixed the error.
I know its Too late But I hope it will work new comers Try This Its Working ... :D
select
case
when isnumeric(my_NvarcharColumn) = 1 then
cast(my_NvarcharColumn AS int)
else
NULL
end
AS 'my_NvarcharColumnmitter'
from A