<script type="text/javascript">
$(document).ready(function () {
$("#txtDate").datepicker({ dateFormat: 'yy/mm/dd' }).datepicker("setDate", "0");
$("#txtDate2").datepicker({ dateFormat: 'yy/mm/dd', }).datepicker("setDate", new Date().getDay+15); }); </script>
If you have code in one subdirectory dependent on code in another subdirectory, you are probably better off with a single makefile at top-level.
See Recursive Make Considered Harmful for the full rationale, but basically you want make to have the full information it needs to decide whether or not a file needs to be rebuilt, and it won't have that if you only tell it about a third of your project.
The link above seems to be not reachable. The same document is reachable here:
Here's a simple example:
Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
list.add(m.group());
}
(if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray()
)
somevar = tag.getArtist()
Your hyphen in your ELSE statement isn't accepted in the column which is being defined under the datetime data type. You could either:
a) Wrap a CAST around your [stat] field to convert it to a varchar representation of a date
b) Use a datetime like 9999-12-31 for your ELSE value.
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.
FOR /d %%K in ("n:\test*") DO (
FOR /d %%J in ("%%K*") DO (
FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"
)
)
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged
Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.
Installation
npm install --save-dev unminified-webpack-plugin
Usage
var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'library.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new UnminifiedWebpackPlugin()
]
};
By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^
You may be able to use the aggregate
(or agg
) function to concatenate the values. (Untested code)
df.groupby('A')['B'].agg(lambda col: ''.join(col))
The number one mistake you can make is creating a globally accessible class called with a generic name, like Constants. This simply gets littered with garbage and you lose all ability to figure out what portion of your system uses these constants.
Instead, constants should go into the class which "owns" them. Do you have a constant called TIMEOUT? It should probably go into your Communications() or Connection() class. MAX_BAD_LOGINS_PER_HOUR? Goes into User(). And so on and so forth.
The other possible use is Java .properties files when "constants" can be defined at run-time, but not easily user changeable. You can package these up in your .jars and reference them with the Class resourceLoader.
You could refer to column alias but you need to define it using CROSS/OUTER APPLY
:
SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;
Pros:
WHERE/GROUP BY/ORDER BY
You can use vertical-align and floating.
In most cases you want to vertical-align: middle, the image.
Here is a test: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_vertical-align
vertical-align: baseline|length|sub|super|top|text-top|middle|bottom|text-bottom|initial|inherit;
For middle, the definition is: The element is placed in the middle of the parent element.
So you might want to apply that to all elements within the element.
The shortest way! it's working for me, Where NA is my default value.
<td th:text="${ins.eValue!=null}? ${ins.eValue}:'NA'" />
For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:
@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
Using :
Set the head of the list to it bottom lv.setStackFromBottom(true);
Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL
.
According to the Go specification:
For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.
A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.
In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.
If you were unsure if it was a string or not, you could test using the two return syntax.
str, ok := data.(string)
If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:
if str, ok := data.(string); ok {
/* act on str */
} else {
/* not string */
}
Carry Flag is a flag set when:
a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.
b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.
Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)
Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.
You can read more about flags on wikipedia
As stated in Date and Time Literals:
MySQL recognizes
DATE
values in these formats:
As a string in either
'YYYY-MM-DD'
or'YY-MM-DD'
format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example,'2012-12-31'
,'2012/12/31'
,'2012^12^31'
, and'2012@12@31'
are equivalent.As a string with no delimiters in either
'YYYYMMDD'
or'YYMMDD'
format, provided that the string makes sense as a date. For example,'20070523'
and'070523'
are interpreted as'2007-05-23'
, but'071332'
is illegal (it has nonsensical month and day parts) and becomes'0000-00-00'
.As a number in either
YYYYMMDD
orYYMMDD
format, provided that the number makes sense as a date. For example,19830905
and830905
are interpreted as'1983-09-05'
.
Therefore, the string '08/25/2012'
is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):
Configure Datepicker to provide dates in a supported format using an altField
together with its altFormat
option:
<input type="hidden" id="actualDate" name="actualDate"/>
$( "selector" ).datepicker({
altField : "#actualDate"
altFormat: "yyyy-mm-dd"
});
Or, if you're happy for users to see the date in YYYY-MM-DD
format, simply set the dateFormat
option instead:
$( "selector" ).datepicker({
dateFormat: "yyyy-mm-dd"
});
Use MySQL's STR_TO_DATE()
function to convert the string:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime
object:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
and then either:
obtain a suitable formatted string:
$date = $dt->format('Y-m-d');
obtain the UNIX timestamp:
$timestamp = $dt->getTimestamp();
which is then passed directly to MySQL's FROM_UNIXTIME()
function:
INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
Manually manipulate the string into a valid literal:
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the mysql_*
functions:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
You appear to be using either a DATETIME
or TIMESTAMP
column for holding a date value; I recommend you consider using MySQL's DATE
type instead. As explained in The DATE
, DATETIME
, and TIMESTAMP
Types:
The
DATE
type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in'YYYY-MM-DD'
format. The supported range is'1000-01-01'
to'9999-12-31'
.The
DATETIME
type is used for values that contain both date and time parts. MySQL retrieves and displaysDATETIME
values in'YYYY-MM-DD HH:MM:SS'
format. The supported range is'1000-01-01 00:00:00'
to'9999-12-31 23:59:59'
.The
TIMESTAMP
data type is used for values that contain both date and time parts.TIMESTAMP
has a range of'1970-01-01 00:00:01'
UTC to'2038-01-19 03:14:07'
UTC.
The only way i could get my ant version updated on the mac from 1.8.2 to 1.9.1 was by following instructions here
Use the DataFrame.select
method:
In [38]: df = DataFrame({'Test1': randn(10), 'Test2': randn(10), 'awesome': randn(10)})
In [39]: df.select(lambda x: not re.search('Test\d+', x), axis=1)
Out[39]:
awesome
0 1.215
1 1.247
2 0.142
3 0.169
4 0.137
5 -0.971
6 0.736
7 0.214
8 0.111
9 -0.214
In (ANSI) C99, you can use a designated initializer to initialize a structure:
MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };
Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)
You are replacing the starting tag and then putting that back in innerHTML
, so the code will be invalid. Make all the replacements before you put the code back in the element:
var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;
It is not too hard. I have not read the license yet. However I have proven this works. You can copy sqljdbc4 jar file to a network share or local directory. Your build.gradle should look like this :
apply plugin: 'java'
//apply plugin: 'maven'
//apply plugin: 'enhance'
sourceCompatibility = 1.8
version = '1.0'
//library versions
def hibernateVersion='4.3.10.Final'
def microsoftSQLServerJDBCLibVersion='4.0'
def springVersion='2.5.6'
def log4jVersion='1.2.16'
def jbossejbapiVersion='3.0.0.GA'
repositories {
mavenCentral()
maven{url "file://Sharedir/releases"}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile "org.hibernate:hibernate-core:$hibernateVersion"
compile "com.microsoft.sqlserver:sqljdbc4:$microsoftSQLServerJDBCLibVersion"
}
task showMeCache << {
configurations.compile.each { println it }
}
under the sharedir/releases directory, I have directory similar to maven structure which is \sharedir\releases\com\microsoft\sqlserver\sqljdbc4\4.0\sqljdbc4-4.0.jar
good luck.
David Yen
Defining a new directive to work around a bug is not really ideal.
Because the datepicker displays later dates correctly, one simple workaround could be just setting the model variable to null first, and then to the current date after a while:
$scope.dt = null;
$timeout( function(){
$scope.dt = new Date();
},100);
If you want to set the timeout to 20 minutes, use something like this:
<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
Don't call finish()
in onCreate()
method then it works fine.
you have to use the To_Date() function to convert the string to date ! http://www.techonthenet.com/oracle/functions/to_date.php
Modules are fine for storing enums and some global variables, constants and shared functions. its very good thing and I often use it. Declared variables are visible acros entire project.
Why don't you simply use set_index
method?
In : col = ['a','b','c']
In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
In : data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In : data2 = data.set_index('a')
In : data2
Out:
b c
a
1 2 3
10 11 12
20 21 22
LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:
Returns the left part of a character string with the specified number of characters.
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse
LEFT ( character_expression , integer_expression )
Another option would be to just use perl with globstar.
Enabling shopt -s globstar
in your .bashrc
(or wherever) allows the **
glob pattern to match all sub-directories and files recursively.
Thus using perl -pXe 's/SEARCH/REPLACE/g' -i **
will recursively
replace SEARCH
with REPLACE
.
The -X
flag tells perl to "disable all warnings" - which means that
it won't complain about directories.
The globstar also allows you to do things like sed -i 's/SEARCH/REPLACE/g' **/*.ext
if you wanted to replace SEARCH
with REPLACE
in all child files with the extension .ext
.
Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get
>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160
There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.
If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_Open"/>
<MenuItem Header="_Close"/>
<MenuItem Header="_Save"/>
</MenuItem>
</Menu>
<StackPanel></StackPanel>
</DockPanel>
Standard class java.util.ArrayList is resizable array, growing when new elements added.
Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1
below test code for ref.
Sub test()
Dim rng As Range
Set rng = Range("A1")
rng.Value2 = 1
End Sub
You can use following code for Alert and Actionsheet for swift4
@IBAction func alert_act(_ sender: Any) {
do {
let alert = UIAlertController(title: "Alert", message: "Would you like to continue learning?", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
@IBAction func action_sheet1(_ sender: Any) {
let action_sheet1 = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)
let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
action_sheet1.addAction(defaultAction)
action_sheet1.addAction(deleteAction)
action_sheet1.addAction(cancelAction)
self.present(action_sheet1, animated: true, completion: nil)
}
}
It was displaying some weird characters (​) until I set the charset to UTF-8 in the head of the html file
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
or for HTML5:
<meta charset="UTF-8">
It it is now transparent but still shows in the html when I use the inspector.
Removing all the scripts from the page didn't remove it either.
I tested it for chrome and IE.
This should work:
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
Code taken from here.
Edit An even simpler solution is given in this thread.
I normally alias using built-in application launcher (open) from OS X:
alias pc='open -a /Applications/PyCharm\ CE.app'
Then I can type:
pc myfile1.txt myfiles*.py
Though you can't (easily) pass args to PyCharm, if you want a quick way to open files (without needing to use full pathnames to the file), this does the trick.
The reason why it is closing is because the program is not running anymore, simply add any sort of loop or input to fix this (or you could just run it through idle.)
This error occurs when one attempts to use a varchar variable longer than 4000 bytes in an SQL statement. PL/SQL allows varchars up to 32767 bytes, but the limit for database tables and SQL language is 4000. You can't use PL/SQL variables that SQL doesn't recognize in SQL statements; an exception, as the message explains, is a direct insert into a long-type column.
create table test (v varchar2(10), c clob);
declare
shortStr varchar2(10) := '0123456789';
longStr1 varchar2(10000) := shortStr;
longStr2 varchar2(10000);
begin
for i in 1 .. 10000
loop
longStr2 := longStr2 || 'X';
end loop;
-- The following results in ORA-01461
insert into test(v, c) values(longStr2, longStr2);
-- This is OK; the actual length matters, not the declared one
insert into test(v, c) values(longStr1, longStr1);
-- This works, too (a direct insert into a clob column)
insert into test(v, c) values(shortStr, longStr2);
-- ORA-01461 again: You can't use longStr2 in an SQL function!
insert into test(v, c) values(shortStr, substr(longStr2, 1, 4000));
end;
I want to make this function generic, without using ifs; is it possible?
The only simple way I see is to use overloading .. which is not available in C programming langage AFAIK.
Did you consider the C++ programming langage for your programm ? Or is there any constraint that forbids its use?
If you're looking to convert easily between other strings types, perhaps the _bstr_t
class would be more appropriate? It supports converstion between char
, wchar_t
and BSTR
.
=SORT(UNIQUE(A:A))
The above formula works best if you want to list unique values in a column.
I do it this way. It's Simple.
import java.util.Map;
import org.json.JSONObject;
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
JSONObject jsonObj = new JSONObject("{ \"f1\":\"v1\"}");
@SuppressWarnings("unchecked")
Map<String, String> map = new Gson().fromJson(jsonObj.toString(),Map.class);
System.out.println(map);
}
}
In the following C# code
public void Method1()
{
int i = 4;
int y = 2;
class1 cls1 = new class1();
}
Here's how the memory is managed
Local Variables
that only need to last as long as the function invocation go in the stack. The heap is used for variables whose lifetime we don't really know up front but we expect them to last a while. In most languages it's critical that we know at compile time how large a variable is if we want to store it on the stack.
Objects (which vary in size as we update them) go on the heap because we don't know at creation time how long they are going to last. In many languages the heap is garbage collected to find objects (such as the cls1 object) that no longer have any references.
In Java, most objects go directly into the heap. In languages like C / C++, structs and classes can often remain on the stack when you're not dealing with pointers.
More information can be found here:
The difference between stack and heap memory allocation « timmurphy.org
and here:
Creating Objects on the Stack and Heap
This article is the source of picture above: Six important .NET concepts: Stack, heap, value types, reference types, boxing, and unboxing - CodeProject
but be aware it may contain some inaccuracies.
I have a field named IsActive in table rows that's True when an item has been deleted. This code applies a CSS class named strikethrough only to deleted items. You can see how it uses the C# Ternary Operator:
<tr class="@(@businesstypes.IsActive ? "" : "strikethrough")">
What include
does is copying all the contents from the file (which is the argument inside the <>
or the ""
), so when the preproccesor finishes its work main.cpp
will look like:
// iostream stuff
int foo(int a){
return ++a;
}
int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}
So foo will be defined in main.cpp
, but a definition also exists in foop.cpp
, so the compiler "gets confused" because of the function duplication.
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
Here´s how I do it:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.project.MainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
And then I just run:
mvn assembly:assembly
A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.
Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.
You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.*;
/* Write an application that prompts the user for a String that contains at least
* five letters and at least five digits. Continuously re-prompt the user until a
* valid String is entered. Display a message indicating whether the user was
* successful or did not enter enough digits, letters, or both.
*/
public class FiveLettersAndDigits {
private static String readIn() { // read input from stdin
StringBuilder sb = new StringBuilder();
int c = 0;
try { // do not use try-with-resources. We don't want to close the stdin stream
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((c = reader.read()) != 0) { // read all characters until null
// We don't want new lines, although we must consume them.
if (c != 13 && c != 10) {
sb.append((char) c);
} else {
break; // break on new line (or else the loop won't terminate)
}
}
// reader.readLine(); // get the trailing new line
} catch (IOException ex) {
System.err.println("Failed to read user input!");
ex.printStackTrace(System.err);
}
return sb.toString().trim();
}
/**
* Check the given input against a pattern
*
* @return the number of matches
*/
private static int getitemCount(String input, String pattern) {
int count = 0;
try {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
while (m.find()) { // count the number of times the pattern matches
count++;
}
} catch (PatternSyntaxException ex) {
System.err.println("Failed to test input String \"" + input + "\" for matches to pattern \"" + pattern + "\"!");
ex.printStackTrace(System.err);
}
return count;
}
private static String reprompt() {
System.out.print("Entered input is invalid! Please enter five letters and five digits in any order: ");
String in = readIn();
return in;
}
public static void main(String[] args) {
int letters = 0, digits = 0;
String in = null;
System.out.print("Please enter five letters and five digits in any order: ");
in = readIn();
while (letters < 5 || digits < 5) { // will keep occuring until the user enters sufficient input
if (null != in && in.length() > 9) { // must be at least 10 chars long in order to contain both
// count the letters and numbers. If there are enough, this loop won't happen again.
letters = getitemCount(in, "[A-Za-z]");
digits = getitemCount(in, "[0-9]");
if (letters < 5 || digits < 5) {
in = reprompt(); // reset in case we need to go around again.
}
} else {
in = reprompt();
}
}
}
}
The variable item
is a string. An index looks like this:
>>> mystring = 'helloworld'
>>> print mystring[0]
'h'
The above example uses the 0
index of the string to refer to the first character.
Strings can't have string indices (like dictionaries can). So this won't work:
>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers
Posting parameters Using POST:-
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
The part which you missed is in the the following... i.e., as follows..
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
The rest of the thing you can do it.
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
if you want to align only this cells, you can do something like this:
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$sheet->getStyle("A1:B1")->applyFromArray($style);
But, if you want to apply this style to all cells, try this:
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$sheet->getDefaultStyle()->applyFromArray($style);
Resolved this problem using a Sequence ID defined in Oracle database.
ORACLE_DB_SEQ_ID
is defined as a sequence for the table. Also look at the console to see the Hibernate SQL that is used to verify.
@Id
@Column(name = "MY_ID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence")
@SequenceGenerator(name = "id_Sequence", sequenceName = "ORACLE_DB_SEQ_ID")
Long myId;
Difference between CMD and ENTRYPOINT by intuition:
Yes, it's mixing up.
You can override any of them when running docker run.
Difference between CMD and ENTRYPOINT by example:
docker run -it --rm yourcontainer /bin/bash <-- /bin/bash overrides CMD
<-- /bin/bash does not override ENTRYPOINT
docker run -it --rm --entrypoint ls yourcontainer <-- overrides ENTRYPOINT with ls
docker run -it --rm --entrypoint ls yourcontainer -la <-- overrides ENTRYPOINT with ls and overrides CMD with -la
More on difference between CMD
and ENTRYPOINT
:
Argument to docker run
such as /bin/bash overrides any CMD command we wrote in Dockerfile.
ENTRYPOINT cannot be overriden at run time with normal commands such as docker run [args]
. The args
at the end of docker run [args]
are provided as arguments to ENTRYPOINT. In this way we can create a container
which is like a normal binary such as ls
.
So CMD can act as default parameters to ENTRYPOINT and then we can override the CMD args from [args].
ENTRYPOINT can be overriden with --entrypoint
.
If you have python installed you could try:
python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
stores.dat
TJ's answer is excellent but I ran into one scenario where my HTML was already rendered and the document.write script would overwrite all of the page contents with just the date year.
For this scenario, you can append a text node to the existing element using the following code:
<div>
©
<span id="copyright">
<script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
</span>
Company Name
</div>
If you are referring to com.example.app, no I understand you can't it would be considered a new app
The answers above me got me tempted so much, that I decided to dry run all the possible combinations with OS, Eclipse and JVM trio. Anyway, whoever is digging down and reading my post, check the following as a hot spot (I am Windows 7 user).
You understand Program Files and Program File (x86) are two different folders... x86 stands for the 32-bit version of programs and the former is the 64-bit version.
If you have multiple versions of Java installed with different bitness and release versions, which is bound to happen with so many open source IDEs, managers, administrative consoles, the best option is to set the VM argument directly in the eclipse.ini
file. If you don't, Eclipse will go crazy and try searching itself which is not good.
Welcome to the future!
Right now we have a "responseURL" property from xhr object. YAY!
See How to get response url in XMLHttpRequest?
However, jQuery (at least 1.7.1) doesn't give an access to XMLHttpRequest object directly. You can use something like this:
var xhr;
var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
xhr = _orgAjax();
return xhr;
};
jQuery.ajax('http://test.com', {
success: function(responseText) {
console.log('responseURL:', xhr.responseURL, 'responseText:', responseText);
}
});
It's not a clean solution and i suppose jQuery team will make something for responseURL in the future releases.
TIP: just compare original URL with responseUrl. If it's equal then no redirect was given. If it's "undefined" then responseUrl is probably not supported. However as Nick Garvey said, AJAX request never has the opportunity to NOT follow the redirect but you may resolve a number of tasks by using responseUrl property.
describe
may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once
In [43]:
df.describe()
Out[43]:
shopper_num is_martian number_of_items count_pineapples
count 14.0000 14 14.000000 14
mean 7.5000 0 3.357143 0
std 4.1833 0 6.452276 0
min 1.0000 False 0.000000 0
25% 4.2500 0 0.000000 0
50% 7.5000 0 0.000000 0
75% 10.7500 0 3.500000 0
max 14.0000 False 22.000000 0
[8 rows x 4 columns]
Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data
As you prefer you can transpose the result if you prefer:
In [47]:
df.describe().transpose()
Out[47]:
count mean std min 25% 50% 75% max
shopper_num 14 7.5 4.1833 1 4.25 7.5 10.75 14
is_martian 14 0 0 False 0 0 0 False
number_of_items 14 3.357143 6.452276 0 0 0 3.5 22
count_pineapples 14 0 0 0 0 0 0 0
[4 rows x 8 columns]
git will show changes in commits that affect the index, such as git rm
. It does not store a log of all git commands you execute.
However, a large number of git commands affect the index in some way, such as creating a new branch. These changes will show up in the commit history, which you can view with git log
.
However, there are destructive changes that git can't track, such as git reset
.
So, to answer your question, git does not store an absolute history of git
commands you've executed in a repository. However, it is often possible to interpolate what command you've executed via the commit history.
while(rs.next())
{
if(f.exists() && !f.isDirectory())
continue; //then skip the iteration
else
{
//proceed
}
}
I was getting the same error when I used this code to update the record:
@mysqli_query($dbc,$query or die()))
After removing or die
, it started working properly.
While calling your sub functions from your main functions you can convert the variables into int and then call. Please refer the below code:
import sys
print("Welcome to Calculator\n")
print("Please find the options:\n" + "1. Addition\n" + "2. Subtraction\n" +
"3. Multiplication\n" + "4. Division\n" + "5. Exponential\n" + "6. Quit\n")
def calculator():
choice = input("Enter choice\n")
if int(choice) == 1:
a = input("Enter first number\n")
b = input("Enter second number\n")
add(int(a), int(b))
if int(choice) == 2:
a = input("Enter first number\n")
b = input("Enter second number\n")
diff(int(a), int(b))
if int(choice) == 3:
a = input("Enter first number\n")
b = input("Enter second number\n")
mult(int(a), int(b))
if int(choice) == 4:
a = input("Enter first number\n")
b = input("Enter second number\n")
div(float(a), float(b))
if int(choice) == 5:
a = input("Enter the base number\n")
b = input("Enter the exponential\n")
exp(int(a), int(b))
if int(choice) == 6:
print("Bye")
sys.exit(0)
def add(a, b):
c = a+b
print("Sum of {} and {} is {}".format(a, b, c))
def diff(a,b):
c = a-b
print("Difference between {} and {} is {}".format(a, b, c))
def mult(a, b):
c = a*b
print("The Product of {} and {} is {}".format(a, b, c))
def div(a, b):
c = a/b
print("The Quotient of {} and {} is {}".format(a, b, c))
def exp(a, b):
c = a**b
print("The result of {} to the power of {} is {}".format(a, b, c))
calculator()
Here what I did is I called each of the function while converting the parameters inputted to int. I hope this has been helpful.
In your case it could be changed like this:
if choice == "0":
numberA = raw_input("Enter your first number: ")
numberB = raw_input("Enter your second number: ")
print "Your result is:"
print addition(int(numberA), int(numberB))
I would do it like this:
my $file = "index.html";
my $document = do {
local $/ = undef;
open my $fh, "<", $file
or die "could not open $file: $!";
<$fh>;
};
Note the use of the three-argument version of open. It is much safer than the old two- (or one-) argument versions. Also note the use of a lexical filehandle. Lexical filehandles are nicer than the old bareword variants, for many reasons. We are taking advantage of one of them here: they close when they go out of scope.
And here's another way, use the type SqlDecimal which has a scale property with the count of the digits right of the decimal. Cast your decimal value to SqlDecimal and then access Scale.
((SqlDecimal)(decimal)yourValue).Scale
I faced the same error but i solved this by selecting invalidate caches/restart option.
Click
If the POM missing warning is of project's self module, the reason is that you are trying to mistakenly build from a sub-module directory. You need to run the build and install command from root directory of the project.
File tree walk ftw
is a recursive way to wall the whole directory tree in the path. More details are here.
NOTE : You can also use fts
that can skip hidden files like .
or ..
or .bashrc
#include <ftw.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
int list(const char *name, const struct stat *status, int type)
{
if (type == FTW_NS)
{
return 0;
}
if (type == FTW_F)
{
printf("0%3o\t%s\n", status->st_mode&0777, name);
}
if (type == FTW_D && strcmp(".", name) != 0)
{
printf("0%3o\t%s/\n", status->st_mode&0777, name);
}
return 0;
}
int main(int argc, char *argv[])
{
if(argc == 1)
{
ftw(".", list, 1);
}
else
{
ftw(argv[1], list, 1);
}
return 0;
}
output looks like following:
0755 ./Shivaji/
0644 ./Shivaji/20200516_204454.png
0644 ./Shivaji/20200527_160408.png
0644 ./Shivaji/20200527_160352.png
0644 ./Shivaji/20200520_174754.png
0644 ./Shivaji/20200520_180103.png
0755 ./Saif/
0644 ./Saif/Snapchat-1751229005.jpg
0644 ./Saif/Snapchat-1356123194.jpg
0644 ./Saif/Snapchat-613911286.jpg
0644 ./Saif/Snapchat-107742096.jpg
0755 ./Milind/
0644 ./Milind/IMG_1828.JPG
0644 ./Milind/IMG_1839.JPG
0644 ./Milind/IMG_1825.JPG
0644 ./Milind/IMG_1831.JPG
0644 ./Milind/IMG_1840.JPG
Let us say if you want to match a filename (example: searching for all the *.jpg, *.jpeg, *.png
files.) for a specific needs, use fnmatch
.
#include <ftw.h>
#include <stdio.h>
#include <sys/stat.h>
#include <iostream>
#include <fnmatch.h>
static const char *filters[] = {
"*.jpg", "*.jpeg", "*.png"
};
int list(const char *name, const struct stat *status, int type)
{
if (type == FTW_NS)
{
return 0;
}
if (type == FTW_F)
{
int i;
for (i = 0; i < sizeof(filters) / sizeof(filters[0]); i++) {
/* if the filename matches the filter, */
if (fnmatch(filters[i], name, FNM_CASEFOLD) == 0) {
printf("0%3o\t%s\n", status->st_mode&0777, name);
break;
}
}
}
if (type == FTW_D && strcmp(".", name) != 0)
{
//printf("0%3o\t%s/\n", status->st_mode&0777, name);
}
return 0;
}
int main(int argc, char *argv[])
{
if(argc == 1)
{
ftw(".", list, 1);
}
else
{
ftw(argv[1], list, 1);
}
return 0;
}
It is the fault of Do.Something()
. The best practice here would be to return an array of size 0 (that is possible) instead of a null.
This seems to work:
/descendant::input[@id="search_query"][2]
I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.
There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.
for people new to this you can also use a callback for example:
In your service:
.factory('DataHandler',function ($http){
var GetRandomArtists = function(data, callback){
$http.post(URL, data).success(function (response) {
callback(response);
});
}
})
In your controller:
DataHandler.GetRandomArtists(3, function(response){
$scope.data.random_artists = response;
});
For Bootstrap v4;
for a thin line;
<div class="divider"></div>
for a medium thick line;
<div class="divider py-1 bg-dark"></div>
for a thick line;
<div class="divider py-1 bg-dark"><hr></div>
Guava provides an onlyElement
Collector
, but only use it if you expect the collection to have exactly one element.
Collection<String> stringCollection = ...;
String string = collection.stream().collect(MoreCollectors.onlyElement())
If you are unsure of how many elements there are, use findFirst
.
Optional<String> optionalString = collection.stream().findFirst();
Change ng-disabled="!contractTypeValid"
to [disabled]="!contractTypeValid"
Every object is linked to a prototype object. When trying to access a property that does not exist, JavaScript will look in the object's prototype object for that property and return it if it exists.
The prototype
property of a function constructor refers to the prototype object of all instances created with that function when using new
.
In your first example, you are adding a property x
to each instance created with the A
function.
var A = function () {
this.x = function () {
//do something
};
};
var a = new A(); // constructor function gets executed
// newly created object gets an 'x' property
// which is a function
a.x(); // and can be called like this
In the second example you are adding a property to the prototype object that all the instances created with A
point to.
var A = function () { };
A.prototype.x = function () {
//do something
};
var a = new A(); // constructor function gets executed
// which does nothing in this example
a.x(); // you are trying to access the 'x' property of an instance of 'A'
// which does not exist
// so JavaScript looks for that property in the prototype object
// that was defined using the 'prototype' property of the constructor
In conclusion, in the first example a copy of the function is assigned to each instance. In the second example a single copy of the function is shared by all instances.
By Using like
use css and font same location
@font-face {
font-family: 'Material-Design-Icons';
src: url('Material-Design-Icons.eot');
src: url('Material-Design-Icons.eot?#iefix') format('embedded-opentype'),
url('Material-Design-Icons.woff2') format('woff2'),
url('Material-Design-Icons.woff') format('woff'),
url('Material-Design-Icons.ttf') format('truetype'),
url('Material-Design-Icons.svg#ge_dinar_oneregular') format('svg');
font-weight: normal;
font-style: normal;
}
There's always the "brute force":
Search->File
Type the following in "Containing text" -> ^.*$
. Then check the "Regular Expression" checkbox
Type the following in "File name patterns" -> *.java
Click "Search"
Check the number of matches in the "Search" Tab.
I was getting this when streaming to ElasticSearch from a Lambda function in AWS. Smashed my head a against a wall trying to figure it out. In the end when setting the request.headers['Host']
I was adding in the https://
to the domain for ES - changing this to [es-domain-name].eu-west-1.es.amazonaws.com
(without https://) worked straight away. Below is the code I used to get it working, hopefully save anyone else smashing their head against a wall...
import path from 'path';
import AWS from 'aws-sdk';
const { region, esEndpoint } = process.env;
const endpoint = new AWS.Endpoint(esEndpoint);
const httpClient = new AWS.HttpClient();
const credentials = new AWS.EnvironmentCredentials('AWS');
/**
* Sends a request to Elasticsearch
*
* @param {string} httpMethod - The HTTP method, e.g. 'GET', 'PUT', 'DELETE', etc
* @param {string} requestPath - The HTTP path (relative to the Elasticsearch domain), e.g. '.kibana'
* @param {string} [payload] - An optional JavaScript object that will be serialized to the HTTP request body
* @returns {Promise} Promise - object with the result of the HTTP response
*/
export function sendRequest ({ httpMethod, requestPath, payload }) {
const request = new AWS.HttpRequest(endpoint, region);
request.method = httpMethod;
request.path = path.join(request.path, requestPath);
request.body = payload;
request.headers['Content-Type'] = 'application/json';
request.headers['Host'] = '[es-domain-name].eu-west-1.es.amazonaws.com';
request.headers['Content-Length'] = Buffer.byteLength(request.body);
const signer = new AWS.Signers.V4(request, 'es');
signer.addAuthorization(credentials, new Date());
return new Promise((resolve, reject) => {
httpClient.handleRequest(
request,
null,
response => {
const { statusCode, statusMessage, headers } = response;
let body = '';
response.on('data', chunk => {
body += chunk;
});
response.on('end', () => {
const data = {
statusCode,
statusMessage,
headers
};
if (body) {
data.body = JSON.parse(body);
}
resolve(data);
});
},
err => {
reject(err);
}
);
});
}
I know this is old but I just encountered the issue in my team (some mac, some linux, some windows , all vscode).
solution was to set the line ending in vscode's settings:
.vscode/settings.json
{
"files.eol": "\n",
}
https://qvault.io/2020/06/18/how-to-get-consistent-line-breaks-in-vs-code-lf-vs-crlf/
const arr = [1, 2, 3];
console.log(`${arr}`)
There are a lot of answers here. The code shows how we can create an Exception, how we can use that exception in our methods, and finally, how you can verify in a unit test, the correct exceptions being raised.
import unittest
class DeviceException(Exception):
def __init__(self, msg, code):
self.msg = msg
self.code = code
def __str__(self):
return repr("Error {}: {}".format(self.code, self.msg))
class MyDevice(object):
def __init__(self):
self.name = 'DefaultName'
def setParameter(self, param, value):
if isinstance(value, str):
setattr(self, param , value)
else:
raise DeviceException('Incorrect type of argument passed. Name expects a string', 100001)
def getParameter(self, param):
return getattr(self, param)
class TestMyDevice(unittest.TestCase):
def setUp(self):
self.dev1 = MyDevice()
def tearDown(self):
del self.dev1
def test_name(self):
""" Test for valid input for name parameter """
self.dev1.setParameter('name', 'MyDevice')
name = self.dev1.getParameter('name')
self.assertEqual(name, 'MyDevice')
def test_invalid_name(self):
""" Test to check if error is raised if invalid type of input is provided """
self.assertRaises(DeviceException, self.dev1.setParameter, 'name', 1234)
def test_exception_message(self):
""" Test to check if correct exception message and code is raised when incorrect value is passed """
with self.assertRaises(DeviceException) as cm:
self.dev1.setParameter('name', 1234)
self.assertEqual(cm.exception.msg, 'Incorrect type of argument passed. Name expects a string', 'mismatch in expected error message')
self.assertEqual(cm.exception.code, 100001, 'mismatch in expected error code')
if __name__ == '__main__':
unittest.main()
I took the Ned Rockson's version and adjusted it to allow upwards scrolls as well.
var smoothScroll = function(elementId) {
var MIN_PIXELS_PER_STEP = 16;
var MAX_SCROLL_STEPS = 30;
var target = document.getElementById(elementId);
var scrollContainer = target;
do {
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop === 0);
var targetY = 0;
do {
if (target === scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
Math.abs(targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
var isUp = targetY < scrollContainer.scrollTop;
var stepFunc = function() {
if (isUp) {
scrollContainer.scrollTop = Math.max(targetY, scrollContainer.scrollTop - pixelsPerStep);
if (scrollContainer.scrollTop <= targetY) {
return;
}
} else {
scrollContainer.scrollTop = Math.min(targetY, scrollContainer.scrollTop + pixelsPerStep);
if (scrollContainer.scrollTop >= targetY) {
return;
}
}
window.requestAnimationFrame(stepFunc);
};
window.requestAnimationFrame(stepFunc);
};
? TWO Simple Solutions:
To install the latest version of node and reinstall the old version packages just run the following command.
nvm install node --reinstall-packages-from=node
To install the latest lts
(long term support) version of node and reinstall the old version packages just run the following command.
nvm install --lts /* --reinstall-packages-from=node
Here's a GIF to support this answer.
Why not just use the following simple call (with any exception handling added)?
File.AppendAllText(strFile, "Start Error Log for today")
EDITED ANSWER
This should answer the question fully!
If File.Exists(strFile)
File.AppendAllText(strFile, String.Format("Error Message in Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))
Else
File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If
One line
document.querySelectorAll(".remove").forEach(el => el.remove());
For example you can do in this page to remove userinfo
document.querySelectorAll(".user-info").forEach(el => el.remove());
If you want all groups known to the system, I would recommend using getent group
instead of parsing /etc/group
:
getent group
The reason is that on networked systems, groups may not only read from /etc/group
file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).
If you want just the group names you can use:
getent group | cut -d: -f1
Outline is good, but only when you want the border all around.
Lets say if you want to make it only on bottom or top you can use
<style>
#border-top {
border-top: 1px solid #ccc;
box-shadow: inset 0 1px 0 #fff;
}
</style>
<p id="border-top">This is my content</p>
And for bottom:
<style>
#border-bottom {
border-top: 1px solid #ccc;
box-shadow: 0 1px 0 #fff;
}
</style>
<p id="border-bottom">This is my content</p>
Hope that this helps.
As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.
So:
Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default
Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com
You may need to wait 5-10 mins for the DNS records to update but that's all you need.
You can use pattern matching in C# 7 or above:
switch (foo.GetType())
{
case var type when type == typeof(Player):
break;
case var type when type == typeof(Address):
break;
case var type when type == typeof(Department):
break;
case var type when type == typeof(ContactType):
break;
default:
break;
}
Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)
server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst
3. If you want to make sure that date and time update at startup run this python script in rpi,
import os
try:
client = ntplib.NTPClient()
response = client.request('xxx.xxx.xxx.xxx', version=4)
print "===================================="
print "Offset : "+str(response.offset)
print "Version : "+str(response.version)
print "Date Time : "+str(ctime(response.tx_time))
print "Leap : "+str(ntplib.leap_to_text(response.leap))
print "Root Delay : "+str(response.root_delay)
print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
print "===================================="
except:
os.system("sudo date")
print "NTP Server Down Date Time NOT Set At The Startup"
pass
I found more info in raspberry pi forum.
Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:
EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")
After that you can do this:
EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )
R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.
As already mentioned by Amro, the most concise way to do this is using cell arrays. However, Budo touched on the new string
class introduced in version R2016b of MATLAB. Using this new object, you can very easily create an array of strings in a loop as follows:
for i = 1:10
Names(i) = string('Sample Text');
end
Also take a look at ILSpy by SharpDevelop. It's in early stages of development and they just made a release on the 24th of February. That in itself works pretty good for me. From their website:
ILSpy is the open-source .NET assembly browser and decompiler.
Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011.
Update: JetBrains has released dotPeek, its free .NET decompiler.
Update 2: Telerik also has a free decompiler: JustDecompile.
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
A simple way is to initialize it at first saying myVar = None
Then later on:
if myVar is not None:
# Do something
strings.xml
<string name="sentence">This price is <b>%1$s</b> USD</string>
page.java
String successMessage = getText(R.string.message,"5.21");
This price 5.21 USD
Go to Preferences
> Key Bindings
> User
and add the code below:
[
{ "keys": ["ctrl+shift+f"], "command": "reindent", "args": {"single_line": false} }
]
Usage
Ctrl + Shift + F
The solution pointed out by jou doesn't support value types, this works fine with them as well
Wrappers
import ObjectiveC
final class Lifted<T> {
let value: T
init(_ x: T) {
value = x
}
}
private func lift<T>(x: T) -> Lifted<T> {
return Lifted(x)
}
func setAssociatedObject<T>(object: AnyObject, value: T, associativeKey: UnsafePointer<Void>, policy: objc_AssociationPolicy) {
if let v: AnyObject = value as? AnyObject {
objc_setAssociatedObject(object, associativeKey, v, policy)
}
else {
objc_setAssociatedObject(object, associativeKey, lift(value), policy)
}
}
func getAssociatedObject<T>(object: AnyObject, associativeKey: UnsafePointer<Void>) -> T? {
if let v = objc_getAssociatedObject(object, associativeKey) as? T {
return v
}
else if let v = objc_getAssociatedObject(object, associativeKey) as? Lifted<T> {
return v.value
}
else {
return nil
}
}
A possible Class extension (Example of usage):
extension UIView {
private struct AssociatedKey {
static var viewExtension = "viewExtension"
}
var referenceTransform: CGAffineTransform? {
get {
return getAssociatedObject(self, associativeKey: &AssociatedKey.viewExtension)
}
set {
if let value = newValue {
setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.viewExtension, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
This is really such a great solution, I wanted to add another usage example that included structs and values that are not optionals. Also, the AssociatedKey values can be simplified.
struct Crate {
var name: String
}
class Box {
var name: String
init(name: String) {
self.name = name
}
}
extension UIViewController {
private struct AssociatedKey {
static var displayed: UInt8 = 0
static var box: UInt8 = 0
static var crate: UInt8 = 0
}
var displayed: Bool? {
get {
return getAssociatedObject(self, associativeKey: &AssociatedKey.displayed)
}
set {
if let value = newValue {
setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.displayed, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
var box: Box {
get {
if let result:Box = getAssociatedObject(self, associativeKey: &AssociatedKey.box) {
return result
} else {
let result = Box(name: "")
self.box = result
return result
}
}
set {
setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.box, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var crate: Crate {
get {
if let result:Crate = getAssociatedObject(self, associativeKey: &AssociatedKey.crate) {
return result
} else {
let result = Crate(name: "")
self.crate = result
return result
}
}
set {
setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.crate, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
The array will be initialized to false when you allocate it.
All arrays in Java are initialized to the default value for the type. This means that arrays of ints are initialised to 0, arrays of booleans are initialised to false and arrays of reference types are initialised to null.
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
Change the number of @grid-columns
. Then use -offset
. Changing the number of columns will allow you to control the amount of space between columns. E.g.
variables.less (approx line 294).
@grid-columns: 20;
someName.html
<div class="row">
<div class="col-md-4 col-md-offset-1">First column</div>
<div class="col-md-13 col-md-offset-1">Second column</div>
</div>
0: U
1: n
2: i
3: v
4: e
5: r
6: s
7: i
8: t
9: y
Start index is inclusive
End index is exclusive
None of the current answers including the accepted one will use Apple's San Francisco font on systems that don't have it installed as the system font. Since the question isn't "how do I use the OS X system font on a webpage" the correct solution is to use web fonts:
@font-face {
font-family: "San Francisco";
font-weight: 400;
src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-regular-webfont.woff");
}
Try an OUTER APPLY
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
OUTER APPLY
(
SELECT TOP 1 *
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
) m
ORDER BY
C.Content_DatePublished ASC
Alternatively, you could GROUP BY
the results
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id
GROUP BY
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
ORDER BY
C.Content_DatePublished ASC
The OUTER APPLY
selects a single row (or none) that matches each row from the left table.
The GROUP BY
performs the entire join, but then collapses the final result rows on the provided columns.
As others have mentioned, objects need a __toString
method to be cast to a string. An object that doesn't define that method can still produce a string representation using the spl_object_hash function.
This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.
I have a base Object class with a __toString
method that defaults to calling md5(spl_object_hash($this))
to make the output clearly unique, since the output from spl_object_hash can look very similar between objects.
This is particularly helpful for debugging code where a variable initializes as an Object and later in the code it is suspected to have changed to a different Object. Simply echoing the variables to the log can reveal the change from the object hash (or not).
I am promoting my comment to an answer:
The easy way is:
You could draw in the original 'frame' itself instead of using gray image.
The hard way (method you were trying to implement):
backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
is the correct syntax.
When I had this issue the cause was a relative reference to template files when using the ui.bootstrap.modal module.
templateUrl: 'js/templates/modal.html'
This works from a root domain (www.example.com) but when a path is added (www.example.com/path/) the reference breaks. The answer in my case was simply to making the reference absolute (js/ -> /js/).
templateUrl: '/js/templates/modal.html'
As this question comes often, here is the simple explanation.
datetime
or time
module has two important functions.
In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.
Now lets assume we have a date object.
>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)
If we want to create a string from this date in the format 'Mon Feb 15 2010'
>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10
Lets assume we want to convert this s
again to a datetime
object.
>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00
Refer This document all formatting directives regarding datetime.
Look at Float.intBitsToFloat
and Double.longBitsToDouble
, which sort of explain how bits correspond to floating-point numbers. In particular, the bits of a normal float
look something like
s * 2^exp * 1.ABCDEFGHIJKLMNOPQRSTUVW
where A...W are 23 bits -- 0s and 1s -- representing a fraction in binary -- s is +/- 1, represented by a 0 or a 1 respectively, and exp is a signed 8-bit integer.
This code:
Option Explicit
Sub ExportMyPicture()
Dim MyChart As String, MyPicture As String
Dim PicWidth As Long, PicHeight As Long
Application.ScreenUpdating = False
On Error GoTo Finish
MyPicture = Selection.Name
With Selection
PicHeight = .ShapeRange.Height
PicWidth = .ShapeRange.Width
End With
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"
Selection.Border.LineStyle = 0
MyChart = Selection.Name & " " & Split(ActiveChart.Name, " ")(2)
With ActiveSheet
With .Shapes(MyChart)
.Width = PicWidth
.Height = PicHeight
End With
.Shapes(MyPicture).Copy
With ActiveChart
.ChartArea.Select
.Paste
End With
.ChartObjects(1).Chart.Export Filename:="MyPic.jpg", FilterName:="jpg"
.Shapes(MyChart).Cut
End With
Application.ScreenUpdating = True
Exit Sub
Finish:
MsgBox "You must select a picture"
End Sub
was copied directly from here, and works beautifully for the cases I tested.
Your settings must be incorrect.
Go to http://www.facebook.com/developers/ and edit the application you're working on.
On the "website" tab, look for "Site URL". This should be set to your website's URL "http://yoursite.com/"
Note that if you're using subdomains, you'll also need to update "Site Domain" to be "yoursite.com"
You can call a reset function before appending. Something like this:
function resetNewReviewBoardForm() {
$("#Description").val('');
$("#PersonName").text('');
$("#members").empty(); //this one what worked in my case
$("#EmailNotification").val('False');
}
I am facing a similar problem here. Our users are migrating their jobs from freestyle to pipeline. They do not want Jenkinsfile stored in their repos(historical reason) and still want to use "Git Parameter" plugin
So we have to use use "Pipeline script" and develop a different plugin which works like "Git Parameter".
This new plugin does not integrate with SCM setting in the project. The plugin is at https://plugins.jenkins.io/list-git-branches-parameter
Hope it helps you as well
If you want to do that yourself, without using any external library, a clean way would be to create a template.html
file with all the static content, like for example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>$title</title>
</head>
<body>$body
</body>
</html>
Put a tag like $tag
for any dynamic content and then do something like this:
File htmlTemplateFile = new File("path/template.html");
String htmlString = FileUtils.readFileToString(htmlTemplateFile);
String title = "New Page";
String body = "This is Body";
htmlString = htmlString.replace("$title", title);
htmlString = htmlString.replace("$body", body);
File newHtmlFile = new File("path/new.html");
FileUtils.writeStringToFile(newHtmlFile, htmlString);
Note: I used org.apache.commons.io.FileUtils for simplicity.
A Kotlin Extension to observe on the global layout and perform a given task when height is ready dynamically.
Usage:
view.height { Log.i("Info", "Here is your height:" + it) }
Implementation:
fun <T : View> T.height(function: (Int) -> Unit) {
if (height == 0)
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
function(height)
}
})
else function(height)
}
You got your answer, but why iterate over the tr when you can go straight for the inputs? That way you can store them easier into an array and it reduce the number of CSS queries. Depends what you want to do of course, but for collecting data it is a more flexible approach.
var array = [];
$("tr.item input").each(function() {
array.push({
name: $(this).attr('class'),
value: $(this).val()
});
});
console.log(array);?
Here's an example - we recently developed a simulation model to measure the remote transmission response time of a yet-to-be-developed system. An emulation analysis would not have given us the answer in time to upgrade the bandwidth capacity so simulation was our approach. Because we were mostly interested in determining bandwidth needs, we cared primarily about transaction size and volume, not the processing of the system. The simulation model was on a stand-alone piece of software that was designed to model discrete-event processes. To summarize in response to your question, emulation is a type of simulation. But, in this case, simulation was NOT an emulation because it didn't fully represent the new system, only the size and volume of transactions.
TL;DR answer - There is no real solution besides "delete app and reinstall".
This answer is not satisfactory for many situations, when you have an existing database that needs to not get deleted within the app.
Lukasz and plivesey are the only ones with solutions that don't require delete, but neither worked for me.
You need to only depend on one major version of angular, so update all modules depending on angular 2.x :
The following class can be used to load a resource
from the classpath
and also receive a fitting error message in case there's a problem with the given filePath
.
import java.io.InputStream;
import java.nio.file.NoSuchFileException;
public class ResourceLoader
{
private String filePath;
public ResourceLoader(String filePath)
{
this.filePath = filePath;
if(filePath.startsWith("/"))
{
throw new IllegalArgumentException("Relative paths may not have a leading slash!");
}
}
public InputStream getResource() throws NoSuchFileException
{
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(filePath);
if(inputStream == null)
{
throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");
}
return inputStream;
}
}
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
My problem was that the TFS Build Controller was running as a network service and for some reason I didn't understand why the Visual Studio Build Host service certificates were not being used. I changed the identity of the Visual Studio Build service to something more manageable, made sure it had rights on the TFS server, and manually added the certificates using the MMC.
The problem was also that MSBuild can't add the password protected certificates to the store.
You can use this library
https://github.com/burhanuddin353/TFTColor
Swift
UIColor.colorWithRGB(hexString: "FF34AE" alpha: 1.0)
Objective-C
[UIColor colorWithRGBHexString:@"FF34AE" alpha:1.0f]
If you want some extra flexibility, you can also set the weights manually.
Say you have input of all ones:
import torch
import torch.nn as nn
input = torch.ones((8, 8))
print(input)
tensor([[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.]])
And you want to make a dense layer with no bias (so we can visualize):
d = nn.Linear(8, 8, bias=False)
Set all the weights to 0.5 (or anything else):
d.weight.data = torch.full((8, 8), 0.5)
print(d.weight.data)
The weights:
Out[14]:
tensor([[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000, 0.5000]])
All your weights are now 0.5. Pass the data through:
d(input)
Out[13]:
tensor([[4., 4., 4., 4., 4., 4., 4., 4.],
[4., 4., 4., 4., 4., 4., 4., 4.],
[4., 4., 4., 4., 4., 4., 4., 4.],
[4., 4., 4., 4., 4., 4., 4., 4.],
[4., 4., 4., 4., 4., 4., 4., 4.],
[4., 4., 4., 4., 4., 4., 4., 4.],
[4., 4., 4., 4., 4., 4., 4., 4.],
[4., 4., 4., 4., 4., 4., 4., 4.]], grad_fn=<MmBackward>)
Remember that each neuron receives 8 inputs, all of which have weight 0.5 and value of 1 (and no bias), so it sums up to 4 for each.
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
I was getting this error
Error:Execution failed for task ':app:preDebugAndroidTestBuild'. Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.
I was having following dependencies in my build.gradle file under Gradle Scripts
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
So, I resolved it by commenting the following dependencies
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
So my dependencies look like this
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
//testImplementation 'junit:junit:4.12'
//androidTestImplementation 'com.android.support.test:runner:1.0.2'
//androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Hope it helps!
The top answer is almost correct, but you also need to add an ampersand at the end of each line. For example write the batch file:
start /d "~\iexplore.exe" "www.google.com" &
start /d "~\iexplore.exe" "www.yahoo.com" &
start /d "~\iexplore.exe" "www.blackholesurfer.com" &
The ampersand allows the prompt to return to the shell and launch another tab. This is a windows solution only, but the ampersand has the same effect in linux shell.
I ended up overriding the OnPaint and OnBackgroundPaint events and manually drawing the button exactly like I need it. It worked pretty well.
Per the comments to the original post, merges / joins are well-suited for this problem. In particular, an inner join will return only values that are present in both dataframes, making thesetdiff
statement unnecessary.
Using the data from Dinre's example:
In base R:
cleanedA <- merge(data_A, data_B[, "index"], by = 1, sort = FALSE)
cleanedB <- merge(data_B, data_A[, "index"], by = 1, sort = FALSE)
Using the dplyr package:
library(dplyr)
cleanedA <- inner_join(data_A, data_B %>% select(index))
cleanedB <- inner_join(data_B, data_A %>% select(index))
To keep the data as two separate tables, each containing only its own variables, this subsets the unwanted table to only its index variable before joining. Then no new variables are added to the resulting table.
Setp 1 : Download the following apk files. 1)com.google.android.gms.apk (https://androidfilehost.com/?fid=95916177934534438) 2)com.android.vending-4.4.22.apk (https://androidfilehost.com/?fid=23203820527945795)
Step 2 : Create a new AVD without the google API's
Step 3 : Run the AVD (Start the emulator)
Step 4 : Install the downloaded apks using adb .
1)adb install com.google.android.gms-6.7.76_\(1745988-038\)-6776038-minAPI9.apk
2)adb install com.android.vending-4.4.22.apk
adb come up with android sdks/studio
Step 5 : Create the application in google developer console
Step 6 : Configure the api key in your Androidmanifest.xml and google api version.
Note : In step1 you need to download the apk based on your Android API level(..18,19,21..) and google play services version (5,5.1,6,6.5......)
This will work 100%.
I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?
There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.
I usually combine PointToScreen
and PointToClient
:
Point locationOnForm = control.FindForm().PointToClient(
control.Parent.PointToScreen(control.Location));
from threading import Thread
from time import sleep
def run(name):
for x in range(10):
print("helo "+name)
sleep(1)
def run1():
for x in range(10):
print("hi")
sleep(1)
T=Thread(target=run,args=("Ayla",))
T1=Thread(target=run1)
T.start()
sleep(0.2)
T1.start()
T.join()
T1.join()
print("Bye")
Please post your code,
<?php
echo $_GET['link'];
?>
or
<?php
echo $_REQUEST['link'];
?>
do work...
If you're using Ionic and the Push and Console plugins that's the problem. Remove the cordova console plugin (which is deprecated) and the error will disappear.
The linker error is saying that a library is duplicated which is, in fact, true because the console plugin is already in cordova-ios 4.5+
It took me a couple of hours to figure this out!
Perhaps you should not store data that way. It is a bad practice to ever store a comma delimited list in a field. IT is very inefficient for querying. This should be a related table.
Have you tried SELECT DISTINCT ?
INSERT INTO destTable
SELECT DISTINCT * FROM srcTable
50% of C++ programmers like to set their pointers to null after a delete:
template<typename T>
void moronic_delete(T*& p)
{
delete p;
p = nullptr;
}
Without the reference, you would only be changing a local copy of the pointer, not affecting the caller.
More clarified version of above answers:
IEnumerable<IGrouping<int, ClassA>> groups = list.GroupBy(x => x.PropertyIntOfClassA);
foreach (var groupingByClassA in groups)
{
int propertyIntOfClassA = groupingByClassA.Key;
//iterating through values
foreach (var classA in groupingByClassA)
{
int key = classA.PropertyIntOfClassA;
}
}
I wrote this awhile back to do just what you're looking for.
namespace STLHelpers
{
//
// iterator helper type for iterating through the *values* of key/value collections
//
/////////////////////////////////////////////
template<typename _traits>
struct _value_iterator
{
explicit _value_iterator(typename _traits::iterator_type _it)
: it(_it)
{
}
_value_iterator(const _value_iterator &_other)
: it(_other.it)
{
}
friend bool operator==(const _value_iterator &lhs, const _value_iterator &rhs)
{
return lhs.it == rhs.it;
}
friend bool operator!=(const _value_iterator &lhs, const _value_iterator &rhs)
{
return !(lhs == rhs);
}
_value_iterator &operator++()
{
++it;
return *this;
}
_value_iterator operator++(int)
{
_value_iterator t(*this);
++*this;
return t;
}
typename _traits::value_type &operator->()
{
return **this;
}
typename _traits::value_type &operator*()
{
return it->second;
}
typename _traits::iterator_type it;
};
template<typename _tyMap>
struct _map_iterator_traits
{
typedef typename _tyMap::iterator iterator_type;
typedef typename _tyMap::mapped_type value_type;
};
template<typename _tyMap>
struct _const_map_iterator_traits
{
typedef typename _tyMap::const_iterator iterator_type;
typedef const typename _tyMap::mapped_type value_type;
};
}
public class SomeClass
{
public void SomeMethod()
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
var type = method.DeclaringType;
var name = method.Name;
}
}
Now let's say you have another class like this:
public class Caller
{
public void Call()
{
SomeClass s = new SomeClass();
s.SomeMethod();
}
}
name will be "Call" and type will be "Caller"
UPDATE Two years later since I'm still getting upvotes on this
In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute
Going with the previous example:
public class SomeClass
{
public void SomeMethod([CallerMemberName]string memberName = "")
{
Console.WriteLine(memberName); //output will be name of calling method
}
}
To answer your question:
In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.
You can define a variable with:
ARG myvalue=3
Spaces around the equal character are not allowed.
And use it later with:
RUN echo $myvalue > /test
I got the same problem, but i find the answer in this page! it works for me, you can try it.
iconv -f cp936 -t utf-8
Your way can't work for two reasons.
You need to use set /p text=
for setting the variable with user input.
The other problem is the pipe.
A pipe starts two asynchronous cmd.exe instances and after finishing the job both instances are closed.
That's the cause why it seems that the variables are not set, but a small example shows that they are set but the result is lost later.
set myVar=origin
echo Hello | (set /p myVar= & set myVar)
set myVar
Outputs
Hello
origin
Alternatives: You can use the FOR loop to get values into variables or also temp files.
for /f "delims=" %%A in ('echo hello') do set "var=%%A"
echo %var%
or
>output.tmp echo Hello
>>output.tmp echo world
<output.tmp (
set /p line1=
set /p line2=
)
echo %line1%
echo %line2%
Alternative with a macro:
You can use a batch macro, this is a bit like the bash equivalent
@echo off
REM *** Get version string
%$set% versionString="ver"
echo The version is %versionString[0]%
REM *** Get all drive letters
`%$set% driveLetters="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveLetters
The definition of the macro can be found at
SO:Assign output of a program to a variable using a MS batch file
To print the content of Root store:
certutil -store Root
To output content to a file:
certutil -store Root > root_content.txt
To add certificate to Root store:
certutil -addstore -enterprise Root file.cer
Its just like creating a WAR
file of your project, you can do it in several ways (from Eclipse, command line, maven).
If you want to do from command line, the command is
jar -cvf my_web_app.war *
Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)
Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame
Windows are just normal WPF application Windows, but can host Pages via a Frame container
You could also create a custom model field type - see http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields
In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.
The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.
This is working for me:
from django.db import models
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value':self.max_value}
defaults.update(kwargs)
return super(IntegerRangeField, self).formfield(**defaults)
Then in your model class, you would use it like this (field being the module where you put the above code):
size = fields.IntegerRangeField(min_value=1, max_value=50)
OR for a range of negative and positive (like an oscillator range):
size = fields.IntegerRangeField(min_value=-100, max_value=100)
What would be really cool is if it could be called with the range operator like this:
size = fields.IntegerRangeField(range(1, 50))
But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...
Without RegEx, with some must-have value checking
public static string ExtractString(string soapMessage, string tag)
{
if (string.IsNullOrEmpty(soapMessage))
return soapMessage;
var startTag = "<" + tag + ">";
int startIndex = soapMessage.IndexOf(startTag);
startIndex = startIndex == -1 ? 0 : startIndex + startTag.Length;
int endIndex = soapMessage.IndexOf("</" + tag + ">", startIndex);
endIndex = endIndex > soapMessage.Length || endIndex == -1 ? soapMessage.Length : endIndex;
return soapMessage.Substring(startIndex, endIndex - startIndex);
}
Just a shot in the dark(since you did not share the compiler
initialization code with us): the way you retrieve the compiler
causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE
.
Thanks for the replies.
I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.
After a while I found the problem: When I was sending the response, I was converting it to a string via .toString()
.
I fixed that and now it works brilliantly. Sorry for the false alarm.
Using regular for loop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + ", ");
}
It gives output as yours 1, 2, 3, 4, 5
you have to float
your image container as follows:
HTML
<div id="container">
<div id="floated">...some other random text</div>
...
some random text
...
</div>
CSS
#container{
width: 400px;
background: yellow;
}
#floated{
float: left;
width: 150px;
background: red;
}
FIDDLE
Try redirecting the output to Out-Null. Like so,
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null
Composition
final class Car {
private final Engine engine;
Car(EngineSpecs specs) {
engine = new Engine(specs);
}
void move() {
engine.work();
}
}
Aggregation
final class Car {
private Engine engine;
void setEngine(Engine engine) {
this.engine = engine;
}
void move() {
if (engine != null)
engine.work();
}
}
In the case of composition, the Engine is completely encapsulated by the Car. There is no way for the outside world to get a reference to the Engine. The Engine lives and dies with the car. With aggregation, the Car also performs its functions through an Engine, but the Engine is not always an internal part of the Car. Engines may be swapped, or even completely removed. Not only that, but the outside world can still have a reference to the Engine, and tinker with it regardless of whether it's in the Car.
I like the solution using the -eq
test, because it's basically a one-liner.
My own solution was to use parameter expansion to throw away all the numerals and see if there was anything left. (I'm still using 3.0, haven't used [[
or expr
before, but glad to meet them.)
if [ "${INPUT_STRING//[0-9]}" = "" ]; then
# yes, natural number
else
# no, has non-numeral chars
fi
You can also use git diff HEAD file
to show the diff for a specific file.
See the EXAMPLE
section under git-diff(1)
A solution with no libraries, dynamic length returned, unsigned integer interpretation (not two's complement)
public static byte[] numToBytes(int num){
if(num == 0){
return new byte[]{};
}else if(num < 256){
return new byte[]{ (byte)(num) };
}else if(num < 65536){
return new byte[]{ (byte)(num >>> 8),(byte)num };
}else if(num < 16777216){
return new byte[]{ (byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
}else{ // up to 2,147,483,647
return new byte[]{ (byte)(num >>> 24),(byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
}
}
The trim() method removes whitespace from both sides of a string.
To remove all the spaces from the string use .replace(/\s/g, "")
this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();
You can compile a piece C# of code into memory and generate assembly bytes with Roslyn. It's already mentioned but would be worth adding some Roslyn example for this here. The following is the complete example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
namespace RoslynCompileSample
{
class Program
{
static void Main(string[] args)
{
// define source code, then parse it (to the type used for compilation)
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
using System;
namespace RoslynCompileSample
{
public class Writer
{
public void Write(string message)
{
Console.WriteLine(message);
}
}
}");
// define other necessary objects for compilation
string assemblyName = Path.GetRandomFileName();
MetadataReference[] references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
};
// analyse and generate IL code from syntax tree
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
// write IL code into memory
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
// handle exceptions
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
}
else
{
// load this 'virtual' DLL so that we can use
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = Assembly.Load(ms.ToArray());
// create instance of the desired class and call the desired function
Type type = assembly.GetType("RoslynCompileSample.Writer");
object obj = Activator.CreateInstance(type);
type.InvokeMember("Write",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
new object[] { "Hello World" });
}
}
Console.ReadLine();
}
}
}
Another option using String.Format()
string.Format("{0:HH:mm:ss tt}", DateTime.Now)
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
I'd set up your HTML like so:
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />
Then use the following code:
<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function(event) {
window.location.href = this.id + '.html';
};
}
</script>
That assigns an onclick
event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id
attribute plus the .html
extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.
Sorry to resurrect this answer, but in iOS 10 things kinda changed, and now cancelling is possible and you can even cancel gracefully!
After iOS 10 you can cancel animations with UIViewPropertyAnimator!
UIViewPropertyAnimator(duration: 2, dampingRatio: 0.4, animations: {
view.backgroundColor = .blue
})
animator.stopAnimation(true)
If you pass true it cancels the animation and it stops right where you cancelled it. The completion method will not be called. However, if you pass false you are responsible for finishing the animation:
animator.finishAnimation(.start)
You can finish your animation and stay in the current state (.current) or go to the initial state (.start) or to the end state (.end)
By the way, you can even pause and restart later...
animator.pauseAnimation()
animator.startAnimation()
Note: If you don't want an abrupt cancelling you can reverse your animation or even change your animation after you pause it!
Because your delimiter is ", " you could use any of the following:
public class StringDelim {
public static void removeBrackets(String string) {
System.out.println(string.substring(1, string.length() - 1));
}
public static void main(String... args) {
// Array.toString() example
String [] arr = {"Hi" , "My", "name", "is", "br3nt"};
String string = Arrays.toString(arr);
removeBrackets(string);
// List#toString() example
List<String> list = new ArrayList<String>();
list.add("Hi");
list.add("My");
list.add("name");
list.add("is");
list.add("br3nt");
string = list.toString();
removeBrackets(string);
// Map#values().toString() example
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("1", "Hi");
map.put("2", "My");
map.put("3", "name");
map.put("4", "is");
map.put("5", "br3nt");
System.out.println(map.values().toString());
removeBrackets(string);
// Enum#toString() example
EnumSet<Days> set = EnumSet.allOf(Days.class);
string = set.toString();
removeBrackets(string);
}
public enum Days {
MON("Monday"),
TUE("Tuesday"),
WED("Wednesday"),
THU("Thursday"),
FRI("Friday"),
SAT("Saturday"),
SUN("Sunday");
private final String day;
Days(String day) {this.day = day;}
public String toString() {return this.day;}
}
}
If your delimiter is ANYTHING else then this isn't going to work for you.
I've started a project to help people making their first GitHub pull request. You can do the hands-on tutorial to make your first PR here
The workflow is simple as
git clone <clone url you copied earlier>
git checkout -b branch-name
git commit
git push origin branch-name
Compare and pull request
buttonUser JQuery is EmptyObject to check whether array is contains elements or not.
var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true
Use SimpleDateFormat parse method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
String inputString = "11-11-2012";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(inputString, dateFormat );
Since we have Java 8 with LocalDate I would suggest use next:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
String inputString = "11-11-2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate inputDate = LocalDate.parse(inputString,formatter);
Use string for shorter field, like names, address, phone, company
Use Text for larger content, comments, content, paragraphs.
My general rule, if it's something that is more than one line, I typically go for text, if it's a short 2-6 words, I go for string.
The official rule is 255 for a string. So, if your string is more than 255 characters, go for text.
If you don't have 'HIBERNATE_SEQUENCE' sequence created in database (if use oracle or any sequence based database), you shall get same type of error;
Ensure the sequence is present there;
For current Android application package:
public String getDataDir(Context context) throws Exception {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir;
}
For any package:
public String getAnyDataDir(Context context, String packageName) throws Exception {
return context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.dataDir;
}
Only Objective-C is allowed by now... but since a few months ago you are allowed to write scripts that will be interpreted in your application.
So you may be able to write a LUA interpreter or a Python interpreter, then write some part of your application in this scripting language. If you want your application accepted on the App Store, these scripts have to be bundled with the application (your application cannot download it from the Internet for example)
Select the block of code that you want indented.
Right-click (or, on Mac, Ctrl-click).
Structure → Re-indent
Renders the HTML widget of a given field. If you apply this to an entire form or collection of fields, each underlying form row will be rendered.
{# render a field row, but display a label with text "foo" #}
{{ form_row(form.name, {'label': 'foo'}) }}
The second argument to form_row() is an array of variables. The templates provided in Symfony only allow to override the label as shown in the example above.
See "More about Form Variables" to learn about the variables argument.
SQL 2003 standard defines the format as follows:
<unquoted timestamp string> ::= <unquoted date string> <space> <unquoted time string>
<date value> ::= <years value> <minus sign> <months value> <minus sign> <days value>
<time value> ::= <hours value> <colon> <minutes value> <colon> <seconds value>
There are some definitions in between that just link back to these, but in short YYYY-MM-DD HH:MM:SS
with optional .mmm
milliseconds is required to work on all SQL databases.
I know, I am tooooo late to post an answer, but hoping that it might help someone. Plus, I just solved this issue I had with my tests. This is what I had in my test:
My test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "path-to-context" })
@Transactional
public class MyIntegrationTest
Context xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
I still had the problem that, the database was not being cleaned up automatically.
Issue was resolved when I added following property to BasicDataSource
<property name="defaultAutoCommit" value="false" />
Hope it helps.
I'm using jquery with yql for feed. You can retrieve twitter,rss,buzz with yql. I read from http://tutorialzine.com/2010/02/feed-widget-jquery-css-yql/ . It's very useful for me.
My solution,
load the app using
NODE_ENV=production node app.js
Then setup config.js
as a function rather than an object
module.exports = function(){
switch(process.env.NODE_ENV){
case 'development':
return {dev setting};
case 'production':
return {prod settings};
default:
return {error or other settings};
}
};
Then as per Jans solution load the file and create a new instance which we could pass in a value if needed, in this case process.env.NODE_ENV
is global so not needed.
var Config = require('./conf'),
conf = new Config();
Then we can access the config object properties exactly as before
conf.twitter.consumerKey
There's also Array.find()
in ES6 which returns the first matching element it finds.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
const myArray = [1, 2, 3]
const myElement = myArray.find((element) => element === 2)
console.log(myElement)
// => 2
$_
is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ...
so $_
represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:
write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH
Just use
del /f /q C:\Users\%username%\AppData\Local\temp
And it will work.
Note: It will delete the whole folder however, Windows will remake it as it needs.
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
There are (at least) two different ways to get to theWorksheet
object
Sheets
or Worksheets
collections as referenced by DanMWhen a new workbook with three worksheets is created there will exist four objects which you can access via unqualified names: ThisWorkbook
; Sheet1
; Sheet2
; Sheet3
. This lets you write things like this:
Sheet1.Range("A1").Value = "foo"
Although this may seem like a useful shortcut, the problem comes when the worksheets are renamed. The unqualified object name remains as Sheet1
even if the worksheet is renamed to something totally different.
There is some logic to this because:
For example (tested in Excel 2003), create a new Workbook
with three worksheets. Create two modules. In one module declare this:
Public Sheet4 As Integer
In the other module put:
Sub main()
Sheet4 = 4
MsgBox Sheet4
End Sub
Run this and the message box should appear correctly.
Now add a fourth worksheet to the workbook which will create a Sheet4
object. Try running main again and this time you will get an "Object does not support this property or method" error
This is how i replace diacritic characters to non-diacritic ones in all my .NET program
C#:
//Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter 'é' is substituted by an 'e'
public string RemoveDiacritics(string s)
{
string normalizedString = null;
StringBuilder stringBuilder = new StringBuilder();
normalizedString = s.Normalize(NormalizationForm.FormD);
int i = 0;
char c = '\0';
for (i = 0; i <= normalizedString.Length - 1; i++)
{
c = normalizedString[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().ToLower();
}
VB .NET:
'Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter "é" is substituted by an "e"'
Public Function RemoveDiacritics(ByVal s As String) As String
Dim normalizedString As String
Dim stringBuilder As New StringBuilder
normalizedString = s.Normalize(NormalizationForm.FormD)
Dim i As Integer
Dim c As Char
For i = 0 To normalizedString.Length - 1
c = normalizedString(i)
If CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark Then
stringBuilder.Append(c)
End If
Next
Return stringBuilder.ToString().ToLower()
End Function
dplyr
package does this with count
/tally
commands, or the n()
function:
First, some data:
df <- data.frame(x = rep(1:6, rep(c(1, 2, 3), 2)), year = 1993:2004, month = c(1, 1:11))
Now the count:
library(dplyr)
count(df, year, month)
#piping
df %>% count(year, month)
We can also use a slightly longer version with piping and the n()
function:
df %>%
group_by(year, month) %>%
summarise(number = n())
or the tally
function:
df %>%
group_by(year, month) %>%
tally()
Something like...
Minutes.minutesBetween(getStart(), getEnd()).getMinutes();
In the related question you posted, we already have a way to achieve that in plain javascript, so we only need to get the js reference to the dom node we want to scroll.
The ref
attribute can be used to declare reference to html elements to make them available in vue's component methods.
Or, if the method in the component
is a handler for some UI event, and the target is related to the div you want to scroll in space, you can simply pass in the event object along with your wanted arguments, and do the scroll like scroll(event.target.nextSibling)
.
If you use nano with a language like python (as in your example) it's also a good idea to convert tabs to spaces.
Edit your ~/.nanorc file (or create it) and add:
set tabsize 4
set tabstospaces
If you already got a file with tabs and want to convert them to spaces i recommend the expand
command (shell):
expand -4 input.py > output.py
import class folder does not work for me, but add jar worked!
1. put the class folder under the project folder
2. Zip the class folder
3. Highlight project name, click "Project" in the top toolbar, click "Properties", click "Libraries" tab, click "Add External jars".
4. Add the zip file. Done!
I can't believe the accepted answer has so many upvotes -- it's a horrible method.
Here's the correct way to do it, with date_trunc:
SELECT date_trunc('month', txn_date) AS txn_month, sum(amount) as monthly_sum
FROM yourtable
GROUP BY txn_month
It's bad practice but you might be forgiven if you use
GROUP BY 1
in a very simple query.
You can also use
GROUP BY date_trunc('month', txn_date)
if you don't want to select the date.