Add z-index:-1
and position:relative
to .content
#header {_x000D_
background: url(http://placehold.it/420x160) center top no-repeat;_x000D_
}_x000D_
#header-inner {_x000D_
background: url(http://placekitten.com/150/200) right top no-repeat;_x000D_
}_x000D_
.logo-class {_x000D_
height: 128px;_x000D_
}_x000D_
.content {_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
z-index: -1;_x000D_
position:relative;_x000D_
}_x000D_
.td-main {_x000D_
text-align: center;_x000D_
padding: 80px 10px 80px 10px;_x000D_
border: 1px solid #A02422;_x000D_
background: #ABABAB;_x000D_
}
_x000D_
<body>_x000D_
<div id="header">_x000D_
<div id="header-inner">_x000D_
<table class="content">_x000D_
<col width="400px" />_x000D_
<tr>_x000D_
<td>_x000D_
<table class="content">_x000D_
<col width="400px" />_x000D_
<tr>_x000D_
<td>_x000D_
<div class="logo-class"></div>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td id="menu"></td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="content">_x000D_
<col width="120px" />_x000D_
<col width="160px" />_x000D_
<col width="120px" />_x000D_
<tr>_x000D_
<td class="td-main">text</td>_x000D_
<td class="td-main">text</td>_x000D_
<td class="td-main">text</td>_x000D_
</tr>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<!-- header-inner -->_x000D_
</div>_x000D_
<!-- header -->_x000D_
</body>
_x000D_
New answer to an old question:
Method 1:
Step 1: You have to put /show
after the URL
you are working on:
http://jsfiddle.net/<fiddle_id>/show/
It shows the output with a result header.
Step 2: Right click the bottom frame and select View Frame Source. That's it. You got the html code with online JS links, CSS.
Just Save it.
For Example: http://jsfiddle.net/YRafQ/20/show/ for the site http://jsfiddle.net/YRafQ/20/
Note: View Frame Source and not View Page Source
Method 2:
You can use this code: view-source:http://fiddle.jshell.net/<fiddle_id>/show/light/
For Example: For my fiddle_id: YRafQ/20
view-source:http://fiddle.jshell.net/YRafQ/20/show/light/
For people having the same error with a similar code:
$(function(){
var app = angular.module("myApp", []);
app.controller('myController', function(){
});
});
Removing the $(function(){ ... }); solved the error.
There is the semicolon missing (;) after the "50%"
but you should also notice that the percentage of your div is connected to the div that contains it.
for instance:
<div id="wrapper">
<div class="container">
adsf
</div>
</div>
#wrapper {
height:100px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.
if you have:
adsf
#wrapper {
height:400px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
then you .container will be 200px. 50% of the wrapper.
So you may want to look at the divs "wrapping" your ".container"...
For the sake of completeness, here's a simple one-liner I ended up with (I had no need checking for non-Foo-properties):
var Foo = function(){ this.bar = 1; };
// angular version
var foo = angular.extend(new Foo(), angular.fromJson('{ "bar" : 2 }'));
// jquery version
var foo = jQuery.extend(new Foo(), jQuery.parseJSON('{ "bar" : 3 }'));
Seems to be a typo error in that package of gcc. The solution:
mv /usr/include/c++/4.x/i486-linux-gnu /usr/include/c++/4.x/i686-linux-gnu/64
I use automapper to copy an object. I just setup a mapping that maps one object to itself. You can wrap this operation any way you like.
MOD() function exists in both Oracle and MySQL, but not in SQL Server.
In SQL Server, try this:
SELECT * FROM Orders where OrderID % 2 = 0;
In Swift 4, just as simple as Swift 3:
self.view.backgroundColor = UIColor.brown
For me, it is exactly what the maven of eclipse complains
So, I press Edit
button and change path to the JDK Folder, then clean project and everything starts to work
The strcomp
function may be appropriate here (returns 0 when strings are identical):
SELECT * from table WHERE Strcmp(user, testername) <> 0;
Regarding client timeouts and the use of XACT_ABORT to handle them, in my opinion there is at least one very good reason to have timeouts in client APIs like SqlClient, and that is to guard the client application code from deadlocks occurring in SQL server code. In this case the client code has no fault, but has to protect it self from blocking forever waiting for the command to complete on the server. So conversely, if client timeouts have to exist to protect client code, so does XACT_ABORT ON has to protect server code from client aborts, in case the server code takes longer to execute than the client is willing to wait for.
This can happen after upgrading macOS. Try running git from a terminal and see if the error message begins with:
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) ...
If so the fix is to run
xcode-select --install
from the terminal. see this answer for more details
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
use the exchange using java. setText = "...", for class java there are many more methods for implementation.
//button fechar
btnclose.setEnabled(false);
btnclose.setText("FECHADO");
View.OnClickListener close = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (btnclose.isClickable()) {
btnOpen.setEnabled(true);
btnOpen.setText("ABRIR");
btnclose.setEnabled(false);
btnclose.setText("FECHADO");
} else {
btnOpen.setEnabled(false);
btnOpen.setText("ABERTO");
btnclose.setEnabled(true);
btnclose.setText("FECHAR");
}
Toast.makeText(getActivity(), "FECHADO", Toast.LENGTH_SHORT).show();
}
};
btnclose.setOnClickListener(close);
refresh the datagridview and refresh the datatable
dataGridView1.Refresh();
datatable.Clear();
The best way to work with args for your winforms app is to use
string[] args = Environment.GetCommandLineArgs();
You can probably couple this with the use of an enum to solidify the use of the array througout your code base.
"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."
Found at:HERE
Changing
RestResponse response = client.Execute(request);
to
IRestResponse response = client.Execute(request);
worked for me.
I solved the issue by following this link
namespace System.Web.Mvc
{
public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return null;
var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
var bodyText = reader.ReadToEnd();
return String.IsNullOrEmpty(bodyText) ? null : new DictionaryValueProvider<object>(JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter()), CultureInfo.CurrentCulture);
}
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//Remove and JsonValueProviderFactory and add JsonDotNetValueProviderFactory
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());
}
Just to enrich the discussion, if you want to move myBranch
branch to your current commit, just omit the second argument after -f
Example:
git branch -f myBranch
I generally do this when I rebase
while in a Detached HEAD state :)
If you have any access to the server at all, convert its processing to UTF-8. The art of submitting non-UTF-8 forms is a long and sorry story; this document about forms and i18n may be of interest. I understand you do not seem to care about international support; you can always convert the UTF-8 data to html entities to make sure it stays Latin-1.
In the past I have used the excellently named MetricsReloaded plugin to get this information.
You can install it from the JetBrains repository.
Once installed, access via: Analyze -> Calculate Metrics...
Aside from the clear: both
hack, you can skip the extra element and use overflow: hidden
on the wrapping div
:
<div style="overflow: hidden;">
<div style="float: left;"></div>
<div style="float: left;"></div>
</div>
This is my code,tested and working fine:
package com.example.com.mak.mediaplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mpp = MediaPlayer.create(this, R.raw.red); //mp3 file in res/raw folder
Button btnplay = (Button) findViewById(R.id.btnplay); //Play
btnplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vone) {
mpp.start();
}
});
Button btnpause = (Button) findViewById(R.id.btnpause); //Pause
btnpause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vtwo) {
if (mpp.isPlaying()) {
mpp.pause();
mpp.seekTo(0);
}
}
});
}
}
You can loop through all non-indexed properties of an object like this:
var s = new MyObject();
foreach (var p in s.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any())) {
Console.WriteLine(p.GetValue(s, null));
}
Since GetProperties()
returns indexers as well as simple properties, you need an additional filter before calling GetValue
to know that it is safe to pass null
as the second parameter.
You may need to modify the filter further in order to weed out write-only and otherwise inaccessible properties.
I'm going to give you 2 way's to call an action from the client side
first
If you just want to navigate to an action you should call just use the follow
window.location = "/Home/Index/" + youid
Notes: that you action need to handle a get type called
Second
If you need to render a View you could make the called by ajax
//this if you want get the html by get
public ActionResult Foo()
{
return View(); //this return the render html
}
And the client called like this "Assuming that you're using jquery"
$.get('your controller path', parameters to the controler , function callback)
or
$.ajax({
type: "GET",
url: "your controller path",
data: parameters to the controler
dataType: "html",
success: your function
});
or
$('your selector').load('your controller path')
Update
In your ajax called make this change to pass the data to the action
function onDropDownChange(e) {
var url = '/Home/Index'
$.ajax({
type: "GET",
url: url,
data: { id = e.value}, <--sending the values to the server
dataType: "html",
success : function (data) {
//put your code here
}
});
}
UPDATE 2
You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div
in your view and do something like this
in the view where you are that have the combo in some place
<div id="theNewView"> </div> <---you're going to load the other view here
in the javascript client
$.ajax({
type: "GET",
url: url,
data: { id = e.value}, <--sending the values to the server
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
With this i think that you solve your problem
In my opinion best way is 1) place the CSS file in the header part in between head tag reason is first page show the view for that css require 2)and all js file should place before the body closing tag. reason is after all component display js can apply
Beginning PowerShell 5.0 New-Item
, Remove-Item
, and Get-ChildItem
have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item
accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.
New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"
Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.
Anyway if you want to create a Run As Administrator shortcut using Powershell you can use
$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)
If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.
I solved it by adding "edit permission" to the application of the site, mapped to the physical directory and then selected the windows user that could have access to this root folder. (private network).
HTML
<img id=imageid src=https://www.google.de/images/srpr/logo11w.png>
JavaScript
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
var base64 = getBase64Image(document.getElementById("imageid"));
This method requires the canvas element, which is perfectly supported.
HTMLCanvasElement.toDataURL()
.Toast.makeText(this, "Text", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Text", Toast.LENGTH_LONG).show();
A very simple solution to the question. Twice or triple of them will make Toast last longer. It is the only way around.
<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));
//Iterate through an array declared above
foreach($php_multi_array as $key => $value)
{
if (!is_array($value))
{
echo $key ." => ". $value ."\r\n" ;
}
else
{
echo $key ." => array( \r\n";
foreach ($value as $key2 => $value2)
{
echo "\t". $key2 ." => ". $value2 ."\r\n";
}
echo ")";
}
}
?>
OUTPUT:
lang => PHP
type => array(
c_type => MULTI
p_type => ARRAY
)
My query I did as follows:
SELECT COUNT(carSold)
FROM cars_sales_tbl
WHERE date
BETWEEN '2015-04-01' AND '2015-04-30'
AND carType = "Hybrid"
I got the hint by @ifredy's answer. The all I did is, I wanted this query to be run in iOS, using Objective-C. And it works!
Hope someone who does iOS Development, will get use out of this answer too!
The image below is from the article written by Erwin van der Valk:
The article explains the differences and gives some code examples in C#
Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.
Just found a post Atomic vs. Non-Atomic Operations to be very helpful to me.
"An operation acting on shared memory is atomic if it completes in a single step relative to other threads.
When an atomic store is performed on a shared memory, no other thread can observe the modification half-complete.
When an atomic load is performed on a shared variable, it reads the entire value as it appeared at a single moment in time."
1. Pass By Value / Call By Value
void printvalue(int x)
{
x = x + 1 ;
cout << x ; // 6
}
int x = 5;
printvalue(x);
cout << x; // 5
In call by value, when you pass a value to printvalue(x)
i.e. the argument which is 5
, it is copied to void printvalue(int x)
. Now, we have two different values 5
and the copied value 5
and these two values are stored in different memory locations. So if you make any change inside void printvalue(int x)
it won't reflect back to the argument.
2. Pass By Reference/ Call By Reference
void printvalue(int &x)
{
x = x + 1 ;
cout << x ; // 6
}
int x = 5;
printvalue(x);
cout << x; // 6
In call by reference, there's only one difference. We use &
i.e. the address operator. By doing
void printvalue(int &x)
we are referring to the address of x
which tells us that it both refers to the same location. Hence, any changes made inside the function will reflect outside.
Now that you're here, you should also know about ...
3. Pass By Pointer/ Call By Address
void printvalue(int* x)
{
*x = *x + 1 ;
cout << *x ; // 6
}
int x = 5;
printvalue(&x);
cout << x; // 6
In pass by address, the pointer int* x
holds the address passed to it printvalue(&x)
. Hence, any changes done inside the function will reflect outside.
If you can not authenticate via the web interface (localhost/phpmyadmin/) then try change authentication type to cookie.
$cfg['Servers'][$i]['auth_type'] = 'cookie';
In a single line, I suggest:
String input = "test string (67)";
input = input.subString(input.indexOf("(")+1, input.lastIndexOf(")"));
System.out.println(input);`
A good and simple example for nested try/except could be the following:
import numpy as np
def divide(x, y):
try:
out = x/y
except:
try:
out = np.inf * x / abs(x)
except:
out = np.nan
finally:
return out
Now try various combinations and you will get the correct result:
divide(15, 3)
# 5.0
divide(15, 0)
# inf
divide(-15, 0)
# -inf
divide(0, 0)
# nan
(Of course, we have NumPy, so we don't need to create this function.)
You will need to define "special characters", but it's likely that for some string s
you mean:
import re
if re.match(r'^\w+$', s):
# s is good-to-go
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
Identifying the column is easy:
SELECT *
FROM ( SELECT id,
time
FROM dbo.a
UNION
SELECT id,
time
FROM dbo.b
)
GROUP BY id
But it doesn't solve the main problem of this query: what's to be done with the second column values upon grouping by the first? Since (peculiarly!) you're using UNION
rather than UNION ALL
, you won't have entirely duplicated rows between the two subtables in the union, but you may still very well have several values of time for one value of the id, and you give no hint of what you want to do - min, max, avg, sum, or what?! The SQL engine should give an error because of that (though some such as mysql just pick a random-ish value out of the several, I believe sql-server is better than that).
So, for example, change the first line to SELECT id, MAX(time)
or the like!
Script vs. Module
Here's an explanation. The short version is that there is a big difference between directly running a Python file, and importing that file from somewhere else. Just knowing what directory a file is in does not determine what package Python thinks it is in. That depends, additionally, on how you load the file into Python (by running or by importing).
There are two ways to load a Python file: as the top-level script, or as a
module. A file is loaded as the top-level script if you execute it directly, for instance by typing python myfile.py
on the command line. It is loaded as a module if you do python -m myfile
, or if it is loaded when an import
statement is encountered inside some other file. There can only be one top-level script at a time; the top-level script is the Python file you ran to start things off.
Naming
When a file is loaded, it is given a name (which is stored in its __name__
attribute). If it was loaded as the top-level script, its name is __main__
. If it was loaded as a module, its name is the filename, preceded by the names of any packages/subpackages of which it is a part, separated by dots.
So for instance in your example:
package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleA.py
if you imported moduleX
(note: imported, not directly executed), its name would be package.subpackage1.moduleX
. If you imported moduleA
, its name would be package.moduleA
. However, if you directly run moduleX
from the command line, its name will instead be __main__
, and if you directly run moduleA
from the command line, its name will be __main__
. When a module is run as the top-level script, it loses its normal name and its name is instead __main__
.
Accessing a module NOT through its containing package
There is an additional wrinkle: the module's name depends on whether it was imported "directly" from the directory it is in, or imported via a package. This only makes a difference if you run Python in a directory, and try to import a file in that same directory (or a subdirectory of it). For instance, if you start the Python interpreter in the directory package/subpackage1
and then do import moduleX
, the name of moduleX
will just be moduleX
, and not package.subpackage1.moduleX
. This is because Python adds the current directory to its search path on startup; if it finds the to-be-imported module in the current directory, it will not know that that directory is part of a package, and the package information will not become part of the module's name.
A special case is if you run the interpreter interactively (e.g., just type python
and start entering Python code on the fly). In this case the name of that interactive session is __main__
.
Now here is the crucial thing for your error message: if a module's name has no dots, it is not considered to be part of a package. It doesn't matter where the file actually is on disk. All that matters is what its name is, and its name depends on how you loaded it.
Now look at the quote you included in your question:
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
Relative imports...
Relative imports use the module's name to determine where it is in a package. When you use a relative import like from .. import foo
, the dots indicate to step up some number of levels in the package hierarchy. For instance, if your current module's name is package.subpackage1.moduleX
, then ..moduleA
would mean package.moduleA
. For a from .. import
to work, the module's name must have at least as many dots as there are in the import
statement.
... are only relative in a package
However, if your module's name is __main__
, it is not considered to be in a package. Its name has no dots, and therefore you cannot use from .. import
statements inside it. If you try to do so, you will get the "relative-import in non-package" error.
Scripts can't import relative
What you probably did is you tried to run moduleX
or the like from the command line. When you did this, its name was set to __main__
, which means that relative imports within it will fail, because its name does not reveal that it is in a package. Note that this will also happen if you run Python from the same directory where a module is, and then try to import that module, because, as described above, Python will find the module in the current directory "too early" without realizing it is part of a package.
Also remember that when you run the interactive interpreter, the "name" of that interactive session is always __main__
. Thus you cannot do relative imports directly from an interactive session. Relative imports are only for use within module files.
Two solutions:
If you really do want to run moduleX
directly, but you still want it to be considered part of a package, you can do python -m package.subpackage1.moduleX
. The -m
tells Python to load it as a module, not as the top-level script.
Or perhaps you don't actually want to run moduleX
, you just want to run some other script, say myfile.py
, that uses functions inside moduleX
. If that is the case, put myfile.py
somewhere else – not inside the package
directory – and run it. If inside myfile.py
you do things like from package.moduleA import spam
, it will work fine.
Notes
For either of these solutions, the package directory (package
in your example) must be accessible from the Python module search path (sys.path
). If it is not, you will not be able to use anything in the package reliably at all.
Since Python 2.6, the module's "name" for package-resolution purposes is determined not just by its __name__
attributes but also by the __package__
attribute. That's why I'm avoiding using the explicit symbol __name__
to refer to the module's "name". Since Python 2.6 a module's "name" is effectively __package__ + '.' + __name__
, or just __name__
if __package__
is None
.)
The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:
<!-- Usage: -->
<form>
<form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
return {
restrict: 'E',
compile: function(element, attrs) {
var fieldGetter = $parse(attrs.field);
return function (scope, element, attrs) {
var template, field, id;
field = fieldGetter(scope);
template = '..your dom structure here...'
element.replaceWith($compile(template)(scope));
}
}
}
})
I've created a gist with more complete code and a writeup of the approach.
"I need to install it to the folder of my C program." Why?
Include usb.h:
#include <usb.h>
and remember to add -lusb to gcc:
gcc -o example example.c -lusb
This work fine for me.
Another way starting from c# 7.0 would be using local functions. You could name the local function with a meaningful name, and call it directly before declaring it (for clarity). Here is your example rewritten:
public void Method()
{
// Some code here
bool something = true, something2 = true;
DoSomething();
void DoSomething()
{
if (something)
{
//some code
if (something2)
{
// now I should break from ifs and go to te code outside ifs
return;
}
return;
}
}
// The code i want to go if the second if is true
// More code here
}
You can do that by using "Narrowing or Explicit type conversion", double ? long ? int. I hope it will work.
double d = 100.04;
long l = (long)d; // Explicit type casting required
int i = (int)l; // Explicit type casting required
PS: It will give 0 as double has all the decimal values and nothing on the left side. In case of 0.58, it will narrow it down to 0. But for others it will do the magic.
This happens because you have added your worker
directory as a volume to your docker-compose.yml
, as the volume is not mounted during the build.
When docker builds the image, the node_modules
directory is created within the worker
directory, and all the dependencies are installed there. Then on runtime the worker
directory from outside docker is mounted into the docker instance (which does not have the installed node_modules
), hiding the node_modules
you just installed. You can verify this by removing the mounted volume from your docker-compose.yml
.
A workaround is to use a data volume to store all the node_modules
, as data volumes copy in the data from the built docker image before the worker
directory is mounted. This can be done in the docker-compose.yml
like this:
redis:
image: redis
worker:
build: ./worker
command: npm start
ports:
- "9730:9730"
volumes:
- ./worker/:/worker/
- /worker/node_modules
links:
- redis
I'm not entirely certain whether this imposes any issues for the portability of the image, but as it seems you are primarily using docker to provide a runtime environment, this should not be an issue.
If you want to read more about volumes, there is a nice user guide available here: https://docs.docker.com/userguide/dockervolumes/
EDIT: Docker has since changed it's syntax to require a leading ./
for mounting in files relative to the docker-compose.yml file.
Why would you want to use a hash?
You can just use a simple translation of your auto-increment value to an alphanumeric value. You can do that easily by using some base conversion. Say you character space (A-Z, a-z, 0-9, etc.) has 62 characters, convert the id to a base-40 number and use the characters as the digits.
We now have seamless integration to unity with Github to Unity extension... https://unity.github.com/
The new GitHub for Unity extension brings the GitHub workflow and more to Unity, providing support for large files with Git LFS and file locking.
At the time of writing the project is in alpha, but is still usable for personal projects.
java .... than debug.. or Remove the 'import R.java' line from your code. Its done by Eclipse in order to solve the problem. Go to "note_edit.xml" file. Wherever you find "match_parent" as an attribute value, replace it with either "fill_parent" or "wrap_content". Do a clean build. R.java will be generated automatically
Use this in your RelativeLayout
android:gravity="center_vertical"
You have to shrink & backup the log a several times to get the log file to reduce in size, this is because the the log file pages cannot be re-organized as data files pages can be, only truncated. For a more detailed explanation check this out.
WARNING : Detaching the db & deleting the log file is dangerous! don't do this unless you'd like data loss
It works like this:
String item = "http://www.youtube.com/embed/";
String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(chromeClient);
wv.getSettings().setPluginsEnabled(true);
try {
wv.loadData(
"<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
+ (w1 - 20)
+ "\" height=\""
+ h1
+ "\" src=\""
+ item
+ "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
"text/html5", "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
private WebChromeClient chromeClient = new WebChromeClient() {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout) {
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView) {
VideoView video = (VideoView) frame.getFocusedChild();
frame.removeView(video);
video.start();
}
}
}
};
ffmpeg -i abc.mp4 2>&1 | grep Duration | cut -d ' ' -f 4 | sed s/,//
gives output
HH:MM:SS.milisecs
I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.
It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR
warning and problem at starting Firefox using Xfvb.
After adding +extension RANDR
it worked again.
$ vim /etc/init/xvfb.conf
#!upstart
description "Xvfb Server as a daemon"
start on filesystem and started networking
stop on shutdown
respawn
env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid
exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1
Here is a bare bones version:
Let's say that you have a date in Cell A1 in the format you described. For example: 19760210
.
Then this formula will give you the date you want:
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)).
On my system (Excel 2010) it works with strings or floats.
I use below trick to make it responsive and remove borders. this tricks maybe hide recaptcha message/error.
This style is for rtl lang but you can change it easy.
.g-recaptcha {
position: relative;
width: 100%;
background: #f9f9f9;
overflow: hidden;
}
.g-recaptcha > * {
float: right;
right: 0;
margin: -2px -2px -10px;/*remove borders*/
}
.g-recaptcha::after{
display: block;
content: "";
position: absolute;
left:0;
right:150px;
top: 0;
bottom:0;
background-color: #f9f9f9;
clear: both;
}
<div class="g-recaptcha" data-sitekey="Your Api Key"></div>
<script src='https://www.google.com/recaptcha/api.js?hl=fa'></script>
Go to the %HUDSON_HOME%\jobs\<projectname>
remove builds
dir and remove lastStable, lastSuccessful
links, and remove nextBuildNumber
file.
After doing above steps go to below link from UI
Jenkins-> Manage Jenkins -> Reload Configuration from Disk
It will do as you need
On my VS install (VS 2008) #if RELEASE
does not work. However you could just use #if !DEBUG
Example:
#if !DEBUG
SendTediousEmail()
#endif
Just use onChange event of the <select>
object.
Selected value is in e.target.value
then.
By the way, it's a bad practice to use id="..."
. It's better to use ref=">.."
http://facebook.github.io/react/docs/more-about-refs.html
I’ve answered your question in-depth here: http://mathiasbynens.be/notes/css-escapes
The article also explains how to escape any character in CSS (and JavaScript), and I made a handy tool for this as well. From that page:
If you were to give an element an ID value of
~!@$%^&*()_+-=,./';:"?><[]{}|`#
, the selector would look like this:CSS:
<style> #\~\!\@\$\%\^\&\*\(\)\_\+-\=\,\.\/\'\;\:\"\?\>\<\[\]\\\{\}\|\`\# { background: hotpink; } </style>
JavaScript:
<script> // document.getElementById or similar document.getElementById('~!@$%^&*()_+-=,./\';:"?><[]\\{}|`#'); // document.querySelector or similar $('#\\~\\!\\@\\$\\%\\^\\&\\*\\(\\)\\_\\+-\\=\\,\\.\\/\\\'\\;\\:\\"\\?\\>\\<\\[\\]\\\\\\{\\}\\|\\`\\#'); </script>
Assuming a
is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
Use test()
method :
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
The accepted solution have following drawbacks:
If your keys do not require to type password, I suggest following solution. Add the following to your .bash_profile
very end (edit key list to your needs):
exec ssh-agent $BASH -s 10<&0 << EOF
ssh-add ~/.ssh/your_key1.rsa \
~/.ssh/your_key2.rsa &> /dev/null
exec $BASH <&10-
EOF
It have following advantages:
It have possible disadvantages:
ssh-add
command will influence only one session, which is in fact an issue only in very untypical circumstances;Note that several ssh-agent
processes is not a disadvantage, because they don't take more memory or CPU time.
Frames were not deprecated in HTML5, but were deprecated in XHTML 1.1 Strict and 2.0, but remained in XHTML Transitional and returned in HTML5. Also here is an interesting article on using CSS to mimic frames without frames. I just tested it in IE 8, FF 3, Opera 11, Safari 5, Chrome 8. I love frames, but they do have their problems, particularly with search engines, bookmarks and printing and with CSS you can create print or display only content. I'm hoping to upgrade Alex's XHTML/CSS frame without frames solution to HTML5/CSS3.
Unfortunately I can't comment with my newbie reputation, but I have a solution for the issue of the screen going blank, or at least this is what worked for me. Instead of setting the wrapper class inside of the errorPlacement function, set it immediately when you're setting the wrapper type.
$('#myForm').validate({
errorElement: "div",
wrapper: "div class=\"message\"",
errorPlacement: function(error, element) {
offset = element.offset();
error.insertBefore(element);
//error.addClass('message'); // add a class to the wrapper
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth() + 5);
error.css('top', offset.top - 3);
}
});
I'm assuming doing it this way allows the validator to know which div elements to remove, instead of all of them. Worked for me but I'm not entirely sure why, so if someone could elaborate that might help others out a ton.
For completeness, you can also use:
mystring = mystring.strip() # the while loop will leave a trailing space,
# so the trailing whitespace must be dealt with
# before or after the while loop
while ' ' in mystring:
mystring = mystring.replace(' ', ' ')
which will work quickly on strings with relatively few spaces (faster than re
in these situations).
In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).
In your example, using the default values of timeit.Timer.repeat(), I get the following times:
str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub: [3.741931446594549, 3.8389395858970374, 3.973777672860706]
split/join: [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]
EDIT:
Just came across this post which provides a rather long comparison of the speeds of these methods.
you can solve that problem in visual basic .net without concatenating your text, you can use this as a return type of your overloaded Tostring:
System.Text.RegularExpressions.Regex.Unescape(String.format("FirstName:{0} \r\n LastName: {1}", "Nordanne", "Isahac"))
Using JODA:
PeriodFormatter periodFormat = new PeriodFormatterBuilder()
.minimumParsedDigits(2)
.appendHour() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendMinute() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendSecond()
.appendSeparator(".")
.appendMillis3Digit()
.toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();
ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.
OU=Your_OU,OU=other_ou,dc=example,dc=com
You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain
Now i miss a parameter to authenticate, this works the same as the path for the username
CN=username,OU=users,DC=example,DC=com
Even if the hash is not for security, you can use sha instead of md5. In my opinion, the people should forget about md5 for now, it's in the past!
The normal nodejs sha256 is deprecated. So, you have two alternatives for now:
var shajs = require('sha.js') - https://www.npmjs.com/package/sha.js (used by Browserify)
var hash = require('hash.js') - https://github.com/indutny/hash.js
I prefer using shajs
instead of hash
, because I consider sha the best hash function nowadays and you don't need a different hash function for now. So to get some hash in hex you should do something like the following:
sha256.update('hello').digest('hex')
To position block elements to the center (works in IE9 and above), needs a wrapper div
:
.vcontainer {
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
An option that hasn't been mentioned is using flex. By applying flex: 1
to the a
tag, it expands to fit the container.
div {_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
display: flex;_x000D_
border: 1px solid;_x000D_
}_x000D_
_x000D_
a {_x000D_
flex: 1;_x000D_
}
_x000D_
<div>_x000D_
<a href="http://google.co.uk">Link</a>_x000D_
</div>
_x000D_
You may need two or more loops depending on your array:
$arr[$key1][$key2][$key3]=$value1; // ....etc
foreach ($arr as $key1 => $values) {
foreach ($key1 as $key2 => $value) {
unset($arr[$key1][$key2]);
}
}
grep -e apple your_site_root/**/*.* -s -l | xargs sed -i "" "s|apple|orage|"
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}
Bootstrap Tokenfield seems good too: http://sliptree.github.io/bootstrap-tokenfield/
I prefer map object when it comes to big arrays.
// create tow arrays_x000D_
array1 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)}))_x000D_
array2 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)}))_x000D_
_x000D_
// calc diff with some function_x000D_
console.time('diff with some');_x000D_
results = array2.filter(({ value: id1 }) => array1.some(({ value: id2 }) => id2 === id1));_x000D_
console.log('diff results ',results.length)_x000D_
console.timeEnd('diff with some');_x000D_
_x000D_
// calc diff with map object_x000D_
console.time('diff with map');_x000D_
array1Map = {};_x000D_
for(const item1 of array1){_x000D_
array1Map[item1.value] = true;_x000D_
}_x000D_
results = array2.filter(({ value: id2 }) => array1Map[id2]);_x000D_
console.log('map results ',results.length)_x000D_
console.timeEnd('diff with map');
_x000D_
How would you check if a variable is a dictionary in Python?
This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict
.
(Note that you should also not use dict
as a variable name - it's the name of the builtin object.)
If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.
I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.
is
is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.
So I will provide several options that do.
This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict
, defaultdict
, or Counter
from the collections module:
if isinstance(any_object, dict):
But there are even more flexible options.
from collections.abc import Mapping
if isinstance(any_object, Mapping):
This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict
, and still get the correct behavior.
You commonly hear the OOP advice, "program to an interface".
This strategy takes advantage of Python's polymorphism or duck-typing.
So just attempt to access the interface, catching the specific expected errors (AttributeError
in case there is no .items
and TypeError
in case items
is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems()
is gone in Python 3):
try:
items = any_object.items()
except (AttributeError, TypeError):
non_items_behavior(any_object)
else: # no exception raised
for item in items: ...
Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.
Don't use is
to check types for standard control flow. Use isinstance
, consider abstractions like Mapping
or MutableMapping
, and consider avoiding type-checking altogether, using the interface directly.
If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.
If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.
What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:
#ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec(dllexport)
#else
# define LIBRARY_API __declspec(dllimport)
#endif
Then on a function that you want to be exported you use LIBRARY_API
:
LIBRARY_API int GetCoolInteger();
In your library build project create a define LIBRARY_EXPORTS
this will cause your functions to be exported for your DLL build.
Since LIBRARY_EXPORTS
will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.
If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:
#ifdef _WIN32
# ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec(dllexport)
# else
# define LIBRARY_API __declspec(dllimport)
# endif
#elif
# define LIBRARY_API
#endif
When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.
If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C"
inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:
The Code:
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT int getEngineVersion() {
return 1;
}
EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
K.getGraphicsServer().addGraphicsDriver(
auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
);
}
And here's what the exports look like with Dumpbin /exports:
Dump of file opengl_plugin.dll
File Type: DLL
Section contains the following exports for opengl_plugin.dll
00000000 characteristics
49866068 time date stamp Sun Feb 01 19:54:32 2009
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
2 1 00011028 registerPlugin = @ILT+35(_registerPlugin)
So this code works fine:
m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");
m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
::GetProcAddress(m_hDLL, "registerPlugin")
);
Adding a quick cheat sheet that may help after the long break with Angular:
Example:
declarations: [AppComponent]
What can we inject here? Components, pipes, directives
Example:
imports: [BrowserModule, AppRoutingModule]
What can we inject here? other modules
Example:
providers: [UserService]
What can we inject here? services
Example:
bootstrap: [AppComponent]
What can we inject here? the main component that will be generated by this module (top parent node for a component tree)
Example:
entryComponents: [PopupComponent]
What can we inject here? dynamically generated components (for instance by using ViewContainerRef.createComponent())
Example:
export: [TextDirective, PopupComponent, BrowserModule]
What can we inject here? components, directives, modules or pipes that we would like to have access to them in another module (after importing this module)
After some diving through some documentation and source code, I think I got it working. Perhaps this will be useful for someone else?
I added the following to my module configuration:
angular.module(...)
.config( ['$routeProvider', function($routeProvider) {...}] )
.run( function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
if ( $rootScope.loggedUser == null ) {
// no logged user, we should be going to #login
if ( next.templateUrl != "partials/login.html" ) {
// not going to #login, we should redirect now
$location.path( "/login" );
}
}
});
})
The one thing that seems odd is that I had to test the partial name (login.html
) because the "next" Route object did not have a url or something else. Maybe there's a better way?
Look for "Windows x86", it's the 32 bit version.
Just implemented my OWIN Service with Bearer (called access_token in the following) and Refresh Tokens. My insight into this is that you can use different flows. So it depends on the flow you want to use how you set your access_token and refresh_token expiration times.
I will describe two flows A and B in the follwing (I suggest what you want to have is flow B):
A) expiration time of access_token and refresh_token are the same as it is per default 1200 seconds or 20 minutes. This flow needs your client first to send client_id and client_secret with login data to get an access_token, refresh_token and expiration_time. With the refresh_token it is now possible to get a new access_token for 20 minutes (or whatever you set the AccessTokenExpireTimeSpan in the OAuthAuthorizationServerOptions to). For the reason that the expiration time of access_token and refresh_token are the same, your client is responsible to get a new access_token before the expiration time! E.g. your client could send a refresh POST call to your token endpoint with the body (remark: you should use https in production)
grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxx
to get a new token after e.g. 19 minutes to prevent the tokens from expiration.
B) in this flow you want to have a short term expiration for your access_token and a long term expiration for your refresh_token. Lets assume for test purpose you set the access_token to expire in 10 seconds (AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10)
) and the refresh_token to 5 Minutes. Now it comes to the interesting part setting the expiration time of refresh_token: You do this in your createAsync function in SimpleRefreshTokenProvider class like this:
var guid = Guid.NewGuid().ToString();
//copy properties and set the desired lifetime of refresh token
var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
{
IssuedUtc = context.Ticket.Properties.IssuedUtc,
ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
//ExpiresUtc = DateTime.UtcNow.AddMonths(3)
};
/*CREATE A NEW TICKET WITH EXPIRATION TIME OF 5 MINUTES
*INCLUDING THE VALUES OF THE CONTEXT TICKET: SO ALL WE
*DO HERE IS TO ADD THE PROPERTIES IssuedUtc and
*ExpiredUtc to the TICKET*/
var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);
//saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
// consider storing only the hash of the handle
RefreshTokens.TryAdd(guid, refreshTokenTicket);
context.SetToken(guid);
Now your client is able to send a POST call with a refresh_token to your token endpoint when the access_token
is expired. The body part of the call may look like this: grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xx
One important thing is that you may want to use this code not only in your CreateAsync function but also in your Create function. So you should consider to use your own function (e.g. called CreateTokenInternal) for the above code. Here you can find implementations of different flows including refresh_token flow(but without setting the expiration time of the refresh_token)
Here is one sample implementation of IAuthenticationTokenProvider on github (with setting the expiration time of the refresh_token)
I am sorry that I can't help out with further materials than the OAuth Specs and the Microsoft API Documentation. I would post the links here but my reputation doesn't let me post more than 2 links....
I hope this may help some others to spare time when trying to implement OAuth2.0 with refresh_token expiration time different to access_token expiration time. I couldn't find an example implementation on the web (except the one of thinktecture linked above) and it took me some hours of investigation until it worked for me.
New info: In my case I have two different possibilities to receive tokens. One is to receive a valid access_token. There I have to send a POST call with a String body in format application/x-www-form-urlencoded with the following data
client_id=YOURCLIENTID&grant_type=password&username=YOURUSERNAME&password=YOURPASSWORD
Second is if access_token is not valid anymore we can try the refresh_token by sending a POST call with a String body in format application/x-www-form-urlencoded
with the following data grant_type=refresh_token&client_id=YOURCLIENTID&refresh_token=YOURREFRESHTOKENGUID
just try (onclick)="this.value = null"
in your html page add onclick method to remove previous value so user can select same file again.
As @Seth Holladay @MinusFour commented, you are parsing an undefined
variable.
Try adding an if
condition before doing the parse.
if (typeof test1 !== 'undefined') {
test2 = JSON.parse(test1);
}
Note: This is just a check for undefined
case. Any other parsing issues still need to be handled.
If you are using a BLL/DAL setup try the iif when reading into the object in the DAL
While reader.Read()
colDropdownListNames.Add(New DDLItem( _
CType(reader("rid"), Integer), _
CType(reader("Item_Status"), String), _
CType(reader("Text_Show"), String), _
CType( IIf(IsDBNull(reader("Text_Use")), "", reader("Text_Use")) , String), _
CType(reader("Text_SystemOnly"), String), _
CType(reader("Parent_rid"), Integer)))
End While
Another one solution: html:
<div class="background">
<div class="container">Hello world!</div>
</div>
css:
.background {
position: relative;
width: 50px;
height: 50px;
border-right: 150px solid lightgreen;
border-bottom: 150px solid lightgreen;
border-radius: 10px;
}
.background::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
border: 25px solid lightgreen;
border-top-color: transparent;
border-left-color: transparent;
}
.container {
position: absolute;
padding-left: 25px;
padding-top: 25px;
font-size: 38px;
font-weight: bolder;
}
You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho
"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.
If you are here because your emulator gives you that Exception, Go to Tools > AVD Manager in your android emulator and Cold boot your Emulator.
As mentioned above BOOL
could be an unsigned char
type depending on your architecture, while bool
is of type int
. A simple experiment will show the difference why BOOL and bool can behave differently:
bool ansicBool = 64;
if(ansicBool != true) printf("This will not print\n");
printf("Any given vlaue other than 0 to ansicBool is evaluated to %i\n", ansicBool);
BOOL objcBOOL = 64;
if(objcBOOL != YES) printf("This might print depnding on your architecture\n");
printf("BOOL will keep whatever value you assign it: %i\n", objcBOOL);
if(!objcBOOL) printf("This will not print\n");
printf("! operator will zero objcBOOL %i\n", !objcBOOL);
if(!!objcBOOL) printf("!! will evaluate objcBOOL value to %i\n", !!objcBOOL);
To your surprise if(objcBOOL != YES)
will evaluates to 1 by the compiler, since YES
is actually the character code 1, and in the eyes of compiler, character code 64 is of course not equal to character code 1 thus the if statement will evaluate to YES/true/1
and the following line will run.
However since a none zero bool
type always evaluates to the integer value of 1, the above issue will not effect your code. Below are some good tips if you want to use the Objective-C BOOL
type vs the ANSI C bool
type:
YES
or NO
value and nothing else.BOOL
types by using double not !!
operator to avoid unexpected results.YES
use if(!myBool) instead of if(myBool != YES)
it is much cleaner to use the not !
operator and gives the expected result.Loading the values in an array would be much faster:
Dim data(), dict As Object, r As Long
Set dict = CreateObject("Scripting.Dictionary")
data = ActiveSheet.UsedRange.Columns(1).Value
For r = 1 To UBound(data)
dict(data(r, some_column_number)) = Empty
Next
data = WorksheetFunction.Transpose(dict.keys())
You should also consider early binding for the Scripting.Dictionary:
Dim dict As New Scripting.Dictionary ' requires `Microsoft Scripting Runtime` '
Note that using a dictionary is way faster than Range.AdvancedFilter on large data sets.
As a bonus, here's a procedure similare to Range.RemoveDuplicates to remove duplicates from a 2D array:
Public Sub RemoveDuplicates(data, ParamArray columns())
Dim ret(), indexes(), ids(), r As Long, c As Long
Dim dict As New Scripting.Dictionary ' requires `Microsoft Scripting Runtime` '
If VarType(data) And vbArray Then Else Err.Raise 5, , "Argument data is not an array"
ReDim ids(LBound(columns) To UBound(columns))
For r = LBound(data) To UBound(data) ' each row '
For c = LBound(columns) To UBound(columns) ' each column '
ids(c) = data(r, columns(c)) ' build id for the row
Next
dict(Join$(ids, ChrW(-1))) = r ' associate the row index to the id '
Next
indexes = dict.Items()
ReDim ret(LBound(data) To LBound(data) + dict.Count - 1, LBound(data, 2) To UBound(data, 2))
For c = LBound(ret, 2) To UBound(ret, 2) ' each column '
For r = LBound(ret) To UBound(ret) ' each row / unique id '
ret(r, c) = data(indexes(r - 1), c) ' copy the value at index '
Next
Next
data = ret
End Sub
Swift 4.2 and Xcode 10. Somewhere in ViewController:
private lazy var debugInfoLabel: UILabel = {
let label = UILabel()
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
yourView.addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: suggestionView.centerXAnchor),
label.centerYAnchor.constraint(equalTo: suggestionView.centerYAnchor, constant: -100),
label.widthAnchor.constraint(equalToConstant: 120),
label.heightAnchor.constraint(equalToConstant: 50)])
return label
}()
...
Using:
debugInfoLabel.text = debugInfo
Another way to do this, although equally unsatisfying is:
s = pd.Series([1,3,0,7,5],index=[0,1,2,3,4])
list(s).index(7)
returns: 3
On time tests using a current dataset I'm working with (consider it random):
[64]: %timeit pd.Index(article_reference_df.asset_id).get_loc('100000003003614')
10000 loops, best of 3: 60.1 µs per loop
In [66]: %timeit article_reference_df.asset_id[article_reference_df.asset_id == '100000003003614'].index[0]
1000 loops, best of 3: 255 µs per loop
In [65]: %timeit list(article_reference_df.asset_id).index('100000003003614')
100000 loops, best of 3: 14.5 µs per loop
It is also worth mentioning that localStorage
cannot be used when users browse in "private" mode in some versions of mobile Safari.
Quoted from MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):
Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.
Actually johann, the #
indicates that it's a preprocessor directive, which basically means it tells the IDE what to do.
In the case of using #region
and #endregion
in your code, it makes NO difference in the final code whether it's there or not. Can you really call it a language element if using it changes nothing?
Apart from that, java doesn't have preprocessor directives, which means the option of code folding is defined on a per-ide basis, in netbeans for example with a //< code-fold> statement
use the inspect module.
import inspect help(inspect.stack) Help on function stack in module inspect:
stack(context=1) Return a list of records for the stack above the caller's frame.
I find it very helpful indeed.
The correct character to use in this case is a full colon (:
), not a semicolon (;
).
I had your issue, i fixed it . this error comes when your target api level is not completely downloaded . you have two ways: go to your SDK menu and download all of the android 9 components or the better way is go to your build.gradle(Module app) and change it like this:But remember, before applying these changes, make sure you have fully downloaded api lvl 8
Random r = new Random();
List<string> list = new List(originalArray);
List<string> randomStrings = new List();
while(list.Count > 0)
{
int i = r.Random(list.Count);
randomStrings.Add(list[i]);
list.RemoveAt(i);
}
If you are trying to join Series of equal length but their indexes don't match (which is a common scenario), then concatenating them will generate NAs wherever they don't match.
x = pd.Series({'a':1,'b':2,})
y = pd.Series({'d':4,'e':5})
pd.concat([x,y],axis=1)
#Output (I've added column names for clarity)
Index x y
a 1.0 NaN
b 2.0 NaN
d NaN 4.0
e NaN 5.0
Assuming that you don't care if the indexes match, the solution is to reindex both Series before concatenating them. If drop=False
, which is the default, then Pandas will save the old index in a column of the new dataframe (the indexes are dropped here for simplicity).
pd.concat([x.reset_index(drop=True),y.reset_index(drop=True)],axis=1)
#Output (column names added):
Index x y
0 1 4
1 2 5
disabled Hyper-V (Control Panel\Programs\Programs and Features\ Hyper-V)
modify BCD (bcdedit /set hypervisorlaunchtype off)
If core isolation is enabled, turn it off (Windows Defender Security Center> Device Security> Core Quarantine)
If you cannot modify it, you can change the value of HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ DeviceGuard \ Scenarios \ HypervisorEnforcedCode Integrity \ Enabled in the registry to 0
To enable msbuild
in Command Prompt, you simply have to add the directory of the msbuild.exe
install on your machine to the PATH
environment variable.
You can access the environment variables by:
PATH
For reference, my path was C:\Windows\Microsoft.NET\Framework\v4.0.30319
As of MSBuild 12 (2013)/VS 2013/.NET 4.5.1+ and onward MSBuild is now installed as a part of Visual Studio.
For VS2015 the path was %ProgramFiles(x86)%\MSBuild\14.0\Bin
For VS2017 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin
For VS2019 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin
Sounds like more work than its worth.
1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.
2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.
If anyone is interested in a "quick reproducible" version of the accepted answer, see below. Credits to a friend who is not on SO. This answer can also be integrated in the accepted answer with an edit,... (It has to run on a (local) server).
<html>
<head>
<title>SO</title>
<meta charset="utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<style type="text/css">
html,
body,
#filecontainer {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<iframe src="http://localhost/tmp/fileWithLink.html" id="filecontainer"></iframe>
<script type="text/javascript">
$('#filecontainer').load(function(){
var iframe = $('#filecontainer').contents();
iframe.find("a").click(function(){
var test = $(this);
alert(test.html());
});
});
</script>
</body>
</html>
fileWithLink.html
<html>
<body>
<a href="https://stackoverflow.com/">SOreadytohelp</a>
</body>
</html>
Here is what worked for me to solve part 1 of this question:
location / {
rewrite ^([^.]*[^/])$ $1/ permanent;
try_files $uri $uri/ /index.php =404;
include fastcgi_params;
fastcgi_pass php5-fpm-sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors on;
}
rewrite ^([^.]*[^/])$ $1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.
try_files $uri $uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.
fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.
<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) {
$content.='<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
require_once('./dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF;
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream("hello.pdf");
}
?>
<html>
<body>
<form action="#" method="post">
<button name="pdf" type="submit">export</button>
<table width="100%" border="1">
<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>
<?php for ($index = 0; $index < 10; $index++) { ?>
<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
<?php } ?>
</table>
</form>
</body>
</html>
I have come across exactly the same problem when trying to write a client for the National Rail SOAP service with Perl.
The problem was caused because the Perl module that I'm using 'SOAP::Lite' inserts a '#' in the SOAPAction header ...
SOAPAction: "http://thalesgroup.com/RTTI/2008-02-20/ldb/#GetDepartureBoard"
This is not interpreted correctly by .NET servers. I found this out from Example 3-19 in O'Reilly's Programming Web Services with SOAP . The solution was given below in section 3-20, namely you need to explicitly specify the format of the header with the 'on_action' method.
print SOAP::Lite
-> uri('urn:Example1')
-> on_action(sub{sprintf '%s/%s', @_ })
-> proxy('http://localhost:8080/helloworld/example1.asmx')
-> sayHello($name)
-> result . "\n\n";
My guess is that soapclient.com is using SOAP::Lite behind the scenes and so are hitting the same problem when talking to National Rail.
The solution is to write your own client so that you have control over the format of the SOAPAction header ... but you've probably done that already.
What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:
npm install --save pug
- to add it to the project and package.json fileapp.set('view engine', 'pug');
- register it as a view engine in express./views
folder and add a simple .pug
file like so:html
head
title= title
body
h1= message
note that the spacing is very important!
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html
For more info on pug you can also check: https://github.com/pugjs/pug
I am using this one for Angular 10 project:
reloadCurrentRoute() {
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
PS: Tested and works also on "Angular 7, 8, 9"
NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.
Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.
Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.
Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.
Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.
PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.
Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.
I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.
Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC
In this problem , i've used some arithmetic solution . Thanks :)
int main(void)
{
int n, x = 10, i = 1;
scanf("%d", &n);
while(n / x > 0)
{
x*=10;
i++;
}
printf("the number contains %d digits\n", i);
return 0;
}
Disposing of a Working Copy
Subversion doesn't track either the state or the existence of working copies on the server, so there's no server overhead to keeping working copies around. Likewise, there's no need to let the server know that you're going to delete a working copy.
If you're likely to use a working copy again, there's nothing wrong with just leaving it on disk until you're ready to use it again, at which point all it takes is an svn update to bring it up to date and ready for use.
However, if you're definitely not going to use a working copy again, you can safely delete the entire thing using whatever directory removal capabilities your operating system offers. We recommend that before you do so you run svn status and review any files listed in its output that are prefixed with a ? to make certain that they're not of importance.
from: http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html
Use '›'
›
-> single right angle quote. For single left angle quote, use ‹
Open SQL Developer. Go to Tools -> Preferences -> Databases -> Advanced Then explicitly set the Tnsnames Directory
My TNSNAMES was set up correctly and I could connect to Toad, SQL*Plus etc. but I needed to do this to get SQL Developer to work. Perhaps it was a Win 7 issue as it was a pain to install too.
You can use native win command:
WMIC /node:ComputerName process call create “cmd.exe /c start.exe”
The WMIC is part of wbem win folder: C:\Windows\System32\wbem
pip defaults to installing Python packages to a system directory (such as /usr/local/lib/python3.4
). This requires root access.
--user
makes pip install packages in your home directory instead, which doesn't require any special privileges.
In Rails 2, I would have written:
validates_uniqueness_of :zipcode, :scope => :recorded_at
In Rails 3:
validates :zipcode, :uniqueness => {:scope => :recorded_at}
For multiple attributes:
validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}
You can use one of following:
android:gravity="fill_horizontal|clip_vertical"
Or
android:gravity="fill_vertical|clip_horizontal"
One way you can achieve this is setting display: inline-block;
on the div
. It is by default a block
element, which will always fill the width it can fill (unless specifying width
of course).
inline-block
's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline
elements, but there are hacks to solve this problem.
There are other options you have, you can either float
it, or set position: absolute
on it, but these also have other effects on layout, you need to decide which one fits your situation better.
Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:
subtractDates: function(date1, date2) {
return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
return moment().subtract(dateSince).milliseconds();
},
Editing hostconfig.json seems to not working now. It only ends with that port being exposed but not published to host. Commiting and recreating containers is not the best approach to me. No one mentioned docker network
?
The best solution would be using reversed proxy within the same network
Create a new network if your previous container not in any named ones.
docker network create my_network
Join your existing container to the created network
docker network connect my_network my_existing_container
Start a reversed proxy service(e.g. nginx) publishing the ports you need, joining the same network
docker run -d --name nginx --network my_network -p 9000:9000 nginx
Optionally remove the default.conf in nginx
docker exec nginx rm /etc/nginx/conf.d/default.conf
Create a new nginx config
server
{
listen 9000;
location / {
proxy_pass http://my_existing_container:9000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Copy the config to nginx container.
docker cp ./my_conf.conf nginx:/etc/nginx/conf.d/my_conf.conf
Restart nginx
docker restart nginx
Advantages: To publish new ports, you can safely stop/update/recreate nginx container as you wish without touching the business container. If you need zero down time for nginx, it is possible to add more reversed proxy services joining the same network. Besides, a container can join more than one network.
Edit:
To reverse proxy non-http services, the config file is a bit different. Here is a simple example:
upstream my_service {
server my_existing_container:9000;
}
server {
listen 9000;
proxy_pass my_service;
}
<form class="form-horizontal" method="post">
<div class="control-group">
<input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
</div>
<div class="control-group">
<input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
</div>
<div class="control-group">
<input type="text" class="span1" name="unit" id="inputPassword" required>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Semester</label>
<div class="controls">
<select name="semester">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deskripsi</label>
<div class="controls">
<textarea name="description" id="ckeditor_full"></textarea>
<script>CKEDITOR.replace('ckeditor_full');</script>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
</div>
</div>
</form>
<?php
if (isset($_POST['save'])){
$subject_code = $_POST['subject_code'];
$title = $_POST['title'];
$unit = $_POST['unit'];
$description = $_POST['description'];
$semester = $_POST['semester'];
$query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
$count = mysql_num_rows($query);
if ($count > 0){ ?>
<script>
alert('Data Sudah Ada');
</script>
<?php
}else{
mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());
mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());
?>
<script>
window.location = "subjects.php";
</script>
<?php
}
}
?>
if the problem still exists try to force changing the pass
Stop MySQL Server (on Linux):
/etc/init.d/mysql stop
Stop MySQL Server (on Mac OS X):
mysql.server stop
Start mysqld_safe daemon with --skip-grant-tables
mysqld_safe --skip-grant-tables &
mysql -u root
Setup new MySQL root user password
use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
flush privileges;
quit;
Stop MySQL Server (on Linux):
/etc/init.d/mysql stop
Stop MySQL Server (on Mac OS X):
mysql.server stop
Start MySQL server service and test to login by root:
mysql -u root -p
You missed the each=
argument to rep()
:
R> n <- 3
R> rep(1:5, each=n)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R>
so your example can be done with a simple
R> rep(1:8, each=20)
All the answers were great however what did it for me was a combination of uninstalling Pillow
pip uninstall Pillow
Then installing whatever packages you need e.g.
sudo apt-get -y install python-imaging
sudo apt-get -y install zlib1g-dev
sudo apt-get -y install libjpeg-dev
And then using easy_install to reinstall Pillow
easy_install Pillow
Hope this helps others
No-one has mentioned cpio
which is easy to type, creates hard links and handles spaces in filenames:
git diff --name-only $from..$to | cpio -pld outdir
put the id you want to check in jquery is method.
var idcheck = $("selector").is("#id");
if(idcheck){ // if the selector contains particular id
// your code if particular Id is there
}
else{
// your code if particular Id is NOT there
}
no, you need to do something like:
$('input.sitebg').val('000000');
but you should really be using unique IDs if you can.
You can also get more specific, such as:
$('input[type=text].sitebg').val('000000');
EDIT:
do this to find your input based on the name attribute:
$('input[name=sitebg]').val('000000');
There isn't anything built-in, but you can easily create your own extension method to do it:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (T item in source)
{
action(item);
}
}
The known problem with the templates is code bloating, which is consequence of generating the class definition in each and every module which invokes the class template specialization. To prevent this, starting with C++0x, one could use the keyword extern in front of the class template specialization
#include <MyClass>
extern template class CMyClass<int>;
The explicit instantion of the template class should happen only in a single translation unit, preferable the one with template definition (MyClass.cpp)
template class CMyClass<int>;
template class CMyClass<float>;
Try this :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<style type="text/css">
#btn_s{
width:100px;
}
#btn_i {
width:125px;
}
#formbox {
width:400px;
margin:auto 0;
text-align: center;
}
</style>
</head>
<body>
<form method="post" action="">
<div id="formbox">
<input value="Search" title="Search" type="submit" id="btn_s">
<input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit" id="btn_i">
</div>
</form>
</body>
This has 2 examples, you can use the one that fits best in your situation.
text-align:center
on the parent container, or create a container for this.auto
left and right margins to center it in the parent container.note that auto
is used with single blocks to center them in the parent space by distrubuting the empty space to the left and right.
For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 4.0 / Alamofire >= 5.0
response.response?.statusCode
More verbose example:
Alamofire.request(urlString)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
var statusCode = response.response?.statusCode
if let error = response.result.error as? AFError {
statusCode = error._code // statusCode private
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
case .parameterEncodingFailed(let reason):
print("Parameter encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .multipartEncodingFailed(let reason):
print("Multipart encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .responseValidationFailed(let reason):
print("Response validation failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
switch reason {
case .dataFileNil, .dataFileReadFailed:
print("Downloaded file could not be read")
case .missingContentType(let acceptableContentTypes):
print("Content Type Missing: \(acceptableContentTypes)")
case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
case .unacceptableStatusCode(let code):
print("Response status code was unacceptable: \(code)")
statusCode = code
}
case .responseSerializationFailed(let reason):
print("Response serialization failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
// statusCode = 3840 ???? maybe..
default:break
}
print("Underlying error: \(error.underlyingError)")
} else if let error = response.result.error as? URLError {
print("URLError occurred: \(error)")
} else {
print("Unknown error: \(response.result.error)")
}
print(statusCode) // the status code
}
(Alamofire 4 contains a completely new error system, look here for details)
For Swift 2.x users with Alamofire >= 3.0
Alamofire.request(.GET, urlString)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
if let alamoError = response.result.error {
let alamoCode = alamoError.code
let statusCode = (response.response?.statusCode)!
} else { //no errors
let statusCode = (response.response?.statusCode)! //example : 200
}
}
Create CustomerDTO Object every time inside while loop
Check the below code
while (rs.next()) {
Customer customer = new Customer();
customer.setId(rs.getInt("id"));
customer.setName(rs.getString("name"));
customer.setAddress(rs.getString("address"));
customer.setPhone(rs.getString("phone"));
customer.setEmail(rs.getString("email"));
customer.setBountPoints(rs.getInt("bonuspoint"));
customer.setTotalsale(rs.getInt("totalsale"));
customers.add(customer);
}
paste your .html file in assets folder of your project folder. and create an xml file in layout folder with the fol code: my.xml:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
add fol code in activity
setContentView(R.layout.my);
WebView mWebView = null;
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("file:///android_asset/new.html"); //new.html is html file name.
With C++11 compiler, for non-negative integers I would use something like this (note the ::
instead of std::
):
bool is_number(const std::string &s) {
return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
}
The height of the bottom Navigation bar is 48dp (in both portrait and landscape mode) and is 42dp when the bar is placed vertically.
Possibly multiple jquery.js file are added in , and the conflict appeared.
Since I don't see the jQuery
tag in the OP, here is a javascript only option :
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelector('input[name=myCheckbox]');
_selector.addEventListener('change', function (event) {
if (_selector.checked) {
// do something if checked
} else {
// do something else otherwise
}
});
});
See JSFIDDLE
I suggest the use of htop, as a better alternative to top.
It subjects to architecture of the server on which PHP runs. For 64-bit,
print PHP_INT_MIN . ", ” . PHP_INT_MAX;
yields -9223372036854775808, 9223372036854775807
For those working with ant
, I use this to indicate a pause of 5 seconds:
<tr>
<td>pause</td>
<td>5000</td>
<td></td>
</tr>
That is, target: 5000
and value
empty. As the reference indicates:
pause(waitTime)
Arguments:
- waitTime - the amount of time to sleep (in milliseconds)
Wait for the specified amount of time (in milliseconds)
My problem was similar but with the inconvenience that sometimes the string contains letters (sometimes empty).
string sNumbers = "1,2,hh,3,4,x,5";
Trying to follow Pcode Xonos Extension Method:
public static List<int> SplitToIntList(this string list, char separator = ',')
{
int result = 0;
return (from s in list.Split(',')
let isint = int.TryParse(s, out result)
let val = result
where isint
select val).ToList();
}
when referencing images in CSS or in an IMG tag, use image-name.jpg
while the image is really located under ./assets/images/image-name.jpg
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
You want to make sure that appropriate files and directories are chmod-ed/permissions for those are appropriate. For all directories you want
find /opt/lampp/htdocs -type d -exec chmod 711 {} \;
And for all the images, JavaScript, CSS, HTML...well, you shouldn't execute them. So use
chmod 644 img/* js/* html/*
But for all the logic code (for instance PHP code), you should set permissions such that the user can't see that code:
chmod 600 file
If you set "Use regular expressions" flag then \n would be translated. But keep in mind that you would have to modify you search term to be regexp friendly. In your case it should be escaped like this "\~\~\?" (no quotes).
Two steps works fine:
create table bu_x as (select a,b,c,d from x ) WITH no data;
insert into bu_x (a,b,c,d) select select a,b,c,d from x ;
The example you are referring to is called Upcasting in java.
It creates a subclass object with a super class variable pointing to it.
The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.
For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine
class Machine{
public void start(){
System.out.println("Machine Started");
}
}
class Camera extends Machine{
public void start(){
System.out.println("Camera Started");
}
public void snap(){
System.out.println("Photo taken");
}
}
Machine machine1 = new Camera();
machine1.start();
If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be "Camera Started"
The variable is still a reference of Machine class. If you attempt machine1.snap();
the code will not compile
The takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example machine1.snap()
wont compile). The superclass reference has access to only the functions known to the superclass (In our example machine1.start()
). You can not ask a machine reference to take a snap. :)
To get rid of ImportError: No module named py4j.java_gateway
, you need to add following lines:
import os
import sys
os.environ['SPARK_HOME'] = "D:\python\spark-1.4.1-bin-hadoop2.4"
sys.path.append("D:\python\spark-1.4.1-bin-hadoop2.4\python")
sys.path.append("D:\python\spark-1.4.1-bin-hadoop2.4\python\lib\py4j-0.8.2.1-src.zip")
try:
from pyspark import SparkContext
from pyspark import SparkConf
print ("success")
except ImportError as e:
print ("error importing spark modules", e)
sys.exit(1)
dictionary["C1"]=map(lambda x:x+10,dictionary["C1"])
Should do it...
Yet, it is possible to fake it using a dedicated table, named for your fake-sp, with an AFTER INSERT trigger. The dedicated table rows contain the parameters for your fake sp, and if it needs to return results you can have a second (poss. temp) table (with name related to the fake-sp) to contain those results. It would require two queries: first to INSERT data into the fake-sp-trigger-table, and the second to SELECT from the fake-sp-results-table, which could be empty, or have a message-field if something went wrong.
It's also important to note that MongoDB has the concept of "authentication database", which can be different than the database you are connecting to. For example, if you use the official Docker image for Mongo and specify the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD, a user will be created on 'admin' database, which is probably not the database you want to use. In this case, you should specify parameters accordingly on your application.properties file using:
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=<username specified on MONGO_INITDB_ROOT_USERNAME>
spring.data.mongodb.password=<password specified on MONGO_INITDB_ROOT_PASSWORD>
spring.data.mongodb.database=<the db you want to use>
I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.
Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.
It'd be better to use List<T>.RemoveAll to accomplish this.
authorsList.RemoveAll((x) => x.firstname == "Bob");
grep /Pattern/ | tail -n 2 | head -n 1
Tail first 2 and then head last one to get exactly first line after match.
This solution does not require manual tweaking of axes locations or colorbar size, works with multi-row and single-row layouts, and works with tight_layout()
. It is adapted from a gallery example, using ImageGrid
from matplotlib's AxesGrid Toolbox.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
# Set up figure and image grid
fig = plt.figure(figsize=(9.75, 3))
grid = ImageGrid(fig, 111, # as in plt.subplot(111)
nrows_ncols=(1,3),
axes_pad=0.15,
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="7%",
cbar_pad=0.15,
)
# Add data to image grid
for ax in grid:
im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
# Colorbar
ax.cax.colorbar(im)
ax.cax.toggle_label(True)
#plt.tight_layout() # Works, but may still require rect paramater to keep colorbar labels visible
plt.show()
To make sure you get the right version with Environment.OSVersion
you should add an app.manifest
using Visual Studio and uncomment following supportedOS
tags:
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on
and is designed to work with. Uncomment the appropriate elements
and Windows will automatically select the most compatible environment. -->
<!-- Windows Vista -->
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
<!-- Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
Then in your code you can use Environment.OSVersion
like this:
var version = System.Environment.OSVersion;
Console.WriteLine(version);
Example
For instance in my machine (Windows 10.0 Build 18362.476
) result would be like this which is incorrect:
Microsoft Windows NT 6.2.9200.0
By adding app.manifest
and uncomment those tags I will get the right version number:
Microsoft Windows NT 10.0.18362.0
If you don't like adding app.manifest
to your project, you can use OSDescription
which is available since .NET Framework 4.7.1 and .NET Core 1.0.
string description = RuntimeInformation.OSDescription;
Note: Don't forget to add following using statement at top of your file.
using System.Runtime.InteropServices;
You can read more about it and supported platforms here.
Another way to paste is via <C-r>
in insert mode and dropping the contents of the register (here the global register). See: :h i_ctrl-r
and h i_CTRL-R_CTRL-O
.
From the vim help documentation:
Insert the contents of a register literally and don't auto-indent. Does the same as pasting with the mouse. Does not replace characters! The '.' register (last inserted text) is still inserted as typed.{not in Vi}
So to paste contents into vim without auto indent, use <C-r><C-o>*
in most unix systems.
You can add a mapping in the your vimrc inoremap <C-r> <C-r><C-o>
so you can paste the contents of the *
register normally without the auto indent by using <C-r>*
.
Note: this only works if vim is compiled with clipboard
.
git show-ref --head --hash head
If you're going for speed though, the approach mentioned by Deestan
cat .git/refs/heads/<branch-name>
is significantly faster than any other method listed here so far.
Most likely you have several adb version on your computer. You start adb server using one version and then trying to connect to this server using another version. For example - Genymotion has it's own adb and if you start Genymotion emulator and then try to use adb from Android SDK most likely you will have such error (the latest Genymotion which is 2.7.2 has adb version 1.0.32 while the latest Android SDK has adb version 1.0.36).
There are a lot of comments arguing the pros and cons of MVVM here. For me, I agree with Nir; it's a matter of using the pattern appropriately and MVVM doesn't always fit. People seems to have become willing to sacrifice all of the most important principles of software design JUST to get it to fit MVVM.
That said,..i think your case could be a good fit with a bit of refactoring.
In most cases I've come across, WPF enables you to get by WITHOUT multiple Window
s. Maybe you could try using Frame
s and Page
s instead of Windows with DialogResult
s.
In your case my suggestion would be have LoginFormViewModel
handle the LoginCommand
and if the login is invalid, set a property on LoginFormViewModel
to an appropriate value (false
or some enum value like UserAuthenticationStates.FailedAuthentication
). You'd do the same for a successful login (true
or some other enum value). You'd then use a DataTrigger
which responds to the various user authentication states and could use a simple Setter
to change the Source
property of the Frame
.
Having your login Window return a DialogResult
i think is where you're getting confused; that DialogResult
is really a property of your ViewModel. In my, admittedly limited experience with WPF, when something doesn't feel right it usually because I'm thinking in terms of how i would've done the same thing in WinForms.
Hope that helps.
DO it like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
Do not forget the %
at the end
The easiest solution is found here install-windows-service-without-installutil-exe by @Hoàng Long
@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"
echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause
Here's a quick solution for most of the cases:
CSS:
.iframe-loading {
background:url(/img/loading.gif) center center no-repeat;
}
You can use an animated loading GIF if you want to,
HTML:
<div class="iframe-loading">
<iframe src="http://your_iframe_url_goes_here" onload="$('.iframe-loading').css('background-image', 'none');"></iframe>
</div>
Using the onload event you can remove the loading image after the source page is loaded inside your iframe.
If you are not using jQuery, just put an id into the div and replace this part of code:
$('.iframe-loading').css('background-image', 'none');
by something like this:
document.getElementById("myDivName").style.backgroundImage = "none";
All the best!
There is a '+' missing after the 'T'
isoDate: function(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
+ d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
should do it.
For the leading zeros you could use this from here:
function PadDigits(n, totalDigits)
{
n = n.toString();
var pd = '';
if (totalDigits > n.length)
{
for (i=0; i < (totalDigits-n.length); i++)
{
pd += '0';
}
}
return pd + n.toString();
}
Using it like this:
PadDigits(d.getUTCHours(),2)
The question does not contain a nested loop, just a single loop. But THIS nested version works, too:
# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b
I add credentials for HttpWebRequest
.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
No need to reinvent the wheel! Use Currency Mask, unlike TextMaskModule, this one works with number input type and it's super easy to configure. I found when I made my own directive, I had to keep converting between number and string to do calculations. Save yourself the time. Here's the link:
Step-by-step:
use-gulp
which
uses(require
s) node_modules
like gulp
and gulp-util
.gulp-util
lib and test it locally with your use-gulp
project... gulp-util
project on github\bitbucket etc.cd use-gulp/node_modules
gulp-util
as gulp-util-dev
: git clone https://.../gulp-util.git gulp-util-dev
npm install
to ensure dependencies of gulp-util-dev
are available.gulp-util
as gulp-util-dev
. In your use-gulp
project, you can now replace: require('gulp-util')...;
call with : require('gulp-util-dev')
to test your changes you made to gulp-util-dev
Here is another way, without the need for nesting the repeaters.
From the Angularjs docs:
It is possible to get ngRepeat to iterate over the properties of an object using the following syntax:
<div ng-repeat="(key, value) in steps"> {{key}} : {{value}} </div>
Escaping strings can be tricky - especially if you want to take unicode into account. I suppose XML is one of the simpler formats/languages to escape but still. I would recommend taking a look at the StringEscapeUtils class in Apache Commons Lang, and its handy escapeXml method.
I resolved this by adding @Transactional
to the base/generic Hibernate DAO implementation class (the parent class which implements the saveOrUpdate() method inherited by the DAO I use in the main program), i.e. the @Transactional
needs to be specified on the actual class which implements the method. My assumption was instead that if I declared @Transactional
on the child class then it included all of the methods that were inherited by the child class. However it seems that the @Transactional
annotation only applies to methods implemented within a class and not to methods inherited by a class.
I ran into the same problem. I use jdk 1.8 and maven 3.3.9 Once I export JAVA_HOME, I did not see this error. export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/
one line of lazy code:
mEditText.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);
Add a given line at the beginning of a file in two commands:
cat <(echo "blablabla") input_file.txt > tmp_file.txt
mv tmp_file.txt input_file.txt
You should be able to call print("yo!") since there is a constructor for std::string which takes a const char*. These single argument constructors define implicit conversions from their aguments to their class type (unless the constructor is declared explicit which is not the case for std::string). Have you actually tried to compile this code?
void print(std::string input)
{
cout << input << endl;
}
int main()
{
print("yo");
}
It compiles fine for me in GCC. However, if you declared print like this void print(std::string& input)
then it would fail to compile since you can't bind a non-const reference to a temporary (the string would be a temporary constructed from "yo")
If you are presenting a ViewController modally, and want to go back to the root ViewController, take care to dismiss this modally presented ViewController before you go back to the root ViewController otherwise this ViewController will not be removed from Memory and cause Memory leaks.
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
Gallery is the best solution, i have tried it. I was working on one mail app, in which mails in the inbox where displayed as listview, i wanted an horizontal view, i just converted listview to gallery and everything worked fine as i needed without any errors. For the scroll effect i enabled gesture listener for the gallery. I hope this answer may help u.
You can use header files.
Good practice.
You can create a file called player.h
declare all functions that are need by other cpp files in that header file and include it when needed.
player.h
#ifndef PLAYER_H // To make sure you don't declare the function more than once by including the header multiple times.
#define PLAYER_H
#include "stdafx.h"
#include <SFML/Graphics.hpp>
int playerSprite();
#endif
player.cpp
#include "player.h" // player.h must be in the current directory. or use relative or absolute path to it. e.g #include "include/player.h"
int playerSprite(){
sf::Texture Texture;
if(!Texture.loadFromFile("player.png")){
return 1;
}
sf::Sprite Sprite;
Sprite.setTexture(Texture);
return 0;
}
main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "player.h" //Here. Again player.h must be in the current directory. or use relative or absolute path to it.
int main()
{
// ...
int p = playerSprite();
//...
Not such a good practice but works for small projects. declare your function in main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
// #include "player.cpp"
int playerSprite(); // Here
int main()
{
// ...
int p = playerSprite();
//...
A just in time compiler (JIT) is a piece of software which takes receives an non executable input and returns the appropriate machine code to be executed. For example:
Intermediate representation JIT Native machine code for the current CPU architecture
Java bytecode ---> machine code
Javascript (run with V8) ---> machine code
The consequence of this is that for a certain CPU architecture the appropriate JIT compiler must be installed.
Although there can be exceptions in general when we want to transform source code into machine code we can use:
It appears that you can throw only RuntimeException from the method orElseThrow
. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException
Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.
const Console = prop => (
console[Object.keys(prop)[0]](...Object.values(prop))
,null // ? React components must return something
)
// Some component with JSX and a logger inside
const App = () =>
<div>
<p>imagine this is some component</p>
<Console log='foo' />
<p>imagine another component</p>
<Console warn='bar' />
</div>
// Render
ReactDOM.render(
<App />,
document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
As of .NET 4.6, you can use a DateTimeOffset
object to get the unix milliseconds. It has a constructor which takes a DateTime
object, so you can just pass in your object as demonstrated below.
DateTime yourDateTime;
long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();
As noted in other answers, make sure yourDateTime
has the correct Kind
specified, or use .ToUniversalTime()
to convert it to UTC time first.
Here you can learn more about DateTimeOffset
.
To manipulate XML in Java, I always tend to use the Transformer API:
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
public static Document loadXMLFrom(String xml) throws TransformerException {
Source source = new StreamSource(new StringReader(xml));
DOMResult result = new DOMResult();
TransformerFactory.newInstance().newTransformer().transform(source , result);
return (Document) result.getNode();
}
Don't know for sure, but it sounds like it is still submitting. I quick solution would be to change your (guessing at your code here):
<input type="submit" value="Submit" onclick="checkform()">
to a button:
<input type="button" value="Submit" onclick="checkform()">
That way your form still gets submitted (from the else part of your checkform()) and it shouldn't be reloading the page.
There are other, perhaps better, ways of handling it but this works in the mean time.
In Django 1.7 this is even easier with the built-in JsonResponse.
https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects
# import it
from django.http import JsonResponse
def my_view(request):
# do something with the your data
data = {}
# just return a JsonResponse
return JsonResponse(data)
Even if you do start the executable outside Visual Studio, you can still use the "Attach" command to connect Visual Studio to your already-running executable. This can be useful e.g. when your application is run as a plug-in within another application.
The Media Source Extensions has been proposed which would allow for Adaptive Bitrate Streaming implementations.
folks, I got this Bootstrap dropdown working. I modified the click event slightly in order to keep the currently-selected image. And as you see, the USD currency is the default selected :
<div class="btn-group" style="margin:10px;"> <!-- CURRENCY, BOOTSTRAP DROPDOWN -->
<!--<a class="btn btn-primary" href="javascript:void(0);">Currency</a>-->
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#"><img src="../../Images/flag-usd-small.png"> USD <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="javascript:void(0);">
<img src="../../Images/flag-aud-small.png" /> AUD</a>
</li>
<li><a href="javascript:void(0);">
<img src="../../Images/flag-cad-small.png" /> CAD</a>
</li>
<li><a href="javascript:void(0);">
<img src="../../Images/flag-cny-small.png" /> CNY</a>
</li>
<li><a href="javascript:void(0);">
<img src="../../Images/flag-gbp-small.png" /> GBP</a>
</li>
<li><a href="javascript:void(0);">
<img src="../../Images/flag-usd-small.png" /> USD</a>
</li>
</ul>
</div>
/* BOOTSTRAP DROPDOWN MENU - Update selected item text and image */
$(".dropdown-menu li a").click(function () {
var selText = $(this).text();
var imgSource = $(this).find('img').attr('src');
var img = '<img src="' + imgSource + '"/>';
$(this).parents('.btn-group').find('.dropdown-toggle').html(img + ' ' + selText + ' <span class="caret"></span>');
});
The -not
test should fire if a property doesn't exist:
$prop = (Get-ItemProperty $regkey).$name
if (-not $prop)
{
New-ItemProperty -Path $regkey -Name $name -Value "X"
}
PDOStatement->execute() can throw an exception
so what you can do is
try
{
PDOStatement->execute();
//record inserted
}
catch(Exception $e)
{
//Some error occured. (i.e. violation of constraints)
}
$('.price').blur(function () {
var sum = 0;
$('.price').each(function() {
if($(this).val()!="")
{
sum += parseFloat($(this).val());
}
});
alert(sum);
});?????????
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
That only works for numbers less than 1.
select to_char(12.34, '0D99') from dual;
-- Result: #####
This won't work.
You could do something like this but this results in leading whitespaces:
select to_char(12.34, '999990D99') from dual;
-- Result: ' 12,34'
Ultimately, you could add a TRIM to get rid of the whitespaces again but I wouldn't consider that a proper solution either...
select trim(to_char(12.34, '999990D99')) from dual;
-- Result: 12,34
Again, this will only work for numbers with 6 digits max.
Edit: I wanted to add this as a comment on DCookie's suggestion but I can't.
For email templates, inline CSS is the properly used method to style:
<thead>
<tr style="color: #fff; background: black;">
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
Assuming your data is in column A, add a formula to column B
="'" & A1 & "'"
and copy the formula down. If you now save to CSV, you should get the quoted values. If you need to keep it in Excel format, copy column B then paste value to get rid of the formula.