LocalDate date = new Date(); date.lengthOfMonth()
or
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM");
String stringDate = formatter.format(date);
String month = monthFormatter.format(date);
$("#myModal").draggable({
handle: ".modal-header"
});
it works for me. I got it from there. if you give me thanks please give 70% to Andres Ilich
try this:
$string = iconv("UTF-8","UTF-8//IGNORE",$string);
According to the iconv manual, the function will take the first parameter as the input charset, second parameter as the output charset, and the third as the actual input string.
If you set both the input and output charset to UTF-8, and append the //IGNORE
flag to the output charset, the function will drop(strip) all characters in the input string that can't be represented by the output charset. Thus, filtering the input string in effect.
Declare the property place holder as follows
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="locations">
<list>
<value>file:///path.to.your.app.config.properties</value>
</list>
</property>
</bean>
Then lets say you want to read System.property("java.io.tmpdir")
for your Tomcat bean or any bean then add following in your properties file:
tomcat.tmp.dir=${java.io.tmpdir}
This errors means that kubectl
is attempting to connect to a Kubernetes apiserver running on your local machine, which is the default if you haven't configured it to talk to a remote apiserver.
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
I have encountered the same error while trying to execute a script file created in windows OS using textpad. so that one can select proper file format like unix/mac etc.. or recreate the script in linux iteself.
var EM = new events_managment();
EM.addEvent(window, 'resize', function(win,doc, event_){
console.log('resized');
//EM.removeEvent(win,doc, event_);
});
function events_managment(){
this.events = {};
this.addEvent = function(node, event_, func){
if(node.addEventListener){
if(event_ in this.events){
node.addEventListener(event_, function(){
func(node, event_);
this.events[event_](win_doc, event_);
}, true);
}else{
node.addEventListener(event_, function(){
func(node, event_);
}, true);
}
this.events[event_] = func;
}else if(node.attachEvent){
var ie_event = 'on' + event_;
if(ie_event in this.events){
node.attachEvent(ie_event, function(){
func(node, ie_event);
this.events[ie_event]();
});
}else{
node.attachEvent(ie_event, function(){
func(node, ie_event);
});
}
this.events[ie_event] = func;
}
}
this.removeEvent = function(node, event_){
if(node.removeEventListener){
node.removeEventListener(event_, this.events[event_], true);
this.events[event_] = null;
delete this.events[event_];
}else if(node.detachEvent){
node.detachEvent(event_, this.events[event_]);
this.events[event_] = null;
delete this.events[event_];
}
}
}
SOAP 1.1 uses namespace http://schemas.xmlsoap.org/wsdl/soap/
SOAP 1.2 uses namespace http://schemas.xmlsoap.org/wsdl/soap12/
The wsdl is able to define operations under soap 1.1 and soap 1.2 at the same time in the same wsdl. Thats useful if you need to evolve your wsdl to support new functionality that requires soap 1.2 (eg. MTOM), in this case you dont need to create a new service but just evolve the original one.
Following work for me:
Keep following setting blank if you have made in build.gradle.
signingConfigs {
release {
storePassword ""
keyAlias ""
keyPassword ""
}
}
and choose Gradle Task from your Editor window. It will show list of all flavor if you have created.
In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before
css to match yours.
In case if it is IE10 then using below css3 it is possible
select::-ms-expand {
display: none;
}
However if you're interested in jQuery plugin, try Chosen.js
or you can create your own in js.
The JS answer to this question is:
or something similar
Use:
struct arg_struct *args = malloc(sizeof(struct arg_struct));
And pass this arguments like this:
pthread_create(&tr, NULL, print_the_arguments, (void *)args);
Don't forget free args! ;)
I think this is the easiest way to do it.
static bool IsPrime(int number)
{
for (int i = 2; i <= number/2; i++)
if (number % i == 0)
return false;
return true;
}
use java.util.Random
to generate a random number between 0 and array length: random_number
, and then use the random number to get the integer: array[random_number]
You don't need .format. Use durations like this:
const duration = moment.duration(83, 'seconds');
console.log(duration.minutes() + ':' +duration.seconds());
// output: 1:23
I found this solution here: https://github.com/moment/moment/issues/463
EDIT:
And with padding for seconds, minutes and hours:
const withPadding = (duration) => {
if (duration.asDays() > 0) {
return 'at least one day';
} else {
return [
('0' + duration.hours()).slice(-2),
('0' + duration.minutes()).slice(-2),
('0' + duration.seconds()).slice(-2),
].join(':')
}
}
withPadding(moment.duration(83, 'seconds'))
// 00:01:23
withPadding(moment.duration(6048000, 'seconds'))
// at least one day
There are two problems with this question:
Assuming you have a gray scale bitmap, you have two factors to consider:
Answer those questions, and then you might be able to find your original answer.
First, let's see what this does:
Arrays.asList(ia)
It takes an array ia
and creates a wrapper that implements List<Integer>
, which makes the original array available as a list. Nothing is copied and all, only a single wrapper object is created. Operations on the list wrapper are propagated to the original array. This means that if you shuffle the list wrapper, the original array is shuffled as well, if you overwrite an element, it gets overwritten in the original array, etc. Of course, some List
operations aren't allowed on the wrapper, like adding or removing elements from the list, you can only read or overwrite the elements.
Note that the list wrapper doesn't extend ArrayList
- it's a different kind of object. ArrayList
s have their own, internal array, in which they store their elements, and are able to resize the internal arrays etc. The wrapper doesn't have its own internal array, it only propagates operations to the array given to it.
On the other hand, if you subsequently create a new array as
new ArrayList<Integer>(Arrays.asList(ia))
then you create new ArrayList
, which is a full, independent copy of the original one. Although here you create the wrapper using Arrays.asList
as well, it is used only during the construction of the new ArrayList
and is garbage-collected afterwards. The structure of this new ArrayList
is completely independent of the original array. It contains the same elements (both the original array and this new ArrayList
reference the same integers in memory), but it creates a new, internal array, that holds the references. So when you shuffle it, add, remove elements etc., the original array is unchanged.
Not all phones and versions of android have things mounted the same.
Limiting options when remounting would be best.
Simply remount as rw (Read/Write):
# mount -o rw,remount /system
Once you are done making changes, remount to ro (read-only):
# mount -o ro,remount /system
There's an overload of String.Split for this:
"THExxQUICKxxBROWNxxFOX".Split(new [] {"xx"}, StringSplitOptions.None);
The easiest way to solve this in pure HTML is to use the <base href="…">
element like so:
<base href="http://localhost/mywebsite/" />
Then all of the URLs in your HTML can just be this:
<a href="images/example.png">Link To Image</a>
Just change the <base href="…">
to match your server. The rest of the HTML paths will just fall in line and will be appended to that.
Another alternative:
myPlanetsList.Select(i => i.Moons).Sum();
If you need to do a file upload, you'll need to use MediaType.MULTIPART_FORM_DATA_TYPE. Looks like MultivaluedMap cannot be used with that so here's a solution with FormDataMultiPart.
InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);
FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
Well, the simple regex is this:
/^dbo\..*_fn$/
It would be better, however, to use the string manipulation functionality of whatever programming language you're using to slice off the first four and the last three characters of the string and check whether they're what you want.
This won't work for InnoDB. Use this workaround only if you are trying to copy MyISAM databases.
If locking the tables during backup, and, possibly, pausing MySQL during the database import is acceptable, mysqlhotcopy may work faster.
# mysqlhotcopy -u root -p password db_name /path/to/backup/directory
cp /path/to/backup/directory/* /var/lib/mysql/db_name
mysqlhotcopy can also transfer files over SSH (scp), and, possibly, straight into the duplicate database directory.
# mysqlhotcopy -u root -p password db_name /var/lib/mysql/duplicate_db_name
jQuery.val() and .text() will never return 'undefined' for an empty selection. It always returns an empty string (i.e. ""). .html() will return null if the element doesn't exist though.You need to do:
if(page_name != '')
For other variables that don't come from something like jQuery.val() you would do this though:
if(typeof page_name != 'undefined')
You just have to use the typeof
operator.
Just use another container to wrap last two divs. Don't forget to use CSS prefixes.
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
height: 100px;_x000D_
background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
display: flex;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
background-color: red;_x000D_
flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
background-color: blue;_x000D_
flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle">1</div>_x000D_
<div id="anotherContainer">_x000D_
<div id="productShowcaseDetail">2</div>_x000D_
<div id="productShowcaseThumbnailContainer">3</div>_x000D_
</div>_x000D_
</div>
_x000D_
have you tried?
<td title="This is Title">
its working fine here on Firefox v 18 (Aurora), Internet Explorer 8 & Google Chrome v 23x
You can do that using the thenAnswer
method (when chaining with when
):
when(someMock.someMethod()).thenAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
});
Or using the equivalent, static doAnswer
method:
doAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
}).when(someMock).someMethod();
For example, you want to sync table todoTable
from MySql
to Sqlite
First, create one column name version (type INT)
in todoTable
for both Sqlite
and MySql
Second, create a table name database_version
with one column name currentVersion(INT)
In MySql
, when you add a new item to todoTable
or update item, you must upgrade the version of this item by +1 and also upgrade the currentVersion
In Android
, when you want to sync (by manual press sync button or a service run with period time):
You will send the request with the Sqlite
currentVersion (currently it is 1) to server.
Then in server, you find what item in MySql
have version value greater than Sqlite
currentVersion(1) then response to Android (in this example the item 3 with version 2 will response to Android)
In SQLite
, you will add or update new item to todoTable
and upgrade the currentVersion
I solved it by updating the Color Filter when the Switch was state was changed...
public void bind(DetailItem item) {
switchColor(item.toggle);
listSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
switchColor(b);
}
});
}
private void switchColor(boolean checked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
listSwitch.getThumbDrawable().setColorFilter(checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
listSwitch.getTrackDrawable().setColorFilter(!checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
}
}
Font.Name
, Font.XYZProperty
, etc are readonly as Font
is an immutable object, so you need to specify a new Font
object to replace it:
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
Check the constructor of the Font
class for further options.
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
No one will ever see this, but it's good to bring back recursion and arrow functions once in a while (pun gloriously intended)
String.prototype.occurrencesOf = function(s, i) {
return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};
In case someone wants to actually knock out SQL statement logging (without changing logging level, and while keeping the logging from their AR models):
The line that writes to the log (in Rails 3.2.16, anyway) is the call to debug
in lib/active_record/log_subscriber.rb:50
.
That debug method is defined by ActiveSupport::LogSubscriber
.
So we can knock out the logging by overwriting it like so:
module ActiveSupport
class LogSubscriber
def debug(*args, &block)
end
end
end
This is a known bug, try to use "axios": "0.13.1"
https://github.com/mzabriskie/axios/issues/378
I had the same problem so I ended up using "axios": "0.12.0"
. It works fine for me.
I found a much simpler alternative way to generating soap message. Given a Person Object:
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
private String name;
private int age;
private String address; //setter and getters below
}
Below is a simple Soap Message Generator:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@Slf4j
public class SoapGenerator {
protected static final ObjectMapper XML_MAPPER = new XmlMapper()
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule());
private static final String SOAP_BODY_OPEN = "<soap:Body>";
private static final String SOAP_BODY_CLOSE = "</soap:Body>";
private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";
public static String soapWrap(String xml) {
return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
}
public static String soapUnwrap(String xml) {
return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
}
}
You can use by:
public static void main(String[] args) throws Exception{
Person p = new Person();
p.setName("Test");
p.setAge(12);
String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
log.info("Generated String");
log.info(xml);
}
Given this file:
$ cat words.txt
line1 word1 word2
line2 word3 word4
line3 word5 word6
If you just want one word at a time (ignoring the meaning of spaces vs line breaks in the file):
with open('words.txt','r') as f:
for line in f:
for word in line.split():
print(word)
Prints:
line1
word1
word2
line2
...
word6
Similarly, if you want to flatten the file into a single flat list of words in the file, you might do something like this:
with open('words.txt') as f:
flat_list=[word for line in f for word in line.split()]
>>> flat_list
['line1', 'word1', 'word2', 'line2', 'word3', 'word4', 'line3', 'word5', 'word6']
Which can create the same output as the first example with print '\n'.join(flat_list)
...
Or, if you want a nested list of the words in each line of the file (for example, to create a matrix of rows and columns from a file):
with open('words.txt') as f:
matrix=[line.split() for line in f]
>>> matrix
[['line1', 'word1', 'word2'], ['line2', 'word3', 'word4'], ['line3', 'word5', 'word6']]
If you want a regex solution, which would allow you to filter wordN
vs lineN
type words in the example file:
import re
with open("words.txt") as f:
for line in f:
for word in re.findall(r'\bword\d+', line):
# wordN by wordN with no lineN
Or, if you want that to be a line by line generator with a regex:
with open("words.txt") as f:
(word for line in f for word in re.findall(r'\w+', line))
I use following code for get different result from condition That worked for me.
Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)
Do offline rendering to a texture and evaluate the texture's data. You can find related code by googling for "render to texture" opengl Then use glReadPixels to read the output into an array and perform assertions on it (since looking through such a huge array in the debugger is usually not really useful).
Also you might want to disable clamping to output values that are not between 0 and 1, which is only supported for floating point textures.
I personally was bothered by the problem of properly debugging shaders for a while. There does not seem to be a good way - If anyone finds a good (and not outdated/deprecated) debugger, please let me know.
How about just using:
result = [VLOOKUP(DATA!AN2, DATA!AA9:AF20, 5, FALSE)]
Note the [ and ].
Try this DEMO:
$(document).ready(function () {
$("input[name='vehicle']").change(function () {
var maxAllowed = 3;
var cnt = $("input[name='vehicle']:checked").length;
if (cnt > maxAllowed)
{
$(this).prop("checked", "");
alert('Select maximum ' + maxAllowed + ' Levels!');
}
});
});
function converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
In a similar use case, this worked for me...
<button onclick="window.open('https://www.w3.org/', '_blank');"> My Button </button>
i it integer, int to Integer
Integer intObj = new Integer(i);
add to collection
list.add(String.valueOf(intObj));
The options are the same as for the fopen function in the C standard library:
w
truncates the file, overwriting whatever was already there
a
appends to the file, adding onto whatever was already there
w+
opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file
a+
opens for appending and reading, allowing you both to append to the file and also read its contents
You can try this, but second dimension values will be equals to indexes:
$array = array_fill_keys(range(0,5), range(0,5));
a little more complicated for empty array:
$array = array_fill_keys(range(0, 5), array_fill_keys(range(0, 5), null));
No, there is no way to access the element by index in JavaScript objects.
One solution to this if you have access to the source of this JSON, would be to change each element to a JSON object and stick the key inside of that object like this:
var obj = [
{"key":"set1", "data":[1, 2, 3]},
{"key":"set2", "data":[4, 5, 6, 7, 8]},
{"key":"set3", "data":[9, 10, 11, 12]}
];
You would then be able to access the elements numerically:
for(var i = 0; i < obj.length; i++) {
var k = obj[i]['key'];
var data = obj[i]['data'];
//do something with k or data...
}
You should use "merge a range of revision".
To merge changes from the trunk to a branch, inside the branch working copy choose "merge range of revisions" and enter the trunk URL and the start and end revisions to merge.
The same in the opposite way to merge a branch in the trunk.
About the --reintegrate flag, check the manual here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-merge.html#tsvn-dug-merge-reintegrate
What is your reason for having a string as a primary key?
I would just set the primary key to an auto incrementing integer field, and put an index on the string field.
That way if you do searches on the table they should be relatively fast, and all of your joins and normal look ups will be unaffected in their speed.
You can also control the amount of the string field that gets indexed. In other words, you can say "only index the first 5 characters" if you think that will be enough. Or if your data can be relatively similar, you can index the whole field.
I also facing this issue but i follow the following steps:-- 1) I add module(Library) to a particular folder name ThirdPartyLib
To resolve this issue i go settings.gradle than just add follwing:-
project(':').projectDir = new File('ThirdPartyLib/')
:- is module name...
If you are happy with "blah" in somestring
but want it to be a function/method call, you can probably do this
import operator
if not operator.contains(somestring, "blah"):
continue
All operators in Python can be more or less found in the operator module including in
.
If [John Smith]
is in cell A1, then use this formula to do what you want:
=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")
The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.
cd <ANDROID_SDK_PATH>
(for me on Windows cd C:\Users\Willi\AppData\Local\Android\sdk
)cd platform-tools
adb shell
(this works only if only one emulator is running)cd data/data
su
(gain super user privileges)cd <PACKAGE_NAME>/databases
sqlite3 <DB_NAME>
;
, otherwise the statement is not issued and it breaks to a new line instead.)Note: Use ls
(Linux) or dir
(Windows) if you need to list directory contents.
Make it
float b= 3.6f;
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
use this method:
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(label, text);
clipboard.setPrimaryClip(clip);
at the place of setPrimaryClip we can also use the following methods:
void clearPrimaryClip()
Clears any current primary clip on the clipboard.
ClipData getPrimaryClip()
Returns the current primary clip on the clipboard.
ClipDescription getPrimaryClipDescription()
Returns a description of the current primary clip on the clipboard but not a copy of its data.
CharSequence getText()
This method is deprecated. Use getPrimaryClip() instead. This retrieves the primary clip and tries to coerce it to a string.
boolean hasPrimaryClip()
Returns true if there is currently a primary clip on the clipboard.
Faster option:
The following code will copy your Pandas DF to postgres DB much faster than df.to_sql method and you won't need any intermediate csv file to store the df.
Create an engine based on your DB specifications.
Create a table in your postgres DB that has equal number of columns as the Dataframe (df).
Data in DF will get inserted in your postgres table.
from sqlalchemy import create_engine
import psycopg2
import io
if you want to replace the table, we can replace it with normal to_sql method using headers from our df and then load the entire big time consuming df into DB.
engine = create_engine('postgresql+psycopg2://username:password@host:port/database')
df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #drops old table and creates new empty table
conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()
You can get the total number of rows containing a specific name using:
SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'
Given the count, you can now get the nth row using:
SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1
Where 1 <= n <= COUNT(*) from the first query.
Example:
getting the 3rd row
SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1
Don't use print ...,
if you don't want spaces. Use string concatenation or formatting.
Concatenation:
print 'Value is "' + str(value) + '"'
Formatting:
print 'Value is "{}"'.format(value)
The latter is far more flexible, see the str.format()
method documentation and the Formatting String Syntax section.
You'll also come across the older %
formatting style:
print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)
but this isn't as flexible as the newer str.format()
method.
Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:
What is Anonymous FTP?
Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".
…
Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.
These are general recommendations, though. Each FTP server may have its own guidelines.
For sample use of the ftp
command on anonymous FTP access, see appendix A:
atlas.arc.nasa.gov% ftp naic.nasa.gov Connected to naic.nasa.gov. 220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready. Name (naic.nasa.gov:amarine): anonymous 331 Guest login ok, send your complete e-mail address as password. Password: 230----------------------------------------------------------------- 230-Welcome to the NASA Network Applications and Info Center Archive 230- 230- Access to NAIC's online services is also available through: 230- 230- Gopher - naic.nasa.gov (port 70) 230- World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html 230- 230- If you experience any problems please send email to 230- 230- [email protected] 230- 230- or call +1 (800) 858-9947 230----------------------------------------------------------------- 230- 230-Please read the file README 230- it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago 230 Guest login ok, access restrictions apply. ftp> cd files/rfc 250-Please read the file README.rfc 250- it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago 250 CWD command successful. ftp> get rfc959.txt 200 PORT command successful. 150 Opening ASCII mode data connection for rfc959.txt (147316 bytes). 226 Transfer complete. local: rfc959.txt remote: rfc959.txt 151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s) ftp> quit 221 Goodbye. atlas.arc.nasa.gov%
See also the example session at the University of Edinburgh site.
I was looking for an elegant solution that support quoting and wouldn't require installing anything fancy on my VMware vMA appliance. Turns out this simple python script does the trick! (I named the script csv2tsv.py
, since it converts CSV into tab-separated values - TSV)
#!/usr/bin/env python
import sys, csv
with sys.stdin as f:
reader = csv.reader(f)
for row in reader:
for col in row:
print col+'\t',
print
Tab-separated values can be split easily with the cut command (no delimiter needs to be specified, tab is the default). Here's a sample usage/output:
> esxcli -h $VI_HOST --formatter=csv network vswitch standard list |csv2tsv.py|cut -f12
Uplinks
vmnic4,vmnic0,
vmnic5,vmnic1,
vmnic6,vmnic2,
In my scripts I'm actually going to parse tsv output line by line and use read or cut to get the fields I need.
http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedWriter.html
In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
$.each(arrofobject, function(index, val) {
console.log(val.category);
});
Try PowerShell Type like:
$cn = new-object system.data.SqlClient.SQLConnection("Data Source=server1;Initial Catalog=db1;User ID=user1;Password=password1");
$cmd = new-object system.data.sqlclient.sqlcommand("exec Proc1", $cn);
$cn.Open();
$cmd.CommandTimeout = 0
$cmd.ExecuteNonQuery()
$cn.Close();
The chunks of SQL are blocked off with "Table structure for table my_table
" and "Dumping data for table my_table
."
You can use a Windows command line as follows to get the line numbers for the various sections. Adjust the searched string as needed.
find /n "for table `" sql.txt
The following will be returned:
---------- SQL.TXT
[4384]-- Table structure for table my_table
[4500]-- Dumping data for table my_table
[4514]-- Table structure for table some_other_table
... etc.
That gets you the line numbers you need... now, if I only knew how to use them... investigating.
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
You are checking isset($_GET['event_id']
but you've not set that get variable in your hyperlink, you are just adding email
http://localhost/main.php?email=" . $email_address . $event_id
And add another GET variable in your link
$url = "http://localhost/main.php?email=$email_address&event_id=$event_id";
You did not use to concatenate your string if you are using "
quotes
Using the JDK, jar -tf
will list the files in the jar. javap
will give you more details from a particular class file.
To ignore untracked files just go to .git/info/exclude. Exclude is a file with a list of ignored extensions or files.
I don't know a good free tool but winmerge is ok(ish). I've been using the beyond compare tools since 1999 and can't rate it enough - it costs about 50 USD and this investment has paid for it self in time savings more than I can possible imagine.
Sometimes tools should be paid for if they are very very good.
This worked for me
If build are missing from Itunes 'Activity' tab. Then check your info.plist keys. If all keys are there, then check all keys description. if their length is short then increase your keys description length.
The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in this activestate recipe
#!/usr/bin/python
import fcntl, socket, struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ':'.join(['%02x' % ord(char) for char in info[18:24]])
print getHwAddr('eth0')
This is the Python 3 compatible code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import fcntl
import socket
import struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
return ':'.join('%02x' % b for b in info[18:24])
def main():
print(getHwAddr('enp0s8'))
if __name__ == "__main__":
main()
based on https://stackoverflow.com/a/27891752/2642478
class Version(private val value: String) : Comparable<Version> {
private val splitted by lazy { value.split("-").first().split(".").map { it.toIntOrNull() ?: 0 } }
override fun compareTo(other: Version): Int {
for (i in 0 until maxOf(splitted.size, other.splitted.size)) {
val compare = splitted.getOrElse(i) { 0 }.compareTo(other.splitted.getOrElse(i) { 0 })
if (compare != 0)
return compare
}
return 0
}
}
you can use like:
System.err.println(Version("1.0").compareTo( Version("1.0")))
System.err.println(Version("1.0") < Version("1.1"))
System.err.println(Version("1.10") > Version("1.9"))
System.err.println(Version("1.10.1") > Version("1.10"))
System.err.println(Version("0.0.1") < Version("1"))
According to the API the constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long. You could use a Calendar implementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillis method.
Hope this wil help
int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };
var duplicates = listOfItems
.GroupBy(i => i)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
foreach (var d in duplicates)
Console.WriteLine(d);
more generally, this could also look like this:
import multiprocessing
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
numberOfThreads = 4
if __name__ == '__main__':
jobs = []
for i, param in enumerate(params):
p = multiprocessing.Process(target=f, args=(i,param))
jobs.append(p)
for i in chunks(jobs,numberOfThreads):
for j in i:
j.start()
for j in i:
j.join()
Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.
Make sure drush is installed (you may also need to make sure the dblog module is enabled) and use:
drush watchdog-show --tail
Available in drush v8 and below.
This will give you a live look at the logs from your console.
This works! https://reacttraining.com/react-router/web/api/withRouter
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
render () {
this.props.history;
}
}
withRouter(MyComponent);
according to @jreback here https://github.com/conda/conda/issues/1166
conda config --set ssl_verify false
will turn off this feature, e.g. here
Sometimes if it was not even defined is better to be prepared. For this I used typeof
if(typeof(variable) !== "undefined") {
//it exist
if(variable !== null) {
//and is not null
}
else {
//but is null
}
}
else {
//it doesn't
}
You're performing an integer division. Append a .0
to the number literals:
per=float(tota)*(100.0/500.0)
In Python 2.7 the division 100/500==0
.
As pointed out by @unwind, the float()
call is superfluous since a multiplication/division by a float returns a float:
per= tota*100.0 / 500
Regarding how you log messages within code, I would opt for the second approach:
ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");
Where messages sent to the log above will be 'named' using the fully-qualifed type Bar
, e.g.
MyNamespace.Foo.Bar [INFO] message
The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar
specifically to DEBUG:
<log4net>
<!-- appenders go here -->
<root>
<level value="INFO" />
<appender-ref ref="myLogAppender" />
</root>
<logger name="MyNamespace.Foo.Bar">
<level value="DEBUG" />
</logger>
</log4net>
The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog"
, you loose much of this power!
Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.
For further reading, here is a codeproject article I wrote on logging:
I know this is an old post but I came across it when faced with a similar issue using core 3.0, hope it helps someone.
@{
Layout = null;
ViewData["SampleString"] = "some string need in the partial";
}
<partial name="_Partial" for="PartialViewModel" view-data="ViewData" />
Structs can have functions just like classes. The only difference is that they are public by default:
struct A {
void f() {}
};
Additionally, structs can also have constructors and destructors.
struct A {
A() : x(5) {}
~A() {}
private: int x;
};
Basically you shouldn't do exact comparisons, you should do something like this:
double a = 1.000001;
double b = 0.000001;
double c = a-b;
if (Math.abs(c-1.0) <= 0.000001) {...}
It sounds like the populate method is what your looking for. First make small change to your post schema:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Then make your model:
var Post = mongoose.model('Post', postSchema);
Then, when you make your query, you can populate references like this:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
For those who Google for this error and arrive here: there might be another reason for receiving it. Eclipse gives this error when you have project setup - system configuration mismatch.
For example, if you import Java 1.7 project to Eclipse and you do not have 1.7 correctly set up then you will get this error. Then you can either go to Project - Preference - Java - Compiler
and switch to 1.6 or earlier
; or go to Window - Preferences - Java - Installed JREs
and add/fix your JRE 1.7 installation.
You can get the context using
getActivity().getApplicationContext();
Also remember that an uninstall can be initiated using the WMIC command:
wmic product get name
--> This will list the names of all installed apps
wmic product where name='myappsname' call uninstall
--> this will uninstall the app.
I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch
, then remove them manually, but this will not work well if there are a lot.
Here is a solution that utilizes bash arrays to capture all files.
# Build bash array of the file names
while read -r file; do
rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)
git rm –-cached "${rmlist[@]}"
git commit -m 'ignore update'
It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.
Note: A) Curly brackets are safer because they don't allow narrowing. B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.
Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)
namespace FileUpload
{
public partial class Form1 : Form
{
string fileName = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = "";
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Attach customer proposal document";
fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
fDialog.InitialDirectory = @"C:\";
if (fDialog.ShowDialog() == DialogResult.OK)
{
fileName = System.IO.Path.GetFileName(fDialog.FileName);
path = Path.GetDirectoryName(fDialog.FileName);
textBox1.Text = path + "\\" + fileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential("erandika1986", "123");
Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
MessageBox.Show(arrReturn.ToString());
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
}
}
using (WebClient client = new WebClient())
{
client.DownloadFile("http://csharpindepth.com/Reviews.aspx",
@"c:\Users\Jon\Test\foo.txt");
}
If your main project using some library projects and have reference to them, you can cause this problem if your project reference to a assembly dll file instead to library project when you change something in your library project (ex: rename a class).
You can check all references to your main project by view in Object Browser window (menu View->Object Browser). A reference to a dll file always has a version number. Ex: TestLib [1.0.0.0]
Solution: delete the current reference of your main project to the library project and add reference to that library project again.
Mid(strYourString, 4)
(i.e. without the optional length argument) will return the substring starting from the 4th character and going to the end of the string.
To have newline in code you use _
Example:
Dim a As Integer
a = 500 _
+ 80 _
+ 90
MsgBox a
I'm late to the party but I found some useful instructions in github help page and I wanted to share them here.
Sometimes, Git can't make your change to a remote repository without losing commits. When this happens, your push is refused.
If another person has pushed to the same branch as you, Git won't be able to push your changes:
$ git push origin master
To https://github.com/USERNAME/REPOSITORY.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/USERNAME/REPOSITORY.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again. See the
'Note about fast-forwards' section of 'git push --help' for details.
You can fix this by fetching and merging the changes made on the remote branch with the changes that you have made locally:
$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work
Or, you can simply use git pull
to perform both commands at once:
$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work
Maybe it's possible to debug PHP on Visual Studio, but it's simpler and more logical to use Eclipse PDT or Netbeans IDE for your PHP projects, aside from Visual Studio if you need to use both technologies from two different vendors.
You can use jQuery
to achieve this
Example:
$(function () {
$('.map').maphilight();
});
Go through this LINK to know more.
If the above one doesnt work then go through this link.
EDIT :
Give same class to each area
tag like class="mapping"
and try this below code
$('.mapping').mouseover(function() {
alert($(this).attr('id'));
}).mouseout(function(){
alert('Mouseout....');
});
library(tidyverse)
df_1 %>%
group_by(Year, Month) %>%
summarise(count= n())
If your List
is sorted and has good random access (as ArrayList
does), you should look into Collections.binarySearch
. Otherwise, you should use List.indexOf
, as others have pointed out.
But your algorithm is sound, fwiw (other than the ==
others have pointed out).
The photos
property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count
property of the array):
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
<input type="image" src="path to image" name="submit" />
UPDATE:
For button states, you can use type="submit" and then add a class to it
<input type="submit" name="submit" class="states" />
Then in css, use background images for:
.states{
background-image:url(path to url);
height:...;
width:...;
}
.states:hover{
background-position:...;
}
.states:active{
background-position:...;
}
Arrays of data are converted into csv 'text/csv' format by built in php function fputcsv takes care of commas, quotes and etc..
Look at
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
http://www.php.net/manual/en/function.fputcsv.php
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
data_initial = open("staff.csv", "rb")
data = csv.reader((line.replace('\0','') for line in data_initial), delimiter=",")
This works for me.
In Jackson 2.4, you can convert as follows:
MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);
where jsonObjectMapper
is a Jackson ObjectMapper
.
In older versions of Jackson, it would be
MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);
Another alternative is to add the appProperties bean shown below:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/app.properties" />
</bean>
<bean id="appProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="singleton" value="true"/>
<property name="properties">
<props>
<prop key="results.max">${results.max}</prop>
</props>
</property>
</bean>
When retrieved, this bean can be cast to a java.util.Properties
which will contain a property named results.max
whose value is read from app.properties
. Again, this bean can be dependency injected (as an instance of java.util.Properties) into any class via the @Resource annotation.
Personally, I prefer this solution (to the other I proposed), as you can limit exactly which properties are exposed by appProperties, and don't need to read app.properties twice.
To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where
In [79]: animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
....: 'height': [9.1, 6.0, 9.5, 34.0],
....: 'weight': [7.9, 7.5, 9.9, 198.0]})
....:
In [80]: animals
Out[80]:
kind height weight
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [81]: animals.groupby("kind").agg(
....: min_height=pd.NamedAgg(column='height', aggfunc='min'),
....: max_height=pd.NamedAgg(column='height', aggfunc='max'),
....: average_weight=pd.NamedAgg(column='weight', aggfunc=np.mean),
....: )
....:
Out[81]:
min_height max_height average_weight
kind
cat 9.1 9.5 8.90
dog 6.0 34.0 102.75
pandas.NamedAgg is just a namedtuple. Plain tuples are allowed as well.
In [82]: animals.groupby("kind").agg(
....: min_height=('height', 'min'),
....: max_height=('height', 'max'),
....: average_weight=('weight', np.mean),
....: )
....:
Out[82]:
min_height max_height average_weight
kind
cat 9.1 9.5 8.90
dog 6.0 34.0 102.75
Additional keyword arguments are not passed through to the aggregation functions. Only pairs of (column, aggfunc) should be passed as **kwargs. If your aggregation functions requires additional arguments, partially apply them with functools.partial().
Named aggregation is also valid for Series groupby aggregations. In this case there’s no column selection, so the values are just the functions.
In [84]: animals.groupby("kind").height.agg(
....: min_height='min',
....: max_height='max',
....: )
....:
Out[84]:
min_height max_height
kind
cat 9.1 9.5
dog 6.0 34.0
I found a solution for this problem after a long analysing procedure.
After properly testing my php installation with the command line features I found out that the php is working well and could work with the mysql database. Btw. you can run code-files with php code with the command php -f filename.php
So I realized, it must something be wrong with the Apache.
I made a file with just the phpinfo() function inside.
Here I saw, that in the line
Loaded Configuration File
my config file was not loaded, instead there was mentioned (none).
Finally I found within the Apache configuration the entry
<IfModule php5_module>
PHPINIDir "C:/xampp/php"
</IfModule>
But I've installed the PHP 7 and so the Apache could not load the php.ini file because there was no entry for that. I added
<IfModule php7_module>
PHPINIDir "C:/xampp/php"
</IfModule>
and after restart Apache all works well.
These code blocks above I found in my httpd-xampp.conf file. May it is somewhere else at your configuration.
In the same file I had changed before the settings for the php 7 as replacement for the php 5 version.
#
# PHP-Module setup
#
#LoadFile "C:/xampp/php/php5ts.dll"
#LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"
LoadFile "C:/xampp/php/php7ts.dll"
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"
As you can see I have the xampp package installed but this problem was just on the Apache side.
Use the -r
option ("use extended regular expressions in the script") to sed
in order to use the {n}
syntax:
$ echo 'pid: 1234'| sed -r 's/^.{5}//'
1234
No, there is no builtin function that converts two's complement binary strings into decimals.
A simple user defined function that does this:
def two2dec(s):
if s[0] == '1':
return -1 * (int(''.join('1' if x == '0' else '0' for x in s), 2) + 1)
else:
return int(s, 2)
Note that this function doesn't take the bit width as parameter, instead positive input values have to be specified with one or more leading zero bits.
Examples:
In [2]: two2dec('1111')
Out[2]: -1
In [3]: two2dec('111111111111')
Out[3]: -1
In [4]: two2dec('0101')
Out[4]: 5
In [5]: two2dec('10000000')
Out[5]: -128
In [6]: two2dec('11111110')
Out[6]: -2
In [7]: two2dec('01111111')
Out[7]: 127
find / -exec grep -lR "{test-string}" {} \;
Create uninitialized multidimensional array:
function MultiArray(a) {
if (a.length < 1) throw "Invalid array dimension";
if (a.length == 1) return Array(a[0]);
return [...Array(a[0])].map(() => MultiArray(a.slice(1)));
}
Create initialized multidimensional array:
function MultiArrayInit(a, init) {
if (a.length < 1) throw "Invalid array dimension";
if (a.length == 1) return Array(a[0]).fill(init);
return [...Array(a[0])].map(() => MultiArrayInit(a.slice(1), init));
}
Usage:
MultiArray([3,4,5]); // -> Creates an array of [3][4][5] of empty cells
MultiArrayInit([3,4,5], 1); // -> Creates an array of [3][4][5] of 1s
I have got kept a handy helper method to take care of this based on one answer posted above:
Imports:
import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil
Function:
fun parseCountryCode( phoneNumberStr: String?): String {
val phoneUtil = PhoneNumberUtil.getInstance()
return try {
// phone must begin with '+'
val numberProto = phoneUtil.parse(phoneNumberStr, "")
numberProto.countryCode.toString()
} catch (e: NumberParseException) {
""
}
}
In git
stash is a storage area where current changed files can be moved.
stash
area is useful when you want to pull some changes from git
repository and detected some changes in some mutual files available in git
repo.
git stash apply //apply the changes without removing stored files from stash area.
git stash pop // apply the changes as well as remove stored files from stash area.
Note :-
git apply
only apply the changes from stash area whilegit pop
apply as well as remove change fromstash
area.
In my career I often needed to draw UML diagrams and generate Java code. I found MagicDraw most appealing and I'm a happy user. I think their licensing model is fair because it allows to pay for what you need. I prefer it to other products I used in my (distant) past: ArgoUML, Poseidon, Rational Rose, Dia. Be aware that my experiences on other products are obsolete and have maybe significantly improved or changed their licensing model. Maybe you should start with an open-source tool and decide later whether to spend some bucks.
With MagicDraw you can document your code by generating diagrams from code. You can also model first, then generate the code. It also integrates well with several IDEs.
When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.
I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91
Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.
If any one searching for Angular
you just need to scroll down add this to your div
#scrollMe [scrollTop]="scrollMe.scrollHeight"
<div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
</div>
Don't forget TemplatedParent:
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>
or
{Binding RelativeSource={RelativeSource TemplatedParent}}
If you ever wondered how to do it using the new BDD style of Mockito:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
And for future reference one may need to throw exception and then do nothing:
willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
If you use MyISAM, you won't be doing any transactions per hour, unless you consider each DML statement to be a transaction (which in any case, won't be durable or atomic in the event of a crash).
Therefore I think you have to use InnoDB.
300 transactions per second sounds like quite a lot. If you absolutely need these transactions to be durable across power failure make sure your I/O subsystem can handle this many writes per second easily. You will need at least a RAID controller with battery backed cache.
If you can take a small durability hit, you could use InnoDB with innodb_flush_log_at_trx_commit set to 0 or 2 (see docs for details), you can improve performance.
There are a number of patches which can increase concurrency from Google and others - these may be of interest if you still can't get enough performance without them.
For my coffeescript peeps!
#disable Delete button until reason is entered
$("#delete_event_button").prop("disabled", true)
$('#event_reason_is_deleted').click ->
$('#event_reason_is_deleted').val('')
$("#delete_event_button").prop("disabled", false)
In plain English: Get the parent element. Check it's height, and save that value. Then loop through all the child elements and check their individual heights.
This is dirty, but you might get the basic idea: http://jsfiddle.net/VgDgz/
You can use the directive v-html to show it. like this:
<td v-html="desc"></td>
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
using System;
using System.IO;
// Get the current directory and make it a DirectoryInfo object.
// Do not use Environment.CurrentDirectory, vistual studio
// and visual studio code will return different result:
// Visual studio will return @"projectDir\bin\Release\netcoreapp2.0\", yet
// vs code will return @"projectDir\"
var currentDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
// On windows, the current directory is the compiled binary sits,
// so string like @"bin\Release\netcoreapp2.0\" will follow the project directory.
// Hense, the project directory is the great grand-father of the current directory.
string projectDirectory = currentDirectory.Parent.Parent.Parent.FullName;
You have two ways to do this, I'll call it dirty way and clean way:
1. The dirty way
Create a box from your current virtual environment, using vagrant package
command:
http://docs.vagrantup.com/v2/cli/package.html
Then copy the box to the other pc, add it using vagrant box add
and run it using vagrant up
as usual.
Keep in mind that files in your working directory (the one with the Vagrantfile
) are shared when the virtual machine boots, so you need to copy it to the other pc as well.
2. The clean way
Theoretically it should never be necessary to do export/import with Vagrant. If you have the foresight to use provisioning for configuring the virtual environment (chef, puppet, ansible), and a version control system like git for your working directory, copying an environment would be at this point simple as running:
git clone <your_repo>
vagrant up
It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:
The black div
will display the full 500px unless overflow:hidden
is set on the 100px li
this
this
(aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scopes like other variables (except for arrow functions, see below). Here are some examples:
function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`
// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
To learn more about this
, have a look at the MDN documentation.
this
ECMAScript 6 introduced arrow functions, which can be thought of as lambda functions. They don't have their own this
binding. Instead, this
is looked up in scope just like a normal variable. That means you don't have to call .bind
. That's not the only special behavior they have, please refer to the MDN documentation for more information.
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => alert(this.data));
}
this
You actually don't want to access this
in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self
and that
.
function MyConstructor(data, transport) {
this.data = data;
var self = this;
transport.on('data', function() {
alert(self.data);
});
}
Since self
is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this
value of the callback itself.
this
of the callback - part 1It might look like you have no control over the value of this
because its value is set automatically, but that is actually not the case.
Every function has the method .bind
[docs], which returns a new function with this
bound to a value. The function has exactly the same behavior as the one you called .bind
on, only that this
was set by you. No matter how or when that function is called, this
will always refer to the passed value.
function MyConstructor(data, transport) {
this.data = data;
var boundFunction = (function() { // parenthesis are not necessary
alert(this.data); // but might improve readability
}).bind(this); // <- here we are calling `.bind()`
transport.on('data', boundFunction);
}
In this case, we are binding the callback's this
to the value of MyConstructor
's this
.
Note: When a binding context for jQuery, use jQuery.proxy
[docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.
this
of the callback - part 2Some functions/methods which accept callbacks also accept a value to which the callback's this
should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map
[docs] is such a method. Its signature is:
array.map(callback[, thisArg])
The first argument is the callback and the second argument is the value this
should refer to. Here is a contrived example:
var arr = [1, 2, 3];
var obj = {multiplier: 42};
var new_arr = arr.map(function(v) {
return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument
Note: Whether or not you can pass a value for this
is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax
method [docs] describes an option called context
:
This object will be made the context of all Ajax-related callbacks.
Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.
Consider the following example:
function Foo() {
this.data = 42,
document.body.onclick = this.method;
}
Foo.prototype.method = function() {
console.log(this.data);
};
The function this.method
is assigned as click event handler, but if the document.body
is clicked, the value logged will be undefined
, because inside the event handler, this
refers to the document.body
, not the instance of Foo
.
As already mentioned at the beginning, what this
refers to depends on how the function is called, not how it is defined.
If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:
function method() {
console.log(this.data);
}
function Foo() {
this.data = 42,
document.body.onclick = this.method;
}
Foo.prototype.method = method;
The solution is the same as mentioned above: If available, use .bind
to explicitly bind this
to a specific value
document.body.onclick = this.method.bind(this);
or explicitly call the function as a "method" of the object, by using an anonymous function as callback / event handler and assign the object (this
) to another variable:
var self = this;
document.body.onclick = function() {
self.method();
};
or use an arrow function:
document.body.onclick = () => this.method();
Lets assume $post_id is array of $item
$post_id = array_map(function($item){
return $item->{'post_id'};
},$post_id);
strong text
Here I am providing a negative example where your want to avoid when converting floating number to strings.
float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;
You get
99463 99.463 99.462997
Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.
I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.
string ftos(float f, int nd) {
ostringstream ostr;
int tens = stoi("1" + string(nd, '0'));
ostr << round(f*tens)/tens;
return ostr.str();
}
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
On 4.2 eclipse it seems to be impossible to remove the eCobertura highlights. Sadly eCobertura plugins seems to be not maintained anymore. However if you start writing into the class, its gone. So type a space, and then undo, and its gone.
Sometimes I need to extract several command line parameters, but not all of them and not from the first one. Let's assume the following call:
Test.bat uno dos tres cuatro cinco seis siete
Of course, the extension ".bat" is not needed at least you have test.exe in same folder. What we want is to get the output "tres cuatro cinco" (no matter if one line or three). The goal is that only I need three parameters and starting in the third one. In order to have a simple example the action for each one is just "echo", but you can think in some other more complex action over the selected parameters.
I've produced some examples, (options) in order you can see which one you consider better for you. Unfortunately, there is not a nice (or I don't know about) way based on a for loop over the range like "for %%i in (%3, 1, %5)".
@echo off
setlocal EnableDelayedExpansion
echo Option 1: one by one (same line)
echo %3, %4, %5
echo.
echo Option 2: Loop For one by one
for %%a in (%3, %4, %5) do echo %%a
echo.
echo Option 3: Loop For with check of limits
set i=0
for %%a in (%*) do (
set /A i=i+1
If !i! GTR 2 if !i! LSS 6 echo %%a
)
echo.
echo Option 4: Loop For with auxiliary list
for /l %%i in (3,1,5) do (
set a=%%i
set b=echo %%
set b=!b!!a!
call !b!
)
echo.
echo Option 5: Assigning to an array of elements previously
set e[0]=%0
set i=0
for %%a in (%*) do (
set /A i=i+1
set e[!i!]=%%a
)
for /l %%i in (3,1,5) do (
echo !e[%%i]!
)
echo.
echo Option 6: using shift and goto loop. It doesn't work with for loop
set i=2
:loop6
set /A i=i+1
echo %3
shift
If %i% LSS 5 goto :loop6
Probably you can find more options or combine several ones. Enjoy them.
You have most of the code…
CURLOPT_HTTPHEADER
for curl_setopt()
takes an array with each header as an element. You have one element with multiple headers.
You also need to add the Authorization header to your $header
array.
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';
All this examples work fine on most of my database servers. However if you have 1 server with multiple instances and all those servers those query's give you no result.
For instance the first query gives a result like:
name DataFileSizeMB LogFileSizeMB
master NULL NULL
tempdb NULL NULL
model NULL NULL
msdb NULL NULL
So the databases are selected from sys.databases
, however the table sys.master_files
seems to be empty or gives no result.
Even a simple query as select * from sys.master_files
has a result of 0 records.
You don't receive any errors but no records are found.
On my servers with only 1 database instance this works fine.
I think it is not useful to configure the mysql server without caching_sha2_password encryption, we have to find a way to publish, send or obtain secure information through the network. As you see in the code below I dont use variable $db_name, and Im using a user in mysql server with standar configuration password. Just create a Standar user password and config all privilages. it works, but how i said without segurity.
<?php
$db_name="db";
$mysql_username="root";
$mysql_password="****";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password);
if ($conn) {
echo "connetion success";
}
else{
echo mysqli_error($conn);
}
?>
This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:
String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
Spaces are initially left in the input so the split will still work.
By removing the rubbish characters before splitting, you avoid having to loop through the elements.
Hello Guys this worked for me, I just modify my BuildTypes like this:
buildTypes {
release {
android {
lintOptions {
checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
abortOnError false
}
}
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
In python3.7.7, the definition of json.load is as below according to cpython source code:
def load(fp, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
return loads(fp.read(),
cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
json.load actually calls json.loads and use fp.read()
as the first argument.
So if your code is:
with open (file) as fp:
s = fp.read()
json.loads(s)
It's the same to do this:
with open (file) as fp:
json.load(fp)
But if you need to specify the bytes reading from the file as like fp.read(10)
or the string/bytes you want to deserialize is not from file, you should use json.loads()
As for json.loads(), it not only deserialize string but also bytes. If s
is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.
def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
...
"""
if isinstance(s, str):
if s.startswith('\ufeff'):
raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
s, 0)
else:
if not isinstance(s, (bytes, bytearray)):
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
f'not {s.__class__.__name__}')
s = s.decode(detect_encoding(s), 'surrogatepass')
This happens sometimes when I'm trying to open my old projects, what helps me is to change projects target framework. Go to Project -> projectname Properties... and change the Target framework to the one that you have installed.
I will recommend an elegant solution using metaclasses
class Singleton(type):
# Inherit from "type" in order to gain access to method __call__
def __init__(self, *args, **kwargs):
self.__instance = None # Create a variable to store the object reference
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
# if the object has not already been created
self.__instance = super().__call__(*args, **kwargs) # Call the __init__ method of the subclass (Spam) and save the reference
return self.__instance
else:
# if object (Spam) reference already exists; return it
return self.__instance
class Spam(metaclass=Singleton):
def __init__(self, x):
print('Creating Spam')
self.x = x
if __name__ == '__main__':
spam = Spam(100)
spam2 = Spam(200)
Output:
Creating Spam
As you can see from the output, only one object is instantiated
you probably change your NT password.
Open IIS -> Right click on your application -> manage application -> advanced Setting -> physical path credentials.
good luck
It might be a java interpreter defect, but java on HPUX does not do a kill -9, but only a kill -TERM.
I did a small test testDestroy.java:
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
Thread.sleep(1000);
process.destroy();
process.waitFor();
And the invocation:
$ tusc -f -p -s signal,kill -e /opt/java1.5/bin/java testDestroy sh -c 'trap "echo TERM" TERM; sleep 10'
dies after 10s (not killed after 1s as expected) and shows:
...
[19999] Received signal 15, SIGTERM, in waitpid(), [caught], no siginfo
[19998] kill(19999, SIGTERM) ............................................................................. = 0
...
Doing the same on windows seems to kill the process fine even if signal is handled (but that might be due to windows not using signals to destroy).
Actually i found Java - Process.destroy() source code for Linux related thread and openjava implementation seems to use -TERM as well, which seems very wrong.
I made NO-dependency static method like this:
import java.nio.file.Files;
import java.nio.file.Paths;
public class ResourceReader {
public static String asString(String resourceFIleName) {
try {
return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}
MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.
You can effectively remove scientific notation in printing with this code:
options(scipen=999)
You will get like this error
Try the following steps
1. Open Command Prompt (Press Windows key and type "cmd" and hit Enter)
Then type this command as show in picture
netstat -aon | find ":8080" | find "LISTENING"
One simple use case when reverting change:
1. Use reset if you want to undo staging of a modified file.
2. Use checkout if you want to discard changes to unstaged file/s.
You don't need to do an explicit typedef
for classes and structs. What do you need the typedef
for? Further, the typedef
after a template<...>
is syntactically wrong. Simply use:
template <class T>
struct array {
size_t x;
T *ary;
} ;
A bit late here, but thanks to "How do I validate a date in rails?" I managed to write this validator, hope is useful to somebody:
Inside your model.rb
validate :date_field_must_be_a_date_or_blank
# If your field is called :date_field, use :date_field_before_type_cast
def date_field_must_be_a_date_or_blank
date_field_before_type_cast.to_date
rescue ArgumentError
errors.add(:birthday, :invalid)
end
Here's the solution for that problem...
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(txt);
If you like doing things the hard way:
my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon) == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
Kotlin Version
via Extension Function
To find a resource id by its name In Kotlin, add below snippet in a kotlin file:
ExtensionFunctions.kt
import android.content.Context
import android.content.res.Resources
fun Context.resIdByName(resIdName: String?, resType: String): Int {
resIdName?.let {
return resources.getIdentifier(it, resType, packageName)
}
throw Resources.NotFoundException()
}
Usage
Now all resource ids are accessible wherever you have a context reference using resIdByName
method:
val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.
Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:
using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
if (stream != null)
{
stream.ReadTimeout = Timeout.Infinite;
using (var reader = new StreamReader(stream, Encoding.UTF8, false))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line != String.Empty)
{
Console.WriteLine("Count {0}", count++);
}
Console.WriteLine(line);
}
}
}
}
Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
Define interface
interface Settings {
lang: 'en' | 'da';
welcome: boolean;
}
Enforce key to be a specific key of Settings interface
private setSettings(key: keyof Settings, value: any) {
// Update settings key
}
In js you can change zoom by
document.body.style.zoom="90%"
But it doesn't work in FF http://caniuse.com/#search=zoom
For ff you can try
-moz-transform: scale(0.9);
And check next topic How can I zoom an HTML element in Firefox and Opera?
You have three options:
In addition to the plt.axvline
and plt.plot((x1, x2), (y1, y2))
OR plt.plot([x1, x2], [y1, y2])
as provided in the answers above, one can also use
plt.vlines(x_pos, ymin=y1, ymax=y2)
to plot a vertical line at x_pos
spanning from y1
to y2
where the values y1
and y2
are in absolute data coordinates.
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
// S is the millisecond
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");
System.out.println(simpleDateFormat.format(timestamp));
System.out.println(simpleDateFormat.format(date));
}
}
The shortest way is indeed just
String fileContents = new File('/path/to/file').text
but in this case you have no control on how the bytes in the file are interpreted as characters. AFAIK groovy tries to guess the encoding here by looking at the file content.
If you want a specific character encoding you can specify a charset name with
String fileContents = new File('/path/to/file').getText('UTF-8')
See API docs on File.getText(String)
for further reference.
I created a simple function to get URL parameter in JavaScript from a URL like this:
.....58e/web/viewer.html?page=*17*&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT: 18
PLplot is a cross-platform software package for creating scientific plots. They aren't very pretty (eye catching), but they look good enough. Have a look at some examples (both source code and pictures).
The PLplot core library can be used to create standard x-y plots, semi-log plots, log-log plots, contour plots, 3D surface plots, mesh plots, bar charts and pie charts. It runs on Windows (2000, XP and Vista), Linux, Mac OS X, and other Unices.
If you simply want to squash all commits into a single, initial commit, just reset the repository and amend the first commit:
git reset hash-of-first-commit
git add -A
git commit --amend
Git reset will leave the working tree intact, so everything is still there. So just add the files using git add commands, and amend the first commit with these changes. Compared to rebase -i you'll lose the ability to merge the git comments though.
The preferred method is actually:
@System.Web.Configuration.WebConfigurationManager.AppSettings["myKey"]
It also doesn't need a reference to the ConfigurationManager assembly, it's already in System.Web.
pip install mysql-connector
Last but not least,You can also install mysql-connector via source code
Download source code from: https://dev.mysql.com/downloads/connector/python/
I had the exact same error message as the OP, but my problem was not addressed by any of the existing answers. Many of the answers deal with conflicts on port 80, which I knew I did not have, since I had had localhost responding on port 80 very recently.
Turns out I had inadvertently changed ServerRoot when I intended to change DocumentRoot (stupid, I know), and though the new ServerRoot directory existed, it did not contain the configuration files and other stuff apache needed, which caused it to fail on startup. The error message probably addresses this scenario by the wording 'missing dependencies'.
On my Windows system, setting ServerRoot back to C:/XAMPP/apache solved the problem.
location / {
is the most general location (with location {
). It will match anything, AFAIU. I doubt that it would be useful to have location / { index index.html; }
because of a lot of duplicate content for every subdirectory of your site.
The approach with
try_files $uri $uri/index.html index.html;
is bad, as mentioned in a comment above, because it returns index.html
for pages which should not exist on your site (any possible $uri
will end up in that).
Also, as mentioned in an answer above, there is an internal redirect in the last argument of try_files
.
Your approach
location = / { index index.html;
is also bad, since index
makes an internal redirect too. In case you want that, you should be able to handle that in a specific location
. Create e.g.
location = /index.html {
as was proposed here. But then you will have a working link http://example.org/index.html
, which may be not desired. Another variant, which I use, is:
root /www/my-root;
# http://example.org
# = means exact location
location = / {
try_files /index.html =404;
}
# disable http://example.org/index as a duplicate content
location = /index { return 404; }
# This is a general location.
# (e.g. http://example.org/contacts <- contacts.html)
location / {
# use fastcgi or whatever you need here
# return 404 if doesn't exist
try_files $uri.html =404;
}
P.S. It's extremely easy to debug nginx (if your binary allows that). Just add into the server {
block:
error_log /var/log/nginx/debug.log debug;
and see there all internal redirects etc.
I was having the same problem with android tabs when trying to place them on the bottom of the screen. My scenario was to not use a layout file and create the tabs in code, I was also looking to fire activities from each tab which seemed a bit too complex using other approaches so, here is the sample code to overcome the problem:
Pyhton3: Most of the solutions listed previously work. However, there are instances when row_number of the dataframe is not required and the each row (record) has to be written individually.
The following method is useful in that case.
import csv
my file= 'C:\Users\John\Desktop\export_dataframe.csv'
records_to_save = data2 #used as in the thread.
colnames = list[records_to_save[0].keys()]
# remember colnames is a list of all keys. All values are written corresponding
# to the keys and "None" is specified in case of missing value
with open(myfile, 'w', newline="",encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(colnames)
for d in records_to_save:
writer.writerow([d.get(r, "None") for r in colnames])
int(hexstring, 16)
does the trick, and works with and without the 0x prefix:
>>> int("a", 16)
10
>>> int("0xa", 16)
10
There's so many answers to this these days:
foreach-object -parallel
as an alternative for #4Here's workflows with literally a foreach -parallel:
workflow work {
foreach -parallel ($i in 1..3) {
sleep 5
"$i done"
}
}
work
3 done
1 done
2 done
Or a workflow with a parallel block:
function sleepfor($time) { sleep $time; "sleepfor $time done"}
workflow work {
parallel {
sleepfor 3
sleepfor 2
sleepfor 1
}
'hi'
}
work
sleepfor 1 done
sleepfor 2 done
sleepfor 3 done
hi
Here's an api with runspaces example:
$a = [PowerShell]::Create().AddScript{sleep 5;'a done'}
$b = [PowerShell]::Create().AddScript{sleep 5;'b done'}
$c = [PowerShell]::Create().AddScript{sleep 5;'c done'}
$r1,$r2,$r3 = ($a,$b,$c).begininvoke() # run in background
$a.EndInvoke($r1); $b.EndInvoke($r2); $c.EndInvoke($r3) # wait
($a,$b,$c).streams.error # check for errors
($a,$b,$c).dispose() # clean
a done
b done
c done
You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.
brew outdated | xargs brew upgrade
You can edit this behavior in:
Tools->Options->Text Editor->All Languages->Tabs
Change Tab to use "Insert Spaces" instead of "Keep Tabs".
Note you can also specify this per language if you wish to have different behavior in a specific language.
First up, you seem to be mixing table variables and tables.
Either way, You can't pass in the table's name like that. You would have to use dynamic TSQL to do that.
If you just want to declare a table variable:
CREATE PROC sp_createATable
@name VARCHAR(10),
@properties VARCHAR(500)
AS
declare @tablename TABLE
(
id CHAR(10) PRIMARY KEY
);
The fact that you want to create a stored procedure to dynamically create tables might suggest your design is wrong.
I had the same problem with Google Drive.
Here's how I solved the problem using Links 2.
Open a browser on your PC, navigate to your file in Google Drive. Give your file a public link.
Copy the public link to your clipboard (eg right click, Copy link address)
Open a Terminal. If you're downloading to another PC/server/machine you should SSH to it as this point
Install Links 2 (debian/ubuntu method, use your distro or OS equivalent)
sudo apt-get install links2
Paste the link in to your terminal and open it with Links like so:
links2 "paste url here"
Navigate to the download link within Links using your Arrow Keys and press Enter
Choose a filename and it'll download your file
//insert this php code, at the end after your closing html tag.
<?php
//setting connection to database
$con = mysqli_connect("localhost","your-username","your-
passowrd","your-dbname");
if(isset($_POST['submit_button'])){
$txt_area = $_POST['update'];
$Our_query= "INSERT INTO your-table-name (field1name, field2name)
VALUES ('abc','def')"; // values should match data
// type to field names
$insert_query = mysqli_query($con, $Our_query);
if($insert_query){
echo "<script>window.open('form.php','_self') </script>";
// supposing form.php is where you have created this form
}
} //if statement close
?>
Hope this helps.
You could also use float and inline-block to center your nav like the following:
nav li {
float: left;
}
nav {
display: inline-block;
}
Small clarification: in "Windows 7 64 bit PC", after adding ...Python34\Scripts
to the path variable, pip install pygame
didn't work for me.
So I checked the "...Python34\Scripts" folder, it didn't have pip
, but it had pip3
and pip3.4
. So I ran pip3.4 install pygame .... .whl
. It worked.
(Further open a command window in the same folder where you have the downloaded pygame...whl
file.)
As android:editable=""
is deprecated,
Setting
android:clickable="false"
android:focusable="false"
android:inputType="none"
android:cursorVisible="false"
will make it "read-only".
However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:
myEditText.setOnLongClickListener { true }
suffices.
I had the same issue "Cannot create a connection to data source...Login failed for user.." on Windows 8.1, SQL Server 2014 Developer Edition and Visual Studio 2013 Pro. All solutions offered above by other Stackoverflow Community members did not work for me.
So, I did the next steps (running all Windows applications as Administrator):
VS2013 SSRS: I converted my Data Source to Shared Data Source (.rds) with Windows Authentication (Integrated Security) on the Right Pane "Solution Explorer".
Original (non-shared) Data Source (on the Left Pane "Report Data") got "Don't Use Credentials".
On the Project Properties, I set for "Deployment" "Overwrite DataSources" to "True" and redeployed the Project.
After that, I could run my report without further requirements to enter Credentials. All Shared DataSources were deployed in a separate Directory "DataSources".
I believe it is because cell.getCellStyle
initially returns the default cell style which you then change.
Create styles like this and apply them to cells:
cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();
Although as the previous poster noted try and create styles and reuse them.
There is also some utility class in the XSSF library that will avoid the code I have provided and automatically try and reuse styles. Can't remember the class 0ff hand.
One more possible reason if you are using Tycho and Maven to build bundles, that you have wrong execution environment (Bundle-RequiredExecutionEnvironment
) in the manifest file (manifest.mf
) defined. For example:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Engine Plug-in
Bundle-SymbolicName: com.foo.bar
Bundle-Version: 4.6.5.qualifier
Bundle-Activator: com.foo.bar.Activator
Bundle-Vendor: Foobar Technologies Ltd.
Require-Bundle: org.eclipse.core.runtime,
org.jdom;bundle-version="1.0.0",
org.apache.commons.codec;bundle-version="1.3.0",
bcprov-ext;bundle-version="1.47.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.5
Export-Package: ...
...
Import-Package: ...
...
In my case everything else was ok. The compiler plugins (normal maven and tycho as well) were set correctly, still m2 generated old compliance level because of the manifest. I thought I share the experience.
I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi
.
My change was only in web.config file and is working.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
Thanks for you solution @Rytis!
Here is an example for how to extract the href
attrbiutes of all a
tags:
import requests as rq
from bs4 import BeautifulSoup as bs
url = "http://www.cde.ca.gov/ds/sp/ai/"
page = rq.get(url)
html = bs(page.text, 'lxml')
hrefs = html.find_all("a")
all_hrefs = []
for href in hrefs:
# print(href.get("href"))
links = href.get("href")
all_hrefs.append(links)
print(all_hrefs)
I use gitk
to see the difference:
gitk k73ud..dj374
It has a GUI mode so that reviewing is easier.
Use the IP instead:
DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';
For more possibilities, see this link.
To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):
mysqladmin -u root password 'mynewpassword'
The DictWriter()
class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer()
and pass in a simple row for the header:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.writer(outcsv)
writer.writerow(["Date", "temperature 1", "Temperature 2"])
with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row + [0.0] for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)
The alternative would be to generate dictionaries when copying across your data:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
writer.writeheader()
with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)
I had same issue and I solved it by "pod setup" after installing cocoapods.
The reason for the collision seems to be because, by default, the context root, "/", is to be handled by org.apache.catalina.servlets.DefaultServlet. This servlet is intended to handle requests for static resources.
If you decide to bump it out of the way with your own servlet, with the intent of handling dynamic requests, that top-level servlet must also carry out any tasks accomplished by catalina's original "DefaultServlet" handler.
If you read through the tomcat docs, they make mention that True Apache (httpd) is better than Apache Tomcat for handling static content, since it is purpose built to do just that. My guess is because Tomcat by default uses org.apache.catalina.servlets.DefaultServlet to handle static requests. Since it's all wrapped up in a JVM, and Tomcat is intended to as a Servlet/JSP container, they probably didn't write that class as a super-optimized static content handler. It's there. It gets the job done. Good enough.
But that's the thing that handles static content and it lives at "/". So if you put anything else there, and that thing doesn't handle static requests, WHOOPS, there goes your static resources.
I've been searching high and low for the same answer and the answer I'm getting everywhere is "if you don't want it to do that, don't do that".
So long story short, your configuration is displacing the default static resource handler with something that isn't a static resource handler at all. You'll need to try a different configuration to get the results you're looking for (as will I).
docker ps -a
You can see all docker containers whether it is alive or dead.