The python error says that wordInput
is not an iterable -> it is of NoneType.
If you print wordInput
before the offending line, you will see that wordInput
is None
.
Since wordInput
is None
, that means that the argument passed to the function is also None
. In this case word
. You assign the result of pickEasy
to word
.
The problem is that your pickEasy
function does not return anything. In Python, a method that didn't return anything returns a NoneType.
I think you wanted to return a word
, so this will suffice:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare
function.
Example
while ((wrong < MAX_WRONG) && (soFar.compare(THE_WORD) != 0))
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
For anyone who comes across this late, like me.
As others have stated, name isn't a valid attribute of an option element. Combining the accepted answer above with the answer from this other question, you get:
$(this).find('option:selected').text();
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
Okay, here's a list of things to look into:
1) If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See:
https://code.google.com/archive/p/browsersec/wikis/Part2.wiki#Same-origin_policy
Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder).
2) The success function returned from $http.get() already splits up the result object for you:
$http({method: 'GET', url: '/someUrl'}).success(function(data, status, headers, config) {
So it's redundant to call success with function(response) and return response.data.
3) The success function does not return the result of the function you pass it, so this does not do what you think it does:
var mainInfo = $http.get('content.json').success(function(response) {
return response.data;
});
This is closer to what you intended:
var mainInfo = null;
$http.get('content.json').success(function(data) {
mainInfo = data;
});
4) But what you really want to do is return a reference to an object with a property that will be populated when the data loads, so something like this:
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
mainInfo.content will start off null, and when the data loads, it will point at it.
Alternatively you can return the actual promise the $http.get returns and use that:
theApp.factory('mainInfo', function($http) {
return $http.get('content.json');
});
And then you can use the value asynchronously in calculations in a controller:
$scope.foo = "Hello World";
mainInfo.success(function(data) {
$scope.foo = "Hello "+data.contentItem[0].username;
});
You probably want an extra wrapper. use a div for the background and position it below your content..
http://jsfiddle.net/pixelass/42F2j/
HTML
<div id="background-image"></div>
<div id="content">
Here is the content at opacity 1
<img src="http://lorempixel.com/100/50/fashion/1/">
</div>
CSS
#background-image {
background-image: url(http://lorempixel.com/400/200/sports/1/);
opacity:0.4;
position:absolute;
top:0;
left:0;
height:200px;
width:400px;
z-index:0;
}
#content {
z-index:1;
position:relative;
}
You can try specifying the BaseException type explicitly. However, this will only catch derivatives of BaseException. While this includes all implementation-provided exceptions, it is also possibly to raise arbitrary old-style classes.
try:
do_something()
except BaseException, e:
logger.error('Failed to do something: ' + str(e))
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
I have seen this instead of the (void)param2
way of silencing the warning:
void foo(int param1, int param2)
{
std::ignore = param2;
bar(param1);
}
Looks like this was added in C++11
You may be interested in std::vector<bool>
(that is bit-packed) and std::bitset
It should be the simplest as requested.
#include <iostream>
#include <bitset>
using namespace std;
int main() {
bitset<8> bs = 5;
bitset<8> rev;
for(int ii=0; ii!= bs.size(); ++ii)
rev[bs.size()-ii-1] = bs[ii];
cerr << bs << " " << rev << endl;
}
Other options may be faster.
EDIT: I owe you a solution using std::vector<bool>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<bool> b{0,0,0,0,0,1,0,1};
reverse(b.begin(), b.end());
copy(b.begin(), b.end(), ostream_iterator<int>(cerr));
cerr << endl;
}
The second example requires c++0x extension (to initialize the array with {...}
). The advantage of using a bitset
or a std::vector<bool>
(or a boost::dynamic_bitset
) is that you are not limited to bytes or words but can reverse an arbitrary number of bits.
HTH
public class X { static {
System.out.println("Main not required to print this");
System.exit(0);
}}
Run from the cmdline with java X
.
You can use "roll-your-own" solution for function overloading. This one is copied from Guido van Rossum's article about multimethods (because there is little difference between multimethods and overloading in Python):
registry = {}
class MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def __call__(self, *args):
types = tuple(arg.__class__ for arg in args) # a generator expression!
function = self.typemap.get(types)
if function is None:
raise TypeError("no match")
return function(*args)
def register(self, types, function):
if types in self.typemap:
raise TypeError("duplicate registration")
self.typemap[types] = function
def multimethod(*types):
def register(function):
name = function.__name__
mm = registry.get(name)
if mm is None:
mm = registry[name] = MultiMethod(name)
mm.register(types, function)
return mm
return register
The usage would be
from multimethods import multimethod
import unittest
# 'overload' makes more sense in this case
overload = multimethod
class Sprite(object):
pass
class Point(object):
pass
class Curve(object):
pass
@overload(Sprite, Point, Direction, int)
def add_bullet(sprite, start, direction, speed):
# ...
@overload(Sprite, Point, Point, int, int)
def add_bullet(sprite, start, headto, speed, acceleration):
# ...
@overload(Sprite, str)
def add_bullet(sprite, script):
# ...
@overload(Sprite, Curve, speed)
def add_bullet(sprite, curve, speed):
# ...
Most restrictive limitations at the moment are:
I had to merge some of those good answers here! This works for me:
git remote set-url origin 'https://bitbucket.org/teamName/repo.git'
In the end, it will always prompt anyone who wants to pull from it
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
with small numbers of points you could run a simulation:
from random import random,randint
r = 10
n = 20
best_closest_d = 0
best_points = []
points = [(r,0,0) for i in range(n)]
for simulation in range(10000):
x = random()*r
y = random()*r
z = r-(x**2+y**2)**0.5
if randint(0,1):
x = -x
if randint(0,1):
y = -y
if randint(0,1):
z = -z
closest_dist = (2*r)**2
closest_index = None
for i in range(n):
for j in range(n):
if i==j:
continue
p1,p2 = points[i],points[j]
x1,y1,z1 = p1
x2,y2,z2 = p2
d = (x1-x2)**2+(y1-y2)**2+(z1-z2)**2
if d < closest_dist:
closest_dist = d
closest_index = i
if simulation % 100 == 0:
print simulation,closest_dist
if closest_dist > best_closest_d:
best_closest_d = closest_dist
best_points = points[:]
points[closest_index]=(x,y,z)
print best_points
>>> best_points
[(9.921692138442777, -9.930808529773849, 4.037839326088124),
(5.141893371460546, 1.7274947332807744, -4.575674650522637),
(-4.917695758662436, -1.090127967097737, -4.9629263893193745),
(3.6164803265540666, 7.004158551438312, -2.1172868271109184),
(-9.550655088997003, -9.580386054762917, 3.5277052594769422),
(-0.062238110294250415, 6.803105171979587, 3.1966101417463655),
(-9.600996012203195, 9.488067284474834, -3.498242301168819),
(-8.601522086624803, 4.519484132245867, -0.2834204048792728),
(-1.1198210500791472, -2.2916581379035694, 7.44937337008726),
(7.981831370440529, 8.539378431788634, 1.6889099589074377),
(0.513546008372332, -2.974333486904779, -6.981657873262494),
(-4.13615438946178, -6.707488383678717, 2.1197605651446807),
(2.2859494919024326, -8.14336582650039, 1.5418694699275672),
(-7.241410895247996, 9.907335206038226, 2.271647103735541),
(-9.433349952523232, -7.999106443463781, -2.3682575660694347),
(3.704772125650199, 1.0526567864085812, 6.148581714099761),
(-3.5710511242327048, 5.512552040316693, -3.4318468250897647),
(-7.483466337225052, -1.506434920354559, 2.36641535124918),
(7.73363824231576, -8.460241422163824, -1.4623228616326003),
(10, 0, 0)]
Expanding on Paul's answer - here's my version of working with associative sub-arrays in bash:
declare -A SUB_1=(["name1key"]="name1val" ["name2key"]="name2val")
declare -A SUB_2=(["name3key"]="name3val" ["name4key"]="name4val")
STRING_1="string1val"
STRING_2="string2val"
MAIN_ARRAY=(
"${SUB_1[*]}"
"${SUB_2[*]}"
"${STRING_1}"
"${STRING_2}"
)
echo "COUNT: " ${#MAIN_ARRAY[@]}
for key in ${!MAIN_ARRAY[@]}; do
IFS=' ' read -a val <<< ${MAIN_ARRAY[$key]}
echo "VALUE: " ${val[@]}
if [[ ${#val[@]} -gt 1 ]]; then
for subkey in ${!val[@]}; do
subval=${val[$subkey]}
echo "SUBVALUE: " ${subval}
done
fi
done
It works with mixed values in the main array - strings/arrays/assoc. arrays
The key here is to wrap the subarrays in single quotes and use *
instead of @
when storing a subarray inside the main array so it would get stored as a single, space separated string: "${SUB_1[*]}"
Then it makes it easy to parse an array out of that when looping through values with IFS=' ' read -a val <<< ${MAIN_ARRAY[$key]}
The code above outputs:
COUNT: 4
VALUE: name1val name2val
SUBVALUE: name1val
SUBVALUE: name2val
VALUE: name4val name3val
SUBVALUE: name4val
SUBVALUE: name3val
VALUE: string1val
VALUE: string2val
#input_box {
margin: 0 auto;
text-align: left;
}
#div {
text-align: center;
}
<div id="div">
<label for="input_box">Input: </label><input type="text" id="input_box" name="input_box" />
</div>
or you could do it using padding, but this is not that great of an idea.
One way is to do:
sys.exit(0)
You will have to import sys
of course.
Another way is to break
out of your infinite loop. For example, you could do this:
while True:
choice = get_input()
if choice == "a":
# do something
elif choice == "q":
break
Yet another way is to put your main loop in a function, and use return
:
def run():
while True:
choice = get_input()
if choice == "a":
# do something
elif choice == "q":
return
if __name__ == "__main__":
run()
The only reason you need the run()
function when using return
is that (unlike some other languages) you can't directly return
from the main part of your Python code (the part that's not inside a function).
Now that Apple has non-cosensually updated all MacOS users to zsh, the correct answer doesn't work anymore.
git reset --soft HEAD^
zsh: no matches found: HEAD^
You can prevent the shell from treating the ^ as a special character by single quoting it.
git reset --soft 'HEAD^'
Alternatively you can disable this behavior in your shell. by updating your ~/.zshrc with
unsetopt nomatch
The PowerShell answers are good, but the Rename-Item command doesn't work in the same target directory unless ALL of your files have the unwanted character in them (fails if it finds duplicates).
If you're like me and had a mix of good names and bad names, try this script instead (will replace spaces with an underscore):
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace(" ", "_") }
USE update_attribute instead of update_attributes
Updates a single attribute and saves the record without going through the normal validation procedure.
if a.update_attribute('state', a.state)
Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
Whatever you return from a promise will be wrapped into a promise to be unwrapped at the next .then()
stage.
It becomes interesting when you need to return one or more promise(s) alongside one or more synchronous value(s) such as;
Promise.resolve([Promise.resolve(1), Promise.resolve(2), 3, 4])
.then(([p1,p2,n1,n2]) => /* p1 and p2 are still promises */);
In these cases it would be essential to use Promise.all()
to get p1
and p2
promises unwrapped at the next .then()
stage such as
Promise.resolve(Promise.all([Promise.resolve(1), Promise.resolve(2), 3, 4]))
.then(([p1,p2,n1,n2]) => /* p1 is 1, p2 is 2, n1 is 3 and n2 is 4 */);
Try this to your .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule >
This solution uses Object.getPrototypeOf
TestA
is super that has getName
TestB
is a child that overrides getName
but, also has
getBothNames
that calls the super
version of getName
as well as the child
version
function TestA() {_x000D_
this.count = 1;_x000D_
}_x000D_
TestA.prototype.constructor = TestA;_x000D_
TestA.prototype.getName = function ta_gn() {_x000D_
this.count = 2;_x000D_
return ' TestA.prototype.getName is called **';_x000D_
};_x000D_
_x000D_
function TestB() {_x000D_
this.idx = 30;_x000D_
this.count = 10;_x000D_
}_x000D_
TestB.prototype = new TestA();_x000D_
TestB.prototype.constructor = TestB;_x000D_
TestB.prototype.getName = function tb_gn() {_x000D_
return ' TestB.prototype.getName is called ** ';_x000D_
};_x000D_
_x000D_
TestB.prototype.getBothNames = function tb_gbn() {_x000D_
return Object.getPrototypeOf(TestB.prototype).getName.call(this) + this.getName() + ' this object is : ' + JSON.stringify(this);_x000D_
};_x000D_
_x000D_
var tb = new TestB();_x000D_
console.log(tb.getBothNames());
_x000D_
Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $
are global, variables with @
are instance variables, @@
means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.
I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:
Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo
and create a constant Offset
, so then all the classes could access Foo::Offset
.
Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.
Here is an SSCCE,
package experiment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class KeyListenerTester extends JFrame implements KeyListener {
JLabel label;
public KeyListenerTester(String s) {
super(s);
JPanel p = new JPanel();
label = new JLabel("Key Listener!");
p.add(label);
add(p);
addKeyListener(this);
setSize(200, 100);
setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key typed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key typed");
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key pressed");
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right key Released");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left key Released");
}
}
public static void main(String[] args) {
new KeyListenerTester("Key Listener Tester");
}
}
Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings
Put String in Intent Object
Intent intent = new Intent(FirstActivity.this,NextAcitivity.class);
intent.putExtra("key",your_String);
StartActivity(intent);
NextAcitvity in onCreate method get String
String my_string=getIntent().getStringExtra("key");
that is easy and short method
On both Operation Systems, must turnoff firewall. I using MS SERVER 2012 R2 & MS WIN-7 as a client. First of all call "RUN BOX" window logo button+ R, once RUN box appeared type "firewall.cpl" at Window Firewall setting you will see "Turn Window Firewall On or Off" like this you click it & chose "turn off window firewall" on both Private and Public Setting then OK. Ping again on guests OS. GOOD-LUCK Aungkokokhant
Whatever function is a class so you can take the name of the class of instance x and compare:
if(x.__class__.__name__ == 'function'):
print "it's a function"
Update 2017
Depending on the environment, conditional comments have been officially deprecated and removed in IE10+.
Original
The simplest way is probably to use an Internet Explorer conditional comment in your HTML:
<!--[if IE]>
<style>
.actual-form table {
width: 100%;
}
</style>
<![endif]-->
There are numerous hacks (e.g. the underscore hack) you can use that will allow you to target only IE within your stylesheet, but it gets very messy if you want to target all versions of IE on all platforms.
Use org.springframework.web.servlet.config.annotation.WebMvcConfigurer
With Spring Boot 2.1.4.RELEASE (Spring Framework 5.1.6.RELEASE), do like this
package vn.bkit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // Deprecated.
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {
@Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".html");
return resolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
It is working fine with me.
I have the following HTML:
<div>
<select id="select1">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
<br/>
<button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>
And the following JavaScript:
function GetSelectedItem(el)
{
var e = document.getElementById(el);
var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
alert(strSel);
}
See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.
I suggest Validator.nu's parser, based on the HTML5 parsing algorithm. It is the parser used in Mozilla from 2010-05-03
Just check for it before you pass to your function. So you would pass:
thing.foo ? thing.foo.bar : undefined
String s = "a.b.c.d";
int charCount = s.length() - s.replaceAll("\\.", "").length();
ReplaceAll(".") would replace all characters.
PhiLho's solution uses ReplaceAll("[^.]",""), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.
When I do this, I like to have some control over the details of how the table is formatted. In particular, I want header cells to have a different format than body cells, and the table column widths to only be as wide as each one needs to be. Here's my solution:
def format_matrix(header, matrix,
top_format, left_format, cell_format, row_delim, col_delim):
table = [[''] + header] + [[name] + row for name, row in zip(header, matrix)]
table_format = [['{:^{}}'] + len(header) * [top_format]] \
+ len(matrix) * [[left_format] + len(header) * [cell_format]]
col_widths = [max(
len(format.format(cell, 0))
for format, cell in zip(col_format, col))
for col_format, col in zip(zip(*table_format), zip(*table))]
return row_delim.join(
col_delim.join(
format.format(cell, width)
for format, cell, width in zip(row_format, row, col_widths))
for row_format, row in zip(table_format, table))
print format_matrix(['Man Utd', 'Man City', 'T Hotspur', 'Really Long Column'],
[[1, 2, 1, -1], [0, 1, 0, 5], [2, 4, 2, 2], [0, 1, 0, 6]],
'{:^{}}', '{:<{}}', '{:>{}.3f}', '\n', ' | ')
Here's the output:
| Man Utd | Man City | T Hotspur | Really Long Column
Man Utd | 1.000 | 2.000 | 1.000 | -1.000
Man City | 0.000 | 1.000 | 0.000 | 5.000
T Hotspur | 2.000 | 4.000 | 2.000 | 2.000
Really Long Column | 0.000 | 1.000 | 0.000 | 6.000
Port Access
Firewalls and other security tools may prevent RabbitMQ from binding to a port. When that happens, RabbitMQ will fail to start. Make sure the following ports can be opened:
4369: epmd, a peer discovery service used by RabbitMQ nodes and CLI tools
5672, 5671: used by AMQP 0-9-1 and 1.0 clients without and with TLS
25672: used by Erlang distribution for inter-node and CLI tools communication and is allocated from a dynamic range (limited to a single port by default, computed as AMQP port + 20000). See networking guide for details.
15672: HTTP API clients and rabbitmqadmin (only if the management plugin is enabled)
61613, 61614: STOMP clients without and with TLS (only if the STOMP plugin is enabled)
1883, 8883: (MQTT clients without and with TLS, if the MQTT plugin is enabled
15674: STOMP-over-WebSockets clients (only if the Web STOMP plugin is enabled)
15675: MQTT-over-WebSockets clients (only if the Web MQTT plugin is enabled)
Reference doc: https://www.rabbitmq.com/install-windows-manual.html
You either want to add "." to your CLASSPATH to specify the current directory, or add it manually at run time the way unbeli suggested.
git rebase -i HEAD~2
Here '2' is the number of commits you want to rebase.
'git rebase -i HEAD`
if you want to rebase all the commits.
Then you will be able to choose one of these options.
p, pick = use commit
r, reword = use commit, but edit the commit message
e, edit = use commit, but stop for amending
s, squash = use commit, but meld into previous commit
f, fixup = like "squash", but discard this commit's log message
x, exec = run command (the rest of the line) using shell
d, drop = remove commit
These lines can be re-ordered; they are executed from top to bottom. If you remove a line here THAT COMMIT WILL BE LOST. However, if you remove everything, the rebase will be aborted. Note that empty commits are commented out
You can simply remove that commit using option "d" or Removing a line that has your commit.
Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.Reflection.TargetInvocationException
I have faced this Error, Application was working fine on some PCs and on some PCs giving the above error. I uninstall the Framework 4.5 and re-install this resolved my problem.
Cheer.
I realize that this is an old question, but I'll post the solution for my use case, in case others run into the same situation I did when implementing James Hill's answer (above).
I found this question while trying to solve the same issue. James' answer got me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchange
event. James' code as written did not trigger this event (at least in Firefox, which I was testing in). As a result, I made the following minor change:
function setSelectedValue(object, value) {
for (var i = 0; i < object.options.length; i++) {
if (object.options[i].text === value) {
object.options[i].selected = true;
object.onchange();
return;
}
}
// Throw exception if option `value` not found.
var tag = object.nodeName;
var str = "Option '" + value + "' not found";
if (object.id != '') {
str = str + " in //" + object.nodeName.toLowerCase()
+ "[@id='" + object.id + "']."
}
else if (object.name != '') {
str = str + " in //" + object.nodeName.toLowerCase()
+ "[@name='" + object.name + "']."
}
else {
str += "."
}
throw str;
}
Note the object.onchange()
call, which I added to the original solution. This calls the handler to make certain that the action on the page occurs.
Added code to throw an exception if option value
is not found; this is needed for my use case.
That Exception is thrown if there is already a key in the dictionary when you try to add the new one.
There must be more than one line in rct3Lines
with the same first word. You can't have 2 entries in the same dictionary with the same key.
You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply
rct3Features[items[0]]=items[1]
but, if not you may want to test if the key already exists with:
if(rect3Features.ContainsKey(items[0]))
{
//Do something
}
else
{
//Do something else
}
Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List<Float> unindexedVectors = new ArrayList<Float>();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);
If you were to hardcode it you would use modulus to extract the time as others suggested.
If you are returning the seconds from MySQL database, assuming you don't need the data in seconds format in your app, there is a much cleaner way to do it, you can use MySQL's SEC_TO_TIME and it will return time in hh:mm:ss format.
Eg.
SELECT SEC_TO_TIME(my_seconds_field) AS my_timestring;
The accepted answer is fine if you can use lookarounds. However, there is also another approach to solve this problem.
If we look at the widely proposed regex for this question:
.*[^a]$
We will find that it almost works. It does not accept an empty string, which might be a little inconvinient. However, this is a minor issue when dealing with just a one character. However, if we want to exclude whole string, e.g. "abc", then:
.*[^a][^b][^c]$
won't do. It won't accept ac, for example.
There is an easy solution for this problem though. We can simply say:
.{,2}$|.*[^a][^b][^c]$
or more generalized version:
.{,n-1}$|.*[^firstchar][^secondchar]$
where n is length of the string you want forbid (for abc
it's 3), and firstchar
, secondchar
, ... are first, second ... nth characters of your string (for abc
it would be a
, then b
, then c
).
This comes from a simple observation that a string that is shorter than the text we won't forbid can not contain this text by definition. So we can either accept anything that is shorter("ab" isn't "abc"), or anything long enough for us to accept but without the ending.
Here's an example of find that will delete all files that are not .jpg:
find . -regex '.{,3}$|.*[^.][^j][^p][^g]$' -delete
In my case the solutions above did not work I had to do the following:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));
myarray = "abc";
...is the assignation of a pointer on "abc" to the pointer myarray.
This is NOT filling the myarray buffer with "abc".
If you want to fill the myarray buffer manually, without strcpy(), you can use:
myarray[0] = 'a', myarray[1] = 'b', myarray[2] = 'c', myarray[3] = 0;
or
char *ptr = myarray;
*ptr++ = 'a', *ptr++ = 'b', *ptr++ = 'c', *ptr = 0;
Your question is about the difference between a pointer and a buffer (an array). I hope you now understand how C addresses each kind.
You should add this import in your file:
import * as fetch from 'node-fetch';
And then, run this code to add the node-fetch
:
yarn add node-fetch
According to the documentation since Symfony 2.1 simply use this shortcut :
$user = $this->getUser();
The above is still working on Symfony 3.2 and is a shortcut for this :
$user = $this->get('security.token_storage')->getToken()->getUser();
The
security.token_storage
service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use thegetToken()
method of thesecurity.context
service.
Example : And if you want directly the username :
$username = $this->getUser()->getUsername();
The user will be an object and the class of that object will depend on your user provider.
I solved this problem by keying the array with the ID. It's simpler and possibly faster for this scenario where the ID is what you're looking for.
[420] => stdClass Object
(
[name] => Mary
)
[10957] => stdClass Object
(
[name] => Blah
)
...
Now I can directly address the array:
$array[$v]->name = ...
Or, if I want to verify the existence of an ID:
if (array_key_exists($v, $array)) { ...
In my case what solved the problem was the folowing:
USE [master]
GO
CREATE DATABASE [AdventureWorks2008R2] ON
( FILENAME = 'C:\Program Files\Microsfot SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\AdventureWors2008R2_Data.mdf')
FOR ATTACH_REBUILD_LOG
If you are searching literally the way to return a JSON list in flask and you are completly sure that your variable is a list then the easy way is (where bin is a list of 1's and 0's):
return jsonify({'ans':bin}), 201
Finally, in your client you will obtain something like
{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }
jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">0p0</span> <span class="value">SEC</span> </div>
</div>
_x000D_
There is no difference at all!
1) git checkout -b branch origin/branch
If there is no --track
and no --no-track
, --track
is assumed as default. The default can be changed with the setting branch.autosetupmerge
.
In effect, 1) behaves like git checkout -b branch --track origin/branch
.
2) git checkout --track origin/branch
“As a convenience”, --track
without -b
implies -b
and the argument to -b
is guessed to be “branch”. The guessing is driven by the configuration variable remote.origin.fetch
.
In effect, 2) behaves like git checkout -b branch --track origin/branch
.
As you can see: no difference.
But it gets even better:
3) git checkout branch
is also equivalent to git checkout -b branch --track origin/branch
if “branch” does not exist yet but “origin/branch” does1.
All three commands set the “upstream” of “branch” to be “origin/branch” (or they fail).
Upstream is used as reference point of argument-less git status
, git push
, git merge
and thus git pull
(if configured like that (which is the default or almost the default)).
E.g. git status
tells you how far behind or ahead you are of upstream, if one is configured.
git push
is configured to push the current branch upstream by default2 since git 2.0.
1 ...and if “origin” is the only remote having “branch”
2 the default (named “simple”) also enforces for both branch names to be equal
I know this is an old post, but here's how I solved it (along with converting null values to empty string) in C# using an extension method.
Create a static class with something like the following:
/// <summary>
/// Wraps value in quotes if necessary and converts nulls to empty string
/// </summary>
/// <param name="value"></param>
/// <returns>String ready for use in CSV output</returns>
public static string Q(this string value)
{
if (value == null)
{
return string.Empty;
}
if (value.Contains(",") || (value.Contains("\"") || value.Contains("'") || value.Contains("\\"))
{
return "\"" + value + "\"";
}
return value;
}
Then for each string you're writing to CSV, instead of:
stringBuilder.Append( WhateverVariable );
You just do:
stringBuilder.Append( WhateverVariable.Q() );
<router-outlet [node]="..."></router-outlet>
is just invalid. The component added by the router is added as sibling to <router-outlet>
and does not replace it.
See also https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
@Injectable()
export class NodeService {
private node:Subject<Node> = new BehaviorSubject<Node>([]);
get node$(){
return this.node.asObservable().filter(node => !!node);
}
addNode(data:Node) {
this.node.next(data);
}
}
@Component({
selector : 'node-display',
providers: [NodeService],
template : `
<router-outlet></router-outlet>
`
})
export class NodeDisplayComponent implements OnInit {
constructor(private nodeService:NodeService) {}
node: Node;
ngOnInit(): void {
this.nodeService.getNode(path)
.subscribe(
node => {
this.nodeService.addNode(node);
},
err => {
console.log(err);
}
);
}
}
export class ChildDisplay implements OnInit{
constructor(nodeService:NodeService) {
nodeService.node$.subscribe(n => this.node = n);
}
}
To take first 5 elements better use expression like this one:
var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5);
or
var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5).OrderBy([ORDER EXPR]);
It will be faster than orderBy variant, because LINQ engine will not scan trough all list due to delayed execution, and will not sort all array.
class MyList : IEnumerable<int>
{
int maxCount = 0;
public int RequestCount
{
get;
private set;
}
public MyList(int maxCount)
{
this.maxCount = maxCount;
}
public void Reset()
{
RequestCount = 0;
}
#region IEnumerable<int> Members
public IEnumerator<int> GetEnumerator()
{
int i = 0;
while (i < maxCount)
{
RequestCount++;
yield return i++;
}
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
class Program
{
static void Main(string[] args)
{
var list = new MyList(15);
list.Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 5;
list.Reset();
list.OrderBy(q => q).Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 15;
list.Reset();
list.Where(q => (q & 1) == 0).Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
list.Reset();
list.Where(q => (q & 1) == 0).Take(5).OrderBy(q => q).ToArray();
Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
}
}
As a slight improvement over the other answers, you can do the mkdir
and chmod
as a single operation using mkdir
's -m
switch.
$ mkdir -m 700 ${HOME}/.ssh
From a Linux system
$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
...
...
Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.
Geocoder call procedure, can be located in a Helper class
public static void getAddressFromLocation(
final Location location, final Context context, final Handler handler) {
Thread thread = new Thread() {
@Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
Here is the call to this Geocoder procedure in your UI Activity:
getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());
And the handler to show the results in your UI:
private class GeocoderHandler extends Handler {
@Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}
Don't forget to put the following permission in your Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
.loc
accept row and column selectors simultaneously (as do .ix/.iloc
FYI)
This is done in a single pass as well.
In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
In [2]: df
Out[2]:
a b c d e
0 0.669701 0.780497 0.955690 0.451573 0.232194
1 0.952762 0.585579 0.890801 0.643251 0.556220
2 0.900713 0.790938 0.952628 0.505775 0.582365
3 0.994205 0.330560 0.286694 0.125061 0.575153
In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]:
a d
0 0.669701 0.451573
1 0.952762 0.643251
2 0.900713 0.505775
And if you want the values (though this should pass directly to sklearn as is); frames support the array interface
In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]:
array([[ 0.66970138, 0.45157274],
[ 0.95276167, 0.64325143],
[ 0.90071271, 0.50577509]])
If you wish to use the bound column value, you can simply refer to the combo:
sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo
You can also refer to the column property:
sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"
Dim rs As DAO.Recordset
Set rs = CurrentDB.OpenRecordset(sSQL)
strText = rs!AText
strText = rs.Fields(1)
In a textbox:
= DlookUp("AText","MyTable","ID=" & MyCombo)
*edited
You could also do this if you'd like a simple one-liner:
puts caller
I've finally done it in this way.
Added a ServletContextListener that does the following:
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
System.setProperty("rootPath", context.getRealPath("/"));
}
Then in the log4j.properties file:
log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log
By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.
It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.
What do you think?
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
Booleans are nothing but integers only, they are just type casted values like...
typedef signed char BOOL;
#define YES (BOOL)1
#define NO (BOOL)0
BOOL value = YES;
NSLog(@"Bool value: %d",value);
If output is 1,YES otherwise NO
When you boil down to it, it's just a fancy overly-complicated proxy, but maybe Catch-All Proxies could do it?
var o = {
a: 'a',
b: 'b',
func: function() { return 'func'; }
};
var proxy = Proxy.create(handlerMaker(o), o);
(function(x){
var obj = x;
console.log(x.a);
console.log(x.b);
obj.foo = 'foo';
obj.bar = 'bar';
})(proxy);
console.log(o.foo);
function handlerMaker(obj) {
return {
getOwnPropertyDescriptor: function(name) {
var desc = Object.getOwnPropertyDescriptor(obj, name);
// a trapping proxy's properties must always be configurable
if (desc !== undefined) { desc.configurable = true; }
return desc;
},
getPropertyDescriptor: function(name) {
var desc = Object.getOwnPropertyDescriptor(obj, name); // not in ES5
// a trapping proxy's properties must always be configurable
if (desc !== undefined) { desc.configurable = true; }
return desc;
},
getOwnPropertyNames: function() {
return Object.getOwnPropertyNames(obj);
},
getPropertyNames: function() {
return Object.getPropertyNames(obj); // not in ES5
},
defineProperty: function(name, desc) {
},
delete: function(name) { return delete obj[name]; },
fix: function() {}
};
}
Assuming a as double and we need a rounded number with no decimal place . Use Math.round() function.
This goes as my solution .
double a = 0.99999;
int rounded_a = (int)Math.round(a);
System.out.println("a:"+rounded_a );
Output :
a:1
If you want to run a task that's associated with a host, but on different host, you should try delegate_to.
In your case, you should delegate to your localhost (ansible master) and calling ansible-playbook
command
Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:
throw new TransactionProblemException(transNbr, originalException);
The stack trace will look like
TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...
While the question has been answered, I'd like to add some useful tips when using matplotlib.pyplot.savefig. The file format can be specified by the extension:
from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
Will give a rasterized or vectorized output respectively, both which could be useful. In addition, you'll find that pylab
leaves a generous, often undesirable, whitespace around the image. You can remove the whitespace using:
plt.savefig('foo.png', bbox_inches='tight')
Simple and easy in javascipt
<script>
document.getElementById("selectsearch").addEventListener("change", function(){
var get_form = document.getElementById("search-form") // get form
get_form.action = '/search/' + this.value; // assign value
});
</script>
Good Solution is to get Nearest Round Number is
var=2.5
echo $var | awk '{print int($1+0.5)}'
Logic is simple if the var decimal value is less then .5 then closest value taken is integer value. Well if decimal value is more than .5 then next integer value gets added and since awk then takes only integer part. Issue solved
Because Label1.Text
is holding Label
which can't be parsed into integer, you need to convert the associated textbox's text to integer
imageWidth = 1 * Convert.ToInt32(TextBox2.Text);
use the aria2 :
aria2c -x 16 [url]
# |
# |
# |
# ----> the number of connections
I love it !!
Apart from the obvious die()
and exit()
, this also works:
<?php
echo "start";
__halt_compiler();
echo "you should not see this";
?>
Assuming you're using Spring Boot, another option is to put the following in your application.properties
:
logging.level.org.springframework.security=DEBUG
This is the same for most other Spring modules as well.
If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.
Here is the application.yml version as well:
logging:
level:
org:
springframework:
security: DEBUG
Docker inspect use to print all container ips and its respective names
docker ps -q | xargs -n 1 docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} {{ .Name }}' | sed 's/ \// /'
A simpler way is
ggplot(data=df, aes(x=xvar, y=yvar)) +
geom_point()
ggsave(path = path, width = width, height = height, device='tiff', dpi=700)
You can use this package from_css_color to get Color
out of a hex string. It supports both three and six digit RGB hex notation.
Color color = fromCSSColor('#ff00aa')
For optimisation sake create Color instance once for each color and store it somewhere for later usage.
If you want cryptographically secure random numbers, and the exact charset is flexible (say, base64 is fine), you can calculate exactly what the length of random characters you need from the desired output size.
Base 64 text is 1/3 longer than base 256. (2^8 vs 2^6; 8bits/6bits = 1.333 ratio)
import (
"crypto/rand"
"encoding/base64"
"math"
)
func randomBase64String(l int) string {
buff := make([]byte, int(math.Round(float64(l)/float64(1.33333333333))))
rand.Read(buff)
str := base64.RawURLEncoding.EncodeToString(buff)
return str[:l] // strip 1 extra character we get from odd length results
}
Note: you can also use RawStdEncoding if you prefer + and / characters to - and _
If you want hex, base 16 is 2x longer than base 256. (2^8 vs 2^4; 8bits/4bits = 2x ratio)
import (
"crypto/rand"
"encoding/hex"
"math"
)
func randomBase16String(l int) string {
buff := make([]byte, int(math.Round(float64(l)/2)))
rand.Read(buff)
str := hex.EncodeToString(buff)
return str[:l] // strip 1 extra character we get from odd length results
}
However, you could extend this to any arbitrary character set if you have a base256 to baseN encoder for your character set. You can do the same size calculation with how many bits are needed to represent your character set. The ratio calculation for any arbitrary charset is: ratio = 8 / log2(len(charset))
).
Though both of these solutions are secure, simple, should be fast, and don't waste your crypto entropy pool.
Here's the playground showing it works for any size. https://play.golang.org/p/i61WUVR8_3Z
Solution
1.Just clean the project and check its working or not
2.Just Restart android studio after closing all the rubbish tasks
3.If both the above things not working add this in gradle.build file
android {
dexOptions {
incremental = true;
preDexLibraries = false
javaMaxHeapSize "4g"
}
}
Try something like:
WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else
That's really an informational message.
Likely, you're doing OPTIMIZE on an InnoDB table (table using the InnoDB storage engine, rather than the MyISAM storage engine).
InnoDB doesn't support the OPTIMIZE the way MyISAM does. It does something different. It creates an empty table, and copies all of the rows from the existing table into it, and essentially deletes the old table and renames the new table, and then runs an ANALYZE to gather statistics. That's the closest that InnoDB can get to doing an OPTIMIZE.
The message you are getting is basically MySQL server repeating what the InnoDB storage engine told MySQL server:
Table does not support optimize is the InnoDB storage engine saying...
"I (the InnoDB storage engine) don't do an OPTIMIZE operation like my friend (the MyISAM storage engine) does."
"doing recreate + analyze instead" is the InnoDB storage engine saying...
"I have decided to perform a different set of operations which will achieve an equivalent result."
v$resource_limit view is so interesting for me in order to glance oracle sessions,processes..:
https://bbdd-error.blogspot.com.es/2017/09/check-sessions-and-processes-limit-in.html
try
with open(f"{os.path.dirname(sys.argv[0])}/data/test.csv", newline='') as f:
The problem is not in Django settings, but in the date passed to the model. Here's how a timezone-aware object looks like:
>>> from django.utils import timezone
>>> import pytz
>>> timezone.now()
datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=pytz.UTC)
And here's a naive object:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2013, 11, 20, 20, 9, 26, 423063)
So if you are passing email date anywhere (and it eventually gets to some model), just use Django's now()
. If not, then it's probably an issue with an existing package that fetches date without timezone and you can patch the package, ignore the warning or set USE_TZ to False.
Log fatal errors using the register_shutdown_function
, which requires PHP 5.2+:
register_shutdown_function( "fatal_handler" );
function fatal_handler() {
$errfile = "unknown file";
$errstr = "shutdown";
$errno = E_CORE_ERROR;
$errline = 0;
$error = error_get_last();
if($error !== NULL) {
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
error_mail(format_error( $errno, $errstr, $errfile, $errline));
}
}
You will have to define the error_mail
and format_error
functions. For example:
function format_error( $errno, $errstr, $errfile, $errline ) {
$trace = print_r( debug_backtrace( false ), true );
$content = "
<table>
<thead><th>Item</th><th>Description</th></thead>
<tbody>
<tr>
<th>Error</th>
<td><pre>$errstr</pre></td>
</tr>
<tr>
<th>Errno</th>
<td><pre>$errno</pre></td>
</tr>
<tr>
<th>File</th>
<td>$errfile</td>
</tr>
<tr>
<th>Line</th>
<td>$errline</td>
</tr>
<tr>
<th>Trace</th>
<td><pre>$trace</pre></td>
</tr>
</tbody>
</table>";
return $content;
}
Use Swift Mailer to write the error_mail
function.
See also:
Why not combine Pablo's reply with a valueOf()?
public enum Choices
{
a1, a2, b1, b2;
public static boolean contains(String s) {
try {
Choices.valueOf(s);
return true;
} catch (Exception e) {
return false;
}
}
Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:
echo '<p>' . $unit1 . "</p>\n";
PS: One clarification, single quotes strings do accept two escape sequences:
\'
when you want to use single quote inside single quoted strings\\
when you want to use backslash literallyI'm sharing what I use, because it appears I've come up with something different. I've been using this for a while and it is fast enough for me. I'm not sure how it stacks up against the others. I uses it in a delimited file writer and run large datatables one field at a time through it.
public static string NormalizeWhiteSpace(string S)
{
string s = S.Trim();
bool iswhite = false;
int iwhite;
int sLength = s.Length;
StringBuilder sb = new StringBuilder(sLength);
foreach(char c in s.ToCharArray())
{
if(Char.IsWhiteSpace(c))
{
if (iswhite)
{
//Continuing whitespace ignore it.
continue;
}
else
{
//New WhiteSpace
//Replace whitespace with a single space.
sb.Append(" ");
//Set iswhite to True and any following whitespace will be ignored
iswhite = true;
}
}
else
{
sb.Append(c.ToString());
//reset iswhitespace to false
iswhite = false;
}
}
return sb.ToString();
}
Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash()
and password_verify()
. Actually these are just wrappers around the function crypt()
, and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.
The easiest way to use this functions will be:
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
This code will hash the password with BCrypt (algorithm 2y
), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.
Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
In contrast to the "cost"
parameter, it is best to omit the "salt"
parameter, because the function already does its best to create a cryptographically safe salt.
For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash()
function. For PHP versions before 5.3.7 there is no support for crypt()
with 2y
, the unicode safe BCrypt algorithm. One could replace it instead with 2a
, which is the best alternative for earlier PHP versions.
Some years ago, in a safety critical field, I have heard something like one day for unit testing ten lines of code.
I have also observed 50% of effort for development and 50% for testing (not only unit testing).
Based on answers I wrote for myself this:
import datetime;
print [(datetime.date.today() - datetime.timedelta(days=x)).strftime('%Y-%m-%d') for x in range(-5, 0)]
Output:
['2017-12-11', '2017-12-10', '2017-12-09', '2017-12-08', '2017-12-07']
The difference is that I get the 'date
' object, not the 'datetime.datetime
' one.
A bit late, but for the record.
You can achieve smooth lines by using cardinal splines (aka canonical spline) to draw smooth curves that goes through the points.
I made this function for canvas - it's split into three function to increase versatility. The main wrapper function looks like this:
function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {
showPoints = showPoints ? showPoints : false;
ctx.beginPath();
drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));
if (showPoints) {
ctx.stroke();
ctx.beginPath();
for(var i=0;i<ptsa.length-1;i+=2)
ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);
}
}
To draw a curve have an array with x, y points in the order: x1,y1, x2,y2, ...xn,yn
.
Use it like this:
var myPoints = [10,10, 40,30, 100,10]; //minimum two points
var tension = 1;
drawCurve(ctx, myPoints); //default tension=0.5
drawCurve(ctx, myPoints, tension);
The function above calls two sub-functions, one to calculate the smoothed points. This returns an array with new points - this is the core function which calculates the smoothed points:
function getCurvePoints(pts, tension, isClosed, numOfSegments) {
// use input value if provided, or use a default value
tension = (typeof tension != 'undefined') ? tension : 0.5;
isClosed = isClosed ? isClosed : false;
numOfSegments = numOfSegments ? numOfSegments : 16;
var _pts = [], res = [], // clone array
x, y, // our x,y coords
t1x, t2x, t1y, t2y, // tension vectors
c1, c2, c3, c4, // cardinal points
st, t, i; // steps based on num. of segments
// clone array so we don't change the original
//
_pts = pts.slice(0);
// The algorithm require a previous and next point to the actual point array.
// Check if we will draw closed or open curve.
// If closed, copy end points to beginning and first points to end
// If open, duplicate first points to befinning, end points to end
if (isClosed) {
_pts.unshift(pts[pts.length - 1]);
_pts.unshift(pts[pts.length - 2]);
_pts.unshift(pts[pts.length - 1]);
_pts.unshift(pts[pts.length - 2]);
_pts.push(pts[0]);
_pts.push(pts[1]);
}
else {
_pts.unshift(pts[1]); //copy 1. point and insert at beginning
_pts.unshift(pts[0]);
_pts.push(pts[pts.length - 2]); //copy last point and append
_pts.push(pts[pts.length - 1]);
}
// ok, lets start..
// 1. loop goes through point array
// 2. loop goes through each segment between the 2 pts + 1e point before and after
for (i=2; i < (_pts.length - 4); i+=2) {
for (t=0; t <= numOfSegments; t++) {
// calc tension vectors
t1x = (_pts[i+2] - _pts[i-2]) * tension;
t2x = (_pts[i+4] - _pts[i]) * tension;
t1y = (_pts[i+3] - _pts[i-1]) * tension;
t2y = (_pts[i+5] - _pts[i+1]) * tension;
// calc step
st = t / numOfSegments;
// calc cardinals
c1 = 2 * Math.pow(st, 3) - 3 * Math.pow(st, 2) + 1;
c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2);
c3 = Math.pow(st, 3) - 2 * Math.pow(st, 2) + st;
c4 = Math.pow(st, 3) - Math.pow(st, 2);
// calc x and y cords with common control vectors
x = c1 * _pts[i] + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;
y = c1 * _pts[i+1] + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;
//store points in array
res.push(x);
res.push(y);
}
}
return res;
}
And to actually draw the points as a smoothed curve (or any other segmented lines as long as you have an x,y array):
function drawLines(ctx, pts) {
ctx.moveTo(pts[0], pts[1]);
for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);
}
var ctx = document.getElementById("c").getContext("2d");_x000D_
_x000D_
_x000D_
function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {_x000D_
_x000D_
ctx.beginPath();_x000D_
_x000D_
drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));_x000D_
_x000D_
if (showPoints) {_x000D_
ctx.beginPath();_x000D_
for(var i=0;i<ptsa.length-1;i+=2) _x000D_
ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);_x000D_
}_x000D_
_x000D_
ctx.stroke();_x000D_
}_x000D_
_x000D_
_x000D_
var myPoints = [10,10, 40,30, 100,10, 200, 100, 200, 50, 250, 120]; //minimum two points_x000D_
var tension = 1;_x000D_
_x000D_
drawCurve(ctx, myPoints); //default tension=0.5_x000D_
drawCurve(ctx, myPoints, tension);_x000D_
_x000D_
_x000D_
function getCurvePoints(pts, tension, isClosed, numOfSegments) {_x000D_
_x000D_
// use input value if provided, or use a default value _x000D_
tension = (typeof tension != 'undefined') ? tension : 0.5;_x000D_
isClosed = isClosed ? isClosed : false;_x000D_
numOfSegments = numOfSegments ? numOfSegments : 16;_x000D_
_x000D_
var _pts = [], res = [], // clone array_x000D_
x, y, // our x,y coords_x000D_
t1x, t2x, t1y, t2y, // tension vectors_x000D_
c1, c2, c3, c4, // cardinal points_x000D_
st, t, i; // steps based on num. of segments_x000D_
_x000D_
// clone array so we don't change the original_x000D_
//_x000D_
_pts = pts.slice(0);_x000D_
_x000D_
// The algorithm require a previous and next point to the actual point array._x000D_
// Check if we will draw closed or open curve._x000D_
// If closed, copy end points to beginning and first points to end_x000D_
// If open, duplicate first points to befinning, end points to end_x000D_
if (isClosed) {_x000D_
_pts.unshift(pts[pts.length - 1]);_x000D_
_pts.unshift(pts[pts.length - 2]);_x000D_
_pts.unshift(pts[pts.length - 1]);_x000D_
_pts.unshift(pts[pts.length - 2]);_x000D_
_pts.push(pts[0]);_x000D_
_pts.push(pts[1]);_x000D_
}_x000D_
else {_x000D_
_pts.unshift(pts[1]); //copy 1. point and insert at beginning_x000D_
_pts.unshift(pts[0]);_x000D_
_pts.push(pts[pts.length - 2]); //copy last point and append_x000D_
_pts.push(pts[pts.length - 1]);_x000D_
}_x000D_
_x000D_
// ok, lets start.._x000D_
_x000D_
// 1. loop goes through point array_x000D_
// 2. loop goes through each segment between the 2 pts + 1e point before and after_x000D_
for (i=2; i < (_pts.length - 4); i+=2) {_x000D_
for (t=0; t <= numOfSegments; t++) {_x000D_
_x000D_
// calc tension vectors_x000D_
t1x = (_pts[i+2] - _pts[i-2]) * tension;_x000D_
t2x = (_pts[i+4] - _pts[i]) * tension;_x000D_
_x000D_
t1y = (_pts[i+3] - _pts[i-1]) * tension;_x000D_
t2y = (_pts[i+5] - _pts[i+1]) * tension;_x000D_
_x000D_
// calc step_x000D_
st = t / numOfSegments;_x000D_
_x000D_
// calc cardinals_x000D_
c1 = 2 * Math.pow(st, 3) - 3 * Math.pow(st, 2) + 1; _x000D_
c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2); _x000D_
c3 = Math.pow(st, 3) - 2 * Math.pow(st, 2) + st; _x000D_
c4 = Math.pow(st, 3) - Math.pow(st, 2);_x000D_
_x000D_
// calc x and y cords with common control vectors_x000D_
x = c1 * _pts[i] + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;_x000D_
y = c1 * _pts[i+1] + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;_x000D_
_x000D_
//store points in array_x000D_
res.push(x);_x000D_
res.push(y);_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
return res;_x000D_
}_x000D_
_x000D_
function drawLines(ctx, pts) {_x000D_
ctx.moveTo(pts[0], pts[1]);_x000D_
for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);_x000D_
}
_x000D_
canvas { border: 1px solid red; }
_x000D_
<canvas id="c"><canvas>
_x000D_
This results in this:
You can easily extend the canvas so you can call it like this instead:
ctx.drawCurve(myPoints);
Add the following to the javascript:
if (CanvasRenderingContext2D != 'undefined') {
CanvasRenderingContext2D.prototype.drawCurve =
function(pts, tension, isClosed, numOfSegments, showPoints) {
drawCurve(this, pts, tension, isClosed, numOfSegments, showPoints)}
}
You can find a more optimized version of this on NPM (npm i cardinal-spline-js
) or on GitLab.
Not very efficient, but if you must use a list, you can deference the iterator
*myList.begin()+N
Sadly this happens to me quite regularly as well and I use git stash
if I realized my mistake before git commit
and use git cherry-pick
otherwise, both commands are explained pretty well in other answers
I want to add a clarification for git checkout targetBranch
: this command will only preserve your working directory and staged snapshot if targetBranch has the same history as your current branch
If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally
@Amber's statement is not false, when you move to a newBranch,git checkout -b newBranch
, a new pointer is created and it is pointing to the exact same commit as your current branch.
In fact, if you happened to have an another branch that shares history with your current branch (both point at the same commit) you can "move your changes" by git checkout targetBranch
However, usually different branches means different history, and Git will not allow you to switch between these branches with a dirty working directory or staging area. in which case you can either do git checkout -f targetBranch
(clean and throwaway changes) or git stage
+ git checkout targetBranch
(clean and save changes), simply running git checkout targetBranch
will give an error:
error: Your local changes to the following files would be overwritten by checkout: ... Please commit your changes or stash them before you switch branches. Aborting
If I'm not mistaken, C# templates are determined at runtime. This must be slower than compile time templates of C++.
And when you take in all the other compile-time optimizations mentioned by so many others, as well as the lack of safety that does, indeed, mean more speed...
I'd say C++ is the obvious choice in terms of raw speed and minimum memory consumption. But this also translates into more time developing the code and ensuring you aren't leaking memory or causing any null pointer exceptions.
Verdict:
C#: Faster development, slower run
C++: Slow development, faster run.
I find this more elegant than the two top answers:
from urllib.parse import urlencode, urlparse, parse_qs
def merge_url_query_params(url: str, additional_params: dict) -> str:
url_components = urlparse(url)
original_params = parse_qs(url_components.query)
# Before Python 3.5 you could update original_params with
# additional_params, but here all the variables are immutable.
merged_params = {**original_params, **additional_params}
updated_query = urlencode(merged_params, doseq=True)
# _replace() is how you can create a new NamedTuple with a changed field
return url_components._replace(query=updated_query).geturl()
assert merge_url_query_params(
'http://example.com/search?q=question',
{'lang':'en','tag':'python'},
) == 'http://example.com/search?q=question&lang=en&tag=python'
The most important things I dislike in the top answers (they are nevertheless good):
query
is in the URL componentsParseResult
What's bad about my response is the magically looking dict
merge using unpacking, but I prefer that to updating an already existing dictionary because of my prejudice against mutability.
To export data to csv/excel from Kibana follow the following steps:-
Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.
Click on caret symbol (^) which is present at the bottom of the visualization.
Then you will get an option of Export:Raw Formatted as the bottom of the page.
Please find below attached image showing Export option after clicking on caret symbol.
As of version 1.3 there's a service in module ng: $interval
function countController($scope, $interval){
$scope.countDown = 10;
$interval(function(){console.log($scope.countDown--)},1000,0);
}??
Use with caution:
Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.
My requirements were a bit stricter:
My initial thought was to substitute our clunky Path class for a case insensitive unicode subclass - but:
some_dict[CIstr(path)]
is ugly)So I had finally to write down that case insensitive dict. Thanks to code by @AaronHall that was made 10 times easier.
class CIstr(unicode):
"""See https://stackoverflow.com/a/43122305/281545, especially for inlines"""
__slots__ = () # does make a difference in memory performance
#--Hash/Compare
def __hash__(self):
return hash(self.lower())
def __eq__(self, other):
if isinstance(other, CIstr):
return self.lower() == other.lower()
return NotImplemented
def __ne__(self, other):
if isinstance(other, CIstr):
return self.lower() != other.lower()
return NotImplemented
def __lt__(self, other):
if isinstance(other, CIstr):
return self.lower() < other.lower()
return NotImplemented
def __ge__(self, other):
if isinstance(other, CIstr):
return self.lower() >= other.lower()
return NotImplemented
def __gt__(self, other):
if isinstance(other, CIstr):
return self.lower() > other.lower()
return NotImplemented
def __le__(self, other):
if isinstance(other, CIstr):
return self.lower() <= other.lower()
return NotImplemented
#--repr
def __repr__(self):
return '{0}({1})'.format(type(self).__name__,
super(CIstr, self).__repr__())
def _ci_str(maybe_str):
"""dict keys can be any hashable object - only call CIstr if str"""
return CIstr(maybe_str) if isinstance(maybe_str, basestring) else maybe_str
class LowerDict(dict):
"""Dictionary that transforms its keys to CIstr instances.
Adapted from: https://stackoverflow.com/a/39375731/281545
"""
__slots__ = () # no __dict__ - that would be redundant
@staticmethod # because this doesn't make sense as a global function.
def _process_args(mapping=(), **kwargs):
if hasattr(mapping, 'iteritems'):
mapping = getattr(mapping, 'iteritems')()
return ((_ci_str(k), v) for k, v in
chain(mapping, getattr(kwargs, 'iteritems')()))
def __init__(self, mapping=(), **kwargs):
# dicts take a mapping or iterable as their optional first argument
super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
def __getitem__(self, k):
return super(LowerDict, self).__getitem__(_ci_str(k))
def __setitem__(self, k, v):
return super(LowerDict, self).__setitem__(_ci_str(k), v)
def __delitem__(self, k):
return super(LowerDict, self).__delitem__(_ci_str(k))
def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
return type(self)(self)
def get(self, k, default=None):
return super(LowerDict, self).get(_ci_str(k), default)
def setdefault(self, k, default=None):
return super(LowerDict, self).setdefault(_ci_str(k), default)
__no_default = object()
def pop(self, k, v=__no_default):
if v is LowerDict.__no_default:
# super will raise KeyError if no default and key does not exist
return super(LowerDict, self).pop(_ci_str(k))
return super(LowerDict, self).pop(_ci_str(k), v)
def update(self, mapping=(), **kwargs):
super(LowerDict, self).update(self._process_args(mapping, **kwargs))
def __contains__(self, k):
return super(LowerDict, self).__contains__(_ci_str(k))
@classmethod
def fromkeys(cls, keys, v=None):
return super(LowerDict, cls).fromkeys((_ci_str(k) for k in keys), v)
def __repr__(self):
return '{0}({1})'.format(type(self).__name__,
super(LowerDict, self).__repr__())
Implicit vs explicit is still a problem, but once dust settles, renaming of attributes/variables to start with ci (and a big fat doc comment explaining that ci stands for case insensitive) I think is a perfect solution - as readers of the code must be fully aware that we are dealing with case insensitive underlying data structures. This will hopefully fix some hard to reproduce bugs, which I suspect boil down to case sensitivity.
Comments/corrections welcome :)
This is a trick,
function OpenInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.
<div onclick="OpenInNewTab();">Something To Click On</div>
For case-insensitive string search, use index
(or rindex
) in combination with fc
. This example expands on the answer by Eugene Yarmash:
use feature qw( fc );
my $str = "Abc";
my $substr = "aB";
print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found
print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found
$str = "Abc";
$substr = "bA";
print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing
print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing
Both index
and rindex
return -1
if the substring is not found.
And fc
returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc
or lc
. Remember to enable this function, for example with use feature qw( fc );
.
A little late to the party, but answers still took me time and foreign reads to understand this problem. So I want to summarize what I have find out about the Gemfile.lock.
When you are building a Rails App, you are using certain versions of gems in your local machine. If you want to avoid errors in the production mode and other branches, you have to use that one Gemfile.lock file everywhere and tell bundler to bundle
for rebuilding gems every time it changes.
If Gemfile.lock
has changed on your production machine and Git doesn't let you git pull
, you should write git reset --hard
to avoid that file change and write git pull
again.
I would like to suggest DBEAVER .it is based on eclipse and supports better data handling
A Callable is an object that has the __call__
method. This means you can fake callable functions or do neat things like Partial Function Application where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as Currying in functional programming circles).
Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.
[nigel@k9 ~]$ python
Python 2.5 (r25:51908, Nov 6 2007, 15:55:44)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'aaa'() # <== Here we attempt to call a string.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>
Update for the new 64bit arch
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -9223372036854775808
LONG_MAX: 9223372036854775807
ULONG_MAX: 18446744073709551615
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
in pure Ruby:
{:a => 1, :b => 2}.tap{|x| x.delete(:a)} # => {:b=>2}
You must use %ld
to print a long int
, and %lld
to print a long long int
.
Note that only long long int
is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).
You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99
option to gcc). This is because the long long int
type was not introduced until C99; and although many compilers implement long long int
in C90 mode as an extension, the constant 2147483648
may have a type of unsigned int
or unsigned long
in C90. If this is the case in your implementation, then the value of -2147483648
will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.
To open a PDF at page 100 the follow works
<path to Adobe Reader> /A "page=100" "<Path To PDF file>"
If you require more than one argument separate them with &
I use the following in a batch file to open the book I'm reading to the page I was up to.
C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe /A "page=149&pagemode=none" "D:\books\MCTS(70-562) ASP.Net 3.5 Development.pdf"
The best list of command line args for Adobe Reader I have found is here.
http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf
It's for version 7 but all the arguments I tried worked.
As for closing the file, I think you will need to use the SDK, or if you are opening the file from code you could close the file from code once you have finished with it.
Passing null would be better. The full codes is like:
WebView wv = (WebView)this.findViewById(R.id.myWebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadDataWithBaseURL(null, "<html>...</html>", "text/html", "utf-8", null);
The thing is that both the application context and the web application context are registered in the WebApplicationContext during server startup. When you run the test you must explicitly tell which contexts to load.
Try this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})
In Oracle, it is wm_concat
. I believe this function is available in the 10g release and higher.
<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox
<div id="div1" style="display:none;">NOTICE</div>
<script type="text/javascript">
<!--
function showMe (box) {
var chboxs = document.getElementById("div1").style.display;
var vis = "none";
if(chboxs=="none"){
vis = "block"; }
if(chboxs=="block"){
vis = "none"; }
document.getElementById(box).style.display = vis;
}
//-->
</script>
check Robocopy:
ROBOCOPY \\server-source\c$\VMExports\ C:\VMExports\ /E /COPY:DAT
make sure you check what robocopy parameter you want. this is just an example.
type robocopy /?
in a comandline/powershell on your windows system.
You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.
I have code on GitHub which uses System.Windows.Forms
NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs
Here are the summary bits:
Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.
At class-level:
private System.Windows.Forms.NotifyIcon notifyIcon = null;
During OnInitialize():
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];
During OnLoaded():
notifyIcon.Visible = true;
And for interaction (shown as notifyIcon.Click and DoubleClick above):
void notifyIcon_Click(object sender, EventArgs e)
{
ShowQuickLaunchMenu();
}
From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.
It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.
Hope that helps.
It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.
In PHP, use random_bytes()
. Reason: your are seeking the way to get a password reminder token, and, if it is a one-time login credentials, then you actually have a data to protect (which is - whole user account)
So, the code will be as follows:
//$length = 78 etc
$token = bin2hex(random_bytes($length));
Update: previous versions of this answer was referring to uniqid()
and that is incorrect if there is a matter of security and not only uniqueness. uniqid()
is essentially just microtime()
with some encoding. There are simple ways to get accurate predictions of the microtime()
on your server. An attacker can issue a password reset request and then try through a couple of likely tokens. This is also possible if more_entropy is used, as the additional entropy is similarly weak. Thanks to @NikiC and @ScottArciszewski for pointing this out.
For more details see
I found a solution why R.class is not made by Eclipse after making it again - 2 clean, build, etc.
The problem is here in strings.xml:
<string name="hello">Hello World, HelloAutoComplete!</string>
<string name="app_name">HelloAutoComplete</string>
These are by default created by Eclipse when you create projects.
Definitely you are changing the strings.xml for your own requirement. Sometimes you clear the string.xmls these two lines from your code:
It is making a problem in the AndroidManifest.xml file:
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HelloAutoComplete" android:label="@string/app_name">
So it can't communicate with strings.xml.
This is in the case if first answer does not work The latest version of git does not require to set proxy it directly uses system proxy settings .so just do these
unset HTTP_PROXY
unset HTTPS_PROXY
in some systems you may also have to do
unset http_proxy
unset https_proxy
if you want to permanantly remove proxy then
sudo gsettings set org.gnome.system.proxy mode 'none'
Be aware that some browser extensions can add code to the pages. In my case I had an "Emmet in all textareas" plugin that messed up with my requireJs. Make sure that no extra code is beign added to your document by inspecting it in the browser.
If you want to do this the C++ way, do it like this:
#include <fstream>
#include <iterator>
#include <algorithm>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
std::ofstream output( "C:\\myfile.gif", std::ios::binary );
std::copy(
std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>( ),
std::ostreambuf_iterator<char>(output));
}
If you need that data in a buffer to modify it or something, do this:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
// copies all data into buffer
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
}
Here's my modified version of lehelk.com's version that also removes html entites that are accents :
http://jsfiddle.net/billybraga/UHmnf/
I still don't know about performance, though...
var defaultDiacriticsRemovalMap = [{
'base': "A",
'letters': /(A|Ⓐ|A|À|Á|Â|Ầ|Ấ|Ẫ|Ẩ|Ã|Ā|Ă|Ằ|Ắ|Ẵ|Ẳ|Ȧ|Ǡ|Ä|Ǟ|Ả|Å|Ǻ|Ǎ|Ȁ|Ȃ|Ạ|Ậ|Ặ|Ḁ|Ą|Ⱥ|Ɐ|[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F])/g},
{
'base': "AA",
'letters': /(Ꜳ|[\uA732])/g},
{
'base': "AE",
'letters': /(Æ|Ǽ|Ǣ|[\u00C6\u01FC\u01E2])/g},
{
'base': "AO",
'letters': /(Ꜵ|[\uA734])/g},
{
'base': "AU",
'letters': /(Ꜷ|[\uA736])/g},
{
'base': "AV",
'letters': /(Ꜹ|Ꜻ|[\uA738\uA73A])/g},
{
'base': "AY",
'letters': /(Ꜽ|[\uA73C])/g},
{
'base': "B",
'letters': /(B|Ⓑ|B|Ḃ|Ḅ|Ḇ|Ƀ|Ƃ|Ɓ|[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181])/g},
{
'base': "C",
'letters': /(C|Ⓒ|C|Ć|Ĉ|Ċ|Č|Ç|Ḉ|Ƈ|Ȼ|Ꜿ|[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E])/g},
{
'base': "D",
'letters': /(D|Ⓓ|D|Ḋ|Ď|Ḍ|Ḑ|Ḓ|Ḏ|Đ|Ƌ|Ɗ|Ɖ|Ꝺ|[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779])/g},
{
'base': "DZ",
'letters': /(DZ|DŽ|[\u01F1\u01C4])/g},
{
'base': "Dz",
'letters': /(Dz|Dž|[\u01F2\u01C5])/g},
{
'base': "E",
'letters': /(E|Ⓔ|E|È|É|Ê|Ề|Ế|Ễ|Ể|Ẽ|Ē|Ḕ|Ḗ|Ĕ|Ė|Ë|Ẻ|Ě|Ȅ|Ȇ|Ẹ|Ệ|Ȩ|Ḝ|Ę|Ḙ|Ḛ|Ɛ|Ǝ|[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E])/g},
{
'base': "F",
'letters': /(F|Ⓕ|F|Ḟ|Ƒ|Ꝼ|[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B])/g},
{
'base': "G",
'letters': /(G|Ⓖ|G|Ǵ|Ĝ|Ḡ|Ğ|Ġ|Ǧ|Ģ|Ǥ|Ɠ|Ꞡ|Ᵹ|Ꝿ|[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E])/g},
{
'base': "H",
'letters': /(H|Ⓗ|H|Ĥ|Ḣ|Ḧ|Ȟ|Ḥ|Ḩ|Ḫ|Ħ|Ⱨ|Ⱶ|Ɥ|[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D])/g},
{
'base': "I",
'letters': /(I|Ⓘ|I|Ì|Í|Î|Ĩ|Ī|Ĭ|İ|Ï|Ḯ|Ỉ|Ǐ|Ȉ|Ȋ|Ị|Į|Ḭ|Ɨ|[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197])/g},
{
'base': "J",
'letters': /(J|Ⓙ|J|Ĵ|Ɉ|[\u004A\u24BF\uFF2A\u0134\u0248])/g},
{
'base': "K",
'letters': /(K|Ⓚ|K|Ḱ|Ǩ|Ḳ|Ķ|Ḵ|Ƙ|Ⱪ|Ꝁ|Ꝃ|Ꝅ|Ꞣ|[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2])/g},
{
'base': "L",
'letters': /(L|Ⓛ|L|Ŀ|Ĺ|Ľ|Ḷ|Ḹ|Ļ|Ḽ|Ḻ|Ł|Ƚ|Ɫ|Ⱡ|Ꝉ|Ꝇ|Ꞁ|[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780])/g},
{
'base': "LJ",
'letters': /(LJ|[\u01C7])/g},
{
'base': "Lj",
'letters': /(Lj|[\u01C8])/g},
{
'base': "M",
'letters': /(M|Ⓜ|M|Ḿ|Ṁ|Ṃ|Ɱ|Ɯ|[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C])/g},
{
'base': "N",
'letters': /(N|Ⓝ|N|Ǹ|Ń|Ñ|Ṅ|Ň|Ṇ|Ņ|Ṋ|Ṉ|Ƞ|Ɲ|Ꞑ|Ꞥ|[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4])/g},
{
'base': "NJ",
'letters': /(NJ|[\u01CA])/g},
{
'base': "Nj",
'letters': /(Nj|[\u01CB])/g},
{
'base': "O",
'letters': /(O|Ⓞ|O|Ò|Ó|Ô|Ồ|Ố|Ỗ|Ổ|Õ|Ṍ|Ȭ|Ṏ|Ō|Ṑ|Ṓ|Ŏ|Ȯ|Ȱ|Ö|Ȫ|Ỏ|Ő|Ǒ|Ȍ|Ȏ|Ơ|Ờ|Ớ|Ỡ|Ở|Ợ|Ọ|Ộ|Ǫ|Ǭ|Ø|Ǿ|Ɔ|Ɵ|Ꝋ|Ꝍ|[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C])/g},
{
'base': "OI",
'letters': /(Ƣ|[\u01A2])/g},
{
'base': "OO",
'letters': /(Ꝏ|[\uA74E])/g},
{
'base': "OU",
'letters': /(Ȣ|[\u0222])/g},
{
'base': "P",
'letters': /(P|Ⓟ|P|Ṕ|Ṗ|Ƥ|Ᵽ|Ꝑ|Ꝓ|Ꝕ|[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754])/g},
{
'base': "Q",
'letters': /(Q|Ⓠ|Q|Ꝗ|Ꝙ|Ɋ|[\u0051\u24C6\uFF31\uA756\uA758\u024A])/g},
{
'base': "R",
'letters': /(R|Ⓡ|R|Ŕ|Ṙ|Ř|Ȑ|Ȓ|Ṛ|Ṝ|Ŗ|Ṟ|Ɍ|Ɽ|Ꝛ|Ꞧ|Ꞃ|[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782])/g},
{
'base': "S",
'letters': /(S|Ⓢ|S|ẞ|Ś|Ṥ|Ŝ|Ṡ|Š|Ṧ|Ṣ|Ṩ|Ș|Ş|Ȿ|Ꞩ|Ꞅ|[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784])/g},
{
'base': "T",
'letters': /(T|Ⓣ|T|Ṫ|Ť|Ṭ|Ț|Ţ|Ṱ|Ṯ|Ŧ|Ƭ|Ʈ|Ⱦ|Ꞇ|[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786])/g},
{
'base': "TZ",
'letters': /(Ꜩ|[\uA728])/g},
{
'base': "U",
'letters': /(U|Ⓤ|U|Ù|Ú|Û|Ũ|Ṹ|Ū|Ṻ|Ŭ|Ü|Ǜ|Ǘ|Ǖ|Ǚ|Ủ|Ů|Ű|Ǔ|Ȕ|Ȗ|Ư|Ừ|Ứ|Ữ|Ử|Ự|Ụ|Ṳ|Ų|Ṷ|Ṵ|Ʉ|[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244])/g},
{
'base': "V",
'letters': /(V|Ⓥ|V|Ṽ|Ṿ|Ʋ|Ꝟ|Ʌ|[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245])/g},
{
'base': "VY",
'letters': /(Ꝡ|[\uA760])/g},
{
'base': "W",
'letters': /(W|Ⓦ|W|Ẁ|Ẃ|Ŵ|Ẇ|Ẅ|Ẉ|Ⱳ|[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72])/g},
{
'base': "X",
'letters': /(X|Ⓧ|X|Ẋ|Ẍ|[\u0058\u24CD\uFF38\u1E8A\u1E8C])/g},
{
'base': "Y",
'letters': /(Y|Ⓨ|Y|Ỳ|Ý|Ŷ|Ỹ|Ȳ|Ẏ|Ÿ|Ỷ|Ỵ|Ƴ|Ɏ|Ỿ|[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE])/g},
{
'base': "Z",
'letters': /(Z|Ⓩ|Z|Ź|Ẑ|Ż|Ž|Ẓ|Ẕ|Ƶ|Ȥ|Ɀ|Ⱬ|Ꝣ|[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762])/g},
{
'base': "a",
'letters': /(a|ⓐ|a|ẚ|à|á|â|ầ|ấ|ẫ|ẩ|ã|ā|ă|ằ|ắ|ẵ|ẳ|ȧ|ǡ|ä|ǟ|ả|å|ǻ|ǎ|ȁ|ȃ|ạ|ậ|ặ|ḁ|ą|ⱥ|ɐ|[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250])/g},
{
'base': "aa",
'letters': /(ꜳ|[\uA733])/g},
{
'base': "ae",
'letters': /(æ|ǽ|ǣ|[\u00E6\u01FD\u01E3])/g},
{
'base': "ao",
'letters': /(ꜵ|[\uA735])/g},
{
'base': "au",
'letters': /(ꜷ|[\uA737])/g},
{
'base': "av",
'letters': /(ꜹ|ꜻ|[\uA739\uA73B])/g},
{
'base': "ay",
'letters': /(ꜽ|[\uA73D])/g},
{
'base': "b",
'letters': /(b|ⓑ|b|ḃ|ḅ|ḇ|ƀ|ƃ|ɓ|[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253])/g},
{
'base': "c",
'letters': /(c|ⓒ|c|ć|ĉ|ċ|č|ç|ḉ|ƈ|ȼ|ꜿ|ↄ|[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184])/g},
{
'base': "d",
'letters': /(d|ⓓ|d|ḋ|ď|ḍ|ḑ|ḓ|ḏ|đ|ƌ|ɖ|ɗ|ꝺ|[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A])/g},
{
'base': "dz",
'letters': /(dz|dž|[\u01F3\u01C6])/g},
{
'base': "e",
'letters': /(e|ⓔ|e|è|é|ê|ề|ế|ễ|ể|ẽ|ē|ḕ|ḗ|ĕ|ė|ë|ẻ|ě|ȅ|ȇ|ẹ|ệ|ȩ|ḝ|ę|ḙ|ḛ|ɇ|ɛ|ǝ|[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD])/g},
{
'base': "f",
'letters': /(f|ⓕ|f|ḟ|ƒ|ꝼ|[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C])/g},
{
'base': "g",
'letters': /(g|ⓖ|g|ǵ|ĝ|ḡ|ğ|ġ|ǧ|ģ|ǥ|ɠ|ꞡ|ᵹ|ꝿ|[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F])/g},
{
'base': "h",
'letters': /(h|ⓗ|h|ĥ|ḣ|ḧ|ȟ|ḥ|ḩ|ḫ|ẖ|ħ|ⱨ|ⱶ|ɥ|[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265])/g},
{
'base': "hv",
'letters': /(ƕ|[\u0195])/g},
{
'base': "i",
'letters': /(i|ⓘ|i|ì|í|î|ĩ|ī|ĭ|ï|ḯ|ỉ|ǐ|ȉ|ȋ|ị|į|ḭ|ɨ|ı|[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131])/g},
{
'base': "j",
'letters': /(j|ⓙ|j|ĵ|ǰ|ɉ|[\u006A\u24D9\uFF4A\u0135\u01F0\u0249])/g},
{
'base': "k",
'letters': /(k|ⓚ|k|ḱ|ǩ|ḳ|ķ|ḵ|ƙ|ⱪ|ꝁ|ꝃ|ꝅ|ꞣ|[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3])/g},
{
'base': "l",
'letters': /(l|ⓛ|l|ŀ|ĺ|ľ|ḷ|ḹ|ļ|ḽ|ḻ|ſ|ł|ƚ|ɫ|ⱡ|ꝉ|ꞁ|ꝇ|[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747])/g},
{
'base': "lj",
'letters': /(lj|[\u01C9])/g},
{
'base': "m",
'letters': /(m|ⓜ|m|ḿ|ṁ|ṃ|ɱ|ɯ|[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F])/g},
{
'base': "n",
'letters': /(n|ⓝ|n|ǹ|ń|ñ|ṅ|ň|ṇ|ņ|ṋ|ṉ|ƞ|ɲ|ʼn|ꞑ|ꞥ|[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5])/g},
{
'base': "nj",
'letters': /(nj|[\u01CC])/g},
{
'base': "o",
'letters': /(o|ⓞ|o|ò|ó|ô|ồ|ố|ỗ|ổ|õ|ṍ|ȭ|ṏ|ō|ṑ|ṓ|ŏ|ȯ|ȱ|ö|ȫ|ỏ|ő|ǒ|ȍ|ȏ|ơ|ờ|ớ|ỡ|ở|ợ|ọ|ộ|ǫ|ǭ|ø|ǿ|ɔ|ꝋ|ꝍ|ɵ|[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275])/g},
{
'base': "oi",
'letters': /(ƣ|[\u01A3])/g},
{
'base': "ou",
'letters': /(ȣ|[\u0223])/g},
{
'base': "oo",
'letters': /(ꝏ|[\uA74F])/g},
{
'base': "p",
'letters': /(p|ⓟ|p|ṕ|ṗ|ƥ|ᵽ|ꝑ|ꝓ|ꝕ|[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755])/g},
{
'base': "q",
'letters': /(q|ⓠ|q|ɋ|ꝗ|ꝙ|[\u0071\u24E0\uFF51\u024B\uA757\uA759])/g},
{
'base': "r",
'letters': /(r|ⓡ|r|ŕ|ṙ|ř|ȑ|ȓ|ṛ|ṝ|ŗ|ṟ|ɍ|ɽ|ꝛ|ꞧ|ꞃ|[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783])/g},
{
'base': "s",
'letters': /(s|ⓢ|s|ß|ś|ṥ|ŝ|ṡ|š|ṧ|ṣ|ṩ|ș|ş|ȿ|ꞩ|ꞅ|ẛ|[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B])/g},
{
'base': "t",
'letters': /(t|ⓣ|t|ṫ|ẗ|ť|ṭ|ț|ţ|ṱ|ṯ|ŧ|ƭ|ʈ|ⱦ|ꞇ|[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787])/g},
{
'base': "tz",
'letters': /(ꜩ|[\uA729])/g},
{
'base': "u",
'letters': /(u|ⓤ|u|ù|ú|û|ũ|ṹ|ū|ṻ|ŭ|ü|ǜ|ǘ|ǖ|ǚ|ủ|ů|ű|ǔ|ȕ|ȗ|ư|ừ|ứ|ữ|ử|ự|ụ|ṳ|ų|ṷ|ṵ|ʉ|[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289])/g},
{
'base': "v",
'letters': /(v|ⓥ|v|ṽ|ṿ|ʋ|ꝟ|ʌ|[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C])/g},
{
'base': "vy",
'letters': /(ꝡ|[\uA761])/g},
{
'base': "w",
'letters': /(w|ⓦ|w|ẁ|ẃ|ŵ|ẇ|ẅ|ẘ|ẉ|ⱳ|[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73])/g},
{
'base': "x",
'letters': /(x|ⓧ|x|ẋ|ẍ|[\u0078\u24E7\uFF58\u1E8B\u1E8D])/g},
{
'base': "y",
'letters': /(y|ⓨ|y|ỳ|ý|ŷ|ỹ|ȳ|ẏ|ÿ|ỷ|ẙ|ỵ|ƴ|ɏ|ỿ|[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF])/g},
{
'base': "z",
'letters': /(z|ⓩ|z|ź|ẑ|ż|ž|ẓ|ẕ|ƶ|ȥ|ɀ|ⱬ|ꝣ|[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763])/g}];
function removeDiacritics(str) {
for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base);
}
return str;
}
Yes, it's OK - it's just like using it in an if
statement. Of course, you can't use a break
to break out of a loop from inside a switch.
We are use modal form with BackgroundWorker
for such a thing.
Here is quick solution:
public class ProgressWorker<TArgument> : BackgroundWorker where TArgument : class
{
public Action<TArgument> Action { get; set; }
protected override void OnDoWork(DoWorkEventArgs e)
{
if (Action!=null)
{
Action(e.Argument as TArgument);
}
}
}
public sealed partial class ProgressDlg<TArgument> : Form where TArgument : class
{
private readonly Action<TArgument> action;
public Exception Error { get; set; }
public ProgressDlg(Action<TArgument> action)
{
if (action == null) throw new ArgumentNullException("action");
this.action = action;
//InitializeComponent();
//MaximumSize = Size;
MaximizeBox = false;
Closing += new System.ComponentModel.CancelEventHandler(ProgressDlg_Closing);
}
public string NotificationText
{
set
{
if (value!=null)
{
Invoke(new Action<string>(s => Text = value));
}
}
}
void ProgressDlg_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
FormClosingEventArgs args = (FormClosingEventArgs)e;
if (args.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
}
}
private void ProgressDlg_Load(object sender, EventArgs e)
{
}
public void RunWorker(TArgument argument)
{
System.Windows.Forms.Application.DoEvents();
using (var worker = new ProgressWorker<TArgument> {Action = action})
{
worker.RunWorkerAsync();
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
ShowDialog();
}
}
void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Error = e.Error;
DialogResult = DialogResult.Abort;
return;
}
DialogResult = DialogResult.OK;
}
}
And how we use it:
var dlg = new ProgressDlg<string>(obj =>
{
//DoWork()
Thread.Sleep(10000);
MessageBox.Show("Background task completed "obj);
});
dlg.RunWorker("SampleValue");
if (dlg.Error != null)
{
MessageBox.Show(dlg.Error.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
dlg.Dispose();
This is how Adding new column to Table
ALTER TABLE [tableName]
ADD ColumnName Datatype
E.g
ALTER TABLE [Emp]
ADD Sr_No Int
And If you want to make it auto incremented
ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL
When you assign a variable to empty curly braces {} eg: new_set = {}
, it becomes a dictionary.
To create an empty set, assign the variable to a 'set()' ie: new_set = set()
Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.
Actually there is another (maybe better solution) where you can use the angular's native 'filter' filter and still pass arguments to your custom filter.
Consider the following code:
<div ng-repeat="group in groups">
<li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
<span>{{friend.name}}</span>
<li>
</div>
To make this work you just define your filter as the following:
$scope.weDontLike = function(name) {
return function(friend) {
return friend.name != name;
}
}
As you can see here, weDontLike actually returns another function which has your parameter in its scope as well as the original item coming from the filter.
It took me 2 days to realise you can do this, haven't seen this solution anywhere yet.
Checkout Reverse polarity of an angular.js filter to see how you can use this for other useful operations with filter.
The problem with many solutions is they only find the next "GAP", while ignoring if "1" is available, or if there aren't any rows they'll return NULL as the next "GAP".
The following will not only find the next available gap, it'll also take into account if the first available number is 1:
SELECT CASE WHEN MIN(MyID) IS NULL OR MIN(MyID)>1
-- return 1 if it's available or if there are no rows yet
THEN
1
ELSE -- find next gap
(SELECT MIN(t.MyID)+1
FROM MyTable t (updlock)
WHERE NOT EXISTS (SELECT NULL FROM MyTable n WHERE n.MyID=t.MyID+1))
END AS NextID
FROM MyTable
first login on git then before push take the pull. issue will be resolved
You can Use Sql Server Integration Service Packages specifically designed for Import and Export operation.
VS has a package for developing these packages if your fully install Sql Server.
Integration Services in Business Intelligence Development Studio
@ManyToMany
associationsMost often, you will need to use @JoinTable
annotation to specify the mapping of a many-to-many table relationship:
So, assuming you have the following database tables:
In the Post
entity, you would map this relationship, like this:
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(
name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();
The @JoinTable
annotation is used to specify the table name via the name
attribute, as well as the Foreign Key column that references the post
table (e.g., joinColumns
) and the Foreign Key column in the post_tag
link table that references the Tag
entity via the inverseJoinColumns
attribute.
Notice that the cascade attribute of the
@ManyToMany
annotation is set toPERSIST
andMERGE
only because cascadingREMOVE
is a bad idea since we the DELETE statement will be issued for the other parent record,tag
in our case, not to thepost_tag
record.
@OneToMany
associationsThe unidirectional @OneToMany
associations, that lack a @JoinColumn
mapping, behave like many-to-many table relationships, rather than one-to-many.
So, assuming you have the following entity mappings:
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
//Constructors, getters and setters removed for brevity
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
@Id
@GeneratedValue
private Long id;
private String review;
//Constructors, getters and setters removed for brevity
}
Hibernate will assume the following database schema for the above entity mapping:
As already explained, the unidirectional @OneToMany
JPA mapping behaves like a many-to-many association.
To customize the link table, you can also use the @JoinTable
annotation:
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
@JoinTable(
name = "post_comment_ref",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "post_comment_id")
)
private List<PostComment> comments = new ArrayList<>();
And now, the link table is going to be called post_comment_ref
and the Foreign Key columns will be post_id
, for the post
table, and post_comment_id
, for the post_comment
table.
Unidirectional
@OneToMany
associations are not efficient, so you are better off using bidirectional@OneToMany
associations or just the@ManyToOne
side.
Using the visibility
property only affects the visibility of the elements on the page; they will still be there in the page layout. To completely remove the elements from the page, use the display
property.
display:none // for hiding
display:block // for showing
Make sure to change your css file to use display instead of visibility too.
As for the javascript (this is not jQuery), make sure you hide the options by default when the page loads:
<script type="text/javascript">
window.onload = function() {
document.getElementById('ifYes').style.display = 'none';
}
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
}
else {
document.getElementById('ifYes').style.display = 'none';
}
}
</script>
If you haven't done so already, I would recommend taking a look at jQuery. jQuery code is much clearer and easier to write and understand.
Use rgba as most of the commonly used browsers supports it..
.social img:hover {
background-color: rgba(0, 0, 0, .5)
}
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class ImageButton extends Button {
public void updateImages(final Image selected, final Image unselected) {
final ImageView iv = new ImageView(selected);
this.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(unselected);
}
});
iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(selected);
}
});
super.setGraphic(iv);
}
}
pickle
module is part of the standard library in Python for a very long time now so there is no need to install it via pip
. I wonder if you IDE or command line is not messed up somehow so that it does not find python installation path. Please check if your %PATH%
contains a path to python (e.g. C:\Python36\
or something similar) or if your IDE correctly detects root path where Python is installed.
Actually you dont need to call document.getElementById()
function to get access to your div
.
You can use this object
directly by id
:
text = test.textContent || test.innerText;
alert(text);
For the bootstrap 4 beta were some big changes between the alpha and beta versions of bootstrap (and also bootstrap 3), esp. in regards to form validation.
First, to place the icons correctly you'll need to add styling which equates to what was in bootstrap 3 and no longer in bootstrap 4 beta...here's what I'm using
.fa.valid-feedback,
.fa.invalid-feedback {
position: absolute;
right: 25px;
margin-top: -50px;
z-index: 2;
display: block;
pointer-events: none;
}
.fa.valid-feedback {
margin-top: -28px;
}
The classes have also changed as the beta uses the 'state' of the control rather than classes which your posted code doesn't reflect, so your above code may not work. Anyway, you'll need to add 'was-validated' class to the form either in the success or highlight/unhighlight callbacks
$(element).closest('form').addClass('was-validated');
I would also recommend using the new element and classes for form control help text
errorElement: 'small',
errorClass: 'form-text invalid-feedback',
Put all the 6 classes to 6 different projects. Then create jar files of all the 6 projects. In this manner you will get 6 executable jar files.
You can use something of the form
s.decode('utf-8')
which will convert a UTF-8 encoded bytestring into a Python Unicode string. But the exact procedure to use depends on exactly how you load and parse the XML file, e.g. if you don't ever access the XML string directly, you might have to use a decoder object from the codecs
module.
Hers's what I used to get the day names (0-6
means monday - sunday
):
public static String getFullDayName(int day) {
Calendar c = Calendar.getInstance();
// date doesn't matter - it has to be a Monday
// I new that first August 2011 is one ;-)
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%tA", c);
}
public static String getShortDayName(int day) {
Calendar c = Calendar.getInstance();
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%ta", c);
}
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
You don't need negative lookahead. There is working example:
/([\s\S]*?)(red|green|blue|)/g
Description:
[\s\S]
- match any character*
- match from 0 to unlimited from previous group?
- match as less as possible(red|green|blue|)
- match one of this words or nothingg
- repeat patternExample:
whiteredwhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredgreenbluewhiteredwhiteredwhiteredwhiteredwhiteredwhiteredgreenbluewhiteredwhiteredwhiteredwhiteredwhiteredredgreenredgreenredgreenredgreenredgreenbluewhiteredbluewhiteredbluewhiteredbluewhiteredbluewhiteredwhite
Will be:
whitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhite
Test it: regex101.com
Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.
Simplest way to get the selected radio button's value is as follows:
$("input[name='optradio']:checked").val();
No space should be used in between selector.
In Webdriver, you should use driver.switchTo().defaultContent();
to get out of a frame.
You need to get out of all the frames first, then switch into outer frame again.
// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click();
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
There isn't a last()
or first()
method in a Collection interface. For getting the last method, you can either do get(size() - 1)
on a List or reverse the List and do get(0)
. I don't see a need to have last()
method in any Collection API unless you are dealing with Stacks
or Queues
When using Webpack you need to require
images in order for Webpack to process them, which would explain why external images load while internal do not, so instead of <img src={"/images/resto.png"} />
you need to use <img src={require('/images/image-name.png')} />
replacing image-name.png with the correct image name for each of them. That way Webpack is able to process and replace the source img.
select advanced options when Write a message, and choose sound activated
this is My solution
I suggest this one:
if [ "$a" = "$b" ]
Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.
Also, be careful of your script header. It's not the same thing whether you use
#!/bin/bash
or
#!/bin/sh
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')
# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.
I tried the most popular answers on this page but ran into an issue: the node_modules
directory in my Docker instance would get cached in the the named or unnamed mount point, and later would overwrite the node_modules
directory that was built as part of the Docker build process. Thus, new modules I added to package.json
would not show up in the Docker instance.
Fortunately I found this excellent page which explains what was going on and gives at least 3 ways to work around it: https://burnedikt.com/dockerized-node-development-and-mounting-node-volumes/
I believe this should also do the job too:
background-size: contain;
It specifies that the image should be resized to fit within the element without losing it's aspect ratio.
Presence of int k;
in the header file causes symbol k
to be defined within each translation unit this header is included to while linker expects it to be defined only once (aka One Definition Rule Violation).
While suggestion involving extern
are not wrong, extern
is a C-ism and should not be used.
Pre C++17 solution that would allow variable in header file to be defined in multiple translation units without causing ODR violation would be conversion to template:
template<typename x_Dummy = void> class
t_HeaderVariableHolder
{
public: static int s_k;
};
template<typename x_Dummy> int t_HeaderVariableHolder<x_Dummy>::s_k{};
// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
return t_HeaderVariableHolder<>::s_k;
}
With C++17 things become much simpler as it allows inline
variables:
inline int g_k{};
// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
return g_k;
}
WARNING: Do not run this on a production machine.
On a Linux box:
redis-cli KEYS "*" | wc -l
Note: As mentioned in comments below, this is an O(N) operation, so on a large DB with many keys you should not use this. For smaller deployments, it should be fine.
Assuming we are using Jupyter Notebook (if using Terminal, drop the exclamation marks):
1) if the package (e.g. xgboost) was installed with pip:
!pip show xgboost
!pip freeze | grep xgboost
!pip list | grep xgboost
2) if the package (e.g. caffe) was installed with conda:
!conda list caffe
public function getdata(){
$this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
$this->db->from('tblmaster t');
$this->db->join('country c', 't.country=c.country_id');
$this->db->join('state s', 't.state=s.state_id');
$this->db->join('city ct', 't.city=ct.city_id');
$this->db->order_by('t.id','desc');
$query = $this->db->get();
return $query->result();
}
This is something I always wanted, especially while setting up test fixtures. Finally, I decided to write a simple fluent builder of my own that could build any Map implementation - https://gist.github.com/samshu/b471f5a2925fa9d9b718795d8bbdfe42#file-mapbuilder-java
/**
* @param mapClass Any {@link Map} implementation type. e.g., HashMap.class
*/
public static <K, V> MapBuilder<K, V> builder(@SuppressWarnings("rawtypes") Class<? extends Map> mapClass)
throws InstantiationException,
IllegalAccessException {
return new MapBuilder<K, V>(mapClass);
}
public MapBuilder<K, V> put(K key, V value) {
map.put(key, value);
return this;
}
public Map<K, V> build() {
return map;
}
Add this class to your css file to override the bootstrap class.modal-header
.modal-header {
background:#0480be;
}
It's important try to never edit Bootstrap CSS, in order to be able to update from the repo and not loose the changes made or break something in futures releases.
Assuming you're using docker-compose, where your docker-compose.yml
file looks like:
version: '3.7'
services:
mysql_db_container:
image: mysql:latest
command: --default-authentication-plugin=mysql_native_password
environment:
MYSQL_ROOT_PASSWORD: rootpassword
ports:
- 3307:3306
volumes:
- mysql_db_data_container:/var/lib/mysql
web:
image: ${DOCKER_IMAGE_NAME-eis}:latest
build:
context: .
links:
- mysql_db_container
ports:
- 4000:3000
command: ["./scripts/wait-for-it.sh", "mysql_db_container:3306", "--", "./scripts/start_web_server.sh"]
volumes:
- .:/opt/eis:cached
env_file:
- .env
volumes:
mysql_db_data_container:
Notice the ports
definition for mysql_db_container
ports:
- 3307:3306
<= That indicates that mysql will be accessible via port 3307 to the localhost workstation and via port 3306 within the docker net
Run the following to see your container names:
$ dc config --services
mysql_db_container
web
In this case, we have two containers.
If you connect to mysql_db_container
from your localhost workstation and try to access the mysql console there, you'll get that error:
docker-compose run mysql_db_container bash
root@8880ffe47962:/# mysql -u root -p
Enter password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
root@8880ffe47962:/# exit
Also, if you try to connect from your local workstation, you'll also get that error:
$ mysql -u root -p -P 3307
Enter password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Just add the --protocol=tcp
parameter (otherwise mysql assumes you want to connect via the mysql socket):
$ mysql --protocol=tcp -u root -p -P 3307
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.21 MySQL Community Server - GPL
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Reference the docker hostname -h mysql_db_container
. Note that when you're running within the context of Docker that the TCP protocol is assumed.
$ dc run web bash
Starting eligibility-service_mysql_db_container_1_d625308b5a77 ... done
root@e7852ff02683:/opt/eis# mysql -h mysql_db_container -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 18
Server version: 8.0.21 MySQL Community Server - GPL
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
Assuming your mysql container name is eis_mysql_db_container_1_d625308b5a77
(that you can see when running docker ps
), the following should work:
$ docker exec -it eis_mysql_db_container_1_d625308b5a77 bash
root@3738cf6eb3e9:/# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.21 MySQL Community Server - GPL
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Simply specify the regexp anchors.
grep '^ABB\.log$' a.tmp
If you want to redirect from a button in the View you could use:
@Html.ActionLink("Back to previous page", null, null, null, new { href = Request.UrlReferrer})
I think there can be several situations that cause the jerking. In my example, the issue deals with bottom margin on the non-animated child (even though the animated parent has no margin / padding). When removing the margin, the animation becomes smooth.
<div class="form-group">
<a for="collapseJerky" data-toggle="collapse" href="#collapseJerky" aria-expanded="true" aria-controls="collapseJerky">+ Jerky</a>
<div class="collapse" id="collapseJerky" style="margin:0; padding: 0;">
<textarea class="form-control" rows="4" style="margin-bottom: 20px;">No margin or padding on animated element. Margin on child.</textarea>
</div>
</div>
<div class="form-group">
<a data-toggle="collapse" href="#collapseNotJerky" aria-expanded="true" aria-controls="collapseNotJerky">+ Not Jerky</a>
<div class="collapse" id="collapseNotJerky" style="margin:0 padding: 0;">
<textarea class="form-control" rows="4" style="margin-bottom: 0;">No margin or padding on animated element or on child.</textarea>
</div>
</div>
<p>
Moles and trolls, moles and trolls, work, work, work, work, work. We never see the light of day. This is just content below the "Not Jerky" to show that the animation is smooth.
</p>
You could also use a CTE to grab groups of information you want and join them together, if you wanted them in the same row. Example, depending on which SQL syntax you use, here:
WITH group1 AS (
SELECT testA
FROM tableA
),
group2 AS (
SELECT testB
FROM tableB
)
SELECT *
FROM group1
JOIN group2 ON group1.testA = group2.testB --your choice of join
;
You decide what kind of JOIN you want based on the data you are pulling, and make sure to have the same fields in the groups you are getting information from in order to put it all into a single row. If you have multiple columns, make sure to name them all properly so you know which is which. Also, for performance sake, CTE's are the way to go, instead of inline SELECT's and such. Hope this helps.
You must create your own SSLSocketFactory based on Bouncy Castle. After to use it, pass to the common HttpsConnextion for using this customized SocketFactory.
1. First : Create a TLSConnectionFactory
Here one tips:
1.1 Extend SSLConnectionFactory
1.2 Override this method :
@Override
public Socket createSocket(Socket socket, final String host, int port, boolean arg3)
This method will call the next internal method,
1.3 Implement an internal method _createSSLSocket(host, tlsClientProtocol);
Here you must create a Socket using TlsClientProtocol . The trick is override ...startHandshake() method calling TlsClientProtocol
private SSLSocket _createSSLSocket(final String host , final TlsClientProtocol tlsClientProtocol) {
return new SSLSocket() {
.... Override and implement SSLSocket methods, particulary:
startHandshake() {
}
}
Important : The full sample how to use TLS Client Protocol is well explained here: Using BouncyCastle for a simple HTTPS query
2. Second : Use this Customized SSLConnextionFactory on common HTTPSConnection.
This is important ! In other samples you can see into the web , u see hard-coded HTTP Commands....so with a customized SSLConnectionFactory u don't need nothing more...
URL myurl = new URL( "http:// ...URL tha only Works in TLS 1.2);
HttpsURLConnection con = (HttpsURLConnection )myurl.openConnection();
con.setSSLSocketFactory(new TSLSocketConnectionFactory());
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
I slightly modified and repaired solution from Thomas Fankhauser
Whole system consists from two files, SwipeInterface and ActivitySwipeDetector
SwipeInterface.java
import android.view.View;
public interface SwipeInterface {
public void bottom2top(View v);
public void left2right(View v);
public void right2left(View v);
public void top2bottom(View v);
}
Detector
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class ActivitySwipeDetector implements View.OnTouchListener {
static final String logTag = "ActivitySwipeDetector";
private SwipeInterface activity;
static final int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;
public ActivitySwipeDetector(SwipeInterface activity){
this.activity = activity;
}
public void onRightToLeftSwipe(View v){
Log.i(logTag, "RightToLeftSwipe!");
activity.right2left(v);
}
public void onLeftToRightSwipe(View v){
Log.i(logTag, "LeftToRightSwipe!");
activity.left2right(v);
}
public void onTopToBottomSwipe(View v){
Log.i(logTag, "onTopToBottomSwipe!");
activity.top2bottom(v);
}
public void onBottomToTopSwipe(View v){
Log.i(logTag, "onBottomToTopSwipe!");
activity.bottom2top(v);
}
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
downY = event.getY();
return true;
}
case MotionEvent.ACTION_UP: {
upX = event.getX();
upY = event.getY();
float deltaX = downX - upX;
float deltaY = downY - upY;
// swipe horizontal?
if(Math.abs(deltaX) > MIN_DISTANCE){
// left or right
if(deltaX < 0) { this.onLeftToRightSwipe(v); return true; }
if(deltaX > 0) { this.onRightToLeftSwipe(v); return true; }
}
else {
Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
}
// swipe vertical?
if(Math.abs(deltaY) > MIN_DISTANCE){
// top or down
if(deltaY < 0) { this.onTopToBottomSwipe(v); return true; }
if(deltaY > 0) { this.onBottomToTopSwipe(v); return true; }
}
else {
Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
v.performClick();
}
}
}
return false;
}
}
it is used like this:
ActivitySwipeDetector swipe = new ActivitySwipeDetector(this);
LinearLayout swipe_layout = (LinearLayout) findViewById(R.id.swipe_layout);
swipe_layout.setOnTouchListener(swipe);
And in implementing Activity
you need to implement methods from SwipeInterface, and you can find out on which View the Swipe Event was called.
@Override
public void left2right(View v) {
switch(v.getId()){
case R.id.swipe_layout:
// do your stuff here
break;
}
}
User JQuery is EmptyObject to check whether array is contains elements or not.
var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true
Update 2019
The :has()
pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.
To use it, we will write something like:
.foo > .bar:has(> .baz) { /* style here */ }
In a structure like:
<div class="foo">
<div class="bar">
<div class="baz">Baz!</div>
</div>
</div>
This CSS will target the .bar
div - because it both has a parent .foo
and from its position in the DOM, > .baz
resolves to a valid element target.
Original Answer (left for historical purposes) - this portion is no longer accurate
For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:
!div > span { /* style here */
The !
before the div
selector indicates that it is the element to be styled, rather than the span
. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.
Why didn't you try to define is_private
in your models as default=False
?
class Foo(models.Models):
is_private = models.BooleanField(default=False)
Procedure to get Python Working in XCode 7
Step 1: Setup your Project with a External Build System
Step 1.1: Edit the Project Scheme
Step 2: Specify Python as the executable for the project (shift-command-g) the path should be /usr/bin/python
Step 3: Specify your custom working directory
Step 4: Specify your command line arguments to be the name of your python file. (in this example "test.py")
Step 5: Thankfully thats it!
(debugging can't be added until OSX supports a python debugger?)
<input type="email" name="email" id="email" value="" placeholder="Email" required />
documentation http://www.w3.org/TR/html-markup/input.email.html
Problem comes from the fact that line breaks (\n\r
?) are not the same as HTML <br/>
tags
var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '<br />');
UPDATE
Since many of the comments and my own experience have show me that this <br>
solution is not working as expected here is an example of how to append a new line to a textarea
using '\r\n'
function log(text) {
var txtArea ;
txtArea = document.getElementById("txtDebug") ;
txtArea.value += text + '\r\n';
}
I decided to do this an edit, and not as a new question because this a far too popular answer to be wrong or incomplete.
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.
If you can, make the fields final.
For a list of default animations see: http://developer.android.com/reference/android/R.anim.html
There is in fact fade_in
and fade_out
for API level 1 and up.
You can wait until the body is ready:
function onReady(callback) {_x000D_
var intervalId = window.setInterval(function() {_x000D_
if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
window.clearInterval(intervalId);_x000D_
callback.call(this);_x000D_
}_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
setVisible('.page', true);_x000D_
setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 100;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
background-color: rgba(192, 192, 192, 0.5);_x000D_
background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
background-repeat: no-repeat;_x000D_
background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
<h1>The standard Lorem Ipsum passage</h1>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
Here is a JSFiddle that demonstrates this technique.
I think what the OP wanted to do was to load a style sheet asynchronously and add it. This works for me in Chrome 22, FF 16 and IE 8 for sets of CSS rules stored as text:
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
$('<style type="text/css">\n' + data + '</style>').appendTo("head");
}
});
In my case, I also sometimes want the loaded CSS to replace CSS that was previously loaded this way. To do that, I put a comment at the beginning, say "/* Flag this ID=102 */", and then I can do this:
// Remove old style
$("head").children().each(function(index, ele) {
if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
$(ele).remove();
return false; // Stop iterating since we removed something
}
});
The path
module does not provide a synchronous version of path.exists
so you have to trick around with the fs
module.
Fastest thing I can imagine is using fs.realpathSync
which will throw an error that you have to catch, so you need to make your own wrapper function with a try/catch.
I'm assuming that you are using React-Router V4, as you used the same in the original Sandbox Link.
You are rendering the Main
component in the call to ReactDOM.render
that renders a Link
and Main component is outside of Router
, that's why it is throwing the error:
You should not use <Link> outside a <Router>
Changes:
Use any one of these Routers, BrowserRouter/HashRouter etc..., because you are using React-Router V4.
Router can have only one child, so wrap all the routes in a div
or Switch.
React-Router V4, doesn't have the concept of nested routes, if you wants to use nested routes then define those routes directly inside that component.
Check this working example with each of these changes.
const App = () => (
<BrowserRouter>
<div className="sans-serif">
<Route path="/" component={Main} />
<Route path="/view/:postId" component={Single} />
</div>
</BrowserRouter>
);
render(<App />, document.getElementById('root'));
Main
component from routeimport React from 'react';
import { Link } from 'react-router-dom';
export default () => (
<div>
<h1>
<Link to="/">Redux example</Link>
</h1>
</div>
)
Etc.
Also check this answer: Nested routes with react router v4
What might be informing you coworker is a notion that most C++ code should be templated to allow for maximum usability. And if it's templated, then everything will need to be in a header file, so that client code can see it and instantiate it. If it's good enough for Boost and the STL, it's good enough for us.
I don't agree with this point of view, but it may be where it's coming from.
Posting this to help someone.
Symptom:
channel 2: open failed: connect failed: Connection refused
debug1: channel 2: free: direct-tcpip:
listening port 8890 for 169.254.76.1 port 8890,
connect from ::1 port 52337 to ::1 port 8890, nchannels 8
My scenario; i had to use the remote server as a bastion host to connect elsewhere. Final Destination/Target: 169.254.76.1, port 8890. Through intermediary server with public ip: ec2-54-162-180-7.compute-1.amazonaws.com
SSH local port forwarding command:
ssh -i ~/keys/dev.tst -vnNT -L :8890:169.254.76.1:8890
[email protected]
What the problem was: There was no service bound on port 8890 in the target host. i had forgotten to start the service.
How did i trouble shoot:
SSH into bastion host and then do curl.
Hope this helps.
@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ")
private WebElementFacade emailLinkToVerifyAccount;
This approach will work for you, hopefully.
If you have ReSharper installed clicking Shift+Alt+L will move focus to the current file in Solution Explorer.
Active Item Tracking will also need to be enabled as described in the accepted answer
Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer
Even i face similar problem after I did some modification in code related to Cursor.
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
Cursor c = (Cursor)adapter.getItem(info.position);
long id = c.getLong(...);
String tempCity = c.getString(...);
//c.close();
...
}
After i commented out //c.close(); It is working fine. Try out at your end and update Initial setup is as... I have a list view in Fragment, and trying to delete and item from list via contextMenu.
The easiest way I found is this:
https://github.com/nteract/hydrogen/issues/922#issuecomment-405456346
Just open another (non-running, existing) notebook on the same kernel, and the issue is magically gone; you can again save the notebooks that were previously showing the _xsrf
error.
If you have already closed the Jupyter home page, you can find a link to it on the terminal from which Jupyter was started.
After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.
Dim intChoice As Integer
Dim strPath As String
' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show
' Get back the user option
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
Exit Sub
End If
Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String
Set fsoStream = FSO.OpenTextFile(strPath)
Do Until fsoStream.AtEndOfStream = True
strLine = fsoStream.ReadLine
' ... do your work ...
Loop
fsoStream.Close
Set FSO = Nothing
Hope it help!
Best regards
Fabio
**strong text**Set the Time out to the ajax calls_x000D_
function testing(){_x000D_
_x000D_
$("#load").css("display", "block");_x000D_
setTimeout(function(){_x000D_
$.ajax({_x000D_
type: "GET",_x000D_
_x000D_
_x000D_
url:testing.com,_x000D_
_x000D_
async: false,_x000D_
_x000D_
success : function(response){_x000D_
_x000D_
alert("connection established");_x000D_
_x000D_
_x000D_
},_x000D_
complete: function(){_x000D_
alert("sended");_x000D_
$("#load").css("display", "none");_x000D_
_x000D_
},_x000D_
error: function(jqXHR, exception) {_x000D_
alert("Write error Message Here");_x000D_
},_x000D_
_x000D_
_x000D_
});_x000D_
},5000);_x000D_
_x000D_
_x000D_
}
_x000D_
.loader {_x000D_
border: 16px solid #f3f3f3;_x000D_
border-radius: 50%;_x000D_
border-top: 16px solid #3498db;_x000D_
width: 120px;_x000D_
height: 120px;_x000D_
-webkit-animation: spin 2s linear infinite; /* Safari */_x000D_
animation: spin 2s linear infinite;_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes spin {_x000D_
0% { -webkit-transform: rotate(0deg); }_x000D_
100% { -webkit-transform: rotate(360deg); }_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
0% { transform: rotate(0deg); }_x000D_
100% { transform: rotate(360deg); }_x000D_
}
_x000D_
<div id="load" style="display: none" class="loader"></div>_x000D_
<input type="button" onclick="testing()" value="SUBMIT" >
_x000D_
//this should allow you to replica an animation effect for any css property, even //properties //that transform animation jQuery plugins do not allow
function twistMyElem(){
var ball = $('#form');
document.getElementById('form').style.zIndex = 1;
ball.animate({ zIndex : 360},{
step: function(now,fx){
ball.css("transform","rotateY(" + now + "deg)");
},duration:3000
}, 'linear');
}
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
Perhaps I'm completely missing the point of this question, but you want to find an integer missing from a sorted file of integers?
Uhh... really? Let's think about what such a file would look like:
1 2 3 4 5 6 ... first missing number ... etc.
The solution to this problem seems trivial.
You need a split function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[udf_Split]
(
@DelimitedList nvarchar(max)
, @Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
+ @DelimitedList
+ Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
As List
, Len(@Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(@Delimiter, CL.list, N.Value + 1)
- ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen )
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value <= DataLength(CL.List) / 2
And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
)
With your split function, you would then use Cross Apply to get the data:
Select T.Col1, T.Col2
, Substring( Z.Value, 1, Charindex(' = ', Z.Value) - 1 ) As AttributeName
, Substring( Z.Value, Charindex(' = ', Z.Value) + 1, Len(Z.Value) ) As Value
From Table01 As T
Cross Apply dbo.udf_Split( T.Col3, '|' ) As Z
My solution will work if you apply the ActionFilter to the Subcategory action method, as long as you always want to redirect the user to the same bookmark:
http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html
It modifies the HTML buffer and outputs a small piece of javascript to instruct the browser to append the bookmark.
You could modify the javascript to manually scroll, instead of using a bookmark in the URL, of course!
Hope it helps :)
Have you tried:
SELECT Cast( 2.555 as decimal(53,8))
This would return 2.55500000
. Is that what you want?
UPDATE:
Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:
SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')
returns 8|7
You may be able to use this in your conversion process...
I navigated to:
Eclipse>Pref>Java>Installed JRE>Search...
2 of them popped up and I checked the latest one. Before I did this I also went to About>Check for Updates
and updated it. I didn't have to reinstall any JRE or JDK either. I might have done it a while back, except it was with 1.6 not 1.4. Hope that helps!
It would be a great feature to have in Notepad++. I use the following technique to extract all the matches out of a file:
powershell
select-string -Path input.txt -Pattern "[0-9a-zA-Z ]*" -AllMatches | % { $_.Matches } | select-object Value > output.txt
And if you'd like only the distinct matches in a sorted list:
powershell
select-string -Path input.txt -Pattern "[0-9a-zA-Z ]" -AllMatches | % { $_.Matches } | select-object Value -unique | sort-object Value > output.txt
I think this is what you want:
JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);
Question 1:
vectorOfGamers.push_back(Player)
This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:
vectorOfGamers.push_back(Player(name, id))
//^^assuming name and id are parameters to the vector, call Player constructor
//^^In other words, push `instance` of Player class into vector
Question 2:
These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?
Yes you can. You can create a vector of pointers that points to the base class Gamer
.
A good choice is to use a vector of smart_pointer
, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer
, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?
A formula for an angle from 0 to 2pi.
There is x=x2-x1 and y=y2-y1.The formula is working for
any value of x and y. For x=y=0 the result is undefined.
f(x,y)=pi()-pi()/2*(1+sign(x))*(1-sign(y^2))
-pi()/4*(2+sign(x))*sign(y)
-sign(x*y)*atan((abs(x)-abs(y))/(abs(x)+abs(y)))
.crossed {
width: 200px;
height: 200px;
border:solid 1px;
background-color: rgb(210, 137, 226);
background-image: repeating-linear-gradient(
45deg,
transparent,
transparent 15px,
#ccc 10px,
#ccc 20px
),
repeating-linear-gradient(
135deg,
transparent,
transparent 15px,
#ccc 10px,
#ccc 20px
);
}
_x000D_
<div class='crossed'>Hello world</div>
_x000D_
One click answer:
open this URL:
https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/Properties