Actions
ADD_PRODUCT : (context,product) => {
return Axios.post(uri, product).then((response) => {
if (response.status === 'success') {
context.commit('SET_PRODUCT',response.data.data)
}
return response.data
});
});
Component
this.$store.dispatch('ADD_PRODUCT',data).then((res) => {
if (res.status === 'success') {
// write your success actions here....
} else {
// write your error actions here...
}
})
I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows
data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))
note that you need to handle the index in the dataset that is also returned by the function.
As this is tagged with the extjs tag it may be worth looking at the extjs method: http://docs.sencha.com/extjs/6.2.0/classic/Ext.Function.html#method-interval
This works much like setInterval, but also takes care of the scope, and allows arguments to be passed too:
function setBgPosition() {
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<numbers.length){
c=0;
}
}
return Ext.Function.interval(run,200);
}
var bgPositionTimer = setBgPosition();
when you want to stop you can use clearInterval
to stop it
clearInterval(bgPositionTimer);
An example use case would be:
Ext.Ajax.request({
url: 'example.json',
success: function(response, opts) {
clearInterval(bgPositionTimer);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
clearInterval(bgPositionTimer);
}
});
Signing indicates you really are the source or vouch for of the object signed. Everyone can read the object, though.
Encrypting means only those with the corresponding private key can read it, but without signing there is no guarantee you are behind the encrypted object.
px
? PixelsAll of these answers seem to be incorrect. Contrary to intuition, in CSS the px
is not pixels. At least, not in the simple physical sense.
Read this article from the W3C, EM, PX, PT, CM, IN…, about how px
is a "magical" unit invented for CSS. The meaning of px
varies by hardware and resolution. (That article is fresh, last updated 2014-10.)
My own way of thinking about it: 1 px is the size of a thin line intended by a designer to be barely visible.
To quote that article:
The px unit is the magic unit of CSS. It is not related to the current font and also not related to the absolute units. The px unit is defined to be small but visible, and such that a horizontal 1px wide line can be displayed with sharp edges (no anti-aliasing). What is sharp, small and visible depends on the device and the way it is used: do you hold it close to your eyes, like a mobile phone, at arms length, like a computer monitor, or somewhere in between, like a book? The px is thus not defined as a constant length, but as something that depends on the type of device and its typical use.
To get an idea of the appearance of a px, imagine a CRT computer monitor from the 1990s: the smallest dot it can display measures about 1/100th of an inch (0.25mm) or a little more. The px unit got its name from those screen pixels.
Nowadays there are devices that could in principle display smaller sharp dots (although you might need a magnifier to see them). But documents from the last century that used px in CSS still look the same, no matter what the device. Printers, especially, can display sharp lines with much smaller details than 1px, but even on printers, a 1px line looks very much the same as it would look on a computer monitor. Devices change, but the px always has the same visual appearance.
That article gives some guidance about using pt
vs px
vs em
, to answer this Question.
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as np
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats
np.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.
This is what I managed to find:
function createKeyboardEvent(name, key, altKey, ctrlKey, shiftKey, metaKey, bubbles) {
var e = new Event(name)
e.key = key
e.keyCode = e.key.charCodeAt(0)
e.which = e.keyCode
e.altKey = altKey
e.ctrlKey = ctrlKey
e.shiftKey = shiftKey
e.metaKey = metaKey
e.bubbles = bubbles
return e
}
var name = 'keydown'
var key = 'a'
var event = createKeyboardEvent(name, key, false, false, false, false, true)
document.addEventListener(name, () => {})
document.dispatchEvent(event)
_x000D_
The particular format for strptime
:
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
Finds the closest parent (or the element itself) that matches the given selector. Also included is a selector to stop searching, in case you know a common ancestor that you should stop searching at.
function closest(el, selector, stopSelector) {
var retval = null;
while (el) {
if (el.matches(selector)) {
retval = el;
break
} else if (stopSelector && el.matches(stopSelector)) {
break
}
el = el.parentElement;
}
return retval;
}
For discard all i like to stash and drop that stash, it's the fastest way to discard all, especially if you work between multiple repos.
This will stash all changes in {0}
key and instantly drop it from {0}
git stash && git stash drop
code:
class Main
{
public static void main(String[] args)
{
int a=10, b=20;
System.out.println(a + " " + b);
}
}
Input: none
Output: 10 20
To have a query working in any locale settings, consider formatting the date yourself:
SELECT *
FROM testbed
WHERE start_date >= to_date('2012-01-01','YYYY-MM-DD')
AND end_date <= to_date('2012-04-13','YYYY-MM-DD');
ALTER session set NLS_LANGUAGE=’AMERICAN’;
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
In my case, installing nodejs-legacy solved the issue.
sudo apt-get install nodejs-legacy
You can use the .not() method:
$(".content_box a").not(".button")
Alternatively, you can also use the :not() selector:
$(".content_box a:not('.button')")
There is little difference between the two approaches, except .not()
is more readable (especially when chained) and :not()
is very marginally faster. See this Stack Overflow answer for more info on the differences.
This works on firefox 3.6.x and IE:
function copyToClipboardCrossbrowser(s) {
s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
Make a virtual enviroment using python3
virtualenv env_name --python="python3"
and run the following command
pip3 install opencv-python
Use a div #overlay
with your loading info / .gif that will cover all your page:
<div id="overlay">
<img src="loading.gif" alt="Loading" />
Loading...
</div>
jQuery:
$(window).load(function(){
// PAGE IS FULLY LOADED
// FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
Here's an example with a Loading bar:
<div id="overlay">
<div id="progstat"></div>
<div id="progress"></div>
</div>
<div id="container">
<img src="http://placehold.it/3000x3000/cf5">
</div>
CSS:
*{margin:0;}
body{ font: 200 16px/1 sans-serif; }
img{ width:32.2%; }
#overlay{
position:fixed;
z-index:99999;
top:0;
left:0;
bottom:0;
right:0;
background:rgba(0,0,0,0.9);
transition: 1s 0.4s;
}
#progress{
height:1px;
background:#fff;
position:absolute;
width:0; /* will be increased by JS */
top:50%;
}
#progstat{
font-size:0.7em;
letter-spacing: 3px;
position:absolute;
top:50%;
margin-top:-40px;
width:100%;
text-align:center;
color:#fff;
}
JavaScript:
;(function(){
function id(v){ return document.getElementById(v); }
function loadbar() {
var ovrl = id("overlay"),
prog = id("progress"),
stat = id("progstat"),
img = document.images,
c = 0,
tot = img.length;
if(tot == 0) return doneLoading();
function imgLoaded(){
c += 1;
var perc = ((100/tot*c) << 0) +"%";
prog.style.width = perc;
stat.innerHTML = "Loading "+ perc;
if(c===tot) return doneLoading();
}
function doneLoading(){
ovrl.style.opacity = 0;
setTimeout(function(){
ovrl.style.display = "none";
}, 1200);
}
for(var i=0; i<tot; i++) {
var tImg = new Image();
tImg.onload = imgLoaded;
tImg.onerror = imgLoaded;
tImg.src = img[i].src;
}
}
document.addEventListener('DOMContentLoaded', loadbar, false);
}());
I would recommend you to install django-extensions and use python manage.py reset_db
command. It does exactly what you want.
In TorpedoQuery it look like this
Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);
The output of this query is very clean (original here)
clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt ' Output filename : '
spool &&outfile..gen
SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON
BEGIN
DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/
SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;
spool off
Use Java 8 Optional
(no filter needed):
public static String orElse(String defaultValue) {
return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue);
}
I've used this function to solve:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
In python3 with virtualenv on a Ubuntu Bionic machine the following commands worked for me:
sudo apt install build-essential python-dev libmysqlclient-dev
sudo apt-get install libssl-dev
pip install mysqlclient
I got this error when I did:
$ git submodule update --init --depth 1
but the commit in the parent project was pointing at an earlier commit.
Deleting the submodule folder and running:
$ git submodule update --init
did NOT solve the problem. I deleted the repo and tried again without the depth flag and it worked.
This error happens in Ubuntu 16.04 git 2.7.4, but not on Ubuntu 18.04 git 2.17, TODO find exact fixing commit or version.
You can use either HttpClient
or RestSharp
. Since I do not know what your code is, here is an example using HttpClient
:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
Use Perl instead perhaps?
perl -e 'print scalar localtime( time - 86400 ) . "\n";'
Or, use nawk and (ab)use /usr/bin/adb:
nawk 'BEGIN{printf "0t%d=Y\n", srand()-86400}' | adb
Came across this too ... insane!
/usr/bin/truss /usr/bin/date 2>&1 | nawk -F= '/^time\(\)/ {gsub(/ /,"",$2);printf "0t%d=Y\n", $2-86400}' | adb
EDIT: as_matrix
is deprecated since version 0.23.0
You can use the built in values
or to_numpy
(recommended option) method on the dataframe:
In [8]:
df.to_numpy()
Out[8]:
array([[ 0.9, 7. , 5.2, ..., 13.3, 13.5, 8.9],
[ 0.9, 7. , 5.2, ..., 13.3, 13.5, 8.9],
[ 0.8, 6.1, 5.4, ..., 15.9, 14.4, 8.6],
...,
[ 0.2, 1.3, 2.3, ..., 16.1, 16.1, 10.8],
[ 0.2, 1.3, 2.4, ..., 16.5, 15.9, 11.4],
[ 0.2, 1.3, 2.4, ..., 16.5, 15.9, 11.4]])
If you explicitly want lists and not a numpy array add .tolist()
:
df.to_numpy().tolist()
If you are looking to block the execution of code with call to sleep
, then no, there is no method for that in JavaScript
.
JavaScript
does have setTimeout
method. setTimeout
will let you defer execution of a function for x milliseconds.
setTimeout(myFunction, 3000);
// if you have defined a function named myFunction
// it will run after 3 seconds (3000 milliseconds)
Remember, this is completely different from how sleep
method, if it existed, would behave.
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
If you run the above function, you will have to wait for 3 seconds (sleep
method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep
function like that in JavaScript
.
function test2()
{
// defer the execution of anonymous function for
// 3 seconds and go to next line of code.
setTimeout(function(){
alert('hello');
}, 3000);
alert('hi');
}
If you run test2, you will see 'hi' right away (setTimeout
is non blocking) and after 3 seconds you will see the alert 'hello'.
If Sheets("Sheet1").OLEObjects("CheckBox1").Object.Value = True Then
I believe Tim is right. You have a Form Control. For that you have to use this
If ActiveSheet.Shapes("Check Box 1").ControlFormat.Value = 1 Then
What if your application does logging some other way – not using the
logging
module?
Now, traceback
could be used here.
import traceback
def log_traceback(ex, ex_traceback=None):
if ex_traceback is None:
ex_traceback = ex.__traceback__
tb_lines = [ line.rstrip('\n') for line in
traceback.format_exception(ex.__class__, ex, ex_traceback)]
exception_logger.log(tb_lines)
Use it in Python 2:
try:
# your function call is here
except Exception as ex:
_, _, ex_traceback = sys.exc_info()
log_traceback(ex, ex_traceback)
Use it in Python 3:
try:
x = get_number()
except Exception as ex:
log_traceback(ex)
On Red Hat this worked for me:
export TERM=xterm
further info here: http://www.cloudfarm.it/fix-error-opening-terminal-xterm-256color-unknown-terminal-type/
Your modification of sys.path
assumes the current working directory is always in main/
. This is not the case. Instead, just add the parent directory to sys.path
:
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import gen_py.lib
Don't forget to include a file __init__.py
in gen_py and lib - otherwise, they won't be recognized as Python modules.
It is working for me
MsgBox(DataGridView1.CurrentRow.Cells(0).Value.ToString)
I wanted to add my solution since the accepted one didn't quite work for me.
I needed to add a directive but also keep mine on the element.
In this example I am adding a simple ng-style directive to the element. To prevent infinite compile loops and allowing me to keep my directive I added a check to see if what I added was present before recompiling the element.
angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
return {
priority: 1001,
controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {
// controller code here
}],
compile: function(element, attributes){
var compile = false;
//check to see if the target directive was already added
if(!element.attr('ng-style')){
//add the target directive
element.attr('ng-style', "{'width':'200px'}");
compile = true;
}
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
if(compile){
$compile(iElement)(scope);
}
}
};
}
};
}]);
This example allows to upload PNG image only.
HTML
<input type="file" class="form-control" id="FileUpload1" accept="image/png" />
JS
$('#FileUpload1').change(
function () {
var fileExtension = ['png'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.png' format is allowed.");
this.value = ''; // Clean field
return false;
}
});
lodash will work, tested even for angular 5, http://jsfiddle.net/L5qrfx3x/
var remoteJSON = {"allowExternalMembers": "false", "whoCanJoin":
"CAN_REQUEST_TO_JOIN"};
var localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN",
"allowExternalMembers": "false"};
if(_.isEqual(remoteJSON, localJSON)){
//TODO
}
it works, for installation in angular, follow this
Hashing is a one-way process but using a password-list you can regenerate the hashes and compare to the stored hash to 'crack' the password.
This site https://crackstation.net/ attempts to do this for you - run through passwords lists and tell you the cleartext password based on your hash.
I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.
For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>
Note that j_username
and j_password
is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case.
After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
This is an interesting problem, complex Angular validation. The following fiddle implements what you want:
I created a new directive, rpattern
, that is a mix of Angular's ng-required
and the ng-pattern
code from input[type=text]
. What it does is watch the required
attribute of the field and take that into account when validating with regexp, i.e. if not required mark field as valid-pattern
.
A dirty (but smaller) solution, if you do not want a new directive, would be something like:
$scope.phoneNumberPattern = (function() {
var regexp = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
return {
test: function(value) {
if( $scope.requireTel === false ) {
return true;
}
return regexp.test(value);
}
};
})();
And in HTML no changes would be required:
<input type="text" ng-model="..." ng-required="requireTel"
ng-pattern="phoneNumberPattern" />
This actually tricks angular into calling our test()
method, instead of RegExp.test()
, that takes the required
into account.
The referenced column must be an index of a single column or the first column in multi column index, and the same type and the same collation.
My two tables have the different collations. It can be shown by issuing show table status like table_name
and collation can be changed by issuing alter table table_name
convert to character set utf8.
If you don't want to use any external polyfill library, you can use this function provided by the Mozilla Developer Network website:
function utf8ArrayToString(aBytes) {_x000D_
var sView = "";_x000D_
_x000D_
for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {_x000D_
nPart = aBytes[nIdx];_x000D_
_x000D_
sView += String.fromCharCode(_x000D_
nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */_x000D_
/* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */_x000D_
(nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
: nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */_x000D_
(nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
: nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */_x000D_
(nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
: nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */_x000D_
(nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
: nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */_x000D_
(nPart - 192 << 6) + aBytes[++nIdx] - 128_x000D_
: /* nPart < 127 ? */ /* one byte */_x000D_
nPart_x000D_
);_x000D_
}_x000D_
_x000D_
return sView;_x000D_
}_x000D_
_x000D_
let str = utf8ArrayToString([50,72,226,130,130,32,43,32,79,226,130,130,32,226,135,140,32,50,72,226,130,130,79]);_x000D_
_x000D_
// Must show 2H2 + O2 ? 2H2O_x000D_
console.log(str);
_x000D_
You can wrap your query in another SELECT
:
select count(*)
from
(
select count(SID) tot -- add alias
from Test
where Date = '2012-12-10'
group by SID
) src; -- add alias
In order for it to work, the count(SID)
need a column alias and you have to provide an alias to the subquery itself.
Java with Selenium 2.53.0
driver.getPageSource();
You can wrap it in a TreeSet like this:
Set mySet = new HashSet();
mySet.add(4);
mySet.add(5);
mySet.add(3);
mySet.add(1);
System.out.println("mySet items "+ mySet);
TreeSet treeSet = new TreeSet(mySet);
System.out.println("treeSet items "+ treeSet);
output :
mySet items [1, 3, 4, 5]
treeSet items [1, 3, 4, 5]
Set mySet = new HashSet();
mySet.add("five");
mySet.add("elf");
mySet.add("four");
mySet.add("six");
mySet.add("two");
System.out.println("mySet items "+ mySet);
TreeSet treeSet = new TreeSet(mySet);
System.out.println("treeSet items "+ treeSet);
output:
mySet items [six, four, five, two, elf]
treeSet items [elf, five, four, six, two]
requirement for this method is that the objects of the set/list should be comparable (implement the Comparable interface)
Store it in a field of type long
. See Date.getTime()
and new Date(long)
I don't believe you can, though I hope that someone will prove me wrong.
I know you can print the query and its toString method will show you the sql without the replacements. That can be handy if you're building complex query strings, but it doesn't give you the full query with values.
The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:
Reference the CSS files in the web folder (after: console assets:install --symlink web
)
{% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
Use the cssembed filter to embed images in the CSS like this.
{% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
I had the problem of expressing newline with \n or \r\n.
Magically the character \r which is used for carriage return worked for me like a newline.
So in some cases, it is useful to consider \r too.
You can configure patterns to hide files and folders from the explorer and searches.
Open VS User Settings (Main menu: File > Preferences > Settings). This will open the setting screen.
Search for files:exclude
in the search at the top.
Configure the User Setting with new glob patterns as needed. In this case, add this pattern node_modules/ then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic.
{
"files.exclude": {
".vscode":true,
"node_modules/":true,
"dist/":true,
"e2e/":true,
"*.json": true,
"**/*.md": true,
".gitignore": true,
"**/.gitkeep":true,
".editorconfig": true,
"**/polyfills.ts": true,
"**/main.ts": true,
"**/tsconfig.app.json": true,
"**/tsconfig.spec.json": true,
"**/tslint.json": true,
"**/karma.conf.js": true,
"**/favicon.ico": true,
"**/browserslist": true,
"**/test.ts": true,
"**/*.pyc": true,
"**/__pycache__/": true
}
}
You can do this simply with a function. For example:
def script():
# program code here...
restart = raw_input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
script()
if restart == "n" or restart == "no":
print "Script terminating. Goodbye."
script()
Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname()
. More on this here.
I didn't see anything that really answered this very well. I found something that worked pretty well here:
Use JAXB XMLAnyElement type of style to return dynamic element names
I modified it a bit to support hashmap trees. You could add other collections.
public class MapAdapter extends XmlAdapter<MapWrapper, Map<String, Object>> {
@Override
public MapWrapper marshal(Map<String, Object> m) throws Exception {
MapWrapper wrapper = new MapWrapper();
List elements = new ArrayList();
for (Map.Entry<String, Object> property : m.entrySet()) {
if (property.getValue() instanceof Map)
elements.add(new JAXBElement<MapWrapper>(new QName(getCleanLabel(property.getKey())),
MapWrapper.class, marshal((Map) property.getValue())));
else
elements.add(new JAXBElement<String>(new QName(getCleanLabel(property.getKey())),
String.class, property.getValue().toString()));
}
wrapper.elements = elements;
return wrapper;
}
@Override
public Map<String, Object> unmarshal(MapWrapper v) throws Exception {
// TODO
throw new OperationNotSupportedException();
}
// Return a XML-safe attribute. Might want to add camel case support
private String getCleanLabel(String attributeLabel) {
attributeLabel = attributeLabel.replaceAll("[()]", "").replaceAll("[^\\w\\s]", "_").replaceAll(" ", "_");
return attributeLabel;
}
}
class MapWrapper {
@XmlAnyElement
List elements;
}
Then to implement it:
static class myxml {
String name = "Full Name";
String address = "1234 Main St";
// I assign values to the map elsewhere, but it's just a simple
// hashmap with a hashmap child as an example.
@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, Object> childMap;
}
Feeding this through a simple Marshaller gives output that looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myxml>
<name>Full Name</name>
<address>1234 Main St</address>
<childMap>
<key2>value2</key2>
<key1>value1</key1>
<childTree>
<childkey1>childvalue1</childkey1>
</childTree>
</childMap>
</myxml>
in case your project use dagger, and then this error show up you can add this at android manifest
<application
...
android: name = ".BaseApplication"
...> ...
if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
OR
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
ImageLocation = @"c:\Images\test.jpg",
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
i'm not sure where you put images in your folder structure but you can find the path as bellow
picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");
It's easier than you wonder.
If you are working with a separated by semicolon file and header too:
$ (head -n1 file.csv && sort file.csv | grep -v <header>) | column -s";" -t
If you are working with array (using tab as separator):
for((i=0;i<array_size;i++));
do
echo stringarray[$i] $'\t' numberarray[$i] $'\t' anotherfieldarray[$i] >> tmp_file.csv
done;
cat file.csv | column -t
This is what we use in ASP.NET:
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// Stop Caching in Firefox
Response.Cache.SetNoStore();
It stops caching in Firefox and IE, but we haven't tried other browsers. The following response headers are added by these statements:
Cache-Control: no-cache, no-store
Pragma: no-cache
'speed up thread
dim lpThreadId as long
dim test as long
dim ptrt as long
'initparams
ptrt=varptr(lpThreadId)
Add = CODEPTR(thread)
'opensocket(191.9.202.255) change depending on configuration
numSock = Sock.Connect("191.9.202.255", 1958)
'port recieving
numSock1=sock.open(5963)
'create thread
hThread= CreateThread (byval 0&,byval 16384, Add , byval 0&, ByVal 1958, ptrt )
edit3.text=str$(hThread)
' use
Declare Function CreateThread Lib "kernel32" Alias "CreateThread" (lpThreadAttributes As long, ByVal dwStackSize As Long, lpStartAddress As Long, lpParameter As long, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long
for me, the problem was from require('jquery-validation')
i added in the begging of that js file which Validate method used which is necessary as an npm module
unfortunately, when web pack compiles the js files, they aren't in order, so that the validate method is before defining it! and the error comes
so better to use another js file for compiling this library or use local validate method file or even using CDN but in all cases make sure you attached jquery before
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
You need to add:
#include <string>
In your header file.
Chrome developer tools now have the ability to list WebSocket frames and also inspect the data if the frames are not binary.
Process:
If your WebSocket connection uses binary frames then you will probably still want to use Wireshark to debug the connection. Wireshark 1.8.0 added dissector and filtering support for WebSockets. An alternative may be found in this other answer.
Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:
$result=array_search($unwantedValue,$array,true);
if($result !== false) {
unset($array[$result]);
}
The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.
Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:
$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
unset($array[$key]);
}
Check http://php.net/manual/en/function.array-search.php for more information.
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined
Unfortunately, no. You will have to cast each value individually.
If you use nano with a language like python (as in your example) it's also a good idea to convert tabs to spaces.
Edit your ~/.nanorc file (or create it) and add:
set tabsize 4
set tabstospaces
If you already got a file with tabs and want to convert them to spaces i recommend the expand
command (shell):
expand -4 input.py > output.py
I just faced this issue, doing some research I found that the data values has to be sended as URLSearchParams, I do it like this:
getAuthToken: async () => {
const data = new URLSearchParams();
data.append('grant_type', 'client_credentials');
const fetchAuthToken = await axios({
url: `${PAYMENT_URI}${PAYMENT_GET_TOKEN_PATH}`,
method: 'POST',
auth: {
username: PAYMENT_CLIENT_ID,
password: PAYMENT_SECRET,
},
headers: {
Accept: 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
},
data,
withCredentials: true,
});
return fetchAuthToken;
},
The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:
comment=$(cat /proc/sys/kernel/random/uuid | sed 's/\-//g')
iptables -A ..... -m comment --comment "${comment}" -j REQUIRED_ACTION
2. When the rule added and you wish to remove it (or everything with this comment), do:
iptables-save | grep -v "${comment}" | iptables-restore
So, you'll 100% delete all rules that match the $comment and leave other lines untouched. This solution works for last 2 months with about 100 changes of rules per day - no issues.Hope, it helps
I know this was answered long ago, but if you don't mind creating the button dynamically, this works using only the jQuery framework:
$(document).ready(function() {_x000D_
$button = $('<input id="1" type="button" value="ahaha" />');_x000D_
$('body').append($button);_x000D_
$button.click(function() {_x000D_
console.log("Id clicked: " + this.id ); // or $(this) or $button_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>And here is my HTML page:</p>_x000D_
_x000D_
<div class="Title">Welcome!</div>
_x000D_
//You may use this example. Might be help you...
$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
->join("items","items.user_id","=","users.id")
->join("jobs",function($join){
$join->on("jobs.user_id","=","users.id")
->on("jobs.item_id","=","items.id");
})
->get();
print_r($user);
Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:
Long.MAX_VALUE + 1
you will notice that the result is the equivalent to Long.MIN_VALUE.
From here: java number exceeds long.max_value - how to detect?
The reason that appendChild
is not a function is because you're executing it on the textContent
of your p
element.
You instead just need to select the paragraph itself, and then append your new text node to that:
var paragraph = document.getElementById("p");_x000D_
var text = document.createTextNode("This just got added");_x000D_
_x000D_
paragraph.appendChild(text);
_x000D_
<p id="p">This is some text</p>
_x000D_
However instead, if you like, you can just modify the text itself (rather than adding a new node):
var paragraph = document.getElementById("p");_x000D_
_x000D_
paragraph.textContent += "This just got added";
_x000D_
<p id="p">This is some text</p>
_x000D_
I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below
Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.
It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below
Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/homepage"
tools:layout_editor_absoluteX="55dp"
tools:layout_editor_absoluteY="130dp" />
You need to give image location using
app:srcCompat="@drawable/imagename"
From what I understand about your question, before passing the character into the switch statement, you can convert it to lowercase. So you don't have to worry about upper cases because they are automatically converted to lower case. For that you need to use the below function:
Character.toLowerCase(c);
By default, every Object in Java has the toString()
method which outputs the ObjectType@HashCode.
If you want more meaningfull information then you need to override the toString()
method in your class.
public class Person {
private String name;
// constructor and getter/setter omitted
// overridding toString() to print name
public String toString(){
return name;
}
}
Now when you print the person object using System.out.prtinln(personObj);
it will print the name of the person instead of the classname and hashcode.
In your second case when you are trying to print the array, it prints [Lcom.foo.Person;@28a418fc
the Array type and it's hashcode.
If you want to print the person names, there are many ways.
You could write your own function that iterates each person and prints
void printPersonArray(Person[] persons){
for(Person person: persons){
System.out.println(person);
}
}
You could print it using Arrays.toString(). This seems the simplest to me.
System.out.println(Arrays.toString(persons));
System.out.println(Arrays.deepToString(persons)); // for nested arrays
You could print it the java 8 way (using streams and method reference).
Arrays.stream(persons).forEach(System.out::println);
There might be other ways as well. Hope this helps. :)
**page 1**
<form action="exapmple.php?variable_name=$value" method="POST">
<button>
<input type="hidden" name="x">
</button>
</form>`
page 2
if(isset($_POST['x'])) {
$new_value=$_GET['variable_name'];
}
An alternative way:
SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
rownum = 1
"whats my ip"
or entering this command: wget http://ipinfo.io/ip -qO -
wget http://ipinfo.io/ip -qO -
again from there too.6006
123.123.12.32:6006
If your remote server is open to traffic from your local IP address, you should be able to see your remote Tensorboard.
Warning: if all internet traffic can access your system (if you haven't specified a single IP address that can access it), anyone may be able to view your TensorBoard results and runaway with creating SkyNet themselves.
If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work
hive> select cast('2147483647' as int);
OK
2147483647
hive> select cast('2147483648' as int);
OK
NULL
hive> select cast('2147483648' as bigint);
OK
2147483648
If you are using Spring, you can force validation by annotating the class with @Validated
:
import org.springframework.validation.annotation.Validated;
More info available here: Javax validation @NotNull annotation usage
For completeness: with dplyr v0.2 ddply
with colwise
will also do this:
> ddply(df, .(grp), colwise(mean))
grp a b c d
1 1 4.333333 4.00 1.000000 2.000000
2 2 2.000000 2.75 2.750000 2.750000
3 3 3.000000 4.00 4.333333 3.666667
but it is slower, at least in this case:
> microbenchmark(ddply(df, .(grp), colwise(mean)),
df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
expr min lq mean
ddply(df, .(grp), colwise(mean)) 3.278002 3.331744 3.533835
df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337
median uq max neval
3.353633 3.378089 7.592209 100
1.121954 1.133428 2.292216 100
C++20 will have "uniform container erasure", and you'll be able to write:
std::erase_if(numbers, [](int n){ return n % 2 == 0 });
And that will work for vector
, set
, deque
, etc.
See cppReference for more info.
What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.
From Microsoft documentation:
In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
This is similar to my case, where I have a table named tabel_buku_besar
. What I need are
Looking for record that have account_code='101.100'
in tabel_buku_besar
which have companyarea='20000'
and also have IDR
as currency
I need to get all record from tabel_buku_besar
which have account_code same as step 1 but have transaction_number
in step 1 result
while using select ... from...where....transaction_number in (select transaction_number from ....)
, my query running extremely slow and sometimes causing request time out or make my application not responding...
I try this combination and the result...not bad...
`select DATE_FORMAT(L.TANGGAL_INPUT,'%d-%m-%y') AS TANGGAL,
L.TRANSACTION_NUMBER AS VOUCHER,
L.ACCOUNT_CODE,
C.DESCRIPTION,
L.DEBET,
L.KREDIT
from (select * from tabel_buku_besar A
where A.COMPANYAREA='$COMPANYAREA'
AND A.CURRENCY='$Currency'
AND A.ACCOUNT_CODE!='$ACCOUNT'
AND (A.TANGGAL_INPUT BETWEEN STR_TO_DATE('$StartDate','%d/%m/%Y') AND STR_TO_DATE('$EndDate','%d/%m/%Y'))) L
INNER JOIN (select * from tabel_buku_besar A
where A.COMPANYAREA='$COMPANYAREA'
AND A.CURRENCY='$Currency'
AND A.ACCOUNT_CODE='$ACCOUNT'
AND (A.TANGGAL_INPUT BETWEEN STR_TO_DATE('$StartDate','%d/%m/%Y') AND STR_TO_DATE('$EndDate','%d/%m/%Y'))) R ON R.TRANSACTION_NUMBER=L.TRANSACTION_NUMBER AND R.COMPANYAREA=L.COMPANYAREA
LEFT OUTER JOIN master_account C ON C.ACCOUNT_CODE=L.ACCOUNT_CODE AND C.COMPANYAREA=L.COMPANYAREA
ORDER BY L.TANGGAL_INPUT,L.TRANSACTION_NUMBER`
I catch this exception when Java out of heap. If I try to put in RAM many data items - first I catch "Communications link failure" and next "OutOfMemoryError".
I logged it and I decrease memory consumption (delete 1/2 data) and all ok.
I think Shaz's answer for local variables is hard to understand, though it works for non-recursive functions. Here's another way that I think it's clearer (but it's still his idea, exact same behavior). It's also not accessing the local variables dynamically, just the property of the local variable.
Essentially, it's using a global variable (attached to the function object)
// Here's a version of it that is more straight forward.
function doIt() {
doIt.objname = {};
var someObject = "objname";
doIt[someObject].value = "value";
console.log(doIt.objname);
})();
Which is essentially the same thing as creating a global to store the variable, so you can access it as a property. Creating a global to do this is such a hack.
Here's a cleaner hack that doesn't create global variables, it uses a local variable instead.
function doIt() {
var scope = {
MyProp: "Hello"
};
var name = "MyProp";
console.log(scope[name]);
}
if(navigator.app){
navigator.app.exitApp();
}else if(navigator.device){
navigator.device.exitApp();
}
For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in execinfo.h
to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found in the libc manual.
Here's an example program that installs a SIGSEGV
handler and prints a stacktrace to stderr
when it segfaults. The baz()
function here causes the segfault that triggers the handler:
#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
void handler(int sig) {
void *array[10];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 10);
// print out all the frames to stderr
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
void baz() {
int *foo = (int*)-1; // make a bad pointer
printf("%d\n", *foo); // causes segfault
}
void bar() { baz(); }
void foo() { bar(); }
int main(int argc, char **argv) {
signal(SIGSEGV, handler); // install our handler
foo(); // this will call foo, bar, and baz. baz segfaults.
}
Compiling with -g -rdynamic
gets you symbol info in your output, which glibc can use to make a nice stacktrace:
$ gcc -g -rdynamic ./test.c -o test
Executing this gets you this output:
$ ./test
Error: signal 11:
./test(handler+0x19)[0x400911]
/lib64/tls/libc.so.6[0x3a9b92e380]
./test(baz+0x14)[0x400962]
./test(bar+0xe)[0x400983]
./test(foo+0xe)[0x400993]
./test(main+0x28)[0x4009bd]
/lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb]
./test[0x40086a]
This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before main
in addition to main
, foo
, bar
, and baz
.
This can be done with a sed one-liner:
sed '/^#/d'
This says, "find all lines that start with # and delete them, leaving everything else."
The correct way in .NET 4.0 is:
if (String.IsNullOrWhiteSpace(strSearch))
The String.IsNullOrWhiteSpace
method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0)
// String.Empty is the same as ""
Reference for IsNullOrWhiteSpace method
http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx
Indicates whether a specified string is Nothing, empty, or consists only of white-space characters.
In earlier versions, you could do something like this:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
The String.IsNullOrEmpty
method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty)
Which means you still need to check for your "IsWhiteSpace" case with the .Trim().Length == 0
as per the example.
Reference for IsNullOrEmpty method
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx
Indicates whether the specified string is Nothing or an Empty string.
Explanation:
You need to ensure strSearch
(or any variable for that matter) is not null
before you dereference it using the dot character (.
) - i.e. before you do strSearch.SomeMethod()
or strSearch.SomeProperty
you need to check that strSearch != null
.
In your example you want to make sure your string has a value, which means you want to ensure the string:
String.Empty
/ ""
)In the cases above, you must put the "Is it null?" case first, so it doesn't go on to check the other cases (and error) when the string is null
.
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.
2) No. See the whatsapp security white paper.
3) See #1.
This seems to happen from time to time with programs that are very sensitive to command lines, but one option is to just use the DOS path instead of the Windows path. This means that C:\Program Files\
would resolve to C:\PROGRA~1\
and generally avoid any issues with spacing.
To get the short path you can create a quick Batch file that echos the short path:
@ECHO OFF
echo %~s1
Which is then called as follows:
C:\>shortPath.bat "C:\Program Files"
C:\PROGRA~1
you also coud try this:
<select ng-model="selectedItem" ng-change="update()">
<option ng-repeat="item in items"
ng-selected="selectedItem == item.Id" value="{{item.Id}}">
{{item.Name}}
</option>
</select>
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
Using JavaScript's slice function:
let string = 'foo_bar';_x000D_
string = string.slice(0, -4); // Slice off last four characters here_x000D_
console.log(string);
_x000D_
This could be used to remove '_bar' at end of a string, of any length.
Set below code in RouteConfig.cs in App_Start folder
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}
IF still not working then do below steps
Second Way : You simple follow below steps,
1) Right click on your Project
2) Select Properties
3) Select Web option and then Select Specific Page (Controller/View) and then set your login page
Here, Account is my controller and Login is my action method (saved in Account Controller)
Please take a look attached screenshot.
The supercalifragilisticexpialidocious answer is:
add this at the top of your js file or script tag
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
document.body.scrollTop = 0; // For Safari
The easiest is:
int label = 0;
loop:while(true) {
switch(state) {
case 0:
// Some code
state = 5;
break;
case 2:
// Some code
state = 4;
break;
...
default:
break loop;
}
}
The other answers to this question all miss the key point that in Java, there is one mutex associated with every object. (I'm assuming you know what a mutex or "lock" is.) This is not the case in most programming languages which have the concept of "locks". For example, in Ruby, you have to explicitly create as many Mutex
objects as you need.
I think I know why the creators of Java made this choice (although, in my opinion, it was a mistake). The reason has to do with the inclusion of the synchronized
keyword. I believe that the creators of Java (naively) thought that by including synchronized
methods in the language, it would become easy for people to write correct multithreaded code -- just encapsulate all your shared state in objects, declare the methods that access that state as synchronized
, and you're done! But it didn't work out that way...
Anyways, since any class can have synchronized
methods, there needs to be one mutex for each object, which the synchronized
methods can lock and unlock.
wait
and notify
both rely on mutexes. Maybe you already understand why this is the case... if not I can add more explanation, but for now, let's just say that both methods need to work on a mutex. Each Java object has a mutex, so it makes sense that wait
and notify
can be called on any Java object. Which means that they need to be declared as methods of Object
.
Another option would have been to put static methods on Thread
or something, which would take any Object
as an argument. That would have been much less confusing to new Java programmers. But they didn't do it that way. It's much too late to change any of these decisions; too bad!
Use sp_helptext
before the view_name
. Example:
sp_helptext Example_1
Hence you will get the query:
CREATE VIEW dbo.Example_1
AS
SELECT a, b, c
FROM dbo.table_name JOIN blah blah blah
WHERE blah blah blah
sp_helptext will give stored procedures.
The indentation is wrong, as the error tells you. As you can see, you have indented the code beginning with the indicated line too little to be in the for
loop, but too much to be at the same level as the for loop. Python sees the lack of indentation as ending the for
loop, then complains you have indented the rest of the code too much. (The def
line I'm betting is just an artifact of how Stack Overflow wants you to format your code.)
Edit: Given your correction, I'm betting you have a mixture of tabs and spaces in the source file, such that it looks to the human eye like the code lines up, but Python considers it not to. As others have suggested, using only spaces is the recommended practice (see PEP 8). If you start Python with python -t
, you will get warnings if there are mixed tabs and spaces in your code, which should help you pinpoint the issue.
As the saying goes, a picture is worth a thousand words. Here is how I visualize it:
Here is how we get to that picture:
Create a name myfile.txt
in the file system that points to a new inode (which contains the metadata for the file and points to the blocks of data that contain its contents, i.e. the text "Hello, World!":
$ echo 'Hello, World!' > myfile.txt
Create a hard link my-hard-link
to the file myfile.txt
, which means "create a file that should point to the same inode that myfile.txt
points to":
$ ln myfile.txt my-hard-link
Create a soft link my-soft-link
to the file myfile.txt
, which means "create a file that should point to the file myfile.txt
":
$ ln -s myfile.txt my-soft-link
Look what will now happen if myfile.txt
is deleted (or moved): my-hard-link
still points to the same contents, and is thus unaffected, whereas my-soft-link
now points to nothing. Other answers discuss the pros/cons of each.
Python’s pass-by-assignment scheme isn’t quite the same as C++’s reference parameters option, but it turns out to be very similar to the argument-passing model of the C language (and others) in practice:
Unfortunately all classes hidden-*-up
and hidden-*-down
were removed from Bootstrap (as of Bootstrap Version 4 Beta, in Version 4 Alpha and Version 3 these classes still existed).
Instead, new classes d-*
should be used, as mentioned here: https://getbootstrap.com/docs/4.0/migration/#utilities
I found out that the new approach is less useful under some circumstances. The old approach was to HIDE elements while the new approach is to SHOW elements. Showing elements is not that easy with CSS since you need to know if the element is displayed as block, inline, inline-block, table etc.
You might want to restore the former "hidden-*" styles known from Bootstrap 3 with this CSS:
/*\
* Restore Bootstrap 3 "hidden" utility classes.
\*/
/* Breakpoint XS */
@media (max-width: 575px)
{
.hidden-xs-down, .hidden-sm-down, .hidden-md-down, .hidden-lg-down, .hidden-xl-down,
.hidden-xs-up,
.hidden-unless-sm, .hidden-unless-md, .hidden-unless-lg, .hidden-unless-xl
{
display: none !important;
}
}
/* Breakpoint SM */
@media (min-width: 576px) and (max-width: 767px)
{
.hidden-sm-down, .hidden-md-down, .hidden-lg-down, .hidden-xl-down,
.hidden-xs-up, .hidden-sm-up,
.hidden-unless-xs, .hidden-unless-md, .hidden-unless-lg, .hidden-unless-xl
{
display: none !important;
}
}
/* Breakpoint MD */
@media (min-width: 768px) and (max-width: 991px)
{
.hidden-md-down, .hidden-lg-down, .hidden-xl-down,
.hidden-xs-up, .hidden-sm-up, .hidden-md-up,
.hidden-unless-xs, .hidden-unless-sm, .hidden-unless-lg, .hidden-unless-xl
{
display: none !important;
}
}
/* Breakpoint LG */
@media (min-width: 992px) and (max-width: 1199px)
{
.hidden-lg-down, .hidden-xl-down,
.hidden-xs-up, .hidden-sm-up, .hidden-md-up, .hidden-lg-up,
.hidden-unless-xs, .hidden-unless-sm, .hidden-unless-md, .hidden-unless-xl
{
display: none !important;
}
}
/* Breakpoint XL */
@media (min-width: 1200px)
{
.hidden-xl-down,
.hidden-xs-up, .hidden-sm-up, .hidden-md-up, .hidden-lg-up, .hidden-xl-up,
.hidden-unless-xs, .hidden-unless-sm, .hidden-unless-md, .hidden-unless-lg
{
display: none !important;
}
}
The classes hidden-unless-*
were not included in Bootstrap 3, but they are useful as well and should be self-explanatory.
You answered the question by yourself: "I know that absolute positioned elements are removed from the flow, thus ignored by other elements." So you can't set the parents height according to an absolutely positioned element.
You either use fixed heights or you need to involve JS.
You can also initialise it like this:
struct name sara = { "Sara", "Black" };
Since (as a special case) you're allowed to initialise char arrays from string constants.
Now, as for what a struct actually is - it's a compound type composed of other values. What sara
actually looks like in memory is a block of 20 consecutive char values (which can be referred to using sara.first
, followed by 0 or more padding bytes, followed by another block of 20 consecutive char values (which can be referred to using sara.last
). All other instances of the struct name
type are laid out in the same way.
In this case, it is very unlikely that there is any padding, so a struct name
is just a block of 40 characters, for which you have a name for the first 20 and the last 20.
You can find out how big a block of memory a struct name
takes using sizeof(struct name)
, and you can find out where within that block of memory each member of the structure is placed at using offsetof(struct name, first)
and offsetof(struct name, last)
.
Similar to Arun Sangal the problem lied in an in .ssh/config entry
Host my.sshhost.com
ProxyCommand ssh -q -W %h:%p myremotemachine.my.company.com
The remote machine was added to avoid with ssh for VPN connections and worked well. But for the vacation period I switched off the myremotemachine and run into the described problem.
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
Linux based Tomcat6 should have /etc/tomcat6/tomcat6.conf
# System-wide configuration file for tomcat6 services
# This will be sourced by tomcat6 and any secondary service
# Values will be overridden by service-specific configuration
# files in /etc/sysconfig
#
# Use this one to change default values for all services
# Change the service specific ones to affect only one service
# (see, for instance, /etc/sysconfig/tomcat6)
#
# Where your java installation lives
#JAVA_HOME="/usr/lib/jvm/java-1.5.0"
# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat6"
...
Foreach before foreach: :)
reset($array);
while(list($key,$value) = each($array))
{
// we used this back in php3 :)
}
@beanland; You have to write
-webkit-appearance:none;
in your css.
read this http://trentwalton.com/2010/07/14/css-webkit-appearance/
Latest update:
Html.fromHtml(string);
//deprecated after Android N versions..
Following code give support to android N and above versions...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(yourHtmlString,Html.FROM_HTML_MODE_LEGACY));
}
else
{
textView.setText(Html.fromHtml(yourHtmlString));
}
Compile parses the regular expression and builds an in-memory representation. The overhead to compile is significant compared to a match. If you're using a pattern repeatedly it will gain some performance to cache the compiled pattern.
Here is a nice way to remove the invalid characters in a Filename:
string.Join(string.Empty, filename.Split(System.IO.Path.GetInvalidFileNameChars()));
It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:
$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);
You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet
of Note
s, where you need to pass in a single Note
.
You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
Try
SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]')
FROM traptabclob;
Here is a sqlfiddle demo
Changing this project setting solve the issue for me.
You can create a surface with text on it. For this take a look at this short example:
pygame.font.init() # you have to call this at the start,
# if you want to use this module.
myfont = pygame.font.SysFont('Comic Sans MS', 30)
This creates a new object on which you can call the render
method.
textsurface = myfont.render('Some Text', False, (0, 0, 0))
This creates a new surface with text already drawn onto it. At the end you can just blit the text surface onto your main screen.
screen.blit(textsurface,(0,0))
Bear in mind, that everytime the text changes, you have to recreate the surface again, to see the new text.
IMHO, Edizkan Adil Ata's idea is actually the most proper way. It extracts the URLs of anchor tags and puts them in a different tag. And if you don't want to let the anchors being seen by the page visitor then just .hide()
them all with JQuery or display: none;
in CSS.
Also you can perform prefetching, like this:
<link rel="prefetch" href="imagefolder/clouds.jpg" />
That way you don't have to hide it and still can extract the path to the image.
Try something like this:
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
Is there something that prevents you from merging all revisions on trunk since the last merge?
svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
should work just fine. At least if you want to merge all changes on trunk to your branch.
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
object.get("key");
//etc. etc.
}
Since both pip
nor python
commands are not installed along Python in Windows, you will need to use the Windows alternative py
, which is included by default when you installed Python. Then you have the option to specify a general or specific version number after the py
command.
C:\> py -m pip install pandas %= one of Python on the system =%
C:\> py -2 -m pip install pandas %= one of Python 2 on the system =%
C:\> py -2.7 -m pip install pandas %= only for Python 2.7 =%
C:\> py -3 -m pip install pandas %= one of Python 3 on the system =%
C:\> py -3.6 -m pip install pandas %= only for Python 3.6 =%
Alternatively, in order to get pip
to work without py -m
part, you will need to add pip to the PATH environment variable.
C:\> setx PATH "%PATH%;C:\<path\to\python\folder>\Scripts"
Now you can run the following command as expected.
C:\> pip install pandas
connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
This is caused by your SSL certificate is unable to verify the host server. You can add pypi.python.org to the trusted host or specify an alternative SSL certificate. For more information, please see this post. (Thanks to Anuj Varshney for suggesting this)
C:\> py -m pip install --trusted-host pypi.python.org pip pandas
PermissionError: [WinError 5] Access is denied
This is a caused by when you don't permission to modify the Python site-package folders. You can avoid this with one of the following methods:
Run Windows Command Prompt as administrator (thanks to DataGirl's suggestion) by:
cmd.exe
in the search boxRun pip in user mode by adding --user
option when installing with pip. Which typically install the package to the local %APPDATA% Python folder.
C:\> py -m pip install --user pandas
C:\> py -m venv c:\path\to\new\venv
C:\> <path\to\the\new\venv>\Scripts\activate.bat
I have used SVN for a long time, but whenever I used Git, I felt that Git is much powerful, lightweight, and although a little bit of learning curve involved but is better than SVN.
What I have noted is that each SVN project, as it grows, becomes a very big size project unless it is exported. Where as, GIT project (along with Git data) is very light weight in size.
In SVN, I've dealt with developers from novice to experts, and the novices and intermediates seem to introduce File conflicts if they copy one folder from another SVN project in order to re-use it. Whereas, I think in Git, you just copy the folder and it works, because Git doesn't introduce .git folders in all its subfolders (as SVN does).
After dealing alot with SVN since long time, I'm finally thinking to move my developers and me to Git, since it is easy to collaborate and merge work, as well as one great advantage is that a local copy's changes can be committed as much desired, and then finally pushed to the branch on server in one go, unlike SVN (where we have to commit the changes from time to time in the repository on server).
Anyone who can help me decide if I should really go with Git?
To get the currently logged in user:
System.getProperty("user.name"); //platform independent
and the hostname of the machine:
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());
For complex C++ files vim does not always get the formatting right when using vim's =
filter command. So for a such situations it is better to use an external C++ formatter like astyle (or uncrustify) e.g.:
:%!astyle
Vim's '=' function uses its internal formatter by default (which doesn't always gets things right) but one can also set it use an external formatter, like astyle, by setting it up appropriately as discussed in this question.
In my machine, ssh-keygen
was available from powershell.
No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).
JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.
You can that way kill the other process, and the current one afterwards.
It sounds like you can pick and choose. If you pick float, you may lose 11 digits of precision. If that's acceptable, go for it -- apparently the Linq designers thought this to be a good tradeoff.
However, if your application needs those extra digits, use decimal. Decimal (implemented correctly) is way more accurate than a float anyway -- no messy translation from base 10 to base 2 and back.
Information from the Official Adobe site about this issue
The issue is when you embed a youtube link:
https://www.youtube.com/embed/kRvL6K8SEgY
in an iFrame, the default wmode is windowed which essentially gives it a z-index greater then everything else and it will overlay over anything.
Try appending this GET parameter to your URL:
wmode=opaque
like so:
https://www.youtube.com/embed/kRvL6K8SEgY?wmode=opaque
Make sure its the first parameter in the URL. Other parameters must go after
In the iframe tag:
Example:
<iframe class="youtube-player" type="text/html" width="520" height="330" src="http://www.youtube.com/embed/NWHfY_lvKIQ?wmode=opaque" frameborder="0"></iframe>
no, it has a number of methods, info(), debug(), warn(), etc (this replaces the priority field)
have a look at http://www.slf4j.org/api/org/slf4j/Logger.html for the full Logger api.
I have fixed it by moving to commit_sha that last is committed to origin/master.
git reset --hard commit_sha
WARNING: You will lose all that is committed after the 'commit_sha' commit.
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
Python3.x
The best aproach I could reach with my knowledge was this.
Note that this code treat set() too.
This approach is generic just needing the extension of class (in the second example).
Note that I'm just doing it to files, but it's easy to modify the behavior to your taste.
However this is a CoDec.
With a little more work you can construct your class in other ways. I assume a default constructor to instance it, then I update the class dict.
import json
import collections
class JsonClassSerializable(json.JSONEncoder):
REGISTERED_CLASS = {}
def register(ctype):
JsonClassSerializable.REGISTERED_CLASS[ctype.__name__] = ctype
def default(self, obj):
if isinstance(obj, collections.Set):
return dict(_set_object=list(obj))
if isinstance(obj, JsonClassSerializable):
jclass = {}
jclass["name"] = type(obj).__name__
jclass["dict"] = obj.__dict__
return dict(_class_object=jclass)
else:
return json.JSONEncoder.default(self, obj)
def json_to_class(self, dct):
if '_set_object' in dct:
return set(dct['_set_object'])
elif '_class_object' in dct:
cclass = dct['_class_object']
cclass_name = cclass["name"]
if cclass_name not in self.REGISTERED_CLASS:
raise RuntimeError(
"Class {} not registered in JSON Parser"
.format(cclass["name"])
)
instance = self.REGISTERED_CLASS[cclass_name]()
instance.__dict__ = cclass["dict"]
return instance
return dct
def encode_(self, file):
with open(file, 'w') as outfile:
json.dump(
self.__dict__, outfile,
cls=JsonClassSerializable,
indent=4,
sort_keys=True
)
def decode_(self, file):
try:
with open(file, 'r') as infile:
self.__dict__ = json.load(
infile,
object_hook=self.json_to_class
)
except FileNotFoundError:
print("Persistence load failed "
"'{}' do not exists".format(file)
)
class C(JsonClassSerializable):
def __init__(self):
self.mill = "s"
JsonClassSerializable.register(C)
class B(JsonClassSerializable):
def __init__(self):
self.a = 1230
self.c = C()
JsonClassSerializable.register(B)
class A(JsonClassSerializable):
def __init__(self):
self.a = 1
self.b = {1, 2}
self.c = B()
JsonClassSerializable.register(A)
A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
print(b.b)
print(b.c.a)
Edit
With some more of research I found a way to generalize without the need of the SUPERCLASS register method call, using a metaclass
import json
import collections
REGISTERED_CLASS = {}
class MetaSerializable(type):
def __call__(cls, *args, **kwargs):
if cls.__name__ not in REGISTERED_CLASS:
REGISTERED_CLASS[cls.__name__] = cls
return super(MetaSerializable, cls).__call__(*args, **kwargs)
class JsonClassSerializable(json.JSONEncoder, metaclass=MetaSerializable):
def default(self, obj):
if isinstance(obj, collections.Set):
return dict(_set_object=list(obj))
if isinstance(obj, JsonClassSerializable):
jclass = {}
jclass["name"] = type(obj).__name__
jclass["dict"] = obj.__dict__
return dict(_class_object=jclass)
else:
return json.JSONEncoder.default(self, obj)
def json_to_class(self, dct):
if '_set_object' in dct:
return set(dct['_set_object'])
elif '_class_object' in dct:
cclass = dct['_class_object']
cclass_name = cclass["name"]
if cclass_name not in REGISTERED_CLASS:
raise RuntimeError(
"Class {} not registered in JSON Parser"
.format(cclass["name"])
)
instance = REGISTERED_CLASS[cclass_name]()
instance.__dict__ = cclass["dict"]
return instance
return dct
def encode_(self, file):
with open(file, 'w') as outfile:
json.dump(
self.__dict__, outfile,
cls=JsonClassSerializable,
indent=4,
sort_keys=True
)
def decode_(self, file):
try:
with open(file, 'r') as infile:
self.__dict__ = json.load(
infile,
object_hook=self.json_to_class
)
except FileNotFoundError:
print("Persistence load failed "
"'{}' do not exists".format(file)
)
class C(JsonClassSerializable):
def __init__(self):
self.mill = "s"
class B(JsonClassSerializable):
def __init__(self):
self.a = 1230
self.c = C()
class A(JsonClassSerializable):
def __init__(self):
self.a = 1
self.b = {1, 2}
self.c = B()
A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
# 1
print(b.b)
# {1, 2}
print(b.c.a)
# 1230
print(b.c.c.mill)
# s
I was having the same problem with android tabs when trying to place them on the bottom of the screen. My scenario was to not use a layout file and create the tabs in code, I was also looking to fire activities from each tab which seemed a bit too complex using other approaches so, here is the sample code to overcome the problem:
You're nearly there, just take out the EXECUTE:
DECLARE
procId NUMBER;
BEGIN
PKG1.INIT(1143824, 0, procId);
DBMS_OUTPUT.PUT_LINE(procId);
END;
<form action="" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file[]" multiple/>
<input type="submit" name="submit" value="Upload Image" />
</form>
Using FOR Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['file']['name']); $x++) {
$file_name = $_FILES['file']['name'][$x];
$file_tmp = $_FILES['file']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Using FOREACH Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
foreach ($_FILES['file']['name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")"
, just add .Dispose()
to it.
File.Create("filename").Dispose();
This way it creates and closes the file for the next process to use it.
There are two possible problems:
AJAX is asynchronous, so json
will be undefined when you return from the outer function. When the file has been loaded, the callback function will set json
to some value but at that time, nobody cares anymore.
I see that you tried to fix this with 'async': false
. To check whether this works, add this line to the code and check your browser's console:
console.log(['json', json]);
The path might be wrong. Use the same path that you used to load your script in the HTML document. So if your script is js/script.js
, use js/content.json
Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc). Check your browser's development tools to see what happens.
bar
is your static variable and you can access it using Foo.bar
.
Basically, you need to qualify your static variable with Class name.
In case you're wondering about the performance of the different approaches, here are some timings:
In [1]: words = [str(i) for i in range(10000)]
In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop
In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop
In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop
In [5]: import re
In [6]: r = re.compile('1')
In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop
as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:
In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop
In [9]: r = re.compile('(1|324|567)')
In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop
This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10
) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.
Check if the Driver Connector jar matches the SQL version.
I was also getting the same error as I was using the
mySQl-connector-java-5.1.30.jar
with MySql 8
Update: 22.01.2019, 13.41 I optimized the solution by jhay, which also supports closing and opening same or different dialogs when for example stepping from one detail data to another forwards or backwards.
(function ($, window) {
'use strict';
var MultiModal = function (element) {
this.$element = $(element);
this.modalIndex = 0;
};
MultiModal.BASE_ZINDEX = 1040;
/* Max index number. When reached just collate the zIndexes */
MultiModal.MAX_INDEX = 5;
MultiModal.prototype.show = function (target) {
var that = this;
var $target = $(target);
// Bootstrap triggers the show event at the beginning of the show function and before
// the modal backdrop element has been created. The timeout here allows the modal
// show function to complete, after which the modal backdrop will have been created
// and appended to the DOM.
// we only want one backdrop; hide any extras
setTimeout(function () {
/* Count the number of triggered modal dialogs */
that.modalIndex++;
if (that.modalIndex >= MultiModal.MAX_INDEX) {
/* Collate the zIndexes of every open modal dialog according to its order */
that.collateZIndex();
}
/* Modify the zIndex */
$target.css('z-index', MultiModal.BASE_ZINDEX + (that.modalIndex * 20) + 10);
/* we only want one backdrop; hide any extras */
if (that.modalIndex > 1)
$('.modal-backdrop').not(':first').addClass('hidden');
that.adjustBackdrop();
});
};
MultiModal.prototype.hidden = function (target) {
this.modalIndex--;
this.adjustBackdrop();
if ($('.modal.in').length === 1) {
/* Reset the index to 1 when only one modal dialog is open */
this.modalIndex = 1;
$('.modal.in').css('z-index', MultiModal.BASE_ZINDEX + 10);
var $modalBackdrop = $('.modal-backdrop:first');
$modalBackdrop.removeClass('hidden');
$modalBackdrop.css('z-index', MultiModal.BASE_ZINDEX);
}
};
MultiModal.prototype.adjustBackdrop = function () {
$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (this.modalIndex * 20));
};
MultiModal.prototype.collateZIndex = function () {
var index = 1;
var $modals = $('.modal.in').toArray();
$modals.sort(function(x, y)
{
return (Number(x.style.zIndex) - Number(y.style.zIndex));
});
for (i = 0; i < $modals.length; i++)
{
$($modals[i]).css('z-index', MultiModal.BASE_ZINDEX + (index * 20) + 10);
index++;
};
this.modalIndex = index;
this.adjustBackdrop();
};
function Plugin(method, target) {
return this.each(function () {
var $this = $(this);
var data = $this.data('multi-modal-plugin');
if (!data)
$this.data('multi-modal-plugin', (data = new MultiModal(this)));
if (method)
data[method](target);
});
}
$.fn.multiModal = Plugin;
$.fn.multiModal.Constructor = MultiModal;
$(document).on('show.bs.modal', function (e) {
$(document).multiModal('show', e.target);
});
$(document).on('hidden.bs.modal', function (e) {
$(document).multiModal('hidden', e.target);
});}(jQuery, window));
Use this command to find your active zone(s):
firewall-cmd --get-active-zones
It will say either public, dmz, or something else. You should only apply to the zones required.
In the case of public try:
firewall-cmd --zone=public --add-port=2888/tcp --permanent
Then remember to reload the firewall for changes to take effect.
firewall-cmd --reload
Otherwise, substitute public for your zone, for example, if your zone is dmz:
firewall-cmd --zone=dmz --add-port=2888/tcp --permanent
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
Use the $_SERVER['HTTP_REFERER']
header, but bear in mind anybody can spoof it at anytime regardless of whether they clicked on a link.
This is an old question maybe even before actual Optional type was introduced but these days you can consider few things: - use method overloading - use Optional type which has advantage of avoiding passing NULLs around Optional type was introduced in Java 8 before it was usually used from third party lib such as Google's Guava. Using optional as parameters / arguments can be consider as over-usage as the main purpose was to use it as a return time.
Ref: https://itcodehub.blogspot.com/2019/06/using-optional-type-in-java.html
You cannot with standard SQL. Column names are not treated like data in SQL.
If you use a SQL engine that has, say, meta-data tables storing column names, types, etc. you may select on that table instead.
You shouldn't be calling .ToString()
.
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString
and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString()
.
Html.Raw
returns an HtmlString
instance that wraps the original string.
The Razor page output knows not to escape HtmlString
instances.
However, calling HtmlString.ToString()
just returns the original string
value again; it doesn't accomplish anything.
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
try
{
for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
{
for (int col = 0; col < dataGridView1.Rows[rows].Cells.Count; col++)
{
s1 = dataGridView1.Rows[0].Cells[0].Value.ToString();
label20.Text = s1;
}
}
}
catch (Exception ex)
{
MessageBox.Show("try again"+ex);
}
Add this code at the end of your .htaccess file
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
If you want to separate the commands into one command per file, you can do
cmd /c start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1"
and in the other file, you can do
cmd /c start "" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow
The command cmd /c will close the command-prompt window after the exe was run.
You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like
value = sequence.index(blarg)
No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/
directory, or Scripts\
on Windows).
The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
I had the same problem and here was my way to solve it:
First, You must know your IP address. On my Windows PC, in the cmd windows i run ipconfig and select my IP V4 address. In my case 192.168.0.13
Second as mention above: runserver 192.168.0.13:8000
It worked for me. The error i did to get the message was the use of the gateway address not my PC address.
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
You have three options:
Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.
As a very blunt hammer, useful for testing, you can use the enable_seqscan
and enable_indexscan
parameters. See:
These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_
params and walk away.
Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?
See also this old newsgroup post.
If you want to see which IP addresses are in use on a specific subnet then there are several different IP Address managers.
Try Angry IP Scanner or Solarwinds or Advanced IP Scanner
I had a similar issue and using %in%
operator instead of the ==
(equality) operator was the solution:
# %in%
Hope it helps.
Sure you can. Something like:
HTML
<div ng-controller="fessCntrl">
<label ng-repeat="(key,val) in list">
<input type="radio" name="localityTypeRadio" ng-model="$parent.localityTypeRadio" ng-value="key" />{{key}}
<div ng-if="key == 'City' || key == 'County'">
<pre>City or County !!! {{$parent.localityTypeRadio}}</pre>
</div>
<div ng-if="key == 'Town'">
<pre>Town!!! {{$parent.localityTypeRadio}}</pre>
</div>
</label>
</div>
JS
var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.list = {
City: [{name: "cityA"}, {name: "cityB"}],
County: [{ name: "countyA"}, {name: "countyB"}],
Town: [{ name: "townA"}, {name: "townB"}]
};
$scope.localityTypeRadio = 'City';
});
fessmodule.$inject = ['$scope'];
Demo Fiddle
Either
svn checkout url://repository/path@1234
or
svn checkout -r 1234 url://repository/path
Since dates are converted to UNIX epoch (numbers), you can use Math.max/min to find those:
var maxDate = Math.max.apply(null, dates)
// convert back to date object
maxDate = new Date(maxDate)
(tested in chrome only, but should work in most browsers)
In Ruby, a block is basically a chunk of code that can be passed to and executed by any method. Blocks are always used with methods, which usually feed data to them (as arguments).
Blocks are widely used in Ruby gems (including Rails) and in well-written Ruby code. They are not objects, hence cannot be assigned to variables.
A block is a piece of code enclosed by { } or do..end. By convention, the curly brace syntax should be used for single-line blocks and the do..end syntax should be used for multi-line blocks.
{ # This is a single line block }
do
# This is a multi-line block
end
Any method can receive a block as an implicit argument. A block is executed by the yield statement within a method. The basic syntax is:
def meditate
print "Today we will practice zazen"
yield # This indicates the method is expecting a block
end
# We are passing a block as an argument to the meditate method
meditate { print " for 40 minutes." }
Output:
Today we will practice zazen for 40 minutes.
When the yield statement is reached, the meditate method yields control to the block, the code within the block is executed and control is returned to the method, which resumes execution immediately following the yield statement.
When a method contains a yield statement, it is expecting to receive a block at calling time. If a block is not provided, an exception will be thrown once the yield statement is reached. We can make the block optional and avoid an exception from being raised:
def meditate
puts "Today we will practice zazen."
yield if block_given?
end meditate
Output:
Today we will practice zazen.
It is not possible to pass multiple blocks to a method. Each method can receive only one block.
See more at: http://www.zenruby.info/2016/04/introduction-to-blocks-in-ruby.html
That's strange, it definitely works for me:
from matplotlib import pyplot as plt
plt.figure(figsize = (20,2))
plt.imshow(random.rand(8, 90), interpolation='nearest')
I am using the "MacOSX" backend, btw.
If you want another approach for solving it that is does not depend on value_counts
or scipy.stats
you can use the Counter
collection
from collections import Counter
get_most_common = lambda values: max(Counter(values).items(), key = lambda x: x[1])[0]
Which can be applied to the above example like this
src = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'],
'City' : ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
'Short_name' : ['NY','New','Spb','NY']})
src.groupby(['Country','City']).agg(get_most_common)
I find answer. Thanks all but right answer next:
$("#myModal").on("hidden", function () {
$('#result').html('yes,result');
});
Events here http://bootstrap-ru.com/javascript.php#modals
UPD
For Bootstrap 3.x need use hidden.bs.modal:
$("#myModal").on("hidden.bs.modal", function () {
$('#result').html('yes,result');
});
This is how you can draw a gray line at the end of your view (same idea as b123400's answer)
class CustomView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
if let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(UIColor.gray.cgColor)
context.setLineWidth(1)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
context.strokePath()
}
}
}
Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.
If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.
Primitives can be converted to objects with @()
expression. So the shortest way is to transform int
to NSNumber
and pick up string representation with stringValue
method:
NSString *strValue = [@(myInt) stringValue];
or
NSString *strValue = @(myInt).stringValue;
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
package-lock.json
is written to when a numerical value in a property such as the "version" property, or a dependency property is changed in package.json
.
If these numerical values in package.json
and package-lock.json
match, package-lock.json
is read from.
If these numerical values in package.json
and package-lock.json
do not match, package-lock.json
is written to with those new values, and new modifiers such as the caret and tilde if they are present. But it is the numeral that is triggering the change to package-lock.json
.
To see what I mean, do the following. Using package.json
without package-lock.json
, run npm install
with:
{
"name": "test",
"version": "1.0.0",
...
"devDependencies": {
"sinon": "7.2.2"
}
}
package-lock.json
will now have:
"sinon": {
"version": "7.2.2",
Now copy/paste both files to a new directory. Change package.json
to (only adding caret):
{
"name": "test",
"version": "1.0.0",
...
"devDependencies": {
"sinon": "^7.2.2"
}
}
run npm install
. If there were no package-lock.json
file, [email protected] would be installed. npm install
is reading from package-lock.json
and installing 7.2.2.
Now change package.json
to:
{
"name": "test",
"version": "1.0.0",
...
"devDependencies": {
"sinon": "^7.3.0"
}
}
run npm install
. package-lock.json
has been written to, and will now show:
"sinon": {
"version": "^7.3.0",
There are long-term maintenance risks as well. First, I'd recommend reading about how Lombok actually works, e.g. some answers from its developers here.
The official site also contains a list of downsides, including this quote from Reinier Zwitserloot:
It's a total hack. Using non-public API. Presumptuous casting (knowing that an annotation processor running in javac will get an instance of JavacAnnotationProcessor, which is the internal implementation of AnnotationProcessor (an interface), which so happens to have a couple of extra methods that are used to get at the live AST).
On eclipse, it's arguably worse (and yet more robust) - a java agent is used to inject code into the eclipse grammar and parser class, which is of course entirely non-public API and totally off limits.
If you could do what lombok does with standard API, I would have done it that way, but you can't. Still, for what its worth, I developed the eclipse plugin for eclipse v3.5 running on java 1.6, and without making any changes it worked on eclipse v3.4 running on java 1.5 as well, so it's not completely fragile.
As a summary, while Lombok may save you some development time, if there is a non-backwards compatible javac update (e.g. a vulnerability mitigation) Lombok might get you stuck with an old version of Java while the developers scramble to update their usage of those internal APIs. Whether this is a serious risk obviously depends on the project.
You need to tell Python to use floating point values, not integers. You can do that simply by using a decimal point yourself in the inputs:
>>> 4/100.0
0.040000000000000001
NetBeans 8.0.2 (PHP) has two problems: the SubVersion client and the Twig templates. In order to drastically improve overall performance, a) disable teh "Twig Templates" plugin (this will also deactivate Symphony2, in case you may require it) and b) override the SVN client with this switch:
run.args.extra=-J-DsvnClientAdapterFactory=commandline
^ project.properties lets one define the CLI arguments individually (which may also make sense with RAM settings and other customization). guess one could re-enable Twig once that linked bug-report has been closed. re-scanning isn't really the issue, while the rescan performs as it should ...in a timely manner.
Just was testing some more and noticed, that on Linux it runs way smoother with the Oracle JDK than the (common) OpenJDK - have seen there is even one version of NetBeans bundled with it.
select * from tbl where (endDate>=@starDate and startDate<=@endDate)
attached the diagram for explanation
storing simple data in DB StartDate =10/01/2020 and endDate=20/01/2020. user can provide @startDate(d1) and @endDate(d2) to search.
here 6 scenarios can happen depicted by the 4 red lines (match data) 2 green lines (no match data).
so by conclusion from the image, to get data from DB by providing d1,d2. ED must be greater than d1(@startDate) and SD must be less than d2(@endDate).
There are multiple ways to do this in particular with Python 3.0 and above
Approach 1
This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
Approach 2
This approach is recommended because it provides more detail about each exception. It includes:
The only drawback is tracback needs to be imported.
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
Hope this helps you.
String fName = "firstname";
String lName = "lastname";
String capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);
String capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);
If you need a body in your response, you can call
return StatusCode(StatusCodes.Status500InternalServerError, responseObject);
This will return a 500 with the response object...
We should ensure that there are no goto statements in the function itself .. taken care by function call being the last thing in the callee function.
Large scale recursions can use this for optimizations, but in small scale, the instruction overhead for making the function call a tail call reduces the actual purpose.
TCO might cause a forever running function:
void eternity()
{
eternity();
}
<?php
// in woocommerce.php
$cat = get_queried_object();
$cat->term_id;
$cat->name;
?>
<?php
// get product cat image
if ( is_product_category() ){
$cat = get_queried_object();
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<img src="' . $image . '" alt="" />';
}
}
?>
See this answer for issues I had with Java 8 and Tomcat 9: Java remote debugging (JPDA) not working for me in Tomcat 9
This is similar to @DAB's warning, and his solution is likely more secure.
Using WifiManager
you can do:
WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}
The method getNeworkId returns -1 only when it's not connected to a network;
The <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
public void paintComponent (Graphics g)
{
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.0f)); // draw transparent background
super.paintComponent(g);
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f)); // turn on opacity
g.setColor(Color.RED);
g.fillRect(20, 20, 500, 300);
}
I have tried to do it this way, but it is very flickery
you could search with
aptitude search intl
after you can choose the right one, for example
sudo aptitude install php-intl
and finally
sudo service apache2 restart
good Luck!
This is an old school approach, but if you're performing an iterative update or insert operation in SQL, something that runs for a long time, it's a good idea to periodically (programmatically) call "checkpoint". Calling "checkpoint" causes SQL to write to disk all of those memory-only changes (dirty pages, they're called) and items stored in the transaction log. This has the effect of cleaning out your transaction log periodically, thus preventing problems like the one described.
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");