#include <Windows.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define window_width 1080
#define window_height 720
void drawFilledSun(){
//static float angle;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0, 0, -10);
int i, x, y;
double radius = 0.30;
//glColor3ub(253, 184, 19);
glColor3ub(255, 0, 0);
double twicePi = 2.0 * 3.142;
x = 0, y = 0;
glBegin(GL_TRIANGLE_FAN); //BEGIN CIRCLE
glVertex2f(x, y); // center of circle
for (i = 0; i <= 20; i++) {
glVertex2f (
(x + (radius * cos(i * twicePi / 20))), (y + (radius * sin(i * twicePi / 20)))
);
}
glEnd(); //END
}
void DrawCircle(float cx, float cy, float r, int num_segments) {
glBegin(GL_LINE_LOOP);
for (int ii = 0; ii < num_segments; ii++) {
float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle
float x = r * cosf(theta);//calculate the x component
float y = r * sinf(theta);//calculate the y component
glVertex2f(x + cx, y + cy);//output vertex
}
glEnd();
}
void main_loop_function() {
int c;
drawFilledSun();
DrawCircle(0, 0, 0.7, 100);
glutSwapBuffers();
c = getchar();
}
void GL_Setup(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glEnable(GL_DEPTH_TEST);
gluPerspective(45, (float)width / height, .1, 100);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitWindowSize(window_width, window_height);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("GLUT Example!!!");
glutIdleFunc(main_loop_function);
GL_Setup(window_width, window_height);
glutMainLoop();
}
This is what I did. I hope this helps. Two types of circle are here. Filled and unfilled.
Datanewolf's code is ALMOST right. I had to reverse both the winding and the normals to make it work properly with the fixed pipeline. The below works correctly with cull on or off for me:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = -x;
*n++ = -y;
*n++ = -z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings-1; r++)
for(s = 0; s < sectors-1; s++) {
/*
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
*/
*i++ = (r+1) * sectors + s;
*i++ = (r+1) * sectors + (s+1);
*i++ = r * sectors + (s+1);
*i++ = r * sectors + s;
}
Edit: There was a question on how to draw this... in my code I encapsulate these values in a G3DModel class. This is my code to setup the frame, draw the model, and end it:
void GraphicsProvider3DPriv::BeginFrame()const{
int win_width;
int win_height;// framework of choice here
glfwGetWindowSize(window, &win_width, &win_height); // retrieve window
float const win_aspect = (float)win_width / (float)win_height;
// set lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
GLfloat lightpos[] = {0, 0.0, 0, 0.};
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
GLfloat lmodel_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
// set up world transform
glClearColor(0.f, 0.f, 0.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT|GL_ACCUM_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
}
void GraphicsProvider3DPriv::DrawModel(const G3DModel* model, const Transform3D transform)const{
G3DModelPriv* privModel = (G3DModelPriv *)model;
glPushMatrix();
glLoadMatrixf(transform.GetOGLData());
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &privModel->vertices[0]);
glNormalPointer(GL_FLOAT, 0, &privModel->normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &privModel->texcoords[0]);
glEnable(GL_TEXTURE_2D);
//glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, privModel->texname);
glDrawElements(GL_QUADS, privModel->indices.size(), GL_UNSIGNED_SHORT, &privModel->indices[0]);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
void GraphicsProvider3DPriv::EndFrame()const{
/* Swap front and back buffers */
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
glDisable(GL_CULL_FACE);
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
XML Schemas describe hierarchial data models and may not map well to a relational data model. Mapping XSD's to database tables is very similar mapping objects to database tables, in fact you could use a framework like Castor that does both, it allows you to take a XML schema and generate classes, database tables, and data access code. I suppose there are now many tools that do the same thing, but there will be a learning curve and the default mappings will most like not be what you want, so you have to spend time customizing whatever tool you use.
XSLT might be the fastest way to generate exactly the code that you want. If it is a small schema hardcoding it might be faster than evaluating and learing a bunch of new technologies.
It's a huge hack, but -moz-appearance: menulist-text
might do the trick.
There is a contemporary way to do that for primitives. Use BYTES
of types.
System.out.println("byte " + Byte.BYTES);
System.out.println("char " + Character.BYTES);
System.out.println("int " + Integer.BYTES);
System.out.println("long " + Long.BYTES);
System.out.println("short " + Short.BYTES);
System.out.println("double " + Double.BYTES);
System.out.println("float " + Float.BYTES);
It results in,
byte 1
char 2
int 4
long 8
short 2
double 8
float 4
I was facing same issue with my one of my feature branch. I tried above mentioned solution nothing worked. I resolved this issue by doing following things.
Well, it's fairly self-explanatory: you've run out of memory.
You may want to try starting it with more memory, using the -Xmx flag, e.g.
java -Xmx2048m [whatever you'd have written before]
This will use up to 2 gigs of memory.
See the non-standard options list for more details.
I had misleading error messages similar to the ones posted in the question:
Compilation error. See log for more details
And:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:16)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.processCompilerExitCode(Tasks.kt:429)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:390)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:274)
at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:233)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
... 32 more
I solved it by
Gradle
(on the right side bar) -> :app
assembleDebug
(or assembleYourFlavor
if you use flavors)In Picture:
1 & 2:
3:
Error will show up in Run: tab.
This way we can do this with minimal changes :)
<html>
<head>
<style>
option:hover {
background-color: yellow;
}
</style>
</head>
<body>
<select onfocus='this.size=10;' onblur='this.size=0;' onchange='this.size=1; this.blur();'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
_x000D_
In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode
property to None
.
\begin{tikzpicture}
\tikzstyle{every node}=[font=\small]
\end{tikzpicture}
will give you font size control on every node.
std::list
doesn't provide any function to get element given an index. You may try to get it by writing some code, which I wouldn't recommend, because that would be inefficient if you frequently need to do so.
What you need is : std::vector
. Use it as:
std::vector<Object> objects;
objects.push_back(myObject);
Object const & x = objects[0]; //index isn't checked
Object const & y = objects.at(0); //index is checked
Here is a fool-proof way:
grep -H -r "<<<<<<< HEAD" /path/to/project/dir
Brackets
if [ CONDITION ] Test construct
if [[ CONDITION ]] Extended test construct
Array[1]=element1 Array initialization
[a-z] Range of characters within a Regular Expression
$[ expression ] A non-standard & obsolete version of $(( expression )) [1]
[1] http://wiki.bash-hackers.org/scripting/obsolete
Curly Braces
${variable} Parameter substitution
${!variable} Indirect variable reference
{ command1; command2; . . . commandN; } Block of code
{string1,string2,string3,...} Brace expansion
{a..z} Extended brace expansion
{} Text replacement, after find and xargs
Parentheses
( command1; command2 ) Command group executed within a subshell
Array=(element1 element2 element3) Array initialization
result=$(COMMAND) Command substitution, new style
>(COMMAND) Process substitution
<(COMMAND) Process substitution
Double Parentheses
(( var = 78 )) Integer arithmetic
var=$(( 20 + 5 )) Integer arithmetic, with variable assignment
(( var++ )) C-style variable increment
(( var-- )) C-style variable decrement
(( var0 = var1<98?9:21 )) C-style ternary operation
press WIN+R and from the run dialog run dialog Execute the following: **%appdata%..\Local\Android**
You should now be presented with Folder Explorer displaying the parent directory of the SDK.
The JOIN syntax keeps conditions near the table they apply to. This is especially useful when you join a large amount of tables.
By the way, you can do an outer join with the first syntax too:
WHERE a.x = b.x(+)
Or
WHERE a.x *= b.x
Or
WHERE a.x = b.x or a.x not in (select x from b)
In Html
<div [style.background]="background"></div>
In Typescript
this.background=
this.sanitization.bypassSecurityTrustStyle(`url(${this.section.backgroundSrc}) no-repeat`);
A working solution.
What is the recommended way to dynamically set background image in Angular 4
you can call mysql_fetch_array() for no_of_row time
I created a little wrapper around the Screen from System.Windows.Forms, currently everything works... Not sure about the "device independent pixels", though.
public class WpfScreen
{
public static IEnumerable<WpfScreen> AllScreens()
{
foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
{
yield return new WpfScreen(screen);
}
}
public static WpfScreen GetScreenFrom(Window window)
{
WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
Screen screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
WpfScreen wpfScreen = new WpfScreen(screen);
return wpfScreen;
}
public static WpfScreen GetScreenFrom(Point point)
{
int x = (int) Math.Round(point.X);
int y = (int) Math.Round(point.Y);
// are x,y device-independent-pixels ??
System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
Screen screen = System.Windows.Forms.Screen.FromPoint(drawingPoint);
WpfScreen wpfScreen = new WpfScreen(screen);
return wpfScreen;
}
public static WpfScreen Primary
{
get { return new WpfScreen(System.Windows.Forms.Screen.PrimaryScreen); }
}
private readonly Screen screen;
internal WpfScreen(System.Windows.Forms.Screen screen)
{
this.screen = screen;
}
public Rect DeviceBounds
{
get { return this.GetRect(this.screen.Bounds); }
}
public Rect WorkingArea
{
get { return this.GetRect(this.screen.WorkingArea); }
}
private Rect GetRect(Rectangle value)
{
// should x, y, width, height be device-independent-pixels ??
return new Rect
{
X = value.X,
Y = value.Y,
Width = value.Width,
Height = value.Height
};
}
public bool IsPrimary
{
get { return this.screen.Primary; }
}
public string DeviceName
{
get { return this.screen.DeviceName; }
}
}
A one-liner:
var encodedMsg = $('<div />').text(message).html();
See it work:
$shorttext = preg_replace('/^([\s\S]{1,200})[\s]+?[\s\S]+/', '$1', $fulltext);
Description:
^
- start from beginning of string([\s\S]{1,200})
- get from 1 to 200 of any character[\s]+?
- not include spaces at the end of short text so we can avoid word ...
instead of word...
[\s\S]+
- match all other contentTests:
regex101.com
let's add to or
few other r
regex101.com
orrrr
exactly 200 characters.regex101.com
after fifth r
orrrrr
excluded.Enjoy.
Add this to your css.
.highcharts-credits {
display: none !important;
}
You need to use Inlines
:
<TextBlock.Inlines>
<Run FontWeight="Bold" FontSize="14" Text="This is WPF TextBlock Example. " />
<Run FontStyle="Italic" Foreground="Red" Text="This is red text. " />
</TextBlock.Inlines>
With binding:
<TextBlock.Inlines>
<Run FontWeight="Bold" FontSize="14" Text="{Binding BoldText}" />
<Run FontStyle="Italic" Foreground="Red" Text="{Binding ItalicText}" />
</TextBlock.Inlines>
You can also bind the other properties:
<TextBlock.Inlines>
<Run FontWeight="{Binding Weight}"
FontSize="{Binding Size}"
Text="{Binding LineOne}" />
<Run FontStyle="{Binding Style}"
Foreground="Binding Colour}"
Text="{Binding LineTwo}" />
</TextBlock.Inlines>
You can bind through converters if you have bold as a boolean (say).
All the provided answers assume that you are able to unplug and reconnect the USB cable. In situations where this is not possible (e.g., when you are remote), you can do the following to essentially do what the suggested udev rules would do on re-plug:
lsusb
Find the device you care about, e.g.:
Bus 003 Device 005: ID 18d1:4ee4 Google Inc. Nexus
Take note of the bus number it is on and then execute, e.g. for bus 003
:
sudo chmod a+w /dev/bus/usb/003/*
Clearly this may be more permissive than you want (there may be more devices attached than just this one), but you get the idea.
Some view have there own double tap recognizers built in (MKMapView
being an example). To get around this you will need to implement UIGestureRecognizerDelegate
method shouldRecognizeSimultaneouslyWithGestureRecognizer
and return YES
:
First implement your double and single recognizers:
// setup gesture recognizers
UITapGestureRecognizer* singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(mapViewTapped:)];
singleTapRecognizer.delegate = self;
singleTapRecognizer.numberOfTapsRequired = 1;
UITapGestureRecognizer* doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(mapViewDoubleTapped:)];
doubleTapRecognizer.delegate = self; // this allows
doubleTapRecognizer.numberOfTapsRequired = 2;
[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];
And then implement:
#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer { return YES; }
Look in the Python re documentation for lookaheads (?=...)
and lookbehinds (?<=...)
-- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.
You should use datetime.datetime.strptime
:
import datetime
dt = datetime.datetime.strptime(string_date, fmt)
fmt
will need to be the appropriate format for your string. You'll find the reference on how to build your format here.
This is the solution:
export default Home;
The pointer str
is never allocated. It should be malloc
'd before use.
Easy
import pymongo
conn = pymongo.MongoClient()
db = conn.test #test is my database
col = db.spam #Here spam is my collection
array = list(col.find())
print array
There you go
This allows you to just get the image data and set to the img src, which is cool.
var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
var blob = oReq.response;
var imgSrc = URL.createObjectURL( blob );
var $img = $( '<img/>', {
"alt": "test image",
"src": imgSrc
} ).appendTo( $( '#bb_theImageContainer' ) );
window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );
The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.
If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)
The two variables you are having trouble with are passed as parameters to the constructor.
The error message is because 'hours' is out of scope in the setter.
You could try something like this:
(pattern1.*pattern2|pattern2.*pattern1)
If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));
A slightly other way of iterating through each column of each line of a CSV-file would be
$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path
foreach($line in $csv)
{
$properties = $line | Get-Member -MemberType Properties
for($i=0; $i -lt $properties.Count;$i++)
{
$column = $properties[$i]
$columnvalue = $line | Select -ExpandProperty $column.Name
# doSomething $column.Name $columnvalue
# doSomething $i $columnvalue
}
}
so you have the choice: you can use either $column.Name
to get the name of the column, or $i
to get the number of the column
By default, inheritance is private. You have to explicitly use public
:
class Bar : public Foo
Try Case
SELECT stock.name,
CASE
WHEN stock.quantity <20 THEN 'Buy urgent'
ELSE 'There is enough'
END
FROM stock
There are a lot of answers here, but I'll add my approach since I found this post while working on the same problem.
Starting with what we know here are the number from 0 to 16.
Number encoded in bits minimum number of bits to encode
0 000000 1
1 000001 1
2 000010 2
3 000011 2
4 000100 3
5 000101 3
6 000110 3
7 000111 3
8 001000 4
9 001001 4
10 001010 4
11 001011 4
12 001100 4
13 001101 4
14 001110 4
15 001111 4
16 010000 5
looking at the breaks, it shows this table
number <= number of bits
1 0
3 2
7 3
15 4
So, now how do we compute the pattern?
Remember that log base 2 (n) = log base 10 (n) / log base 10 (2)
number logb10 (n) logb2 (n) ceil[logb2(n)]
1 0 0 0 (special case)
3 0.477 1.58 2
7 0.845 2.807 3
8 0.903 3 3 (special case)
15 1.176 3.91 4
16 1.204 4 4 (special case)
31 1.491 4.95 5
63 1.799 5.98 6
Now the desired result matching the first table. Notice how also some values are special cases. 0 and any number which is a powers of 2. These values dont change when you apply ceiling so you know you need to add 1 to get the minimum bit field length.
To account for the special cases add one to the input. The resulting code implemented in python is:
from math import log
from math import ceil
def min_num_bits_to_encode_number(a_number):
a_number=a_number+1 # adjust by 1 for special cases
# log of zero is undefined
if 0==a_number:
return 0
num_bits = int(ceil(log(a_number,2))) # logbase2 is available
return (num_bits)
For those who are looking for the quick one-liner:
plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()])
Or if you are using Latex as the axis text formatter, you have to add one backslash '\'
plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()])
A couple of things might affect the results you're seeing:
clock_t
as a floating-point type, I don't think it is.1^4
) to do something else than compute the bitwise XOR of 1 and 4., i.e. it's 5.You're not specifying how fast your machine is, but it's not unreasonable for this to run very quickly on modern hardware, no.
If you have it, try adding a call to sleep()
between the start/stop snapshots. Note that sleep()
is POSIX though, not standard C.
Call Angular Scope function from outside the controller.
// Simply Use "Body" tag, Don't try/confuse using id/class.
var scope = angular.element('body').scope();
scope.$apply(function () {scope.YourAngularJSFunction()});
I use a script which redirects the user from index.html to relative url of Login Page
<html>
<head>
<title>index.html</title>
</head>
<body onload="document.getElementById('lnkhome').click();">
<a href="/Pages/Login.aspx" id="lnkhome">Go to Login Page<a>
</body>
</html>
You can also try using multiprocessing.Process
with daemon=True
; the process.start()
method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.
I experienced similar problem while working with falcon framework and using daemon
process helped.
You'd need to do the following:
from multiprocessing import Process
@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
...
heavy_process = Process( # Create a daemonic process with heavy "my_func"
target=my_func,
daemon=True
)
heavy_process.start()
return Response(
mimetype='application/json',
status=200
)
# Define some heavy function
def my_func():
time.sleep(10)
print("Process finished")
You should get a response immediately and, after 10s you should see a printed message in the console.
NOTE: Keep in mind that daemonic
processes are not allowed to spawn any child processes.
Have you checked these official docs?
HostListener - Declares a host listener. Angular will invoke the decorated method when the host element emits the specified event.
@HostListener
- will listen to the event emitted by the host element that's declared with @HostListener
.
HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.
@HostBinding
- will bind the property to the host element, If a binding changes, HostBinding
will update the host element.
NOTE: Both links have been removed recently. The "HostBinding-HostListening" portion of the style guide may be a useful alternative until the links return.
Here's a simple code example to help picture what this means:
DEMO : Here's the demo live in plunker - "A simple example about @HostListener & @HostBinding"
role
property -- declared with @HostBinding
-- to the host's element
role
is an attribute, since we're using attr.role
.<p myDir>
becomes <p mydir="" role="admin">
when you view it in developer tools.onClick
event declared with @HostListener
, attached to the component's host element, changing role
with each click.
<p myDir>
is clicked is that its opening tag changes from <p mydir="" role="admin">
to <p mydir="" role="guest">
and back.directives.ts
import {Component,HostListener,Directive,HostBinding,Input} from '@angular/core';
@Directive({selector: '[myDir]'})
export class HostDirective {
@HostBinding('attr.role') role = 'admin';
@HostListener('click') onClick() {
this.role= this.role === 'admin' ? 'guest' : 'admin';
}
}
AppComponent.ts
import { Component,ElementRef,ViewChild } from '@angular/core';
import {HostDirective} from './directives';
@Component({
selector: 'my-app',
template:
`
<p myDir>Host Element
<br><br>
We have a (HostListener) listening to this host's <b>click event</b> declared with @HostListener
<br><br>
And we have a (HostBinding) binding <b>the role property</b> to host element declared with @HostBinding
and checking host's property binding updates.
If any property change is found I will update it.
</p>
<div>View this change in the DOM of the host element by opening developer tools,
clicking the host element in the UI.
The role attribute's changes will be visible in the DOM.</div>
`,
directives: [HostDirective]
})
export class AppComponent {}
Or you can use the fetch API
fetch(URL.createObjectURL(myBlob)).then(res => res.arrayBuffer())
I don't know what the performance difference is, and this will show up on your network tab in DevTools as well.
My environment,
Firefox 45.9 ,
Windows 7
swagger-ui ie 3.x
I did the unzip and the petstore comes up fine in a Firefox tab. I then opened a new Firefox tab and went to File > Open File and opened my swagger.json file. The file comes up clean, ie as a file.
I then copied the 'file location' from Firefox ( ie the URL location eg: file:///D:/My%20Applications/Swagger/swagger-ui-master/dist/MySwagger.json ).
I then went back to the swagger UI tab and pasted the file location text into the swagger UI explore window and my swagger came up clean.
Hope this helps.
UPDATE TableName
SET YourField = ''
WHERE YourField REGEXP 'YOUR REGEX'
And :
SELECT * from TableName
WHERE YourField REGEXP 'YOUR REGEX'
There is specific purpose to design these methods. We can't say use anyone to check file exist or not.
Yes. The VBA equivalent of AltEnter is to use a linebreak character:
ActiveCell.Value = "I am a " & Chr(10) & "test"
Note that this automatically sets WrapText
to True.
Proof:
Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub
I made this powershell script to unblock all files on a share on my server
Get-ChildItem "\\ServerName\e$\MyDirectory\" -Recurse -File | % {
Unblock-File -Path $_.FullName
}
If the number is stored in a string (which it would be if typed by a user), you can use atoi()
to convert it to an integer.
An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.
char c = atoi("61");
Look into git-reflog. It will list all the states it remembers (default is 30 days), and you can simply checkout the one you want. For example:
$ git init > /dev/null
$ touch a
$ git add .
$ git commit -m"Add file a" > /dev/null
$ echo 'foo' >> a
$ git commit -a -m"Append foo to a" > /dev/null
$ for i in b c d e; do echo $i >>a; git commit -a -m"Append $i to a" ;done > /dev/null
$ git reset --hard HEAD^^ > /dev/null
$ cat a
foo
b
c
$ git reflog
145c322 HEAD@{0}: HEAD^^: updating HEAD
ae7c2b3 HEAD@{1}: commit: Append e to a
fdf2c5e HEAD@{2}: commit: Append d to a
145c322 HEAD@{3}: commit: Append c to a
363e22a HEAD@{4}: commit: Append b to a
fa26c43 HEAD@{5}: commit: Append foo to a
0a392a5 HEAD@{6}: commit (initial): Add file a
$ git reset --hard HEAD@{2}
HEAD is now at fdf2c5e Append d to a
$ cat a
foo
b
c
d
I found that in the project it was not referencing the Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly. Instead, it was referencing Microsoft.VisualStudio.TestPlatform.TestFramework and Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions. When I removed those two references and added the reference to the Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly the tests that were previously marked with the blue exclamation point suddenly became active and started working.
You can do git merge --abort
after seeing that there are conflicts.
I don't know why but this works for me.
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
toolbar.setSubtitle("Test Subtitle");
toolbar.inflateMenu(R.menu.main_manu);
For menu item click do this
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if(item.getItemId()==R.id.item1)
{
// do something
}
else if(item.getItemId()== R.id.filter)
{
// do something
}
else{
// do something
}
return false;
}
});
Will update the 'why' part of this answer when I find a proper explanation.
Happy to help anyway :) Peace.
public class WeatherResponse {
private int cod;
private String base;
private Weather main;
public int getCod(){
return this.cod;
}
public void setCod(int cod){
this.cod = cod;
}
public String getBase(){
return base;
}
public void setBase(String base){
this.base = base;
}
public Weather getWeather() {
return main;
}
// default constructor, getters and setters
}
public class Weather {
private int id;
private String main;
private String description;
public String getMain(){
return main;
}
public void setMain(String main){
this.main = main;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
// default constructor, getters and setters
}
// accessing methods
// success!
Log.i("App", weatherResponse.getBase());
Log.i("App", weatherResponse.getWeather().getMain());
Log.i("App", weatherResponse.getWeather().getDescription());
you are better off with a decompiler like redgates .net reflector or jetbrains resharper decompiler. there are open source ones also like
There is no specific option to disable caching only for JavaScript, you will have to disable caching entirely.
FireBug has an option to disable the browser cache on the Network tab's drop down menu.
^\d\d?[,.]\d\d?$
The ^ and $ means begin and end of input string (without this part 23.45 of string like 123.45 will be matched). The \d means digit, the \d? means optional digit, the [,.] means dot or comma. Working example (when you click on left menu> tools> code generator you can gen code for one of 9 popular languages like c#, js, php, java, ...) here.
// TEST
[
// valid
'11,11',
'11.11',
'1.1',
'1,1',
// nonvalid
'111,1',
'11.111',
'11-11',
',11',
'11.',
'a.11',
'11,a',
].forEach(n=> {
let result = /^\d\d?[,.]\d\d?$/.test(n);
console.log(`${n}`.padStart(6,' '), 'is valid:', result);
})
_x000D_
Alternatively, you can use requests.Session
and observe cookies
before and after a request:
>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}
Terminate the Timer once after awake at a specific time in milliseconds.
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);
The container div, and sometimes content div, are almost always used to allow for more sophisticated CSS styling. The body tag is special in some ways. Browsers don't treat it like a normal div; its position and dimensions are tied to the browser window.
But a container div is just a div and you can style it with margins and borders. You can give it a fixed width, and you can center it with margin-left: auto; margin-right: auto
.
Plus, content, like a copyright notice for example, can go on the outside of the container div, but it can't go on the outside of the body, allowing for content on the outside of a border.
'a' in x
and a quick search reveals some nice information about it: http://docs.python.org/3/tutorial/datastructures.html#dictionaries
Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx
Set-ExecutionPolicy RemoteSigned
Run this python script on your powershell script helloworld.py
:
# -*- coding: iso-8859-1 -*-
import subprocess, sys
p = subprocess.Popen(["powershell.exe",
"C:\\Users\\USER\\Desktop\\helloworld.ps1"],
stdout=sys.stdout)
p.communicate()
This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.
C:\Users\MacEwin\Desktop>python helloworld.py
Hello World
There is a lot of incompatibility between different versions of cglib and lots of poor advice that can be googled on this subject (use ancient versions of cglib-nodeb, etc). After wrestling with this nonsense for 3 days with an ancient version of Spring (2.5.6)I have discovered:
or if you have VS 2012 you can goto the package manager console and type Install-Package Microsoft.AspNet.WebApi.Client
This would download the latest version of the package
This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.
Here is a good post on permanent generation.
I like the descriptions given for each space in Oracle's guide on JConsole:
For the HotSpot Java VM, the memory pools for serial garbage collection are the following.
- Eden Space (heap): The pool from which memory is initially allocated for most objects.
- Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
- Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
- Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
- Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.
Old question but just had that problem /dumb jira having problems with java 10/ and didn't find a simple answer here so just gonna leave it:
$ /usr/libexec/java_home -V
shows the versions installed and their locations so you can simply remove /Library/Java/JavaVirtualMachines/<the_version_you_want_to_remove>
. Voila
In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
Since version 2.1 of the Maven Dependency Plugin, there is a dependency:get goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":
mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \ -DrepoUrl=http://download.java.net/maven/2/ \ -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT
After updating the manifest file, instead of building your project, go to command line and reach the path ...bld\Debug\platforms\android. Run the command "ant release". Your new release.apk file will have a new version code.
I also wrote a small library which is specialized for the mapping of the json response into an object structure. I am internally using the library json-swift from David Owens. Maybe it is useful for someone else.
https://github.com/prine/ROJSONParser
Example Employees.json
{
"employees": [
{
"firstName": "John",
"lastName": "Doe",
"age": 26
},
{
"firstName": "Anna",
"lastName": "Smith",
"age": 30
},
{
"firstName": "Peter",
"lastName": "Jones",
"age": 45
}]
}
As next step you have to create your data model (EmplyoeeContainer and Employee).
Employee.swift
class Employee : ROJSONObject {
required init() {
super.init();
}
required init(jsonData:AnyObject) {
super.init(jsonData: jsonData)
}
var firstname:String {
return Value<String>.get(self, key: "firstName")
}
var lastname:String {
return Value<String>.get(self, key: "lastName")
}
var age:Int {
return Value<Int>.get(self, key: "age")
}
}
EmployeeContainer.swift
class EmployeeContainer : ROJSONObject {
required init() {
super.init();
}
required init(jsonData:AnyObject) {
super.init(jsonData: jsonData)
}
lazy var employees:[Employee] = {
return Value<[Employee]>.getArray(self, key: "employees") as [Employee]
}()
}
Then to actually map the objects from the JSON response you only have to pass the data into the EmployeeContainer class as param in the constructor. It does automatically create your data model.
var baseWebservice:BaseWebservice = BaseWebservice();
var urlToJSON = "http://prine.ch/employees.json"
var callbackJSON = {(status:Int, employeeContainer:EmployeeContainer) -> () in
for employee in employeeContainer.employees {
println("Firstname: \(employee.firstname) Lastname: \(employee.lastname) age: \(employee.age)")
}
}
baseWebservice.get(urlToJSON, callback:callbackJSON)
The console output looks then like the following:
Firstname: John Lastname: Doe age: 26
Firstname: Anna Lastname: Smith age: 30
Firstname: Peter Lastname: Jones age: 45
There is an attribute called android:weightSum.
You can set android:weightSum="2" in the parent linear_layout and android:weight="1" in the inner linear_layout.
Remember to set the inner linear_layout to fill_parent so weight attribute can work as expected.
Btw, I don't think its necesary to add a second view, altough I haven't tried. :)
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:weightSum="2">
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_weight="1">
</LinearLayout>
</LinearLayout>
Here you could find the CA certs with instructions to download and convert Mozilla CA certs.
Once you get ca-bundle.crt
or cacert.pem
you just use:
curl.exe --cacert cacert.pem https://www.google.com
or
curl.exe --cacert ca-bundle.crt https://www.google.com
Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
To update each submodule, you could invoke the following command (at the root of the repository):
git submodule -q foreach git pull -q origin master
You can remove the -q option to follow the whole process.
Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/
Also v2 can use mobile gesture such as swipe ;)
This is pretty easy using the JavaScript selenium-webdriver
client:
First, make sure you have a WebDriver server running. For example, download ChromeDriver, then run chromedriver --port=9515
.
Second, create the driver like this:
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.usingServer('http://localhost:9515') // <- this
.build();
Here's a complete example:
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.usingServer('http://localhost:9515')
.build();
driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.getTitle().then(function(title) {
console.log(title);
});
driver.quit();
Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).
You can limit the whole search to one row by using Limit 0,1
SELECT COUNT(UserName)
FROM TableName
WHERE UserName = 'User' AND
Password = 'Pass'
LIMIT 0, 1
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
l = [1,2,3,4,5]
sum = 0
for x in l:
sum = sum + x
And you can change l for any list you want.
I encountered the SSL error on a CentOS server running JDK 6.
My plan was to install a higher JDK version (JDK 7) to co-exist with JDK 6 but it turns out that merely installing the newer JDK with rpm -i
was not enough.
The JDK 7 installation would only succeed with the rpm -U
upgrade option as illustrated below.
wget -O /root/jdk-7u79-linux-x64.rpm --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; o raclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u79-b15/jdk-7u79-linux-x64.rpm"
rpm -ivh jdk-7u79-linux-x64.rpm
Preparing... ########################################### [100%]
file /etc/init.d/jexec from install of jdk-2000:1.7.0_79-fcs.x86_64 conflicts with file from package jdk-2000:1.6.0_43-fcs.x86_64
rpm -Uvh jdk-7u79-linux-x64.rpm
Preparing... ########################################### [100%]
1:jdk ########################################### [100%]
Unpacking JAR files...
rt.jar...
jsse.jar...
charsets.jar...
tools.jar...
localedata.jar...
jfxrt.jar...
java -version
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
int i;
cout << "Please enter an integer value: ";
// cin >> i; leaves '\n' among possible other junk in the buffer.
// '\n' also happens to be the default delim character for getline() below.
cin >> i;
if (cin.fail())
{
cout << "\ncin failed - substituting: i=1;\n\n";
i = 1;
}
cin.clear(); cin.ignore(INT_MAX,'\n');
cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";
string myString;
cout << "What's your full name? (spaces inclded) \n";
getline (cin, myString);
cout << "\nHello '" << myString << "'.\n\n\n";
Hmm, there're obviously many ways to solve this.
But I have a <div>
that's positioned absolutely, height:100%
(actually, top:0;bottom:0
and fixed width) and display:table-cell
just didn't work to center text vertically. My solution did require an inner span element, but I see many of the other solutions do also, so I might as well add it:
My container is a .label
and I want the number vertically centered in it. I did it by positioning absolutely at top:50%
and setting line-height:0
<div class="label"><span>1.</span></div>
And the CSS is as follows:
.label {
position:absolute;
top:0;
bottom:0;
width:30px;
}
.label>span {
position:absolute;
top:50%;
line-height:0;
}
See it in action: http://jsfiddle.net/jcward/7gMLx/
Adding on to the accepted answer. I ran into a similar problem and ended up using a user defined function that returned clob instead of varchar2. Here's my solution:
CREATE OR REPLACE TYPE temp_data FORCE AS OBJECT
(
temporary_data NVARCHAR2(4000)
)
/
CREATE OR REPLACE TYPE temp_data_table FORCE AS TABLE OF temp_data;
/
CREATE OR REPLACE FUNCTION my_agg_func (p_temp_data_table IN temp_data_table, p_delimiter IN NVARCHAR2)
RETURN CLOB IS
l_string CLOB;
BEGIN
FOR i IN p_temp_data_table.FIRST .. p_temp_data_table.LAST LOOP
IF i != p_temp_data_table.FIRST THEN
l_string := l_string || p_delimiter;
END IF;
l_string := l_string || p_temp_data_table(i).temporary_data;
END LOOP;
RETURN l_string;
END my_agg_func;
/
Now, instead of doing
LISTAGG(column_to_aggregate, '#any_delimiter#') WITHIN GROUP (ORDER BY column_to_order_by)
I have to do this
my_agg_func (
cast(
collect(
temp_data(column_to_aggregate)
order by column_to_order_by
) as temp_data_table
),
'#any_delimiter#'
)
grep LMN20113456 LMN2011*
or if you want to search recursively through subdirectories:
find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \;
Simply place normal button indide Ajax.BeginForm and on click find parent form and normal submit. Ajax form in Razor:
@using (Ajax.BeginForm("AjaxPost", "Home", ajaxOptions))
{
<div class="form-group">
<div class="col-md-12">
<button class="btn btn-primary" role="button" type="button" onclick="submitParentForm($(this))">Submit parent from Jquery</button>
</div>
</div>
}
and Javascript:
function submitParentForm(sender) {
var $formToSubmit = $(sender).closest('form');
$formToSubmit.submit();
}
This method is almost identical to yours, just more numpyst (also working on numpy arrays only):
def reject_outliers(data, m=2):
return data[abs(data - np.mean(data)) < m * np.std(data)]
Iterators are first choice over operator[]
. C++11 provides std::begin()
, std::end()
functions.
As your code uses just std::vector
, I can't say there is much difference in both codes, however, operator []
may not operate as you intend to. For example if you use map, operator[]
will insert an element if not found.
Also, by using iterator
your code becomes more portable between containers. You can switch containers from std::vector
to std::list
or other container freely without changing much if you use iterator such rule doesn't apply to operator[]
.
You can simply add show.legend=FALSE
to geom to suppress the corresponding legend
There Are 2 ways to return a string from the controller to the view:
First
You could return only the string, but it will not be included in your .cshtml file. it will be just a string appearing in your browser.
Second
You could return a string as the Model object of View Result.
Here is the code sample to do this:
public class HomeController : Controller
{
// GET: Home
// this will return just a string, not html
public string index()
{
return "URL to show";
}
public ViewResult AutoProperty()
{
string s = "this is a string ";
// name of view , object you will pass
return View("Result", s);
}
}
In the view file to run AutoProperty, It will redirect you to the Result view and will send s
code to the view
<!--this will make this file accept string as it's model-->
@model string
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Result</title>
</head>
<body>
<!--this will represent the string -->
@Model
</body>
</html>
I run this at http://localhost:60227/Home/AutoProperty.
If we use msvc or Qt (up to Qt 4.5), since GCC(up to 3.4) , msvc both support #pragma once
, I can see no reason for not using #pragma once
.
Source file name usually same equal class name, and we know, sometime we need refactor, to rename class name, then we had to change the #include XXXX
also, so I think manual maintain the #include xxxxx
is not a smart work. even with Visual Assist X extension, maintain the "xxxx" is not a necessary work.
With PHP 7.0+ now here you can do the following:
$dateString = substr($millseconds_go_here,0,10);
$drawDate = new \DateTime(Date('Y-m-d H:i',$dateString));
$drawDate->setTimezone(new \DateTimeZone('UTC'));
This does the following in order:
Date()
can handle the date.DateTime()
can then allow you to modify the time zone you are in, but ensure that date_default_timezone_set("Timezone");
is set before you use DateTime()
functions and classes.DateTime()
classes or functions are used.Why do people keep confusing php and javascript?
PHP is SERVER SIDE
JAVASCRIPT (like onclick) is CLIENT SIDE
You will have to use just javascript to redirect. Otherwise if you want PHP involved you can use an AJAX call to log a hit or whatever you like to send back a URL or additional detail.
$('#table1').find(input).length
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
Use asymptote instead!
This is what it can look like:
https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.html
This is the code: https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.asy
Asymptote can also read in data files.
And the full gallery: https://asymptote.sourceforge.io/gallery/index.html
To use asymptote from within Python:
https://ctan.org/tex-archive/graphics/asymptote/base/asymptote.py
You could use the maven enforcer plugin with the banned dependency rule. This would allow you to ban all the aliases that you don't want and allow only the one you do want. These rules will fail the maven build of your project when violated. Furthermore, if this rule applies to all projects in an enterprise you could put the plugin configuration in a corporate parent pom.
see:
In case anyone is wondering what input value
<input (keydown.enter)="search($event.target.value)" />
The "Premature end of script headers" error message is probably the most loathed and common error message you'll find. What the error actually means, is that the script stopped for whatever reason before it returned any output to the web server. A common cause of this for script writers is to fail to set a content type before printing output code. In Perl for example, before printing any HTML it is necessary to tell the Perl script to set the content type to text/html, this is done by sending a header, like so:
print "Content-type: text/html\n\n";
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
Are you sure that all the lines have at least 2 columns? Can you try something like, just to check?:
sc.textFile("file.csv") \
.map(lambda line: line.split(",")) \
.filter(lambda line: len(line)>1) \
.map(lambda line: (line[0],line[1])) \
.collect()
Alternatively, you could print the culprit (if any):
sc.textFile("file.csv") \
.map(lambda line: line.split(",")) \
.filter(lambda line: len(line)<=1) \
.collect()
You have a basic answer here: Get city name using geolocation
But for what you are looking for, i'd recommend this way.
Only if you also need administrative_area_level_1,to store different things for Paris, Texas, US and Paris, Ile-de-France, France and provide a manual fallback:
--
There is a problem in Michal's way, in that it takes the first result, not a particular one. He uses results[0]. The way I see fit (I just modified his code) is to take ONLY the result whose type is "locality", which is always present, even in an eventual manual fallback in case the browser does not support geolocation.
His way: fetched results are different from using http://maps.googleapis.com/maps/api/geocode/json?address=bucharest&sensor=false than from using http://maps.googleapis.com/maps/api/geocode/json?latlng=44.42514,26.10540&sensor=false (searching by name / searching by lat&lng)
This way: same fetched results.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(results);
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++)
{
if (results[j].types[0]=='locality')
{
indice=j;
break;
}
}
alert('The good number is: '+j);
console.log(results[j]);
for (var i=0; i<results[j].address_components.length; i++)
{
if (results[j].address_components[i].types[0] == "locality") {
//this is the object you are looking for City
city = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
//this is the object you are looking for State
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country") {
//this is the object you are looking for
country = results[j].address_components[i];
}
}
//city data
alert(city.long_name + " || " + region.long_name + " || " + country.short_name)
} else {
alert("No results found");
}
//}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
<input type="button" id="btnTexWrapped" style="background:
url('http://i0006.photobucket.com/albums/0006/findstuff22/Backgrounds/bokeh2backgrounds.jpg');background-size:30px;width:50px;height:3em;" />
Change input style elements as you want to get the button you need.
I hope it was helpful.
Refer to MySQL 8.0 Reference Manual -- 6.1.6 Security Issues with LOAD DATA LOCAL
On the server side, run
mysql.server start --local-infile
On the client side, run
mysql --local-infile database_name -u username -p
So many answers, yet ALL fail to pinpoint one very significant problem with a custom generic ForEach
extension: Performance! And more specifically, memory usage and GC.
Consider the sample below. Targeting .NET Framework 4.7.2
or .NET Core 3.1.401
, configuration is Release
and platform is Any CPU
.
public static class Enumerables
{
public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
foreach (T item in @this)
{
action(item);
}
}
}
class Program
{
private static void NoOp(int value) {}
static void Main(string[] args)
{
var list = Enumerable.Range(0, 10).ToList();
for (int i = 0; i < 1000000; i++)
{
// WithLinq(list);
// WithoutLinqNoGood(list);
WithoutLinq(list);
}
}
private static void WithoutLinq(List<int> list)
{
foreach (var item in list)
{
NoOp(item);
}
}
private static void WithLinq(IEnumerable<int> list) => list.ForEach(NoOp);
private static void WithoutLinqNoGood(IEnumerable<int> enumerable)
{
foreach (var item in enumerable)
{
NoOp(item);
}
}
}
At a first glance, all three variants should perform equally well. However, when the ForEach
extension method is called many, many times, you will end up with garbage that implies a costly GC. In fact, having this ForEach
extension method on a hot path has been proven to totally kill performance in our loop-intensive application.
Similarly, the weekly typed foreach
loop will also produce garbage, but it will still be faster and less memory-intensive than the ForEach
extension (which also suffers from a delegate allocation).
For a strongly typed foreach
the compiler is able to use any optimized enumerator (e.g. value based) of a class, whereas a generic ForEach
extension must fall back to a generic enumerator which will be allocated on each run. Furthermore, the actual delegate will also imply an additional allocation.
You would get similar bad results with the WithoutLinqNoGood
method. There, the argument is of type IEnumerable<int>
instead of List<int>
implying the same type of enumerator allocation.
Below are the relevant differences in IL
. A value based enumerator is certainly preferable!
IL_0001: callvirt instance class
[mscorlib]System.Collections.Generic.IEnumerator`1<!0>
class [mscorlib]System.Collections.Generic.IEnumerable`1<!!T>::GetEnumerator()
vs
IL_0001: callvirt instance valuetype
[mscorlib]System.Collections.Generic.List`1/Enumerator<!0>
class [mscorlib]System.Collections.Generic.List`1<int32>::GetEnumerator()
The OP asked how to call ForEach()
on an IEnumerable<T>
. The original answer clearly shows how it can be done. Sure you can do it, but then again; my answer clearly shows that you shouldn't.
Verified the same behavior when targeting .NET Core 3.1.401
(compiling with Visual Studio 16.7.2
).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
$('#content').toggle('show');
});
});
</script>
And the html
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
$(document).ready(function(){
$('.lbOn').click();
});
Suppose this would work too.
To get the keys on a deeper node in an JSON:
echo '{"data": "1", "user": { "name": 2, "phone": 3 } }' | jq '.user | keys[]'
"name"
"phone"
You could also do it like this, not sure if it's a good plan :D
class Parent extends Component {
handleClick() {
if (this._getAlert !== null) {
this._getAlert()
}
}
render() {
return (
<div>
<Child>
{(getAlert, childScope) => (
<span> {!this._getAlert ? this._getAlert = getAlert.bind(childScope) : null}</span>
)}
</Child>
<button onClick={() => this.handleClick()}> Click me</button>
</div>
);
}
}
class Child extends Component {
constructor() {
super();
this.state = { count: 0 }
}
getAlert() {
alert(`Child function called state: ${this.state.count}`);
this.setState({ count: this.state.count + 1 });
}
render() {
return this.props.children(this.getAlert, this)
}
}
a = [2 3 5];
b = [1 1 0];
c = a+b;
starts = zeros(3,3);
ends = [a;b;c];
quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3))
axis equal
Here is how you can do it with a socket on php-fpm 7
install socat
apt-get install socat
#!/bin/sh
if echo /dev/null | socat UNIX:/var/run/php/php7.0-fpm.sock - ; then
echo "$home/run/php-fpm.sock connect OK"
else
echo "$home/run/php-fpm.sock connect ERROR"
fi
You can also check if the service is running like this.
service php7.0-fpm status | grep running
It will return
Active: active (running) since Sun 2017-04-09 12:48:09 PDT; 48s ago
Quick and dirty:
#!/usr/bin/perl -w
use strict;
open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);
foreach(@lines) {
$_ =~ s/<PREF>/ABCD/g;
}
open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);
Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.
I wanted to be able to take a function name as a string, call it, AND pass an argument to the function. I couldn't get the selected answer for this question to do that, but this answer explained it exactly, and here is a short demo.
function test_function(argument) {
alert('This function ' + argument);
}
functionName = 'test_function';
window[functionName]('works!');
This also works with multiple arguments.
For an ArrayAdapter
, notifyDataSetChanged
only works if you use the add()
, insert()
, remove()
, and clear()
on the Adapter.
When an ArrayAdapter
is constructed, it holds the reference for the List
that was passed in. If you were to pass in a List
that was a member of an Activity, and change that Activity member later, the ArrayAdapter
is still holding a reference to the original List
. The Adapter does not know you changed the List
in the Activity.
Your choices are:
ArrayAdapter
to modify the underlying List (add()
, insert()
, remove()
, clear()
, etc.)ArrayAdapter
with the new List
data. (Uses a lot of resources and garbage collection.)BaseAdapter
and ListAdapter
that allows changing of the underlying List
data structure.notifyDataSetChanged()
every time the list is updated. To call it on the UI-Thread, use the runOnUiThread()
of Activity
.
Then, notifyDataSetChanged()
will work.Try one of these:
ApplicationRef.tick()
- similar to AngularJS's $rootScope.$digest()
-- i.e., check the full component treeNgZone.run(callback)
- similar to $rootScope.$apply(callback)
-- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.ChangeDetectorRef.detectChanges()
- similar to $scope.$digest()
-- i.e., check only this component and its childrenYou can inject ApplicationRef
, NgZone
, or ChangeDetectorRef
into your component.
Sounds like you should stay with the defaults ;-)
Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.
See here how to configure...
Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html
Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html
Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html
Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html
You should use .Load
and not .LoadXML
"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."
ref : Link
you can just do an svn add path/to/dir/*
you'll get warning about anything already in version control but it will add everything that isn't.
The Mozilla.org FAQ on debugging Mozilla on Windows is of interest here.
In short, the Visual Studio debugger can be invoked on a program from the command line, allowing one to specify the command line arguments when invoking a command line program, directly on the command line.
This looks like the following for Visual Studio 8 or 9 (Visual Studio 2005 or Visual Studio 2008, respectively)
devenv /debugexe 'program name' 'program arguments'
It is also possible to have an explorer action to start a program in the Visual Studio debugger.
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
I used the below code from this website, it works great https://www.freecodecamp.org/news/how-to-redirect-http-to-https-using-htaccess/
RewriteEngine On_x000D_
RewriteCond %{SERVER_PORT} 80_x000D_
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
_x000D_
Hope it helps
try this function
public static Date StringToDate(String strDate) throws ModuleException {
Date dtReturn = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
try {
dtReturn = simpleDateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dtReturn;
}
If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:
var currentUrl = document.referrer;
and - here you've got the main url!
You can use any of the following methods for setting the Drawable on TextView:
1- setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)
2- setCompoundDrawables(Left_Drawable, Top_Drawable, Right_Drawable, Bottom_Drawable)
And to get drawable from resources you can use:
getResources().getDrawable(R.drawable.your_drawable_id);
Similarly using Bash regexp. Shall be able to snatch any key/value pair.
key="Body"
re="\"($key)\": \"([^\"]*)\""
while read -r l; do
if [[ $l =~ $re ]]; then
name="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
echo "$name=$value"
else
echo "No match"
fi
done
Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded "
. This is an illustration. Better to use some "industrial" parser :)
If the run method ends, the thread will end.
If you use a loop, a proper way is like following:
// In your imlemented Runnable class:
private volatile boolean running = true;
public void run()
{
while (running)
{
...
}
}
public void stopRunning()
{
running = false;
}
Of course returning is the best way.
In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:
Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase
To declare a function that takes a pointer to an int:
void Foo(int *x);
To use this function:
int x = 4;
int *x_ptr = &x;
Foo(x_ptr);
Foo(&x);
If you want a pointer for another type of object, it's much the same:
void Foo(Object *o);
But, you may prefer to use references. They are somewhat less confusing than pointers:
// pass a reference
void Foo(int &x)
{
x = 2;
}
//pass a pointer
void Foo_p(int *p)
{
*x = 9;
}
// pass by value
void Bar(int x)
{
x = 7;
}
int x = 4;
Foo(x); // x now equals 2.
Foo_p(&x); // x now equals 9.
Bar(x); // x still equals 9.
With references, you still get to change the x that was passed to the function (as you would with a pointer), but you don't have to worry about dereferencing or address of operations.
As recommended by others, check out the C++FAQLite. It's an excellent resource for this.
Edit 3 response:
bar = &foo means: Make bar point to foo in memory
Yes.
*bar = foo means Change the value that bar points to to equal whatever foo equals
Yes.
If I have a second pointer (int *oof), then:
bar = oof means: bar points to the oof pointer
bar will point to whatever oof points to. They will both point to the same thing.
bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself
No. You can't do this (assuming bar is of type int *) You can make pointer pointers. (int **), but let's not get into that... You cannot assign a pointer to an int (well, you can, but that's a detail that isn't in line with the discussion).
*bar = *oof means: change the value that bar points to to the value that oof points to
Yes.
&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to
No. You can't do this because the address of operator returns an rvalue. Basically, that means you can't assign something to it.
Here's a bit of a polyfill that leverages document.CurrentScript
if it exists and falls back to finding the script by ID.
<script id="uniqueScriptId">
(function () {
var thisScript = document.CurrentScript || document.getElementByID('uniqueScriptId');
// your code referencing thisScript here
());
</script>
If you include this at the top of every script tag I believe you'll be able to consistently know which script tag is being fired, and you'll also be able to reference the script tag in the context of an asynchronous callback.
Untested, so leave feedback for others if you try it.
To reset every file in a particular folder (and its subfolders), you can use the following command:
git reset *
I came here because the Remove button was not available from Add/Remove programs. It was saying "Node.js cannot be removed".
This worked:
msiexec /uninstall <node.msi>
.Since you're using SQL Server 2008, you have the geography
data type available, which is designed for exactly this kind of data:
DECLARE @source geography = 'POINT(0 51.5)'
DECLARE @target geography = 'POINT(-3 56)'
SELECT @source.STDistance(@target)
Gives
----------------------
538404.100197555
(1 row(s) affected)
Telling us it is about 538 km from (near) London to (near) Edinburgh.
Naturally there will be an amount of learning to do first, but once you know it it's far far easier than implementing your own Haversine calculation; plus you get a LOT of functionality.
If you want to retain your existing data structure, you can still use STDistance
, by constructing suitable geography
instances using the Point
method:
DECLARE @orig_lat DECIMAL(12, 9)
DECLARE @orig_lng DECIMAL(12, 9)
SET @orig_lat=53.381538 set @orig_lng=-1.463526
DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326);
SELECT *,
@orig.STDistance(geography::Point(dest.Latitude, dest.Longitude, 4326))
AS distance
--INTO #includeDistances
FROM #orig dest
select CASE
when exists (SELECT U.USERID,U.USERNAME,U.PASSWORDHASH
FROM TBLUSERS U WHERE U.USERID =U.USERID
AND U.PASSWORDHASH=U.PASSWORDHASH)
then 'OLD PASSWORD EXISTS'
else 'OLD PASSWORD NOT EXISTS'
end as OUTPUT
from DUAL;
Have you seen the SqlDateTime object? use SqlDateTime.MinValue
to get your minimum date (Jan 1 1753).
To complete the answer of Hannes.
You need to change some setting in your php.ini:
upload_max_filesize = 2M
;or whatever size you want
max_execution_time = 60
; also, higher if you must
If someone want put in unlimited (I don't know why but if you want), you can set the time to 0:
You need to change some setting in your php.ini:
upload_max_filesize = 0
max_execution_time = 0
And if you don't know where is your php.ini. You can do a file "name.php" in your server and put:
<?php phpinfo(); ?>
And on your website, you can see the config of your php.ini and it's marked where is it.
If you can't access your php.ini, you have two more options.
You can set this line directly in your "name.php" file but I don't find for upload_max_filesize for this option:
set_time_limit(0);
Or in ".htaccess"
php_value upload_max_filesize 0
php_value max_execution_time 0
It does seem you would have to use a MessageBodyReader
here. Here's an example, using jdom:
import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;
@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
private SAXBuilder builder = new SAXBuilder();
public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
// check if we're requesting a jdom Document
return Document.class.isAssignableFrom(type);
}
public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
try {
return builder.build(entityStream);
}
catch (Exception e) {
// handle error somehow
}
}
}
Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:
@Path("/somepath") @POST
public void handleXMLData(Document doc) {
// do something with the document
}
I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:
I had a similar issue trying to split a file path and struggled to find a simple answer. This worked for me and didn't involve having to substitute delimiters back into the split text:
my_path = 'folder1/folder2/folder3/file1'
import re
re.findall('[^/]+/|[^/]+', my_path)
returns:
['folder1/', 'folder2/', 'folder3/', 'file1']
There is a nice CLI based tool for accessing MSSQL databases now.
It's called mssql-cli
and it's a bit similar to postgres' psql
.
Install for example via pip
(global installation, for a local one omit the sudo
part):
sudo pip install mssql-cli
All the workaround mentioned above may work or may not work, in most cases it will not work. I have given the solution here
Currently I am working on Angular and Web API(.net Core) and came across CORS issue explained below
The solution provided above will always work. With 'OPTIONS' request it is really necessary to enable 'Anonymous Authentication'. With the solution mentioned here you don't have to do all the steps mentioned above, like IIS settings.
Anyways someone marked my above post as duplicate with this post, but I can see that this post is only to enable CORS in ASP.net Core, but my post is related to, Enabling and implementing CORS in ASP.net Core and Angular.
Initially used only ViewDidLoad with tableView. On testing with loss of Wifi, by setting device to airplane mode, realized that the table did not refresh with return of Wifi. In fact, there appears to be no way to refresh tableView on the device even by hitting the home button with background mode set to YES in -Info.plist.
My solution:
-(void) viewWillAppear: (BOOL) animated { [self.tableView reloadData];}
Get a decent text editor like Notepad++ or Vim (if you're already proficient with it). Search for the table name and you should be able to highlight just the CREATE, ALTER, and INSERT commands for that table. It may be easier to navigate with your keyboard rather than a mouse. And I would make sure you're on a machine with plenty or RAM so that it will not have a problem loading the entire file at once. Once you've highlighted and copied the rows you need, it would be a good idea to back up just the copied part into it's own backup file and then import it into MySQL.
Best and most generic way to control the music is to create a mother Activity in which you override startActivity(Intent intent)
- in it you put shouldPlay=true
,
and onBackPressed()
- in it you put shouldPlay = true
.
onStop
- in it you put a conditional mediaPlayer.stop with shouldPlay as condition
Then, just extend the mother activity to all other activities, and no code duplicating is needed.
Depending on your logic, if you want to close only the current fragment you have to pass viewLifecycleOwner, code is shown below:
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
requireActivity().finish()
}
})
However, if you want to close application on backPressed no matter from what fragment(probably you wouldn't want that!), don't pass the viewLifecycleOwner. Also if you want to disable the back button, do not do anything inside the handleOnBackPressed(), see below:
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// do nothing it will disable the back button
}
})
Use insert
if you want to insert a new element. insert
will not
overwrite an existing element, and you can verify that there was no
previously exising element:
if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
// Element already present...
}
Use []
if you want to overwrite a possibly existing element:
myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition
This form will overwrite any existing entry.
<
stands for the less-than sign: <
>
stands for the greater-than sign: >
≤
stands for the less-than or equals sign: =
≥
stands for the greater-than or equals sign: =
By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers:
old 1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new 1: insert into customers (customer_name) values ('Marks Ltd')
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks Ltd
If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off
to switch off the behaviour while running the script:
SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd
You might want to add set define on
at the end of the script to restore the default behaviour.
Passed parameter like below,
Param([parameter(Mandatory=$true,
HelpMessage="Enter name and key values")]
$Name,
$Key)
.\script_name.ps1 -Name name -Key key
You can use a ComboBox
with its ComboBoxStyle
(appears as DropDownStyle
in later versions) set to DropDownList
. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx
Assuming there is a table config
with unique index on config_code
column:
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
config1 abc 123
config2 def 456
This query returns line for config1
values, because it exists in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config1'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
config1 abc 123
This one returns default record as config3
doesn't exist in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config3'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
In comparison with other solutions this one queries table config
only once.
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
You can change your approach slightly - use Console.ReadKey()
to stop your app, but do your work in a background thread:
static void Main(string[] args)
{
var myWorker = new MyWorker();
myWorker.DoStuff();
Console.WriteLine("Press any key to stop...");
Console.ReadKey();
}
In the myWorker.DoStuff()
function you would then invoke another function on a background thread (using Action<>()
or Func<>()
is an easy way to do it), then immediately return.
function ArrayToObject( arr ) {
var obj = {};
for (var i = 0; i < arr.length; ++i){
var name = arr[i].name;
var value = arr[i].value;
obj[name] = arr[i].value;
}
return obj;
}
var form_data = $('#my_form').serializeArray();
form_data = ArrayToObject( form_data );
form_data.action = event.target.id;
form_data.target = event.target.dataset.event;
console.log( form_data );
$.post("/api/v1/control/", form_data, function( response ){
console.log(response);
}).done(function( response ) {
$('#message_box').html('SUCCESS');
})
.fail(function( ) { $('#message_box').html('FAIL'); })
.always(function( ) { /*$('#message_box').html('SUCCESS');*/ });
if you want to execute ENABLE TRIGGER Directly From Source :
we can't write like this:
Conn.Execute "ENABLE TRIGGER trigger_name ON table_name"
instead, we can write :
Conn.Execute "ALTER TABLE table_name DISABLE TRIGGER trigger_name"
I have created a JSFiddle with my bindHTML knockout binding handler here: https://jsfiddle.net/glaivier/9859uq8t/
First, save the binding handler into its own (or a common) file and include after Knockout.
If you use this switch your bindings to this:
<div data-bind="bindHTML: htmlValue"></div>
OR
<!-- ko bindHTML: htmlValue --><!-- /ko -->
I just update the pod file 'pod update' and it start to work for me normally.
You can use $.isEmptyObject(json)
I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
I can't remember where I got this from that I used in my assignment (I usually copy paste the URL where I found it as an easy form of citation) and I cannot decipher what the trailing (file) = 0
is although my best guess is that it is redundancy to set any references to file to 0.
#define fclose(file) ((file) ? fclose(file) : 0, (file) = 0)
file
if a pointer declared as:
FILE *file=NULL;
In general I fully agree with Jason's use of css selector, but in some cases you may not want to change the css, e.g. when using a 3rd party css-template, and rather prefer to add/remove a class on the element.
The following sample shows a simple way of adding/removing a class on ng-mouseenter/mouseleave:
<div ng-app>
<div
class="italic"
ng-class="{red: hover}"
ng-init="hover = false"
ng-mouseenter="hover = true"
ng-mouseleave="hover = false">
Test 1 2 3.
</div>
</div>
with some styling:
.red {
background-color: red;
}
.italic {
font-style: italic;
color: black;
}
See running example here: jsfiddle sample
Styling on hovering is a view concern. Although the solution above sets a "hover" property in the current scope, the controller does not need to be concerned about this.
The first thing I would check is the config for mod_nss. It is the odd one out, for it is yours and there is none in the world like it :-) Whereas if there was some huge bug in Firefox or mod_nss itself, I guess you'd have found out about it by now in your google quest. The fact that you've fiddled with the config (e.g. disabling SSL3, and various other random tweaks), is also suspicious.
I'd back track to a very vanilla mod_nss config and see if that works. Then change things systematically towards your current config until you can reproduce the problem. By the sound of it the source of the error is somewhere in the cipher spec config of mod_nss and the related protocol negotiation stuff. So maybe you inadvertently changed something there when trying to turn off SSLv3 (incidentally, why disable SSL3? Normally people disable V2?).
One other thing to check is that you're on the latest mod_nss and it's not a known bug in that. The fact that it manages to start the session and then fails later is interesting - it suggests that maybe it is trying to renegotiate the session and failing to negotiate ciphers at that point. So it might be the symmetric ciphers. Or it could simply be an implementation bug in your version of mod_nss that somehow garbles the protocol.
One other idea, and this is a wild guess, is the browser is trying to resume a session which was negotiated with SSLv3 before you disabled it, and something breaks when trying to resume that session when V3 is turned off, or maybe mod_nss just doesn't implement it right.
The java/tomcat stuff seems like a red herring as unless I've misunderstood your description, none of that is involved in the SSL handshake/protocol.
I know it's been a while this has been posted, but with iOS 7.1, a few things have changed.
So far, if you are developing an App, you MUST have a valid SSL certificate recognized by Apple, otherwise you will get an error message on you iDevice. No more self-signed certificates. See here a list:
http://support.apple.com/kb/ht5012
Additionally, if you are here, it means that you are trying to make you iDevice resolve a name (to your https server), on a test or development environment.
Instead of using squid, which is a great application, you could simply run a very basic DNS server like dnsmasq. It will use your hosts file as a first line of name resolution, so, you can basically fool your iDevice there, saying that www.blah.com is 192.168.10.10.
The configuration file is as simple as 3 to 4 lines, and you can even configure its internal DHCP server if you want.
Here is mine:
listen-address=192.168.10.35
domain-needed
bogus-priv
no-dhcp-interface=eth0
local=/localnet/
Of course you have to configure networking on your iDevice to use that DNS (192.168.10.35 in my case), or just start using DHCP from that server anyway, after properly configured.
Additionally, if dnsmasq cannot resolve the name internally, it uses your regular DNS server (like 8.8.8.8) to resolve it for you. VERY simple, elegant, and solved my problems with iDevice App installation in-house.
By the way, solves many name resolution problems with regular macs (OS X) as well.
Now, my rant: bloody Apple. Making a device safe should not include castrating the operating system or the developers.
This will Help to Keep a fixed length when you want to print several elements at one print statement
25s format a string with 25 spaces, left justified by default
5d format an integer reserving 5 spaces, right justified by default
members=["Niroshan","Brayan","Kate"]
print("__________________________________________________________________")
print('{:25s} {:32s} {:35s} '.format("Name","Country","Age"))
print("__________________________________________________________________")
print('{:25s} {:30s} {:5d} '.format(members[0],"Srilanka",20))
print('{:25s} {:30s} {:5d} '.format(members[1],"Australia",25))
print('{:25s} {:30s} {:5d} '.format(members[2],"England",30))
print("__________________________________________________________________")
25s format a string with 25 spaces, left justified by default
5d format an integer reserving 5 spaces, right justified by default
And this will print
__________________________________________________________________
Name Country Age
__________________________________________________________________
Niroshan Srilanka 20
Brayan Australia 25
Kate England 30
__________________________________________________________________
If you don't have an image with that name locally, docker will try to pull it from docker hub, but there's no such image on docker hub. Or simply try "docker login".
Use the Application.DispatcherUnhandledException Event
. See this question for a summary (see Drew Noakes' answer).
Be aware that there'll be still exceptions which preclude a successful resuming of your application, like after a stack overflow, exhausted memory, or lost network connectivity while you're trying to save to the database.
The file is a gzipped (compressed) SQL file, almost certainly a plain text file with .sql as its extension. The first thing you need to do is copy the file to your database server via scp.. I think PuTTY's is pscp.exe
# Copy it to the server via pscp
C:\> pscp.exe numbers.sql.gz user@serverhostname:/home/user
Then SSH into your server and uncompress the file with gunzip
user@serverhostname$ gunzip numbers.sql.gz
user@serverhostname$ ls
numbers.sql
Finally, import it into your MySQL database using the <
input redirection operator:
user@serverhostname$ mysql -u mysqluser -p < numbers.sql
If the numbers.sql file doesn't create a database but expects one to be present already, you will need to include the database in the command as well:
user@serverhostname$ mysql -u mysqluser -p databasename < numbers.sql
If you have the ability to connect directly to your MySQL server from outside, then you could use a local MySQL client instead of having to copy and SSH. In that case, you would just need a utility that can decompress .gz files on Windows. I believe 7zip does so, or you can obtain the gzip/gunzip binaries for Windows.
Use the json
module to produce JSON output:
import json
with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
This writes the JSON result directly to the file (replacing any previous content if the file already existed).
If you need the JSON result string in Python itself, use json.dumps()
(added s
, for 'string'):
json_string = json.dumps(row)
The L
is just Python syntax for a long integer value; the json
library knows how to handle those values, no L
will be written.
Demo string output:
>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
class Program
{
static void Main(string[] args)
{
String unicodeString =
"This Unicode string contains two characters " +
"with codes outside the traditional ASCII code range, " +
"Pi (\u03a0) and Sigma (\u03a3).";
Console.WriteLine("Original string:");
Console.WriteLine(unicodeString);
UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
byte[] utf16Bytes = unicodeEncoding.GetBytes(unicodeString);
char[] chars = unicodeEncoding.GetChars(utf16Bytes, 2, utf16Bytes.Length - 2);
string s = new string(chars);
Console.WriteLine();
Console.WriteLine("Char Array:");
foreach (char c in chars) Console.Write(c);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("String from Char Array:");
Console.WriteLine(s);
Console.ReadKey();
}
}
I had this problem and like Anderson Imes said it had to do with app settings. My problem was the scope of one of my settings was set to "User" when it should have been "Application".
Use this code instead of it:
<frameset rows="100%,*">
<frame src="-------------------------URL-------------------------------">
<noframes>
<body>
Your browser does not support frames. To wiew this page please use supporting browsers.
</body>
</noframes>
</frameset>
select u from UserGroup ug inner join ug.user u
where ug.group_id = :groupId
order by u.lastname
As a named query:
@NamedQuery(
name = "User.findByGroupId",
query =
"SELECT u FROM UserGroup ug " +
"INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)
Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.
O(n) is big O notation used for writing time complexity of an algorithm. When you add up the number of executions in an algoritm you'll get an expression in result like 2N+2, in this expression N is the dominating term(the term having largest effect on expression if its value increases or decreases). Now O(N) is the time comlexity while N is dominating term. Example
For i= 1 to n;
j= 0;
while(j<=n);
j=j+1;
here total number of executions for inner loop are n+1 and total number of executions for outer loop are n(n+1)/2, so total number of executions for whole algorithm are n+1+n(n+1/2) = (n^2+3n)/2. here n^2 is the dominating term so the time complexity for this algorithm is O(n^2)
I too had this problem, when I checked I image that I was pulling from a private registry was removed If we describe pod it will show pulling event and the image it's trying to pull
kubectl describe pod <POD_NAME>
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Pulling 18h (x35 over 20h) kubelet, gsk-kub Pulling image "registeryName:tag"
Normal BackOff 11m (x822 over 20h) kubelet, gsk-kub Back-off pulling image "registeryName:tag"
Warning Failed 91s (x858 over 20h) kubelet, gsk-kub Error: ImagePullBackOff
Quick and dirty way:
<View
android:id="@+id/colored_bar"
android:layout_width="48dp"
android:layout_height="3dp"
android:background="@color/bar_red" />
You can either go for f5 it will execute all the scrips on the tab.
Or
You can create a sql file and put all the insert statements in it and than give the file path in sql plus and execute.
margin: 0 auto
then the element should be centered, but the width is left as-is--whatever it is calculated to be, disregarding any margin settings.<INPUT>
tag to display:block
, then it should be centered with margin: 0 auto
. See Visual formatting model details - calculating widths and margins from the CSS 2.1 specs for more details. Relavent bits include:
In a block formatting context, each box's left outer edge touches the left edge of the containing block.
and
When the total width of the inline boxes on a line is less than the width of the line box containing them, their horizontal distribution within the line box is determined by the 'text-align' property.
finally
If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.
If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.
A YAML sequence is an array. So this is the right way to express it:
key:
- string1
- string2
- string3
- string4
- string5
- string6
That's identical in meaning to:
key: ['string1', 'string2', 'string3', 'string4', 'string5', 'string6']
It's also legal to split a single-line array over several lines:
key: ['string1', 'string2', 'string3',
'string4', 'string5',
'string6']
and even have multi-line strings in single-line arrays:
key: ['string1', 'long
string', 'string3', 'string4', 'string5', 'string6']
a+
to open a file for reading, writing as well as create it if it doesn't exist.a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes
with open('"File.txt', 'a+') as file:
print(file.readlines())
file.write("test")
Note: opening file in a with
block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally
, but much shorter.
Your HTML
$html='<ul id="main">
<li>
<h1><a href="[link]">My Title</a></h1>
<span class="date">Date</span>
<div class="section">
[content]
</div>
</li>
</ul>';
//function call you can change the tag name
echo contentBetweenTags($html,"span");
// this function will help you to fetch the data from a specific tag
function contentBetweenTags($content, $tagname){
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match($pattern, $content, $matches);
if(empty($matches))
return;
$str = "<$tagname>".html_entity_decode($matches[1])."</$tagname>";
return $str;
}
You could always ensure they're in the same case before the comparison:
if ([[stringX uppercaseString] isEqualToString:[stringY uppercaseString]]) {
// They're equal
}
The main benefit being you avoid the potential issue described by matm regarding comparing nil strings. You could either check the string isn't nil before doing one of the compare:options:
methods, or you could be lazy (like me) and ignore the added cost of creating a new string for each comparison (which is minimal if you're only doing one or two comparisons).
Neither one. Use final class for Constants
declare them as public static final
and static import all constants wherever necessary.
public final class Constants {
private Constants() {
// restrict instantiation
}
public static final double PI = 3.14159;
public static final double PLANCK_CONSTANT = 6.62606896e-34;
}
Usage :
import static Constants.PLANCK_CONSTANT;
import static Constants.PI;//import static Constants.*;
public class Calculations {
public double getReducedPlanckConstant() {
return PLANCK_CONSTANT / (2 * PI);
}
}
See wiki link : http://en.wikipedia.org/wiki/Constant_interface
This question is old but here is another answer because it is useful fo others:
thread.sleep is not a good method for waiting, because usually it freezes the software until finishing its time, this function is better:
Imports VB = Microsoft.VisualBasic
Public Sub wait(ByVal seconds As Single)
Static start As Single
start = VB.Timer()
Do While VB.Timer() < start + seconds
System.Windows.Forms.Application.DoEvents()
Loop
End Sub
The above function waits for a specific time without freezing the software, however increases the CPU usage.
This function not only doesn't freeze the software, but also doesn't increase the CPU usage:
Private Sub wait(ByVal seconds As Integer)
For i As Integer = 0 To seconds * 100
System.Threading.Thread.Sleep(10)
Application.DoEvents()
Next
End Sub
You can (should) use CROSS JOIN
. Following query will be equivalent to yours:
SELECT
table1.columnA
, table2.columnA
FROM table1
CROSS JOIN table2
WHERE table1.columnA = 'Some value'
or you can even use INNER JOIN with some always true conditon:
FROM table1
INNER JOIN table2 ON 1=1
do not forget to insert (or unCommanet) this line at the beginning of your pod file:
platform :iOS, '9.0'
that saves my day
For printing I don't set any width and remove any obstacles which keep your print layout from having a dynamic width. Meaning if you make your browser window smaller and smaller, no content is cut/hidden but the document just gets longer. Like this, you can be sure that the rest will be handled by the printer/pdf-creator.
What about elements with a fixed width such as images or tables?
Options I can think of:
http://www.intensivstation.ch/en/css/print/
or any other google result for combinations of: CSS, print, media, layout
Try this
SELECT ID, Name
FROM Table1
WHERE ID NOT IN (SELECT ID FROM Table2)
1- Just open https://developer.android.com/studio/index.html
2- scroll down to the bottom of that page
3- download last version of tools for your OS (for example tools_r25.2.3-windows.zip)
4- Unzip it
5- Delete folder tools from previous Android Sdk folder
6- Copy new folder tools to Android SDK Folder like this image:
Check if element is visible in viewport using jquery:
First determine the top and bottom positions of the element. Then determine the position of the viewport's bottom (relative to the top of your page) by adding the scroll position to the viewport height.
If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially). In simpler terms, when any part of the element is between the top and bottom bounds of your viewport, the element is visible on your screen.
Now you can write an if/else statement, where the if statement only runs when the above condition is met.
The code below executes what was explained above:
// this function runs every time you are scrolling
$(window).scroll(function() {
var top_of_element = $("#element").offset().top;
var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
var top_of_screen = $(window).scrollTop();
if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
// the element is visible, do something
} else {
// the element is not visible, do something else
}
});
This answer is a summary of what Chris Bier and Andy were discussing below. I hope it helps anyone else who comes across this question while doing research like I did. I also used an answer to the following question to formulate my answer: Show Div when scroll position.
For those of you scanning through these answers for a complete working example for Python3... well here ya go:
def numgen():
x = 1000
while True:
x += 1
yield x
nums = numgen() # because it must be the _same_ generator
for n in range(3):
numnext = next(nums)
print(numnext)
This outputs:
1001
1002
1003
In .Net Core (as of v2.2) it should be:
new Process
{
StartInfo = new ProcessStartInfo(@"file path")
{
UseShellExecute = true
}
}.Start();
Related github issue can be found here
int i;
for (i = 0; i < ARRAY_SIZE; ++i)
{
myArray[i] = VALUE;
}
I think this is better than
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5...
incase the size of the array changes.
Django employs a slightly modified kind of MVC. There's no concept of a "controller" in Django. The closest proxy is a "view", which tends to cause confusion with MVC converts because in MVC a view is more like Django's "template".
In Django, a "model" is not merely a database abstraction. In some respects, it shares duty with the Django's "view" as the controller of MVC. It holds the entirety of behavior associated with an instance. If that instance needs to interact with an external API as part of it's behavior, then that's still model code. In fact, models aren't required to interact with the database at all, so you could conceivable have models that entirely exist as an interactive layer to an external API. It's a much more free concept of a "model".
dovers gives us his great answer and based on it you can try use it like
public static class CellDataFormat
{
public static string General { get { return "General"; } }
public static string Number { get { return "0"; } }
// Your custom format
public static string NumberDotTwoDigits { get { return "0.00"; } }
public static string Currency { get { return "$#,##0.00;[Red]$#,##0.00"; } }
public static string Accounting { get { return "_($* #,##0.00_);_($* (#,##0.00);_($* \" - \"??_);_(@_)"; } }
public static string Date { get { return "m/d/yy"; } }
public static string Time { get { return "[$-F400] h:mm:ss am/pm"; } }
public static string Percentage { get { return "0.00%"; } }
public static string Fraction { get { return "# ?/?"; } }
public static string Scientific { get { return "0.00E+00"; } }
public static string Text { get { return "@"; } }
public static string Special { get { return ";;"; } }
public static string Custom { get { return "#,##0_);[Red](#,##0)"; } }
}
If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z
) to timestamp, here's how you'd do it:
function UTCToTimestamp($utc_datetime_str)
{
preg_match_all('/(.+?)T(.+?)\.(.*?)Z/i', $utc_datetime_str, $matches_arr);
$datetime_str = $matches_arr[1][0]." ".$matches_arr[2][0];
return strtotime($datetime_str);
}
$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';
$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);
AWS / Heroku are both free for small hobby projects (to start with).
If you want to start an app right away, without much customization of the architecture, then choose Heroku.
If you want to focus on the architecture and to be able to use different web servers, then choose AWS. AWS is more time-consuming based on what service/product you choose, but can be worth it. AWS also comes with many plugin services and products.
Heroku
AWS
Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.
export default function useGoogleMapMarker(props) {
const [marker, setMarker] = useState();
useEffect(() => {
// ...code
const marker = new maps.Marker({ position, map, title, icon });
// ...code
setMarker(marker);
return () => marker.setMap(null); // to remove markers when unmounts
}, []);
return marker;
}
instead of using " + " operator
print( "Alireza" + 1980)
Use comma " , " operator
print( "Alireza" , 1980)
String.Format("{0:#,###.##}", value)
A more complex example from String Formatting in C#:
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);
This will output “$1,240.00" if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.