After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.
It's incorrect to use zeros in date or in datetime, just put null instead of zeros.
These do the same thing:
window.location.assign(url);
window.location = url;
window.location.href = url;
They simply navigate to the new URL. The replace
method on the other hand navigates to the URL without adding a new record to the history.
So, what you have read in those many forums is not correct. The assign
method does add a new record to the history.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location
Try this , if you are using PHP 5.3+, in php
$query_date = '2010-02-04';
$date = new DateTime($query_date);
//First day of month
$date->modify('first day of this month');
$firstday= $date->format('Y-m-d');
//Last day of month
$date->modify('last day of this month');
$lastday= $date->format('Y-m-d');
For finding next month last date, modify as follows,
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
and so on..
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
should works
Got this from here
var f = document.getElementById('iframe1');
f.src = f.src;
Sorry with my English, When you create a new android project, you should choose api of high level, for example: from api 17 to api 21, It will not have appcompat and very easy to share project. If you did it with lower API, you just edit in Android Manifest to have upper API :), after that, you can delete Appcompat V7.
Use this code for IE9 and above:
window.frames["printf"].focus();
window.frames["printf"].print();
For IE8:
window.frames[0].focus();
window.frames[0].print();
For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.
import urllib.request
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()
Output:
>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]
And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:
import random
upper_words = [word for word in words if word[0].isupper()]
name_words = [word for word in upper_words if not word.isupper()]
rand_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
And some random names:
>>> for n in range(10):
' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])
'Semiramis Sicilian'
'Julius Genevieve'
'Rwanda Cohn'
'Quito Sutherland'
'Eocene Wheller'
'Olav Jove'
'Weldon Pappas'
'Vienna Leyden'
'Io Dave'
'Schwartz Stromberg'
The original question asked to "remove illegal characters":
public string RemoveInvalidChars(string filename)
{
return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));
}
You may instead want to replace them:
public string ReplaceInvalidChars(string filename)
{
return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));
}
This answer was on another thread by Ceres, I really like it neat and simple.
I was wondering if/how I can 'create' a html page for each database row?
You just need to create one php
file that generate an html template, what changes is the text based content on that page. In that page is where you can get a parameter (eg. row id) via POST
or GET
and then get the info form the database.
I'm assuming this would be better for SEO?
Search Engine as Google interpret that example.php?id=33
and example.php?id=44
are different pages, and yes, this way is better than single listing page from the SEO point of view, so you just need two php files at least (listing.php
and single.php
), because is better link this pages from the listing.php
.
Extra advice:
example.php?id=33
is really ugly and not very seo friendly, maybe you need some url rewriting code. Something like example/properties/property-name
is better ;)
You only need []
to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.
The same thing applies at the first level in your loop. It is merely an array and []
is a new empty array - job done.
As for the second level, if Thing
is a class then new Thing()
will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.
class Something {
private things: Thing[][];
constructor() {
this.things = [];
for(var i: number = 0; i < 10; i++) {
this.things[i] = [];
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing();
}
}
}
}
Place it inside another div, use CSS to move the button to the middle:
<div style="width:100%;height:100%;position:absolute;vertical-align:middle;text-align:center;">
<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
mybuttonname</button>
</div>?
Here is an example: JsFiddle
Well, using the static Drawable.createFromPath(String pathName)
seems a bit more straightforward to me than decoding it yourself... :-)
If your mImg
is a simple ImageView
, you don't even need it, use mImg.setImageUri(Uri uri)
directly.
There are two methods you can sometimes use to determine if a recipient actually exists:
You can connect to the server, and issue a VRFY
command. Very few servers support this command, but it is intended for exactly this. If the server responds with a 2.0.0 DSN, the user exists.
VRFY user
You can issue a RCPT
, and see if the mail is rejected.
MAIL FROM:<>
RCPT TO:<user@domain>
If the user doesn't exist, you'll get a 5.1.1 DSN. However, just because the email is not rejected, does not mean the user exists. Some server will silently discard requests like this to prevent enumeration of their users. Other servers cannot verify the user and have to accept the message regardless.
There is also an antispam technique called greylisting, which will cause the server to reject the address initially, expecting a real SMTP server would attempt a re-delivery some time later. This will mess up attempts to validate the address.
Honestly, if you're attempting to validate an address the best approach is to use a simple regex to block obviously invalid addresses, and then send an actual email with a link back to your system that will validate the email was received. This also ensures that they user entered their actual email, not a slight typo that happens to belong to somebody else.
As mentioned in some of the answers/comments already, Python objects already store a dictionary of their attributes (methods aren't included). This can be accessed as __dict__
, but the better way is to use vars
(the output is the same, though). Note that modifying this dictionary will modify the attributes on the instance! This can be useful, but also means you should be careful with how you use this dictionary. Here's a quick example:
class A():
def __init__(self, x=3, y=2, z=5):
self.x = x
self._y = y
self.__z__ = z
def f(self):
pass
a = A()
print(vars(a))
# {'x': 3, '_y': 2, '__z__': 5}
# all of the attributes of `a` but no methods!
# note how the dictionary is always up-to-date
a.x = 10
print(vars(a))
# {'x': 10, '_y': 2, '__z__': 5}
# modifying the dictionary modifies the instance attribute
vars(a)["_y"] = 20
print(vars(a))
# {'x': 10, '_y': 20, '__z__': 5}
Using dir(a)
is an odd, if not outright bad, approach to this problem. It's good if you really needed to iterate over all attributes and methods of the class (including the special methods like __init__
). However, this doesn't seem to be what you want, and even the accepted answer goes about this poorly by applying some brittle filtering to try to remove methods and leave just the attributes; you can see how this would fail for the class A
defined above.
(using __dict__
has been done in a couple of answers, but they all define unnecessary methods instead of using it directly. Only a comment suggests to use vars
).
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.
You can loop through the columns collection of the datatable.
VB
Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
Console.WriteLine(column.ColumnName)
Next
C#
DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}
Hope this helps!
ModeleREP#getTimeSeries()
have to be with @Transient
annotation. That would help.
You could throw the enum value and string into an STL map. Then you could use it like so.
return myStringMap[Enum::Apple];
You have code that is compliled into some IL (intermediate language). When you run your program, the computer doesn't understand this code. It only understands native code. So the JIT compiler compiles your IL into native code on the fly. It does this at the method level.
I have Python 2.7.5, MySQL 5.6 and CentOS 7.1.1503.
For me it worked with the following command:
# pip install mysql-python
Note pre-requisites here:
Install Python pip:
# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm
# yum -y update
Reboot the machine (if kernel is also updated)
# yum -y install python-pip
Install Python devel packages:
# yum install python-devel
Install MySQL devel packages:
# yum install mysql-devel
here is simplest way to do this
first copy these server.crt & server.key files (find in attachment ) into your apache/conf/ssl directory
then open httpd.conf file & add following line
Listen 80
Listen 443
NameVirtualHost *:80
NameVirtualHost *:443
<VirtualHost *:443>
DocumentRoot "d:/wamp/www" #your wamp www root dir
ServerName localhost
SSLEngine on
SSLCertificateFile "d:/wamp/bin/apache/Apache2.4.4/conf/ssl/server.crt"
SSLCertificateKeyFile "d:/wamp/bin/apache/Apache2.4.4/conf/ssl/server.key"
</VirtualHost>
Add a border
to the regular item, the same color
as the background
, so that it cannot be seen. That way the item has a border: 1px
whether it is being hovered or not.
The problem is that /var/www
doesn't exist either, and mkdir
isn't recursive by default -- it expects the immediate parent directory to exist.
Use:
mkdir -p /var/www/app
...or install a package that creates a /var/www
prior to reaching this point in your Dockerfile.
I want to share how I did this. I spent the last few days rattling my head with how to pass a couple of parameters to the bootstrap modal dialog. After much head bashing, I came up with a rather simple way of doing this.
Here is my modal code:
<div class="modal fade" id="editGroupNameModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div id="editGroupName" class="modal-header">Enter new name for group </div>
<div class="modal-body">
<%= form_tag( { action: 'update_group', port: portnum } ) do %>
<%= text_field_tag( :gid, "", { type: "hidden" }) %>
<div class="input-group input-group-md">
<span class="input-group-addon" style="font-size: 16px; padding: 3;" >Name</span>
<%= text_field_tag( :gname, "", { placeholder: "New name goes here", class: "form-control", aria: {describedby: "basic-addon1"}}) %>
</div>
<div class="modal-footer">
<%= submit_tag("Submit") %>
</div>
<% end %>
</div>
</div>
</div>
</div>
And here is the simple javascript to change the gid, and gname input values:
function editGroupName(id, name) {
$('input#gid').val(id);
$('input#gname.form-control').val(name);
}
I just used the onclick event in a link:
// ' is single quote
// ('1', 'admin')
<a data-toggle="modal" data-target="#editGroupNameModal" onclick="editGroupName('1', 'admin'); return false;" href="#">edit</a>
The onclick fires first, changing the value property of the input boxes, so when the dialog pops up, values are in place for the form to submit.
I hope this helps someone someday. Cheers.
Hope this helps, with Serverless framework you can do something like this:
plugins:
- serverless-webpack
custom:
webpackIncludeModules:
forceInclude:
- <your package name> (for example: node-fetch)
2. Then create your Lambda function, deploy it by serverless deploy
, the package that included in serverless.yml will be there for you.
For more information about serverless: https://serverless.com/framework/docs/providers/aws/guide/quick-start/
Just set the TextBox.PasswordChar property to '*'.
This will return you the required cursor
Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw"},
"title_raw like " + "'%Smith%'", null, null, null, null);
try something like this
echo "yours ip addresses are:"
ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1
linux like systems
Building on lonesomeday
's example (upvote that answer not this one), I ran into this output:
undefined NaN, NaN
var datetime = '1324339200000'; //LOOK HERE_x000D_
_x000D_
function prettyDate(date) {_x000D_
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(datetime))); //AND HERE
_x000D_
The cause was using a string as input. To fix it, prefix the string with a plus sign:
prettyDate(new Date(+datetime));
var datetime = '1324339200000';_x000D_
_x000D_
function prettyDate(date) {_x000D_
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(+datetime))); //HERE
_x000D_
To add Hours/Minutes to the output:
var datetime = '1485010730253';_x000D_
_x000D_
function prettyDate(date) {_x000D_
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
return months[date.getUTCMonth()] +' '+ date.getUTCDate()+ ', '+ date.getUTCHours() +':'+ date.getUTCMinutes();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(+datetime)));
_x000D_
Regular grammar:- grammar containing production as follows is RG:
V->TV or VT
V->T
where V=variable and T=terminal
RG may be Left Linear Grammar or Right Liner Grammar, but not Middle linear Grammar.
As we know all RG are Linear Grammar but only Left Linear or Right Linear Grammar are RG.
A regular grammar can be ambiguous.
S->aA|aB
A->a
B->a
Ambiguous Grammar:- for a string x their exist more than one LMD or More than RMD or More than one Parse tree or One LMD and One RMD but both Produce different Parse tree.
S S
/ \ / \
a A a B
\ \
a a
this Grammar is ambiguous Grammar because two parse tree.
CFG:- A grammar said to be CFG if its Production is in form:
V->@ where @ belongs to (V+T)*
DCFL:- as we know all DCFL are LL(1) Grammar and all LL(1) is LR(1) so it is Never be ambiguous. so DCFG is Never be ambiguous.
We also know all RL are DCFL so RL never be ambiguous. Note that RG may be ambiguous but RL not.
CFL: CFl May or may not ambiguous.
Note: RL never be Inherently ambiguous.
Complementing the above answers and also "Parroting" from the Windows Dev Center documentation,
The Winsock2.h header file internally includes core elements from the Windows.h header file, so there is not usually an #include line for the Windows.h header file in Winsock applications. If an #include line is needed for the Windows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, the Windows.h header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in the Winsock.h header file will conflict with the declarations in the Winsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents the Winsock.h from being included by the Windows.h header ..
You can't actually render markup inside a textarea.
But, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.
JavaScript takes care of syncing the content and scroll position.
var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');
var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);
function applyHighlights(text) {
text = text
.replace(/\n$/g, '\n\n')
.replace(/[A-Z].*?\b/g, '<mark>$&</mark>');
if (isIE) {
// IE wraps whitespace differently in a div vs textarea, this fixes it
text = text.replace(/ /g, ' <wbr>');
}
return text;
}
function handleInput() {
var text = $textarea.val();
var highlightedText = applyHighlights(text);
$highlights.html(highlightedText);
}
function handleScroll() {
var scrollTop = $textarea.scrollTop();
$backdrop.scrollTop(scrollTop);
var scrollLeft = $textarea.scrollLeft();
$backdrop.scrollLeft(scrollLeft);
}
function fixIOS() {
$highlights.css({
'padding-left': '+=3px',
'padding-right': '+=3px'
});
}
function bindEvents() {
$textarea.on({
'input': handleInput,
'scroll': handleScroll
});
}
if (isIOS) {
fixIOS();
}
bindEvents();
handleInput();
_x000D_
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 30px;
background-color: #fff;
caret-color: #000;
}
.container,
.backdrop,
textarea {
width: 460px;
height: 180px;
}
.highlights,
textarea {
padding: 10px;
font: 20px/28px 'Open Sans', sans-serif;
letter-spacing: 1px;
}
.container {
display: block;
margin: 0 auto;
transform: translateZ(0);
-webkit-text-size-adjust: none;
}
.backdrop {
position: absolute;
z-index: 1;
border: 2px solid #685972;
background-color: #fff;
overflow: auto;
pointer-events: none;
transition: transform 1s;
}
.highlights {
white-space: pre-wrap;
word-wrap: break-word;
color: #000;
}
textarea {
display: block;
position: absolute;
z-index: 2;
margin: 0;
border: 2px solid #74637f;
border-radius: 0;
color: transparent;
background-color: transparent;
overflow: auto;
resize: none;
transition: transform 1s;
}
mark {
border-radius: 3px;
color: red;
background-color: transparent;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="backdrop">
<div class="highlights"></div>
</div>
<textarea>All capitalized Words will be highlighted. Try Typing to see how it Works</textarea>
</div>
_x000D_
Original Pen: https://codepen.io/lonekorean/pen/gaLEMR
For me the Anonymous User access was fine at the server level, but varied at just one of my "virtual" folders.
Took me quite a bit of foundering about and then some help from a colleague to learn that IIS has "authentication" settings at the virtual folder level too - hopefully this helps someone else with my predicament.
As we know jQuery validate plugin invalidates Select field when it has blank value. Why don't we set its value to blank when required.
Yes, you can validate select field with some predefined value.
$("#everything").validate({
rules: {
select_field:{
required: {
depends: function(element){
if('none' == $('#select_field').val()){
//Set predefined value to blank.
$('#select_field').val('');
}
return true;
}
}
}
}
});
We can set blank value for select field but in some case we can't. For Ex: using a function that generates Dropdown field for you and you don't have control over it.
I hope it helps as it helps me.
Recursively update Windows 7 until it shows no more updates, using Windows Update check option in Windows 7.
Then download and install Visual C++ Redistributable vc_redist.x64.exe from the Windows website.
Then try to run Apache server.
LinearLayout - In LinearLayout, views are organized either in vertical or horizontal orientation.
RelativeLayout - RelativeLayout is way more complex than LinearLayout, hence provides much more functionalities. Views are placed, as the name suggests, relative to each other.
FrameLayout - It behaves as a single object and its child views are overlapped over each other. FrameLayout takes the size of as per the biggest child element.
Coordinator Layout - This is the most powerful ViewGroup introduced in Android support library. It behaves as FrameLayout and has a lot of functionalities to coordinate amongst its child views, for example, floating button and snackbar, Toolbar with scrollable view.
I think the simplest way is to use awk. Example:
$ echo "11383 pts/1 00:00:00 bash" | awk '{ print $4; }'
bash
Easiest way I've found is with feDropShadow
.
<filter id="shadow" x="0" y="0" width="200%" height="200%">
<feDropShadow dx="40" dy="40" stdDeviation="35" flood-color="#ff0000" flood-opacity="1" />
</filter>
On the element:
<path d="..." filter="url(#shadow)"/>
To restart a running service:
net stop "service name" && net start "service name"
However, if you don't know if the service is running in the first place and want to restart or start it, use this:
net stop "service name" & net start "service name"
This works if the service is already running or not.
For reference, here is the documentation on conditional processing symbols.
names = ["tim", "tom", "bob", "alex"]
sql_string = names.map { |t| "name = '#{t}'" }.join(" OR ")
@people = People.where(sql_string)
None of these solutions worked for me.
Instead, I elaborate on @Martin v. Löwis 's mention of setting a config
file for SSH.
SSH will look for the user's ~/.ssh/config
file. I have mine setup as:
Host gitserv
Hostname remote.server.com
IdentityFile ~/.ssh/id_rsa.github
IdentitiesOnly yes # see NOTES below
And I add a remote git repository:
git remote add origin git@gitserv:myrepo.git
And then git commands work normally for me.
git push -v origin master
NOTES
IdentitiesOnly yes
is required to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. If you have a file named ~/.ssh/id_rsa
that will get tried BEFORE your ~/.ssh/id_rsa.github
without this option.References
Some great news! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries (https://mail.python.org/pipermail/python-dev/2016-September/146327.html). This means that the json library is now order preserving by default. Observe the difference in behaviour between python 3.5 and 3.6. The code:
import json
data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
print(json.dumps(data, indent=4))
In py3.5 the resulting order is undefined:
{
"fiddle": {
"bar": 2,
"foo": 1
},
"bar": 2,
"foo": 1
}
In the cPython implementation of python 3.6:
{
"foo": 1,
"bar": 2,
"fiddle": {
"bar": 2,
"foo": 1
}
}
The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html
So the answer to your question now becomes: upgrade to python 3.6! :)
Actually, I did something like this:
select case myconfigtable.valpar
when 'WEEK' then to_char(next_day(datetime-7,'Monday'),'DD/MM/YYYY')|| ' - '|| to_char(next_day(datetime,'Sunday'),'DD/MM/YYYY')
when 'MONTH' then to_char(to_date(yearweek,'yyyyMM'),'DD/MM/YYYY') || ' - '|| to_char(last_day(to_date(yearweek,'yyyyMM')),'DD/MM/YYYY')
else 'NA'
end
from
(
select to_date(YEAR||'01','YYYYMM') + 7 * (WEEK - 1) datetime, yearweek
from
(
select substr(yearweek,1,4) YEAR,
to_number(substr(yearweek,5)) WEEK,
yearweek
from (select '201018' yearweek from dual
)
)
), myconfigtable myconfigtable
where myconfigtable.codpar='TYPEOFPERIOD'
Use Iterators...
var myarray = ['hello', ' hello again'];
processArray(myarray[Symbol.iterator](), () => {
console.log('all done')
})
function processArray(iter, cb) {
var curr = iter.next()
if(curr.done)
return cb()
console.log(curr.value)
processArray(iter, cb)
}
More in depth overview: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters - - p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request.
This example demonstrates how to include the value of a request parameter in the generated output:
Hello <b><%= request.getParameter("name") %></b>!
If the page was accessed with the URL:
http://hostname.com/mywebapp/mypage.jsp?name=John+Smith
the resulting output would be:
Hello <b>John Smith</b>!
If name is not specified on the query string, the output would be:
Hello <b>null</b>!
This example uses the value of a query parameter in a scriptlet:
<%
if (request.getParameter("name") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request. getParameter("name")+"</b>!");
}
%>
If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.
$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!
if (file_exists($vid)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $vid); // check mime type
finfo_close($finfo);
if (preg_match('/video\/*/', $mime_type)) {
$video_attributes = _get_video_attributes($vid, $ffmpeg_path);
print_r('Codec: ' . $video_attributes['codec'] . '<br/>');
print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');
print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
. $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');
print_r('Size: ' . _human_filesize(filesize($vid)));
} else {
print_r('File is not a video.');
}
} else {
print_r('File does not exist.');
}
function _get_video_attributes($video, $ffmpeg) {
$command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
$output = shell_exec($command);
$regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
if (preg_match($regex_sizes, $output, $regs)) {
$codec = $regs [1] ? $regs [1] : null;
$width = $regs [3] ? $regs [3] : null;
$height = $regs [4] ? $regs [4] : null;
}
$regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
if (preg_match($regex_duration, $output, $regs)) {
$hours = $regs [1] ? $regs [1] : null;
$mins = $regs [2] ? $regs [2] : null;
$secs = $regs [3] ? $regs [3] : null;
$ms = $regs [4] ? $regs [4] : null;
}
return array('codec' => $codec,
'width' => $width,
'height' => $height,
'hours' => $hours,
'mins' => $mins,
'secs' => $secs,
'ms' => $ms
);
}
function _human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
The following php snippets would return the text between html tags/elements.
regex : "/tagname(.*)endtag/" will return text between tags.
i.e.
$regex="/[start_tag_name](.*)[/end_tag_name]/";
$content="[start_tag_name]SOME TEXT[/end_tag_name]";
preg_replace($regex,$content);
It will return "SOME TEXT".
Blast from the past but I think I found an easy answer to this. The following worked for me. I think it's the equivalent of selecting the cell hitting F2 and then hitting enter, which makes Excel recognize the text as a date.
Columns("A").Select
Selection.Value = Selection.Value
A little late to the game on this post, but I found this way to be pretty flexible / efficient
select
s1.id
,s1.name
,s1.city
from
stuff s1
,stuff s2
Where
s1.id <> s2.id
and s1.name = s2.name
and s1.city = s2.city
I'll provide a simple Server Side Real World Example here, say if the records are looped and each record has a form with a delete button and you need to delete a specific record, so here comes the hidden
field in action, else you won't get the reference of the record to be deleted in this case, it will be id
For example
<?php
if(isset($_POST['delete_action'])) {
mysqli_query($connection, "DELETE FROM table_name
WHERE record_id = ".$_POST['row_to_be_deleted']);
//Here is where hidden field value is used
}
while(condition) {
?>
<span><?php echo 'Looped Record Name'; ?>
<form method="post">
<input type="hidden" name="row_to_be_deleted" value="<?php echo $record_id; ?>" />
<input type="submit" name="delete_action" />
</form>
<?php
}
?>
Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection
from wget
if you're behind a proxy and don't have HTTP_PROXY
and HTTPS_PROXY
environment variables set correctly. Make sure to set HTTP_PROXY
and HTTPS_PROXY
to point to your proxy.
This is a common situation if you work for a large corporation.
(new FileInfo(filePath)).Directory.Create()
Before writing to the file.
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
As per Prerak K's update comment (since deleted):
I guess I have not presented the question properly.
Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.
So only accessing the value so that corresponding data can be fetched from the database.
The solution you want then should look like:
UserContrl1_LOadDataMethod()
{
string name = "";
if(textbox1.InvokeRequired)
{
textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));
}
if(name == "MyName")
{
// do whatever
}
}
Do your serious processing in the separate thread before you attempt to switch back to the control's thread. For example:
UserContrl1_LOadDataMethod()
{
if(textbox1.text=="MyName") //<<======Now it wont give exception**
{
//Load data correspondin to "MyName"
//Populate a globale variable List<string> which will be
//bound to grid at some later stage
if(InvokeRequired)
{
// after we've done all the processing,
this.Invoke(new MethodInvoker(delegate {
// load the control with the appropriate data
}));
return;
}
}
}
Just use the Cells function and loop thru columns. Cells(Row,Column)
./node_modules/.bin/jest --config test/jest-unit-config.json --runInBand src/components/OpenForm/OpenForm.spec.js -t 'show expanded'
./node_modules/.bin/...
is a wonderful way, to access the locally installed Jest (or Mocha or...) binary that came with the locally installed package. (Yes, in your npm scripts you can jest
with nothing before, but this is handy on command line... (that's also a good start for your debugging config, whichever IDE you are using...)package.json
), this is, what you need.--runInBand
– as said, don't know about your configuration, but if you concentrate on developing/fixing a single test, you rather do not want to deal with web workers...-t
to not run all tests in that file, but only a single one (here: the one, that has something with ‘show expanded
’ in its name). Same effect can be achieved by glueing .only()
into that file.First
pip install pymysql
Then put the code below into __init__.py
(projectname/__init__.py
)
import pymysql
pymysql.install_as_MySQLdb()
My environment is (python3.5, django1.10) and this solution works for me!
Hope this helps!!
For Angular9+, according to this, you can use:
.mat-select-panel {
background: red;
....
}
mat-select-content
as class name for the select list content. For its styling I would suggest four options.
1. Use ::ng-deep:
Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
CSS:
::ng-deep .mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
2. Use ViewEncapsulation
... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.
None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:
Typscript:
import {ViewEncapsulation } from '@angular/core';
....
@Component({
....
encapsulation: ViewEncapsulation.None
})
CSS
.mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
3. Set class style in style.css
This time you have to 'force' styles with !important
too.
style.css
.mat-select-content{
width:2000px !important;
background-color: red !important;
font-size: 10px !important;
}
4. Use inline style
<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>
No, there is no difference, pure syntactic sugar.
What you are probably really wanting to do here is use the union operator like this:
(select ID from Logo where AccountID = 1 and Rendered = 'True')
union
(select ID from Design where AccountID = 1 and Rendered = 'True')
order by ID limit 0, 51
Here's the docs for it https://dev.mysql.com/doc/refman/5.0/en/union.html
-fix- because you want to change from radians to degrees, it is actually rad=deg * math.pi /180 and not deg*180/math.pi
import math
x=1 # in deg
x = x*math.pi/180 # convert to rad
y = math.cos(x) # calculate in rad
print y
in 1 line it can be like this
y=math.cos(1*math.pi/180)
As has been said, they are the same. There are two because bool is a C# keyword and Boolean a .Net class.
Alright, before I go into the solution, lets be on the same line about this one fact: Javascript is Event Based. So you'll usually have to setup callbacks to be able to do procedures.
Based on your comment I assumed you have a trigger that will do the logic that launched the function depending if the element is clicked; for sake of demonstration I made it a "submit button"; but this can be a timer or something else.
var the_action = function(type) {
switch(type) {
case 'a':
console.log('Case A');
break;
case 'b':
console.log('Case B');
break;
}
};
$('.clickme').click(function() {
console.log('Clicked');
$(this).data('clicked', true);
});
$('.submit').click(function() {
// All your logic can go here if you want.
if($('.clickme').data('clicked') == true) {
the_action('a');
} else {
the_action('b');
}
});
Live Example: http://jsfiddle.net/kuroir/6MCVJ/
If you have no option to use server-side programming, such as PHP, you could use the query string, or GET parameters.
In the form, add a method="GET"
attribute:
<form action="display.html" method="GET">
<input type="text" name="serialNumber" />
<input type="submit" value="Submit" />
</form>
When they submit this form, the user will be directed to an address which includes the serialNumber
value as a parameter. Something like:
http://www.example.com/display.html?serialNumber=XYZ
You should then be able to parse the query string - which will contain the serialNumber
parameter value - from JavaScript, using the window.location.search
value:
// from display.html
document.getElementById("write").innerHTML = window.location.search; // you will have to parse
// the query string to extract the
// parameter you need
See also JavaScript query string.
The alternative is to store the values in cookies when the form is submit and read them out of the cookies again once the display.html
page loads.
See also How to use JavaScript to fill a form on another page.
Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:
$(':button.myclass')
To change to a directory with spaces on the name you just have to type like this:
cd My\ Documents
Hit enter and you will be good
Roughly the same kinds of things you've done in C#. Calling getch()
is probably the simplest.
See an example below (this example uses the native JSON object). My changes are commented in CAPITALS:
function Foo(obj) // CONSTRUCTOR CAN BE OVERLOADED WITH AN OBJECT
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
// IF AN OBJECT WAS PASSED THEN INITIALISE PROPERTIES FROM THAT OBJECT
for (var prop in obj) this[prop] = obj[prop];
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
// INITIALISE A NEW FOO AND PASS THE PARSED JSON OBJECT TO IT
var fooJSON = new Foo(JSON.parse('{"a":4,"b":3}'));
alert(fooJSON.test() ); //Prints 12
I just had the same problem in GoLand (which is Intellij IDEA for Go) and worked out a solution. You need to change the Run kind
from File
to Package
or Directory
. You can choose this from a drop-down if you go into Run/Edit
Configurations.
Eg: for package ~/go/src/a_package
, use a Package path
of a_package
and a Directory
of ~/go/src/a_package
and Run kind
of Package
or Directory
.
subprocess.check_output()
returns a bytestring.
In Python 3, there's no implicit conversion between unicode (str
) objects and bytes
objects. If you know the encoding of the output, you can .decode()
it to get a string, or you can turn the \n
you want to add to bytes
with "\n".encode('ascii')
This is a very rudimentary text-based c# program that simulates the spinning action of a slot machine. It doesn't include different odds of winning or cash payouts, but that could be a nice exercise for the students.
Sorry that it is more than 10 lines.
string[] symbols = new[] { "#", "?", "~" }; // The symbols on the reel
Random rand = new Random();
do
{
string a="",b="",c="";
for( int i = 0; i < 20; i++ )
{
Thread.Sleep( 50 + 25 * i ); // slow down more the longer the loop runs
if( i < 10 )
a = symbols[rand.Next( 0, symbols.Length )];
if( i < 15 )
b = symbols[rand.Next( 0, symbols.Length )];
c = symbols[rand.Next( 0, symbols.Length )];
Console.Clear();
Console.WriteLine( "Spin: " + a + b + c );
}
if( a == b && b == c )
Console.WriteLine( "You win. Press enter to play again or type \"exit\" to exit" );
else
Console.WriteLine( "You lose. Press enter to play again or type \"exit\" to exit" );
}
while( Console.ReadLine() != "exit" );
Use the Index property in your DGV's SelectedRows collection:
int index = yourDGV.SelectedRows[0].Index;
If you check the length seperately, you can do the following:
var regularExpression = /^[a-zA-Z]$/;
if (regularExpression.test(newPassword)) {
alert("password should contain atleast one number and one special character");
return false;
}
The Bundle
is a container for all the information you want to save. You use the put* functions to insert data into it. Here's a short list (there are more) of put functions you can use to store data in the Bundle
.
putString
putBoolean
putByte
putChar
putFloat
putLong
putShort
putParcelable (used for objects but they must implement Parcelable)
In your onCreate
function, this Bundle
is handed back to the program. The best way to check if the application is being reloaded, or started for the first time is:
if (savedInstanceState != null) {
// Then the application is being reloaded
}
To get the data back out, use the get* functions just like the put* functions. The data is stored as a name-value pair. This is like a hashmap. You provide a key and the value, then when you want the value back, you give the key and the function gets the value. Here's a short example.
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("message", "This is my message to be reloaded");
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String message = savedInstanceState.getString("message");
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Your saved message will be toasted to the screen. Hope this helps.
I had the same problem (on CentOS 7) and I fixed it by giving execute permissions to /etc/local:
chmod +x /etc/rc.local
I use this line for Spring Boot applications:
logging.level.org.springframework.jdbc.core = TRACE
This approach pretty universal and I usually use it for any other classes inside my application.
According to a quick google search, this update only applies to the current shell you have open. It can probably be fixed by typing python3, as mac and linux are similar enough for things like this to coincide. Link to the result of google search.
Also, as ninjagecko stated, most programs have not been updated to 3.x yet, so having the default python as 3.x would break many python scripts used in applications.
if (position ==0) {
if (rYes.isChecked()) {
Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
} else if (rNo.isChecked()) {
Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
}
}
This code is supposed to select both check boxes.
Is there a problem with it?
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
It's the term slug you want.Looks like you can get the id like this if that's what you need:
function get_term_link( $term, $taxonomy = '' ) {
global $wp_rewrite;
if ( !is_object($term) ) {
if ( is_int( $term ) ) {
$term = get_term( $term, $taxonomy );
} else {
$term = get_term_by( 'slug', $term, $taxonomy );
}
}
1.Run VirtualBox as administrator
2.Go to File -> Preferences -> Network -> Host Only Networks
3.Add a new one or just edit and delete all existed
Adapter Tab:
IPv4 Address: 192.168.0.201
IPv4 Network Mask: 255.255.255.0
DHCP Server Tab:
Server Address: 192.168.0.100
Server Mask: 255.255.255.0
Lower Address Bound: 192.168.0.101
Upper Address Bound: 192.168.0.199
At fast open VirtualBox and then open Genymotion. It then not work just change the Address and try again and restart your PC.
In the end i came to the conclusion that without modifying how the query works i could not store the values in variables. I used SQL profiler to catch the values and then hard coded them into the query to see how it worked. There were 18 of these integer arrays and some had over 30 elements in them.
I think that there is a need for MS/SQL to introduce some aditional datatypes into the language. Arrays are quite common and i don't see why you couldn't use them in a stored proc.
I'm just giving my real time example:
In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".
document.querySelectorAll("[id^='select2-qownerName_select-result']");
When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.
$("[id^='select2-qownerName_select-result']")
I think that the best way to do It, is using google-gson (A Java library to convert JSON to Java objects and vice-versa)
Download It, add "jar" file to your project
HashMap<String, String> map = new HashMap<String, String>();
map.put("key_1", "Baku");
map.put("key_2", "Azerbaijan");
map.put("key_3", "Ali Mamedov");
Gson gson = new Gson();
System.out.println(gson.toJson(map));
Output:
{"key_3":"Ali Mamedov","key_2":"Azerbaijan","key_1":"Baku"}
You can convert any object (arrays, lists and etc) to JSON. I think, that It is the best analog of PHP's var_dump()
Replace
volume = (4 / 3) Math.PI * Math.pow(radius, 3);
With:
volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
The dword ptr
part is called a size directive. This page explains them, but it wasn't possible to direct-link to the correct section.
Basically, it means "the size of the target operand is 32 bits", so this will bitwise-AND the 32-bit value at the address computed by taking the contents of the ebp
register and subtracting four with 0.
What about a private method that simply looks for the element and determines if it is present like this:
private boolean existsElement(String id) {
try {
driver.findElement(By.id(id));
} catch (NoSuchElementException e) {
return false;
}
return true;
}
This would be quite easy and does the job.
Edit: you could even go further and take a By elementLocator
as parameter, eliminating problems if you want to find the element by something other than id.
I got to your case using Bootstrap. This is the simplest solution that works:
select.form-control {_x000D_
-moz-appearance: none;_x000D_
-webkit-appearance: none;_x000D_
appearance: none;_x000D_
background-position: right center;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 1ex;_x000D_
background-origin: content-box;_x000D_
background-image: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMiIKICAgdmlld0JveD0iMCAwIDM1Ljk3MDk4MyAyMy4wOTE1MTgiCiAgIGhlaWdodD0iNi41MTY5Mzk2bW0iCiAgIHdpZHRoPSIxMC4xNTE4MTFtbSI+CiAgPGRlZnMKICAgICBpZD0iZGVmczQiIC8+CiAgPG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhNyI+CiAgICA8cmRmOlJERj4KICAgICAgPGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPgogICAgICAgIDxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PgogICAgICAgIDxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz4KICAgICAgICA8ZGM6dGl0bGU+PC9kYzp0aXRsZT4KICAgICAgPC9jYzpXb3JrPgogICAgPC9yZGY6UkRGPgogIDwvbWV0YWRhdGE+CiAgPGcKICAgICB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMjAyLjAxNDUxLC00MDcuMTIyMjUpIgogICAgIGlkPSJsYXllcjEiPgogICAgPHRleHQKICAgICAgIGlkPSJ0ZXh0MzMzNiIKICAgICAgIHk9IjYyOS41MDUwNyIKICAgICAgIHg9IjI5MS40Mjg1NiIKICAgICAgIHN0eWxlPSJmb250LXN0eWxlOm5vcm1hbDtmb250LXdlaWdodDpub3JtYWw7Zm9udC1zaXplOjQwcHg7bGluZS1oZWlnaHQ6MTI1JTtmb250LWZhbWlseTpzYW5zLXNlcmlmO2xldHRlci1zcGFjaW5nOjBweDt3b3JkLXNwYWNpbmc6MHB4O2ZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MXB4O3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICB4bWw6c3BhY2U9InByZXNlcnZlIj48dHNwYW4KICAgICAgICAgeT0iNjI5LjUwNTA3IgogICAgICAgICB4PSIyOTEuNDI4NTYiCiAgICAgICAgIGlkPSJ0c3BhbjMzMzgiPjwvdHNwYW4+PC90ZXh0PgogICAgPGcKICAgICAgIGlkPSJ0ZXh0MzM0MCIKICAgICAgIHN0eWxlPSJmb250LXN0eWxlOm5vcm1hbDtmb250LXZhcmlhbnQ6bm9ybWFsO2ZvbnQtd2VpZ2h0Om5vcm1hbDtmb250LXN0cmV0Y2g6bm9ybWFsO2ZvbnQtc2l6ZTo0MHB4O2xpbmUtaGVpZ2h0OjEyNSU7Zm9udC1mYW1pbHk6Rm9udEF3ZXNvbWU7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjpGb250QXdlc29tZTtsZXR0ZXItc3BhY2luZzowcHg7d29yZC1zcGFjaW5nOjBweDtmaWxsOiMwMDAwMDA7ZmlsbC1vcGFjaXR5OjE7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIj4KICAgICAgPHBhdGgKICAgICAgICAgaWQ9InBhdGgzMzQ1IgogICAgICAgICBzdHlsZT0iZmlsbDojMzMzMzMzO2ZpbGwtb3BhY2l0eToxIgogICAgICAgICBkPSJtIDIzNy41NjY5Niw0MTMuMjU1MDcgYyAwLjU1ODA0LC0wLjU1ODA0IDAuNTU4MDQsLTEuNDczMjIgMCwtMi4wMzEyNSBsIC0zLjcwNTM1LC0zLjY4MzA0IGMgLTAuNTU4MDQsLTAuNTU4MDQgLTEuNDUwOSwtMC41NTgwNCAtMi4wMDg5MywwIEwgMjIwLDQxOS4zOTM0NiAyMDguMTQ3MzIsNDA3LjU0MDc4IGMgLTAuNTU4MDMsLTAuNTU4MDQgLTEuNDUwODksLTAuNTU4MDQgLTIuMDA4OTMsMCBsIC0zLjcwNTM1LDMuNjgzMDQgYyAtMC41NTgwNCwwLjU1ODAzIC0wLjU1ODA0LDEuNDczMjEgMCwyLjAzMTI1IGwgMTYuNTYyNSwxNi41NDAxNyBjIDAuNTU4MDMsMC41NTgwNCAxLjQ1MDg5LDAuNTU4MDQgMi4wMDg5MiwwIGwgMTYuNTYyNSwtMTYuNTQwMTcgeiIgLz4KICAgIDwvZz4KICA8L2c+Cjwvc3ZnPgo=");_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<section class="container">_x000D_
<form class="form-horizontal">_x000D_
<select class="form-control">_x000D_
<option>One</option>_x000D_
<option>Two</option>_x000D_
</select>_x000D_
</form>_x000D_
</section>
_x000D_
Note: the base64 stuff is fa-chevron-down
in SVG.
Use
table{border-collapse:collapse}
tr{border-top:thin solid}
Replace "thin solid" with CSS properties.
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
Put this line at the top of your source
# -*- coding: utf-8 -*-
If your editor uses a different encoding, substitute for utf-8
Then you can include utf-8 characters directly in the source
By the time you say rate = lambda whatever...
you've defeated the point of lambda and should just define a function. But, if you want a lambda, you can use 'and' and 'or'
lambda(T): (T>200) and (200*exp(-T)) or (400*exp(-T))
Word of warning: if you put config files in your WEB-INF/classes
folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.
I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes
folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.
I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib
folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.
So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties
, next to the classes folder, which is Balus option 2.
It seems the problem is that /
is not floor operation.
int mod(int m, float n)
{
return m - floor(m/n)*n;
}
do {
stuff()
} while (condition())
->
while True:
stuff()
if not condition():
break
You can do a function:
def do_while(stuff, condition):
while condition(stuff()):
pass
But 1) It's ugly. 2) Condition should be a function with one parameter, supposed to be filled by stuff (it's the only reason not to use the classic while loop.)
Free Software 'Bulk Rename Utility' also works well (and is powerful for advanced tasks also). Download and installation takes a minute.
See screenshots and tutorial on original website.
--
I cannot provide step-by-step screenshots as the images will have to be released under Creative Commons License, and I do not own the screenshots of the software.
Disclaimer: I am not associated with the said software/company in any way. I liked the product for my own task, it serves OP's and similar requirements, thus recommending.
There is a boolean type for use in pl/sql, but none that can be used as the data type of a column.
PostgreSQL DLL to add an FK column:
ALTER TABLE one
ADD two_id INTEGER REFERENCES two;
1)Right Click On drawable directory then go to new then go to vector assets 2)change asset type from clip art to local 3)browse your file 4)give size 5)then click next then done Your usable svg will be generated in drawable directory
You have to change
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json");
console.log(this.navItems);
}
for
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json")
.map(res => res.json())
.do(data => console.log(data));
//This is optional, you can remove the last line
// if you don't want to log loaded json in
// console.
}
Because this.http.get
returns an Observable<Response>
and you don't want the response, you want its content.
The console.log
shows you an observable, which is correct because navItems contains an Observable<Response>
.
In order to get data properly in your template, you should use async
pipe.
<app-nav-item-comp *ngFor="let item of navItems | async" [item]="item"></app-nav-item-comp>
This should work well, for more informations, please refer to HTTP Client documentation
To convert from string representation to integer value, we can use std::stringstream.
if the value converted is out of range for integer data type, it returns INT_MIN or INT_MAX.
Also if the string value can’t be represented as an valid int data type, then 0 is returned.
#include
#include
#include
int main() {
std::string x = "50";
int y;
std::istringstream(x) >> y;
std::cout << y << '\n';
return 0;
}
Output: 50
As per the above output, we can see it converted from string numbers to integer number.
Source and more at string to int c++
This can be done by two ways according to your Android OS.
android:largeHeap="true"
in application tag of Android manifest to request a larger heap size, but this will not work on any pre Honeycomb devices.VMRuntime.getRuntime().setMinimumHeapSize(BIGGER_SIZE);
Before Setting HeapSize make sure that you have entered the appropriate size which will not affect other application or OS functionality. Before settings just check how much size your app takes & then set the size just to fulfill your job. Dont use so much of memory otherwise other apps might affect.
Reference: http://dwij.co.in/increase-heap-size-of-android-application
You can write a fallback if Array.isArray and Object.getOwnPropertyNames is not available
XX.isEmpty = function(a){
if(Array.isArray(a)){
return (a.length==0);
}
if(!a){
return true;
}
if(a instanceof Object){
if(a instanceof Date){
return false;
}
if(Object.getOwnPropertyNames(a).length == 0){
return true;
}
}
return false;
}
I have tried all the stuff except clearing the mess in .htaccess file.
Go to www/ directory and make a copy of .htaccess file in another folder. Then clear all the lines in .htaccess original file. And add this line,
RewriteEngine On
Then restart the server. This has solved my problem and got access to all my localhost sites. Hope it would solve yours too.
Just to make someone's life easier, the linq query with lambda expression
(from x in Items where x.Id == 123 select x).FirstOrDefault();
does result in an SQL query with a
select top (1)
in it.
very simple, yet effective method to adjust the size of label text progmatically :-
label.font=[UIFont fontWithName:@"Chalkduster" size:36];
:-)
JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.
Unfortunately, the code
var a = new B(args)(stuff)()
does not result in a syntax error, so no ;
will be inserted. (An example which can run is
var answer = new Function("x", "return x")(function(){return 42;})();
To avoid surprises like this, train yourself to always end a statement with ;
.
If you want only portrait mode, in iOS 9 (Xcode 7) you can:
Say you want to know all methods associated with list class Just Type The following
print (dir(list))
Above will give you all methods of list class
Use
[self dismissViewControllerAnimated:NO completion:nil];
According to the widget's page, it should be:
var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
return this.value;
}).get();
It works for me :)
When passing by value:
void func(Object o);
and then calling
func(a);
you will construct an Object
on the stack, and within the implementation of func
it will be referenced by o
. This might still be a shallow copy (the internals of a
and o
might point to the same data), so a
might be changed. However if o
is a deep copy of a
, then a
will not change.
When passing by reference:
void func2(Object& o);
and then calling
func2(a);
you will only be giving a new way to reference a
. "a
" and "o
" are two names for the same object. Changing o
inside func2
will make those changes visible to the caller, who knows the object by the name "a
".
const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");
Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)
In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
DO NOT use this:
System.Environment.GetEnvironmentVariable("TEMP")
Environment variables can be overridden, so the TEMP
variable is not necessarily the directory.
The correct way is to use System.IO.Path.GetTempPath()
as in the accepted answer.
Use window.open()
:
<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
Share Page
</a>
This will create a link titled Share Page
which opens the current url in a new window with a height of 570 and width of 520.
Always specify the minimum required version of cmake
cmake_minimum_required(VERSION 3.9)
You should declare a project. cmake
says it is mandatory and it will define convenient variables PROJECT_NAME
, PROJECT_VERSION
and PROJECT_DESCRIPTION
(this latter variable necessitate cmake 3.9):
project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
Declare a new library target. Please avoid the use of file(GLOB ...)
. This feature does not provide attended mastery of the compilation process. If you are lazy, copy-paste output of ls -1 sources/*.cpp
:
add_library(mylib SHARED
sources/animation.cpp
sources/buffers.cpp
[...]
)
Set VERSION
property (optional but it is a good practice):
set_target_properties(mylib PROPERTIES VERSION ${PROJECT_VERSION})
You can also set SOVERSION
to a major number of VERSION
. So libmylib.so.1
will be a symlink to libmylib.so.1.0.0
.
set_target_properties(mylib PROPERTIES SOVERSION 1)
Declare public API of your library. This API will be installed for the third-party application. It is a good practice to isolate it in your project tree (like placing it include/
directory). Notice that, private headers should not be installed and I strongly suggest to place them with the source files.
set_target_properties(mylib PROPERTIES PUBLIC_HEADER include/mylib.h)
If you work with subdirectories, it is not very convenient to include relative paths like "../include/mylib.h"
. So, pass a top directory in included directories:
target_include_directories(mylib PRIVATE .)
or
target_include_directories(mylib PRIVATE include)
target_include_directories(mylib PRIVATE src)
Create an install rule for your library. I suggest to use variables CMAKE_INSTALL_*DIR
defined in GNUInstallDirs
:
include(GNUInstallDirs)
And declare files to install:
install(TARGETS mylib
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
You may also export a pkg-config
file. This file allows a third-party application to easily import your library:
pkg-config
PKG_CHECK_MODULES
pkg_check_modules
Create a template file named mylib.pc.in
(see pc(5) manpage for more information):
prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=@CMAKE_INSTALL_PREFIX@
libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: @PROJECT_NAME@
Description: @PROJECT_DESCRIPTION@
Version: @PROJECT_VERSION@
Requires:
Libs: -L${libdir} -lmylib
Cflags: -I${includedir}
In your CMakeLists.txt
, add a rule to expand @
macros (@ONLY
ask to cmake to not expand variables of the form ${VAR}
):
configure_file(mylib.pc.in mylib.pc @ONLY)
And finally, install generated file:
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)
You may also use cmake EXPORT
feature. However, this feature is only compatible with cmake
and I find it difficult to use.
Finally the entire CMakeLists.txt
should looks like:
cmake_minimum_required(VERSION 3.9)
project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
include(GNUInstallDirs)
add_library(mylib SHARED src/mylib.c)
set_target_properties(mylib PROPERTIES
VERSION ${PROJECT_VERSION}
SOVERSION 1
PUBLIC_HEADER api/mylib.h)
configure_file(mylib.pc.in mylib.pc @ONLY)
target_include_directories(mylib PRIVATE .)
install(TARGETS mylib
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)
If you are wanting a client side validation also so you get less of a need to throw exceptions you could try to implement client side file size validation.
Note: This only works in browsers that support HTML5. http://www.html5rocks.com/en/tutorials/file/dndfiles/
<form id="FormID" action="post" name="FormID">
<input id="target" name="target" class="target" type="file" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$('.target').change(function () {
if (typeof FileReader !== "undefined") {
var size = document.getElementById('target').files[0].size;
// check file size
if (size > 100000) {
$(this).val("");
}
}
});
</script>
use this formula to convert a pandas DataFrame to a list of dictionaries :
import json
json_list = json.loads(json.dumps(list(DataFrame.T.to_dict().values())))
So easy we can get the String from files by method: getText();
public class Main {
static int countOfWords(String str) {
if (str.equals("") || str == null) {
return 0;
}else{
int numberWords = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
numberWords++;
}
}
return ++numberWordss;
}
}
}
I can see many answers, not really addressing the three questions of the OP.
1) A word on performance: byte arrays are likely unefficient unless you can use an exact pixel byte ordering which matches to your display adapters current resolution and color depth.
To achieve the best drawing performance, simply convert your image to a BufferedImage which is generated with a type corresponding to your current graphics configuration. See createCompatibleImage at https://docs.oracle.com/javase/tutorial/2d/images/drawonimage.html
These images will be automatically cached on the display card memory after drawing a few times without any programming effort (this is standard in Swing since Java 6), and therefore the actual drawing will take negligible amount of time - if you did not change the image.
Altering the image will come with an additional memory transfer between main memory and GPU memory - which is slow. Avoid "redrawing" the image into a BufferedImage therefore, avoid doing getPixel and setPixel at all means.
For example, if you are developing a game, instead of drawing all the game actors to a BufferedImage and then to a JPanel, it is a lot faster to load all actors as smaller BufferedImages, and draw them one by one in your JPanel code at their proper position - this way there is no additional data transfer between the main memory and GPU memory except of the initial transfer of the images for caching.
ImageIcon will use a BufferedImage under the hood - but basically allocating a BufferedImage with the proper graphics mode is the key, and there is no effort to do this right.
2) The usual way of doing this is to draw a BufferedImage in an overridden paintComponent method of the JPanel. Although Java supports a good amount of additional goodies such as buffer chains controlling VolatileImages cached in the GPU memory, there is no need to use any of these since Java 6 which does a reasonably good job without exposing all of these details of GPU acceleration.
Note that GPU acceleration may not work for certain operations, such as stretching translucent images.
3) Do not add. Just paint it as mentioned above:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
"Adding" makes sense if the image is part of the layout. If you need this as a background or foreground image filling the JPanel, just draw in paintComponent. If you prefer brewing a generic Swing component which can show your image, then it is the same story (you may use a JComponent and override its paintComponent method) - and then add this to your layout of GUI components.
4) How to convert the array to a Bufferedimage
Converting your byte arrays to PNG, then loading it is quite resource intensive. A better way is to convert your existing byte array to a BufferedImage.
For that: do not use for loops and copy pixels. That is very very slow. Instead:
You switch to:
json_decode($response->getBody(), true)
Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.
For PHP 7.x
sudo apt-get install php-zip
For PHP 5.x
sudo apt-get install php5.x-zip
// (for example sudo apt-get install php5.6-zip)
And then restart the Apache server
sudo service apache2 restart
When you tried above solutions and nothing helps, you may need to checkout your local network settings and try to add 8.8.8.8
and your local router ip to the DNS
filed.
For those like @sha1 wondering why the OP's code doesn't work -
OP's logic for deleting player at server side is in the handler for DelPlayer
event,
and the code that emits this event (DelPlayer
) is in inside disconnected
event callback of client.
The server side code that emits this disconnected
event is inside the disconnect
event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected
event doesn't reach the client.
Accepted solution executes the logic on disconnect
event at server side, which is fired when the socket disconnects, hence works.
For me in Java 11 and gradle this is what worked out:
plugins {
id 'java'
}
dependencies {
runtimeOnly 'javax.xml.bind:jaxb-api:2.3.1'
}
With respect to the git vocabulary, a Project is the folder in which the actual content(files) lives. Whereas Repository (repo) is the folder inside which git keeps the record of every change been made in the project folder. But in a general sense, these two can be considered to be the same. Project = Repository
Get meta tags from url, php function example:
function get_meta_tags ($url){
$html = load_content ($url,false,"");
print_r ($html);
preg_match_all ("/<title>(.*)<\/title>/", $html["content"], $title);
preg_match_all ("/<meta name=\"description\" content=\"(.*)\"\/>/i", $html["content"], $description);
preg_match_all ("/<meta name=\"keywords\" content=\"(.*)\"\/>/i", $html["content"], $keywords);
$res["content"] = @array("title" => $title[1][0], "descritpion" => $description[1][0], "keywords" => $keywords[1][0]);
$res["msg"] = $html["msg"];
return $res;
}
Example:
print_r (get_meta_tags ("bing.com") );
Here is my complete, cross browser solution:
In the iframe page:
function printPage() { print(); }
In the main page
function printIframe(id)
{
var iframe = document.frames
? document.frames[id]
: document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
iframe.focus();
ifWin.printPage();
return false;
}
Update: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread!
This works for me.
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = "myusername",
Password = "password"
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Finally - THERE IS YOUR .APP PROJECT FILE !
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), which gives the possibility to name the result of an expression, we can use a list comprehension to replicate what other languages call fold/foldleft/reduce operations:
Given a list, a reducing function and an accumulator:
items = [1, 2, 3, 4, 5]
f = lambda acc, x: acc * x
accumulator = 1
we can fold items
with f
in order to obtain the resulting accumulation
:
[accumulator := f(accumulator, x) for x in items]
# accumulator = 120
or in a condensed formed:
acc = 1; [acc := acc * x for x in [1, 2, 3, 4, 5]]
# acc = 120
Note that this is actually also a "scanleft" operation as the result of the list comprehension represents the state of the accumulation at each step:
acc = 1
scanned = [acc := acc * x for x in [1, 2, 3, 4, 5]]
# scanned = [1, 2, 6, 24, 120]
# acc = 120
This may not be the answer you're looking for, but I'd recommend using the now community maintained repository Laravel Collective Forms & HTML as the main repositories have been deprecated.
Laravel Collective is in the process of updating their website. You may view the documentation on GitHub if needed.
You need to use these parameters in your list view:
Scroll
lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
Set the head of the list to it bottom
lv.setStackFromBottom(true);
You can also set these parameters in XML, eg. like this:
<ListView
...
android:transcriptMode="alwaysScroll"
android:stackFromBottom="true" />
UPDATE FOR VS CODE 1.40.0
After doing:
$ pip install pylint-django
Follow this link: https://code.visualstudio.com/docs/python/linting#_default-pylint-rules
Notice that the way to make pylint
have into account pylint-django
is by specifying:
"python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
in the settings.json
of VS Code.
But after that, you will notice a lot of new linting errors. Then, read what it said here:
These arguments are passed whenever the
python.linting.pylintUseMinimalCheckers
is set totrue
(the default). If you specify a value inpylintArgs
or use a Pylint configuration file (see the next section), thenpylintUseMinimalCheckers
is implicitly set to false.
What I have done is creating a .pylintrc
file as described in the link, and then, configured the following parameters inside the file (leaving the rest of the file untouched):
load-plugins=pylint_django
disable=all
enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode
Now pylint
works as expected.
To complete André's answer, an ant solution could be like the one described in Emacs, JDEE, Ant, and the Eclipse Java Compiler, as in:
<javac
srcdir="${src}"
destdir="${build.dir}/classes">
<compilerarg
compiler="org.eclipse.jdt.core.JDTCompilerAdapter"
line="-warn:+unused -Xemacs"/>
<classpath refid="compile.classpath" />
</javac>
The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.
You can find a full ant script example here which would be invoked in a command line with:
java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data "C:\Documents and Settings\Administrator\workspace" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose
BUT all that involves ant, which is not what Keith is after.
For a batch compilation, please refer to Compiling Java code, especially the section "Using the batch compiler"
The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.
Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.
Running the batch compiler From the command line would give
java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java
or:
java -jar ecj.jar -classpath rt.jar A.java
All java compilation options are detailed in that section as well.
The difference with the Visual Studio command line compilation feature is that Eclipse does not seem to directly read its .project and .classpath in a command-line argument. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.
So, then short answer is: "yes, Eclipse kind of does." ;)
Objective-C:
[label setFont: [label.font fontWithSize: sizeYouWant]];
Swift:
label.font = label.font.fontWithSize(sizeYouWant)
just changes font size of a UILabel.
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
Go to build settings, search for code signing identity, and set Any iOS SDK value for iOS Developer:
UPDATE:
Since this question still gets a lot of hits I'm also adding the current jQM Docs on how to disable the button:
Updated Examples:
enable enable a disabled form button
$('[type="submit"]').button('enable');
disable disable a form button
$('[type="submit"]').button('disable');
refresh update the form button
If you manipulate a form button via JavaScript, you must call the refresh method on it to update the visual styling.
$('[type="submit"]').button('refresh');
Original Post Below:
Live Example: http://jsfiddle.net/XRjh2/2/
UPDATE:
Using @naugtur example below: http://jsfiddle.net/XRjh2/16/
UPDATE #2:
Link button example:
JS
var clicked = false;
$('#myButton').click(function() {
if(clicked === false) {
$(this).addClass('ui-disabled');
clicked = true;
alert('Button is now disabled');
}
});
$('#enableButton').click(function() {
$('#myButton').removeClass('ui-disabled');
clicked = false;
});
HTML
<div data-role="page" id="home">
<div data-role="content">
<a href="#" data-role="button" id="myButton">Click button</a>
<a href="#" data-role="button" id="enableButton">Enable button</a>
</div>
</div>
NOTE: - http://jquerymobile.com/demos/1.0rc2/docs/buttons/buttons-types.html
Links styled like buttons have all the same visual options as true form-based buttons below, but there are a few important differences. Link-based buttons aren't part of the button plugin and only just use the underlying buttonMarkup plugin to generate the button styles so the form button methods (enable, disable, refresh) aren't supported. If you need to disable a link-based button (or any element), it's possible to apply the disabled class ui-disabled yourself with JavaScript to achieve the same effect.
This works:
find ./<SOURCE_DIR>/ -type d | sed 's/\.\/<SOURCE_DIR>//g' | xargs -I {} mkdir -p <DEST_DIR>"/{}"
Just replace SOURCE_DIR and DEST_DIR.
IEnumerable
and IEnumerator
are both interfaces. IEnumerable
has just one method called GetEnumerator
. This method returns (as all methods return something including void) another type which is an interface and that interface is IEnumerator
. When you implement enumerator logic in any of your collection class, you implement IEnumerable
(either generic or non generic). IEnumerable
has just one method whereas IEnumerator
has 2 methods (MoveNext
and Reset
) and a property Current
. For easy understanding consider IEnumerable
as a box that contains IEnumerator
inside it (though not through inheritance or containment). See the code for better understanding:
class Test : IEnumerable, IEnumerator
{
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
public object Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
throw new NotImplementedException();
}
public void Reset()
{
throw new NotImplementedException();
}
}
An easier alternative for those who would prefer not to write all that configuration boilerplate manually...
1) Install Nerdle.AutoConfig from NuGet
2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)
public interface IServiceConfiguration
{
int Port { get; }
ReportType ReportType { get; }
}
3) You'll need a type to hold the collection, e.g.
public interface IServiceCollectionConfiguration
{
IEnumerable<IServiceConfiguration> Services { get; }
}
4) Add the config section like so (note camelCase naming)
<configSections>
<section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>
<serviceCollection>
<services>
<service port="6996" reportType="File" />
<service port="7001" reportType="Other" />
</services>
</serviceCollection>
5) Map with AutoConfig
var services = AutoConfig.Map<IServiceCollectionConfiguration>();
For private schema 'xxx'
in postgresql :
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'xxx' AND table_type = 'BASE TABLE'
Without table_type = 'BASE TABLE'
, you will list tables and views
Hey Try This Code.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "Data has been saved", true);
Cheers
For make a list, simply do that
colors=(red orange white "light gray")
Technically is an array, but - of course - it has all list features.
Even python list are implemented with array
Using the awesome psutil
library it's pretty simple:
p = psutil.Process(pid)
p.terminate() #or p.kill()
If you don't want to install a new library, you can use the os
module:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
See also the os.kill
documentation.
If you are interested in starting the command python StripCore.py
if it is not running, and killing it otherwise, you can use psutil
to do this reliably.
Something like:
import psutil
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'StripCore.py']:
print('Process found. Terminating it.')
process.terminate()
break
else:
print('Process not found: starting it.')
Popen(['python', 'StripCore.py'])
Sample run:
$python test_strip.py #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
$killall python
$python test_strip.py
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
Note: In previous psutil
versions cmdline
was an attribute instead of a method.
I've had this problem many times before with my Galaxy Nexus. Despite having the Android SDK's USB drivers installed, it did not seem to suffice.
I've always solved this by installing a program called PdaNet. While I don't know exactly what it is used for and where it gets its drivers - it comes with the drivers that has always fixed the problem for me. You can uninstall the program itself once it has finished.
Here is a complete sample to show RecyclerView with 2 types, the view type decide by the object
Class model
open class RecyclerViewItem
class SectionItem(val title: String) : RecyclerViewItem()
class ContentItem(val name: String, val number: Int) : RecyclerViewItem()
Adapter code
const val VIEW_TYPE_SECTION = 1
const val VIEW_TYPE_ITEM = 2
class UserAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var data = listOf<RecyclerViewItem>()
override fun getItemViewType(position: Int): Int {
if (data[position] is SectionItem) {
return VIEW_TYPE_SECTION
}
return VIEW_TYPE_ITEM
}
override fun getItemCount(): Int {
return data.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == VIEW_TYPE_SECTION) {
return SectionViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_user_section, parent, false)
)
}
return ContentViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_user_content, parent, false)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = data[position]
if (holder is SectionViewHolder && item is SectionItem) {
holder.bind(item)
}
if (holder is ContentViewHolder && item is ContentItem) {
holder.bind(item)
}
}
internal inner class SectionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: SectionItem) {
itemView.text_section.text = item.title
}
}
internal inner class ContentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: ContentItem) {
itemView.text_name.text = item.name
itemView.text_number.text = item.number.toString()
}
}
}
item_user_section.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eee"
android:padding="16dp" />
item_user_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="32dp">
<TextView
android:id="@+id/text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Name" />
<TextView
android:id="@+id/text_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Example using
val dataSet = arrayListOf<RecyclerViewItem>(
SectionItem("A1"),
ContentItem("11", 11),
ContentItem("12", 12),
ContentItem("13", 13),
SectionItem("A2"),
ContentItem("21", 21),
ContentItem("22", 22),
SectionItem("A3"),
ContentItem("31", 31),
ContentItem("32", 32),
ContentItem("33", 33),
ContentItem("33", 34),
)
recyclerAdapter.data = dataSet
recyclerAdapter.notifyDataSetChanged()
Verify the length
property of the array to be greater than 0
:
<p ng-if="post.capabilities.items.length > 0">
<strong>Topics</strong>:
<span ng-repeat="topic in post.capabilities.items">
{{topic.name}}
</span>
</p>
Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items">
evaluates always to true
, even if the array is empty.
Your PersonSheets has a property int Id
, Id
isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .
According to the docs you can set the parse_mode
field to:
Markdown still works but it's now considered a legacy mode.
You can pass the parse_mode
parameter like this:
https://api.telegram.org/bot[yourBotKey]/sendMessage?chat_id=[yourChatId]&parse_mode=MarkdownV2&text=[yourMessage]
For bold and italic using MarkdownV2:
*bold text*
_italic text_
And for HTML:
<b>bold</b> or <strong>bold</strong>
<i>italic</I> or <em>italic</em>
Make sure to encode your query-string parameters regardless the format you pick. For example:
val message = "*bold text*";
val encodedMsg = URLEncoder.encode(message, "UTF-8");
var message = "*bold text*"
var encodedMsg = encodeURIComponent(message)
$message = "*bold text*";
$encodedMsg = urlencode($message);
If you happen to have a volume bar that you want to adjust –similar to what you see on iPhone's iPod app– here's how.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
//Raise the Volume Bar on the Screen
volumeControl.setProgress( audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
+ AudioManager.ADJUST_RAISE);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
//Adjust the Volume
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
//Lower the VOlume Bar on the Screen
volumeControl.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)
+ AudioManager.ADJUST_LOWER);
return true;
default:
return false;
}
You gave a condition ID (>79 and < 296) then the answer is:
delete from tab
where id > 79 and id < 296
this is the same as:
delete from tab
where id between 80 and 295
if id
is an integer.
All answered:
delete from tab
where id between 79 and 296
this is the same as:
delete from tab
where id => 79 and id <= 296
Mind the difference.
You can find examples for writing OAuth clients here:
In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails
. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:
@EnableOAuth2Client
@Configuration
class MyConfig{
@Value("${oauth.resource:http://localhost:8082}")
private String baseUrl;
@Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
private String authorizeUrl;
@Value("${oauth.token:http://localhost:8082/oauth/token}")
private String tokenUrl;
@Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource;
resource = new ResourceOwnerPasswordResourceDetails();
List scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setAccessTokenUri(tokenUrl);
resource.setClientId("restapp");
resource.setClientSecret("restapp");
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername("**USERNAME**");
resource.setPassword("**PASSWORD**");
return resource;
}
@Bean
public OAuth2RestOperations restTemplate() {
AccessTokenRequest atr = new DefaultAccessTokenRequest();
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
}
}
@Service
@SuppressWarnings("unchecked")
class MyService {
@Autowired
private OAuth2RestOperations restTemplate;
public MyService() {
restTemplate.getAccessToken();
}
}
Do not forget about @EnableOAuth2Client
on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger
with debug
enabled set.
Good luck
I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;
public class NonSwipeableViewPager extends ViewPager {
public NonSwipeableViewPager(Context context) {
super(context);
}
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// stop swipe
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// stop switching pages
return false;
}
private void setMyScroller() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
scroller.set(this, new MyScroller(getContext()));
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyScroller extends Scroller {
public MyScroller(Context context) {
super(context, new DecelerateInterpolator());
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int
duration) {
super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
}
}
}
Then in your Layout.XML file replace any --- com.android.support.V4.ViewPager --- tags with --- com.yourpackage.NonSwipeableViewPager --- tags.
With JTable.AUTO_RESIZE_OFF
, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using the JTable.AUTO_RESIZE_LAST_COLUMN
autoResizeMode, but it might be most effective when used with TableColumn.setMaxWidth()
instead of TableColumn.setPreferredWidth() for all but the last column.
Once you are satisfied that AUTO_RESIZE_LAST_COLUMN
does in fact work, you can experiment with a combination of TableColumn.setMaxWidth()
and TableColumn.setMinWidth()
Check your server's Java version. Happened to me because my Weblogic 10.3.6 was on JDK 1.7.0_75 which was on TLSv1. The rest endpoint I was trying to consume was shutting down anything below TLSv1.2.
By default Weblogic was trying to negotiate the strongest shared protocol. See details here: Issues with setting https.protocols System Property for HTTPS connections.
I added verbose SSL logging to identify the supported TLS. This indicated TLSv1 was being used for the handshake.
-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager -Djava.security.debug=access:stack
I resolved this by pushing the feature out to our JDK8-compatible product, JDK8 defaults to TLSv1.2. For those restricted to JDK7, I also successfully tested a workaround for Java 7 by upgrading to TLSv1.2. I used this answer: How to enable TLS 1.2 in Java 7
Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:
import numpy as np
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
label.set_y(label.get_position()[1] - (i % 2) * 0.075)
For more background and alternatives, see this post on my blog
The backslash \
is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash.
\ (backslash) followed by any of [\^$.|?*+(){} escapes the special character to suppress its special meaning.
You should do the transaction in a Handler
as follows:
@Override
protected void onPostExecute(String result) {
Log.v("MyFragmentActivity", "onFriendAddedAsyncTask/onPostExecute");
new Handler().post(new Runnable() {
public void run() {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
ft.remove(dummyFragment);
ft.commit();
}
});
}
I posted another solution here Which is the best approach to insert an vector (svg) graph into a react native application, This approach use a vector font(from svg) instead a svg file. PS: Its works great in ios and android, and you also can change the color and size of your vector icon.
If you want to insert a svg directly into your app, you can try a 3rd party library : react-native-svg. With more than 3k stars in github it's one of the best approach.
And here's a sample:
import * as React from 'react';
import SvgUri from 'react-native-svg-uri';
import testSvg from './test.svg';
export default () => (
<SvgUri
width="200"
height="200"
svgXmlData={testSvg}
/>
);
Embedded environment, sometime, there is no MMU, less memory, less storage space. In C programming level, almost same, cross compiler do their job.
If you're writing C++, I can't recommend using the Boost libraries strongly enough.
The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.
#include <boost/predef.h>
// ...
#if BOOST_OS_WINDOWS
#elif BOOST_OS_LINUX
#elif BOOST_OS_MACOS
#endif
You can access the first element adding the following code to the highlight
function
$(this).find(".selected td:first").html()
Working Code:JSFIDDLE
public static boolean isPrime(int number) {
if(number < 2)
return false;
else if(number == 2 || number == 3)
return true;
else {
for(int i=2;i<=number/2;i++)
if(number%i == 0)
return false;
else if(i==number/2)
return true;
}
return false;
}
The image below helps show the differences between B+ trees and B trees.
Advantages of B+ trees:
Advantage of B trees:
// import following package
import scala.util.control._
// create a Breaks object as follows
val loop = new Breaks;
// Keep the loop inside breakable as follows
loop.breakable{
// Loop will go here
for(...){
....
// Break will go here
loop.break;
}
}
use Break module http://www.tutorialspoint.com/scala/scala_break_statement.htm
There are several good explanations of "Segmentation fault" in the answers, but since with segmentation fault often there's a dump of the memory content, I wanted to share where the relationship between the "core dumped" part in Segmentation fault (core dumped) and memory comes from:
From about 1955 to 1975 - before semiconductor memory - the dominant technology in computer memory used tiny magnetic doughnuts strung on copper wires. The doughnuts were known as "ferrite cores" and main memory thus known as "core memory" or "core".
Taken from here.
You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.
As of docker-compose file version 3.2, you can specify a volume mount of type "bind" (instead of the default type "volume") that allows you to mount a single file into the container. Search for "bind mount" in the docker-compose volume docs: https://docs.docker.com/compose/compose-file/#volumes
In my case, I was trying to mount a single ".secrets" file into my application that contained secrets for local development and testing only. In production, my application fetches these secrets from AWS instead.
If I mounted this file as a volume using the shorthand syntax:
volumes:
- ./.secrets:/data/app/.secrets
Docker would create a ".secrets" directory inside the container instead of mapping to the file outside of the container. My code would then raise an error like "IsADirectoryError: [Errno 21] Is a directory: '.secrets'".
I fixed this by using the long-hand syntax instead, specifying my secrets file using a read-only "bind" volume mount:
volumes:
- type: bind
source: ./.secrets
target: /data/app/.secrets
read_only: true
Now Docker correctly mounts my .secrets file into the container, creating a file inside the container instead of a directory.
If one uses PDO, additional to all the answers above.
I log my errors silently as below
$q = $this->db->conn_id->prepare($query);
if($q instanceof PDOStatement) {
// go on with bind values and execute
} else {
$dbError = $this->db->error();
$this->Logger_model->logError('Db Error', date('Y-m-d H:i:s'), __METHOD__.' Line '.__LINE__, 'Code: '.$dbError['code'].' - '.'Message: '.$dbError['message']);
}
How to reproduce the bug:
Settings -> Developer Options -> Don't keep Activities
.AsyncTask
is executing and the ProgressDialog
is showing.The Android OS will destroy an activity as soon as it is hidden. When onPostExecute
is called the Activity
will be in "finishing" state and the ProgressDialog
will be not attached to Activity
.
How to fix it:
onPostExecute
method. ProgressDialog
in onDestroy
method. Otherwise, android.view.WindowLeaked
exception will be thrown. This exception usually comes from dialogs that are still active when the activity is finishing.Try this fixed code:
public class YourActivity extends Activity {
private void showProgressDialog() {
if (pDialog == null) {
pDialog = new ProgressDialog(StartActivity.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
}
pDialog.show();
}
private void dismissProgressDialog() {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
@Override
protected void onDestroy() {
dismissProgressDialog();
super.onDestroy();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
@Override
protected void onPreExecute() {
showProgressDialog();
}
//getting All products from url
protected String doInBackground(String... args) {
doMoreStuff("internet");
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
return;
}
dismissProgressDialog();
something(note);
}
}
}
Getting encoding right is really tricky - there are too many layers:
The SQL command "SET CHARSET utf8" from PHP will ensure that the client side (PHP) will get the data in utf8, no matter how they are stored in the database. Of course, they need to be stored correctly first.
Encoding defined for a table/column doesn't really mean that the data are in that encoding. If you happened to have a table defined as utf8
but stored as differtent encoding, then MySQL will treat them as utf8
and you're in trouble. Which means you have to fix this first.
You need to check in what encoding the data flow at each layer.
If you receive data in e.g. windows-1250
, and want to store in utf-8
, then use this SQL before storing:
SET NAMES 'cp1250';
If you have data in DB as windows-1250
and want to retreive utf8
, use:
SET CHARSET 'utf8';
Make sure u close all instances wcfSvcHost and try again. It worked for me!
The answer I was looking for is at https://unix.stackexchange.com/a/9557/114862.
Using the
-c
flag when the local file is of greater or equal size to the server version will avoid re-downloading.
In WebApi 2 you can add this to global.asax
protected void Application_PostAuthorizeRequest()
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
Then you could access the session through:
HttpContext.Current.Session
From Chorme v81 the params --user-data-dir=
requires an actual parameter, whereas in the past it didn't.
Something like this works fine for me
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="\tmp\chrome_test"
Step 1: Highlight the entire column (not including the header) of the column you wish to populate
Step 2: (Using Kutools) On the Insert dropdown, click "Fill Custom List"
Step 3: Click Edit
Step 4: Create your list (For Ex: 1, 2)
Step 5: Choose your new custom list and then click "Fill Range"
DONE!!!
Almost, we can say Python is interpreted language. But we are using some part of one time compilation process in python to convert complete source code into byte-code like java language.
Sometimes it is just how you export and import it. For this error message it could be, that the default keyword is missing.
export default SampleClass {}
Where you instantiate it:
import SampleClass from 'path/to/class';
let sampleClass = new SampleClass();
Option 2, with curly braces:
export SampleClass {}
import { SampleClass } from 'path/to/class';
let sampleClass = new SampleClass();
When you write List
, you actually tell, that your object implements List
interface only, but you don't specify what class your object belongs to.
When you write ArrayList
, you specify that your object class is a resizable-array.
So, the first version makes your code more flexible in future.
Look at Java docs:
Class ArrayList
- Resizable-array implementation of the List
interface.
Interface List
- An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted.
Array
- container object that holds a fixed number of values of a single type.
You can do this two options:
Say if you have
/**
*
*/
public KKSSocket(final KKSApp app, final String name) {
this.app = app;
this.name = name;
...
}
then a sub-class named KKSUDPSocket extending KKSSocket could have:
/**
* @param app
* @param path
* @param remoteAddr
*/
public KKSUDPSocket(KKSApp app, String path, KKSAddress remoteAddr) {
super(app, path, remoteAddr);
}
and
/**
* @param app
* @param path
*/
public KKSUDPSocket(KKSApp app, String path) {
super(app, path);
}
You simply pass the arguments up the constructor chain, like method calls to super classes, but using super(...) which references the super-class constructor and passes in the given args.
The two answers did not solve my issue but combining them, I was able to solve the problem. My situation was I was trying to install and run Docker on a Windows 7 pc and kept getting an error: "Looks like something went wrong... Press any key to continue..."
After much digging, I was able to relate the issue to the host network adapter that was created by Docker. I had the NDIS6 driver installed but it was enabled. I tried to uncheck, disable, recheck, enable etc but it did not help.
I then uninstalled VB and reinstalled as per the first answer to get the NDIS5 driver. This was unchecked, so checking it I was able to move past this issue.
Assume you were:
There are many more examples, but these are the most common, in my experience.
Mutable default arguments don't generally do what you want. Instead, try this:
class Node:
def __init__(self, wordList=None, adjacencyList=None):
if wordList is None:
self.wordList = []
else:
self.wordList = wordList
if adjacencyList is None:
self.adjacencyList = []
else:
self.adjacencyList = adjacencyList
String str = (String)Class.forName("java.lang.String").newInstance();
How does your .NET Webservice look like?
I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)
And everytime I used
Integer result = (Integer)envelope.getResponse();
to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive
exception.
I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.
[SoapRpcMethod(), WebMethod]
public Object GetInteger1(int i)
{
// android device will throw exception
return 0;
}
[WebMethod]
public Object GetInteger2(int i)
{
// android device will get the value
return 0;
}
Then I changed my Android code to:
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString()
method, so I use Integer.parseInt(result.toString())
to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.
Here is the full source:
private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";
public int GetInteger2() throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("i");
pi.setValue(123);
request.addProperty(pi);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
return Integer.parseInt(result.toString());
}
Apache PDF Box can convert PDFs to jpg,bmp,wbmp,png, and gif.
The library even comes with a command line utility called PDFToImage to do this.
If you download the source code and look at the PDFToImage class you should be able to figure out how to use PDF Box to convert PDFs to images from your own Java code.
It depends a bit on what you want:
A) If you want to specify which libraries to link to, you can use find_library to find libs and then use link_directories and target_link_libraries to.
Of course, it is often worth the effort to write a good find_package script, which nicely adds "imported" libraries with add_library( YourLib IMPORTED ) with correct locations, and platform/build specific pre- and suffixes. You can then simply refer to 'YourLib' and use target_link_libraries.
B) If you wish to specify particular linker-flags, e.g. '-mthreads' or '-Wl,--export-all-symbols' with MinGW-GCC, you can use CMAKE_EXE_LINKER_FLAGS. There are also two similar but undocumented flags for modules, shared or static libraries:
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS
Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this:
NameVirtualHost *:80
).Add your virtual host (~line 36):
<VirtualHost *:80>
DocumentRoot C:\Projects\transitCalculator\trunk
ServerName transitcalculator.localhost
<Directory C:\Projects\transitCalculator\trunk>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Open your hosts file (C:\Windows\System32\drivers\etc\hosts).
Add
127.0.0.1 transitcalculator.localhost #transitCalculator
to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).
Now you can access that directory by browsing to http://transitcalculator.localhost/.
Starting ~line 200 of your http.conf
file, copy everything between <Directory "C:/xampp/htdocs">
and </Directory>
(~line 232) and paste it immediately below with C:/xampp/htdocs
replaced with your desired directory (in this case C:/Projects
) to give your server the correct permissions for the new directory.
Find the <IfModule alias_module></IfModule>
section (~line 300) and add
Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
(or whatever is relevant to your desires) below the Alias
comment block, inside the module tags.
Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs"
to #DocumentRoot "C:/Projects"
(or whatever you want).
Edit ~line 203 to match your new location (in this case C:/Projects
).
Notes:
Dispose() calls the code below, which closes the connections opened by the HttpClient instance. The code was created by decompiling with dotPeek.
HttpClientHandler.cs - Dispose
ServicePointManager.CloseConnectionGroups(this.connectionGroupName);
If you don't call dispose then ServicePointManager.MaxServicePointIdleTime, which runs by a timer, will close the http connections. The default is 100 seconds.
ServicePointManager.cs
internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(ServicePointManager.IdleServicePointTimeoutCallback);
private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100000);
private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
ServicePoint servicePoint = (ServicePoint) context;
if (Logging.On)
Logging.PrintInfo(Logging.Web, SR.GetString("net_log_closed_idle", (object) "ServicePoint", (object) servicePoint.GetHashCode()));
lock (ServicePointManager.s_ServicePointTable)
ServicePointManager.s_ServicePointTable.Remove((object) servicePoint.LookupString);
servicePoint.ReleaseAllConnectionGroups();
}
If you haven't set the idle time to infinite then it appears safe not to call dispose and let the idle connection timer kick-in and close the connections for you, although it would be better for you to call dispose in a using statement if you know you are done with an HttpClient instance and free up the resources faster.
in command line first reach the directory where psql is present then write commands like this:
psql [database name] [username]
and then press enter psql asks for password give the user password:
then write
> \i [full path and file name with extension]
then press enter insertion done.
The easiest way is to use supervisord
. Please see full details here: http://supervisord.org/
More info:
To read a binary file to a bytes
object:
from pathlib import Path
data = Path('/path/to/file').read_bytes() # Python 3.5+
To create an int
from bytes 0-3 of the data:
i = int.from_bytes(data[:4], byteorder='little', signed=False)
To unpack multiple int
s from the data:
import struct
ints = struct.unpack('iiii', data[:16])
VSCommands - not an alternative per se, but rather a complementary tool with plenty of unique features not available in ReSharper, CodeRush, and JustCode.
From the website:
IDE Enhancements
* Custom Formatting
o Build Output
o Debug Output
o Search Output
* Solution Properties
o Manage Reference Paths
o Manage Project Properties
* Apply Fix
o File being used by another process
o [StyleCop][2] warnings
o Importing .pfx key file was cancelled
* Search Online
* Cancel Build When First Project Fails
* Advanced Zooming
Solution Explorer Enhancements
* Prevent Accidental Drag & Drop
* Prevent Accidental Linked Item Delete
* Group / Ungroup Items
* Show Assembly Details
* Build Startup Projects
* Open Command Prompt
* Open PowerShell
* Locate Source File
* Open File Location
* Show / Hide All Files
* Edit Project / Solution File
* Copy / Paste As Link
* Copy / Paste Reference
* Open In Expression Blend
* Collapse All
* Clean All Build Configurations
Debugging Assistance
* Attach To Local IIS
* Debug As Administrator
* Debug As Normal user
* Debug As Different user
Code Assistance
* Create Code Contract
You want Directory.CreateDirectory()
Here is a class I use (converted to C#) that if you pass it a source directory and a destination it will copy all of the files and sub-folders of that directory to your destination:
using System.IO;
public class copyTemplateFiles
{
public static bool Copy(string Source, string destination)
{
try {
string[] Files = null;
if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
destination += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(destination)) {
Directory.CreateDirectory(destination);
}
Files = Directory.GetFileSystemEntries(Source);
foreach (string Element in Files) {
// Sub directories
if (Directory.Exists(Element)) {
copyDirectory(Element, destination + Path.GetFileName(Element));
} else {
// Files in directory
File.Copy(Element, destination + Path.GetFileName(Element), true);
}
}
} catch (Exception ex) {
return false;
}
return true;
}
private static void copyDirectory(string Source, string destination)
{
string[] Files = null;
if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
destination += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(destination)) {
Directory.CreateDirectory(destination);
}
Files = Directory.GetFileSystemEntries(Source);
foreach (string Element in Files) {
// Sub directories
if (Directory.Exists(Element)) {
copyDirectory(Element, destination + Path.GetFileName(Element));
} else {
// Files in directory
File.Copy(Element, destination + Path.GetFileName(Element), true);
}
}
}
}