Bill K.'s answer was the most elegant if you just want to start a window at startup or start from a shortcut on the desktop.
Just open the window where you want it, right click and choose properties. select Layout uncheck "let system position window" and click OK.
Window will now open just where you want it. You can set font and window colors at the same time on other tabs. sweet.
StarUML does just that and it is free. Unfortunately it hasn't been updated for a while. There were a couple of offshoot projects (as the project admins wouldn't allow it to be taken over) but they too have died a death.
The select box arrow is a native ui element, it depends on the desktop theme or the web browser. Use a jQuery plugin (e.g. Select2, Chosen) or CSS.
Use this:
strstr('filename.ext','.',true);
//result filename
You can also use .map() as:
var list=[];
response.data.message.map(function(value, key) {
list.push(value);
});
One mistake I was making was saving the file as a.condarc
or b.condarc
.
Save it only as .condarc
and paste the following code in the file and save the file in your home directory. Make necessary changes to hostname, user etc.
channels:
- defaults
show_channel_urls: True
allow_other_channels: True
proxy_servers:
http: http://user:pass@hostname:port
https: http://user:pass@hostname:port
ssl_verify: False
user1247808 has a good link with: wget -c
http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip
If that isn't enough words for you:
http://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-all-titles-in-ns0.gz (updated url from Michael Kropat's suggestion)
Although that file name changes, you'll want to find the latest ... that turns out just to be a big (very big) text file.
here is the playground example with pointers in it. https://play.golang.org/p/uNpTKeCt0sH
package main
import (
"fmt"
)
type t struct {
a int
b string
}
func (tt *t) String() string{
return fmt.Sprintf("[%d %s]", tt.a, tt.b)
}
func remove(slice []*t, i int) []*t {
copy(slice[i:], slice[i+1:])
return slice[:len(slice)-1]
}
func main() {
a := []*t{&t{1, "a"}, &t{2, "b"}, &t{3, "c"}, &t{4, "d"}, &t{5, "e"}, &t{6, "f"}}
k := a[3]
a = remove(a, 3)
fmt.Printf("%v || %v", a, k)
}
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
If you use a context manager, the file is closed automatically for you
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
If you're using Python2.6 or higher, it's preferred to use str.format()
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
For python2.7 and higher you can use {}
instead of {0}
In Python3, there is an optional file
parameter to the print
function
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introduced f-strings for another alternative
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
Not that I know of, but what about doing something like this when you create an instance of TestedClass that you want to test:
TestedClass toTest = new TestedClass() {
public LoginContext login(String user, String password) {
//return mocked LoginContext
}
};
Another option would be to use Mockito to create an instance of TestedClass and let the mocked instance return a LoginContext.
looking at your error message first of all I would suggest you to recompile your whole application, make sure all the required dlls are there in bin folder when you recompile it.
I suposse this is the output you need:
title,intro,tagline
2.9,Gardena,CA
It can be done with this changes to your code:
import csv
import itertools
with open('log.txt', 'r') as in_file:
lines = in_file.read().splitlines()
stripped = [line.replace(","," ").split() for line in lines]
grouped = itertools.izip(*[stripped]*1)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro', 'tagline'))
for group in grouped:
writer.writerows(group)
The following works for me in Gradle / Groovy for build.gradle
for an Android project, without having to import groovy.io.FileType
(NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):
FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
println "Proguard file located and processed: " + it
}
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
I haven't tested this - but it should give you a general idea of the direction you need to take.
For this to work, I'm going to assume a few things about the text of the TextView
:
TextView
consists of lines delimited with "\n"
.TextView
which will all include one operator and one number.Char
of a line.First we get the text:
String input = tv1.getText().toString();
Then we split it up for each line:
String[] lines = input.split( "\n" );
Now we need to calculate the total value:
int total = Integer.parseInt( lines[0].trim() ); //We know this is a number.
for( int i = 1; i < lines.length(); i++ ) {
total = calculate( lines[i].trim(), total );
}
The method calculate should look like this, assuming that we know the first Char
of a line is the operator:
private int calculate( String input, int total ) {
switch( input.charAt( 0 ) )
case '+':
return total + Integer.parseInt( input.substring( 1, input.length() );
case '-':
return total - Integer.parseInt( input.substring( 1, input.length() );
case '*':
return total * Integer.parseInt( input.substring( 1, input.length() );
case '/':
return total / Integer.parseInt( input.substring( 1, input.length() );
}
EDIT
So the above as stated in the comment below does "left-to-right" calculation, ignoring the normal order ( + and / before + and -).
The following does the calculation the right way:
String input = tv1.getText().toString();
input = input.replace( "\n", "" );
input = input.replace( " ", "" );
int total = getValue( input );
The method getValue
is a recursive method and it should look like this:
private int getValue( String line ) {
int value = 0;
if( line.contains( "+" ) ) {
String[] lines = line.split( "\\+" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value += getValue( lines[i] );
return value;
}
if( line.contains( "-" ) ) {
String[] lines = line.split( "\\-" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value -= getValue( lines[i] );
return value;
}
if( line.contains( "*" ) ) {
String[] lines = line.split( "\\*" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value *= getValue( lines[i] );
return value;
}
if( line.contains( "/" ) ) {
String[] lines = line.split( "\\/" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value /= getValue( lines[i] );
return value;
}
return Integer.parseInt( line );
}
Special cases that the recursive method does not handle:
Also the fact the we're using Integers
might give some "odd" results in some cases as e.g. 5/3 = 1.
I'd try something like:
#!/usr/bin/python
from __future__ import print_function
import shlex
from subprocess import Popen, PIPE
def shlep(cmd):
'''shlex split and popen
'''
parsed_cmd = shlex.split(cmd)
## if parsed_cmd[0] not in approved_commands:
## raise ValueError, "Bad User! No output for you!"
proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
return (proc.returncode, out, err)
... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.
Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.
As per docker-compose 1.6.0:
You can now specify both a build and an image key if you're using the new file format.
docker-compose build
will build the image and tag it with the name you've specified, whiledocker-compose pull
will attempt to pull it.
So your docker-compose.yml
would be
version: '2'
services:
wildfly:
build: /path/to/dir/Dockerfile
image: wildfly_server
ports:
- 9990:9990
- 80:8080
To update docker-compose
sudo pip install -U docker-compose==1.6.0
Easiest way for a lazy Mac user like me: Drag-and-drop the startup.sh
file from the Finder to the Terminal window and press Return.
To shutdown Tomcat, do the same with shutdown.sh
.
You can delete all the .bat
files as they are only for a Windows PC, of no use on a Mac to other Unix computer. I delete them as it makes it easier to read that folder's listing.
I find that a fresh Tomcat download will not run on my Mac because of file permission restrictions throwing errors during startup. I use the BatChmod
app which wraps a GUI around the equivelant Unix commands to reset file permissions.
Unix systems protect access to ports numbered under 1024. So if you want to use port 80 with Tomcat you will need to learn how to do "port-forwarding" to forward incoming requests to port 8080 where Tomcat listens by default. To do port-forwarding, you issue commands to the packet-filtering (firewall) app built into Mac OS X (and BSD). In the old days we used ipfw
. In Mac OS X 10.7 (Lion) and later Apple is moving to a newer tool, pf
.
I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read()
returns a byte
object rather than string.
You might try to feed it into a StringIO
object, or even do a str(response)
.
As Mikkel posted before Collections.rotate is a simple way. I'm using this method for moving items up- and downward in a List.
public static <T> void moveItem(int sourceIndex, int targetIndex, List<T> list) {
if (sourceIndex <= targetIndex) {
Collections.rotate(list.subList(sourceIndex, targetIndex + 1), -1);
} else {
Collections.rotate(list.subList(targetIndex, sourceIndex + 1), 1);
}
}
ArrayList
is newer and 20-30% faster.
If you don't need something explitly apparent in Vector
, use ArrayList
OK, found solution.
In the file database.php, by default, it comes the "mysql" part:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
all you need to do is change the values :
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
by your database name (you must create one if you dont have any) and by that database username
like this
'database' => env('DB_DATABASE', 'MyDatabase'),
'username' => env('DB_USERNAME', 'MyUsername'),
My answer
Use nested for
loops to provide break points to the for /l
loop.
for %%a in (0 1 2 3 4 5 6 7 8 9) do (
for %%b in (0 1 2 3 4 5 6 7 8 9) do (
for /l %%c in (1,1,10) do (
if not exist %%a%%b%%c goto :continue
)
)
)
:continue
Explanation
The code must be tweaked significantly to properly use the nested loops. For example, what is written will have leading zeros.
"Regular" for
loops can be immediately broken out of with a simple goto
command, where for /l
loops cannot. This code's innermost for /l
loop cannot be immediately broken, but an overall break point is present after every 10 iterations (as written). The innermost loop doesn't have to be 10 iterations -- you'll just have to account for the math properly if you choose to do 100 or 1000 or 2873 for that matter (if math even matters to the loop).
History I found this question while trying to figure out why a certain script was running slowly. It turns out I used multiple loops with a traditional loop structure:
set cnt=1
:loop
if "%somecriteria%"=="finished" goto :continue
rem do some things here
set /a cnt += 1
goto :loop
:continue
echo the loop ran %cnt% times
This script file had become somewhat long and it was being run from a network drive. This type of loop file was called maybe 20 times and each time it would loop 50-100 times. The script file was taking too long to run. I had the bright idea of attempting to convert it to a for /l
loop. The number of needed iterations is unknown, but less than 10000. My first attempt was this:
setlocal enabledelayedexpansion
set cnt=1
for /l %%a in (1,1,10000) do (
if "!somecriteria!"=="finished" goto :continue
rem do some things here
set /a cnt += 1
)
:continue
echo the loop ran %cnt% times
With echo
on, I quickly found out that the for /l
loop still did ... something ... without actually doing anything. It ran much faster, but still slower than I thought it could/should. Therefore I found this question and ended up with the nested loop idea presented above.
Side note
It turns out that the for /l
loop can be sped up quite a bit by simply making sure it doesn't have any output. I was able to do this for a noticeable speed increase:
setlocal enabledelayedexpansion
set cnt=1
@for /l %%a in (1,1,10000) do @(
if "!somecriteria!"=="finished" goto :continue
rem do some things here
set /a cnt += 1
) > nul
:continue
echo the loop ran %cnt% times
The bandwidth of a link is the theoretical maximum amount of data that could be sent over that channel without regard to practical considerations. For example, you could pump 10^9 bits per second down a Gigabit Ethernet link over a Cat-6e or fiber optic cable. Unfortunately this would be a completely unformatted stream of bits.
To make it actually useful there's a start of frame sequence which precedes any actual data bits, a frame check sequence at the end for error detection and an idle period between transmitted frames. All of those occupy what is referred to as "bit times" meaning the amount of time it takes to transmit one bit over the line. This is all necessary overhead, but is subtracted from the total bandwidth of the link.
And this is only for the lowest level protocol which is stuffing raw data out onto the wire. Once you start adding in the MAC addresses, an IP header and a TCP or UDP header, then you've added even more overhead.
Check out http://en.wikipedia.org/wiki/Ethernet_frame. Similar problems exist for other transmission media.
You can use menu left sidebar collapse accordion, animated with right arrow
I quote Andrew Dunstan on the pgsql-hackers list:
At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.
Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.
Offers an arsenal of new functions and operators to add "json-processing".
The answer to the original question in Postgres 9.3:
SELECT *
FROM json_array_elements(
'[{"name": "Toby", "occupation": "Software Engineer"},
{"name": "Zaphod", "occupation": "Galactic President"} ]'
) AS elem
WHERE elem->>'name' = 'Toby';
Advanced example:
For bigger tables you may want to add an expression index to increase performance:
Adds jsonb
(b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb
also supports GIN, btree and hash indexes, GIN being the most potent of these.
json
and jsonb
data types and functions.The manual goes as far as suggesting:
In general, most applications should prefer to store JSON data as
jsonb
, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.
Bold emphasis mine.
Performance benefits from general improvements to GIN indexes.
Complete jsonb
functions and operators. Add more functions to manipulate jsonb
in place and for display.
With css:
.img {
display:table-cell;
max-width:...px;
max-height:...px;
width:100%;
}
You can put two figures inside one figure environment. For example:
\begin{figure}[p]
\centering
\includegraphics{fig1}
\caption{Caption 1}
\includegraphics{fig2}
\caption{Caption 2}
\end{figure}
Each caption will generate a separate figure number.
You probably want to check the length of the string first and do something like this:
if (!myStr.empty())
{
char lastChar = *myStr.rbegin();
}
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
Even if this is already answered (1 year ago) you could also let the fields be calculated automatically.
The HTML
<tr>
<td><input type="text" value="" ></td>
<td><input type="text" class="class_name" placeholder="bla bla"/></td>
</tr>
<tr>
<td><input type="text" value="" ></td>
<td><input type="text" class="class_name" placeholder="bla bla."/></td>
</tr>
The script
$(document).ready(function(){
$(".class_name").each(function(){
$(this).keyup(function(){
calculateSum()
;})
;})
;}
);
function calculateSum(){
var sum=0;
$(".class_name").each(function(){
if(!isNaN(this.value) && this.value.length!=0){
sum+=parseFloat(this.value);
}
else if(isNaN(this.value)) {
alert("Maybe an alert if they type , instead of .");
}
}
);
$("#sum").html(sum.toFixed(2));
}
When looking for the existence of a element in an array, proper casting is required to pass the SQL parser of postgres. Here is one example query using array contains operator in the join clause:
For simplicity I only list the relevant part:
table1 other_name text[]; -- is an array of text
The join part of SQL shown
from table1 t1 join table2 t2 on t1.other_name::text[] @> ARRAY[t2.panel::text]
The following also works
on t2.panel = ANY(t1.other_name)
I am just guessing that the extra casting is required because the parse does not have to fetch the table definition to figure the exact type of the column. Others please comment on this.
Use find. Seriously, it is the best way because then you can really see what files it's operating on:
find . -name "*.sql" -exec grep -H "slow" {} \;
Note, the -H is mac-specific, it shows the filename in the results.
check out distributionUrl setting in gradle-wrapper.properties. I changed https to http, then my problem was solved.
Stephen Canon answered it very well!
But
This is 3 times as fast as testing all m up to vn.
int IsPrime(unsigned int number) {
if (number <= 3 && number > 1)
return 1; // as 2 and 3 are prime
else if (number%2==0 || number%3==0)
return 0; // check if number is divisible by 2 or 3
else {
unsigned int i;
for (i=5; i*i<=number; i+=6) {
if (number % i == 0 || number%(i + 2) == 0)
return 0;
}
return 1;
}
}
Setting 'checked' or null instead of true or false respectively will do the work.
// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');
jQuery provides several selectors (full list) in order to make the queries you are looking for work. To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." you can also use contains, starts with, and ends with to look at these html5 data attributes. See the full list above in order to see all of your options.
The basic querying has been covered above, and using John Hartsock's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not
).
In order to expand this to the other points you are looking for, we can use several meta selectors. First, if you are going to do multiple queries, it is nice to cache the parent selection.
var group = $('ul[data-group="Companies"]');
Next, we can look for companies in this set who start with G
var google = $('[data-company^="G"]',group);//google
Or perhaps companies which contain the word soft
var microsoft = $('[data-company*="soft"]',group);//microsoft
It is also possible to get elements whose data attribute's ending matches
var facebook = $('[data-company$="book"]',group);//facebook
//stored selector_x000D_
var group = $('ul[data-group="Companies"]');_x000D_
_x000D_
//data-company starts with G_x000D_
var google = $('[data-company^="G"]',group).css('color','green');_x000D_
_x000D_
//data-company contains soft_x000D_
var microsoft = $('[data-company*="soft"]',group).css('color','blue');_x000D_
_x000D_
//data-company ends with book_x000D_
var facebook = $('[data-company$="book"]',group).css('color','pink');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul data-group="Companies">_x000D_
<li data-company="Microsoft">Microsoft</li>_x000D_
<li data-company="Google">Google</li>_x000D_
<li data-company ="Facebook">Facebook</li>_x000D_
</ul>
_x000D_
Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .
public class StringReverse1 {
public static void main(String[] args) {
String a = "Gini Gina Proti";
List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));
list.stream()
.collect(Collectors.toCollection( LinkedList :: new ))
.descendingIterator()
.forEachRemaining(System.out::println);
}}
/*
The output :
i
t
o
r
P
a
n
i
G
i
n
i
G
*/
Be careful with rebase. If you're sharing your develop branch with anybody, rebase can make a mess of things. Rebase is good only for your own local branches.
Rule of thumb, if you've pushed the branch to origin, don't use rebase. Instead, use merge.
You no longer need to type in bash.exe path manually. This answer is deprecated. Now you can switch to bash directly, if you have git installed in the default path. If you installed git to a different path you need to use the below solution.
Install Git from https://git-scm.com/download/win.
Then open Visual Studio Code and open the command palette using Ctrl + Shift + P. Then type "open user setting", and then select "Open User Settings" from the drop down menu.
Then this tab will open up with default settings on left and your settings on the right:
Now copy this line of code to your own settings page (the pane on the right hand side) and save -
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
Note: "C:\\Program Files\Git\bin\bash.exe"
is the path where the bash.exe
file is located from the Git installation. If you are using the Windows Subsystem for Linux (WSL) Bash shell, the path would be "C:\Windows\System32\bash.exe"
Now press Ctrl + ` to open up the terminal from Visual Studio Code. And you will have Bash -
The macros defined in <inttypes.h>
are the most correct way to print values of types uint32_t
, uint16_t
, and so forth -- but they're not the only way.
Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf
format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)
An alternative is to cast the values to a predefined type and use the format for that type.
Types int
and unsigned int
are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t
or uint16_t
, respectively. Similarly, long
and unsigned long
are at least 32 bits wide, and long long
and unsigned long long
are at least 64 bits wide.
For example, I might write your program like this (with a few additional tweaks):
#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>
int main(void)
{
uint32_t a=12, a1;
uint16_t b=1, b1;
a1 = htonl(a);
printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
b1 = htons(b);
printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
return 0;
}
One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>
. Such an implementation most likely wouldn't have <stdint.h>
either, but the technique is useful for other integer types.
Once you have your image, you can use
$ docker tag <image> <newName>/<repoName>:<tagName>
Build and tag the image with creack/node:latest
$ ID=$(docker build -q -t creack/node .)
Add a new tag
$ docker tag $ID creack/node:0.10.24
You can use this and skip the -t part from build
$ docker tag $ID creack/node:latest
Page -- Takes the specified XAML file, and compiles into BAML, and embeds that output into the managed resource stream for your assembly (specifically AssemblyName.g.resources), Additionally, if you have the appropriate attributes on the root XAML element in the file, it will create a blah.g.cs file, which will contain a partial class of the "codebehind" for that page; this basically involves a call to the BAML goop to re-hydrate the file into memory, and to set any of the member variables of your class to the now-created items (e.g. if you put x:Name="foo" on an item, you'll be able to do this.foo.Background = Purple; or similar.
ApplicationDefinition -- similar to Page, except it goes onestep furthur, and defines the entry point for your application that will instantiate your app object, call run on it, which will then instantiate the type set by the StartupUri property, and will give your mainwindow.
Also, to be clear, this question overall is infinate in it's results set; anyone can define additional BuildActions just by building an MSBuild Task. If you look in the %systemroot%\Microsoft.net\framework\v{version}\ directory, and look at the Microsoft.Common.targets file, you should be able to decipher many more (example, with VS Pro and above, there is a "Shadow" action that allows you generate private accessors to help with unit testing private classes.
Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.
Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.
If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error
object given to the catch block has a stack
property that shows where the exception happened.
Use:
AND oh.tran_date BETWEEN TRUNC(SYSDATE - 1) AND TRUNC(SYSDATE) - 1/86400
Reference: TRUNC
Calling a function on the tran_date
means the optimizer won't be able to use an index (assuming one exists) associated with it. Some databases, such as Oracle, support function based indexes which allow for performing functions on the data to minimize impact in such situations, but IME DBAs won't allow these. And I agree - they aren't really necessary in this instance.
If you are developing for Windows, the com0com project might be, what you are looking for.
It provides pairs of virtual COM ports that are linked via a nullmodem connetion. You can then use your favorite terminal application or whatever you like to send data to one COM port and recieve from the other one.
As Thomas pointed out the project lacks of a signed driver, which is especially problematic on certain Windows version (e.g. Windows 7 x64).
There are a couple of unofficial com0com versions around that do contain a signed driver. One recent verion (3.0.0.0) can be downloaded e.g. from here.
Another way is injecting org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
This answer covers what's what in terms of variables and importantly, output size shall be same for input frame and video size.
import cv2
save_name = "output.mp4"
fps = 10
width = 600
height = 480
output_size = (width, height)
out = cv2.VideoWriter(save_name,cv2.VideoWriter_fourcc('M','J','P','G'), fps , output_size )
cap = cv2.VideoCapture(0) # 0 for webcam or you can put in videopath
while(True):
_, frame = cap.read()
cv2.imshow('Video Frame', frame)
out.write(cv2.resize(frame, output_size ))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
Did you install flask-sqlalchemy
? It looks like you have SQLAlchemy installed but not the Flask extension. Try pip install Flask-SQLAlchemy
in your project's virtualenv to install it from PyPI.
Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.
In your posted question, there is one extra space after try:
, and there are 12 extra spaces after pass
:
>>> post_text = '''\
... if self.tagname and self.tagname2 in list1:
... try:
... question = soup.find("div", "post-text")
... title = soup.find("a", "question-hyperlink")
... self.list2.append(str(title)+str(question)+url)
... current += 1
... except AttributeError:
... pass
... logging.info("%s questions passed, %s questions \
... collected" % (count, current))
... count += 1
... return self.list2
... '''
>>> for line in post_text.splitlines():
... if line.rstrip() != line:
... print(repr(line))
...
' try: '
' pass '
See where the strings end? There are spaces before the lines (indentation), but also spaces after.
Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.
This should be even easier.
$("#e1").select2("val", ["View" ,"Modify"]);
But make sure the values which you pass are already present in the HTMl
You cannot do it in PHP. Once the page is loaded, PHP dies and is out of control.
You have a few options:
<meta http-equiv="refresh" content="5">
I think that the refresh meta tag is the easiest and most convenient.
Try this in PowerShell(admin enabled):
Enable-WindowsOptionalFeature –Online -FeatureName Microsoft-Hyper-V –All -NoRestart
This will install HyperVisor without management tools, and then you can run Docker after this.
'below is from
'http://www.zipcodeworld.com/samples/distance.vbnet.html
Public Function distance(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim theta As Double = lon1 - lon2
Dim dist As Double = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + _
Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * _
Math.Cos(deg2rad(theta))
dist = Math.Acos(dist)
dist = rad2deg(dist)
dist = dist * 60 * 1.1515
If unit = "K" Then
dist = dist * 1.609344
ElseIf unit = "N" Then
dist = dist * 0.8684
End If
Return dist
End Function
Public Function Haversine(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim R As Double = 6371 'earth radius in km
Dim dLat As Double
Dim dLon As Double
Dim a As Double
Dim c As Double
Dim d As Double
dLat = deg2rad(lat2 - lat1)
dLon = deg2rad((lon2 - lon1))
a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(deg2rad(lat1)) * _
Math.Cos(deg2rad(lat2)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))
d = R * c
Select Case unit.ToString.ToUpper
Case "M"c
d = d * 0.62137119
Case "N"c
d = d * 0.5399568
End Select
Return d
End Function
Private Function deg2rad(ByVal deg As Double) As Double
Return (deg * Math.PI / 180.0)
End Function
Private Function rad2deg(ByVal rad As Double) As Double
Return rad / Math.PI * 180.0
End Function
For files in folder named /files
for i in `IFS="";find /files -name *\ *`
do
echo $i
done > /tmp/list
while read line
do
mv "$line" `echo $line | sed 's/ /_/g'`
done < /tmp/list
rm /tmp/list
Don't we all sometimes wish there was a
<T>void java.util.Arrays.deepFill(T[]…multiDimensional)
. Problems start with
Object threeByThree[][] = new Object[3][3];
threeByThree[1] = null;
and
threeByThree[2][1] = new int[]{42};
being perfectly legal.
(If only Object twoDim[]final[]
was legal and well defined…)
(Using one of the public methods from below keeps loops from the calling source code.
If you insist on using no loops at all, substitute the loops and the call to Arrays.fill()
(!) using recursion.)
/** Fills matrix {@code m} with {@code value}.
* @return {@code m}'s dimensionality.
* @throws java.lang.ArrayStoreException if the component type
* of a subarray of non-zero length at the bottom level
* doesn't agree with {@code value}'s type. */
public static <T>int deepFill(Object[] m, T value) {
Class<?> components;
if (null == m ||
null == (components = m.getClass().getComponentType()))
return 0;
int dim = 0;
do
dim++;
while (null != (components = components.getComponentType()));
filler((Object[][])m, value, dim);
return dim;
}
/** Fills matrix {@code m} with {@code value}.
* @throws java.lang.ArrayStoreException if the component type
* of a subarray of non-zero length at level {@code dimensions}
* doesn't agree with {@code value}'s type. */
public static <T>void fill(Object[] m, T value, int dimensions) {
if (null != m)
filler(m, value, dimensions);
}
static <T>void filler(Object[] m, T value, int toGo) {
if (--toGo <= 0)
java.util.Arrays.fill(m, value);
else
for (Object[] subArray : (Object[][])m)
if (null != subArray)
filler(subArray, value, toGo);
}
You should use RegExp (they are awesome) an easy solution is:
if( /^bird/.test(animals[i]) ){
// a bird :D
}
If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/
It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.
You can find source code of any .jar file online, import the same project in your IDE with basic setups. Make necessary changes in .java file and compile it for .class files.
Once compilation is done You need to extract the jar file, replace the old .class file with new one.
And use below command for reconstruct .jar file
Jar cf test.jar *
Note : I have done so many time this changes in our project, hope you will find it useful.
The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?
For example, we have i values and get the value of id field
alert(obj[i].id); //works!
But what if we need key with spaces?
In this case, the following construction can help (without point between [] blocks):
alert(obj[i]["No. of interfaces"]); //works too!
These two settings worked for me to upload 1GB mp4 videos.
<system.web>
<httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
psql --set=sslmode=require -h localhost -p 2345 -U thirunas \
-d postgres -f test_schema.ddl
Another Example for securely connecting to Azure's managed Postgres database:
psql --file=product_data.sql --host=hostname.postgres.database.azure.com --port=5432 \
--username=postgres@postgres-esprit --dbname=product_data \
--set=sslmode=verify-full --set=sslrootcert=/opt/ssl/BaltimoreCyberTrustRoot.crt.pem
Just Small change to what Gary W mentioned, adding 'SELECT':
IF (SELECT CURSOR_STATUS('global','myCursor')) >= -1
BEGIN
DEALLOCATE myCursor
END
http://social.msdn.microsoft.com/Forums/en/sqlgetstarted/thread/eb268010-75fd-4c04-9fe8-0bc33ccf9357
CTRL+SHIFT+D
And there are many shortcuts you can see them by going to
Settings » Shortcuts, as displayed here:
Alternatively, use CTRL + ? to go to the settings, from there one can reach the "Shortcuts" sub-item on the left or use the Official reference.
A ListView
is basically like a ListBox
(and inherits from it), but it also has a View
property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView
, but you can easily create your own.
Another difference is the default selection mode: it's Single
for a ListBox
, but Extended
for a ListView
This flexbox principle also works horizontally
During calculations of flex bases and flexible lengths, auto margins
are treated as 0.
Prior to alignment via justify-content and
align-self, any positive free space is distributed to auto margins in
that dimension.
Setting an automatic left margin for the Last Item will do the work.
.last-item {
margin-left: auto;
}
Code Example:
.container {_x000D_
display: flex;_x000D_
width: 400px;_x000D_
outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
margin: 5px;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p class="last-item"></p>_x000D_
</div>
_x000D_
This can be very useful for Desktop Footers.
As Envato did here with the company logo.
The code below will run in O(N) time and O(N) space complexity. Check this codility link for complete running report.
The program first put all the values inside a HashMap meanwhile finding the max number in the array. The reason for doing this is to have only unique values in provided array and later check them in constant time. After this, another loop will run until the max found number and will return the first integer that is not present in the array.
static int solution(int[] A) {
int max = -1;
HashMap<Integer, Boolean> dict = new HashMap<>();
for(int a : A) {
if(dict.get(a) == null) {
dict.put(a, Boolean.TRUE);
}
if(max<a) {
max = a;
}
}
for(int i = 1; i<max; i++) {
if(dict.get(i) == null) {
return i;
}
}
return max>0 ? max+1 : 1;
}
You can use the -TotalCount
parameter of the Get-Content
cmdlet to read the first n
lines, then use Select-Object
to return only the n
th line:
Get-Content file.txt -TotalCount 9 | Select-Object -Last 1;
Per the comment from @C.B. this should improve performance by only reading up to and including the n
th line, rather than the entire file. Note that you can use the aliases -First
or -Head
in place of -TotalCount
.
To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)
sed -i '/pattern/a \
line1 \
line2' inputfile
Output:
#cat inputfile
pattern
line1 line2
To prepend the lines before:
sed -i '/pattern/i \
line1 \
line2' inputfile
Output:
#cat inputfile
line1 line2
pattern
Try the following:
foo(*values)
This can be found in the Python docs as Unpacking Argument Lists.
Why don't you just save/serve the CSS file as UTF-8?
nav a:hover:after {
content: "?";
}
If that's not good enough, and you want to keep it all-ASCII:
nav a:hover:after {
content: "\2193";
}
The general format for a Unicode character inside a string is \000000
to \FFFFFF
– a backslash followed by six hexadecimal digits. You can leave out leading 0
digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.
Relevant part of the CSS2 spec:
Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:
- with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
- by providing exactly 6 hexadecimal digits: "\000026B" ("&B")
In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.
If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).
- Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
The identifier "te\st" is exactly the same identifier as "test".
Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).
If you want nice json without hardcoding attributes into your service classes,
use <webHttp defaultOutgoingResponseFormat="Json"/>
in your behavior config
The + operator uses public String concat(String str)
internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent.
However I have read here that the concatination code using the + operater is changed to StringBuilder on post Java 4 compilers. So this might not be an issue at all. (Though I would really check this statement if I depend on it in my code!)
What I ended up doing is something like this:
In the controller:
link: function($scope, $element, $attr) {
$scope.scope = $scope; // or $scope.$parent, as needed
$scope.field = $attr.field = '_suffix';
$scope.subfield = $attr.sub_node;
...
so in the templates I could use totally dynamic names, and not just under a certain hard-coded element (like in your "Answers" case):
<textarea ng-model="scope[field][subfield]"></textarea>
Hope this helps.
You may want to try the following:
SELECT CONCAT(title, ' ', forename, ' ', surname) AS name
FROM customer c
JOIN (
SELECT MAX(id) max_id, customer_id
FROM customer_data
GROUP BY customer_id
) c_max ON (c_max.customer_id = c.customer_id)
JOIN customer_data cd ON (cd.id = c_max.max_id)
WHERE CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
LIMIT 10, 20;
Note that a JOIN
is just a synonym for INNER JOIN
.
Test case:
CREATE TABLE customer (customer_id int);
CREATE TABLE customer_data (
id int,
customer_id int,
title varchar(10),
forename varchar(10),
surname varchar(10)
);
INSERT INTO customer VALUES (1);
INSERT INTO customer VALUES (2);
INSERT INTO customer VALUES (3);
INSERT INTO customer_data VALUES (1, 1, 'Mr', 'Bobby', 'Smith');
INSERT INTO customer_data VALUES (2, 1, 'Mr', 'Bob', 'Smith');
INSERT INTO customer_data VALUES (3, 2, 'Mr', 'Jane', 'Green');
INSERT INTO customer_data VALUES (4, 2, 'Miss', 'Jane', 'Green');
INSERT INTO customer_data VALUES (5, 3, 'Dr', 'Jack', 'Black');
Result (query without the LIMIT
and WHERE
):
SELECT CONCAT(title, ' ', forename, ' ', surname) AS name
FROM customer c
JOIN (
SELECT MAX(id) max_id, customer_id
FROM customer_data
GROUP BY customer_id
) c_max ON (c_max.customer_id = c.customer_id)
JOIN customer_data cd ON (cd.id = c_max.max_id);
+-----------------+
| name |
+-----------------+
| Mr Bob Smith |
| Miss Jane Green |
| Dr Jack Black |
+-----------------+
3 rows in set (0.00 sec)
I had the same problem and after some searching I was able to find my logs at the following location:
C:\Users\<yourid>\.AndroidStudioPreview\system\log
Use OpenFileDialog.SafeFileName
OpenFileDialog.SafeFileName
Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.
Now vs has built-in terminal
View > Terminal (Ctrl+")
To change default terminal
Tools > Options - Terminal > Set As Default
Before Visual Studio 2019
From comments best answer is from @Hans Passant
Tools > External Tools > Add
Title: Terminal (or name it yourself)
Command=cmd.exe Or Command=powershell.exe
Arguments= /k
Initial Directory=$(ProjectDir)
Tools > Terminal (or whatever you put in title)
Enjoy!
Before implementying any of this, please see Scott Arciszewski's answer.
I want you to be very careful with what I'm about to share as I have little to no security knowledge (There's a high chance that I'm misusing the API below), so I'd be more than welcome to update this answer with the help of the community.
As @richardtallent mentioned in his answer, there's support for the Web Crypto API, so this example uses the standard. As of this writing, there's a 95.88% of global browser support.
I'm going to be sharing an example using the Web Crypto API
Before we proceed, please note (Quoting from MDN):
This API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle.
Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right and are generally the domain of specialist security experts.
Errors in security system design and implementation can make the security of the system completely ineffective.
If you're not sure you know what you are doing, you probably shouldn't be using this API.
I respect security a lot, and I even bolded additional parts from MDN... You've been warned
Now, to the actual example...
Found here: https://jsfiddle.net/superjose/rm4e0gqa/5/
Note the use of await
keywords. Use it inside an async
function or use .then()
and .catch()
.
// https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey
// https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams
// https://github.com/diafygi/webcrypto-examples#rsa-oaep---generatekey
const stringToEncrypt = 'https://localhost:3001';
// https://github.com/diafygi/webcrypto-examples#rsa-oaep---generatekey
// The resultant publicKey will be used to encrypt
// and the privateKey will be used to decrypt.
// Note: This will generate new keys each time, you must store both of them in order for
// you to keep encrypting and decrypting.
//
// I warn you that storing them in the localStorage may be a bad idea, and it gets out of the scope
// of this post.
const key = await crypto.subtle.generateKey({
name: 'RSA-OAEP',
modulusLength: 4096,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: 'SHA-512'},
}, true,
// This depends a lot on the algorithm used
// Go to https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto
// and scroll down to see the table. Since we're using RSA-OAEP we have encrypt and decrypt available
['encrypt', 'decrypt']);
// key will yield a key.publicKey and key.privateKey property.
const encryptedUri = await crypto.subtle.encrypt({
name: 'RSA-OAEP'
}, key.publicKey, stringToArrayBuffer(stringToEncrypt))
console.log('The encrypted string is', encryptedUri);
const msg = await crypto.subtle.decrypt({
name: 'RSA-OAEP',
}, key.privateKey, encryptedUri);
console.log(`Derypted Uri is ${arrayBufferToString(msg)}`)
private arrayBufferToString(buff: ArrayBuffer) {
return String.fromCharCode.apply(null, new Uint16Array(buff) as unknown as number[]);
}
private stringToArrayBuffer(str: string) {
const buff = new ArrayBuffer(str.length*2) // Because there are 2 bytes for each char.
const buffView = new Uint16Array(buff);
for(let i = 0, strLen = str.length; i < strLen; i++) {
buffView[i] = str.charCodeAt(i);
}
return buff;
}
You can find more examples here (I'm not the owner): // https://github.com/diafygi/webcrypto-examples
The second way is a tad more efficient, but a much better way is to execute them in batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
}
statement.executeBatch();
}
}
You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
int i = 0;
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.
If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.
public void executeBatch(List<Entity> entities) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement statement = connection.prepareStatement(SQL)) {
// ...
try {
connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
}
}
HttpContext.Current.Request.QueryString.Get("id");
This is more pythonic
my_list = [0, 1, 2, 3, 4, 5] # some list
my_list_copy = list(my_list) # my_list_copy and my_list does not share reference now.
NOTE: This is not safe with a list of referenced objects
Thanks to duncan answer, I end up with this:
marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())
Sometimes, the best solution is to use both. Sometimes, it is to use neither. And sometimes, it is to use one or the other. If you want all the styles, including margin and padding reset across all browsers, use reset.css. Then apply all decorations and stylings yourself. If you simply like the built-in stylings but want more cross-browser synchronicity i.e. normalizations then use normalize.css. But if you choose to use both reset.css and normalize.css, link the reset.css stylesheet first and then the normalize.css stylesheet (immediately) afterwards. Sometimes it's not always a matter of which is better, but when to use which one versus when to use both versus when to use neither. IMHO.
If this just happened randomly and has been working perfectly in the past, as is my case, try logging out (cmd+shift+q
) and logging back in. Worked for me
if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int)
if you want your dataset to be unchangeable.
recently i have faced with this error in my mysql
ERROR 2002 (HY000)
:
Can't connect to local MySQL server through socket
'/var/lib/mysql/mysql.sock' (111)
because i forget to start my mariadb. just type this command on ur terminal.
systemctl start mariadb.service
In my case I had to give the IIS_IUSRS
Read\write permission to the log file.
I actually came across something like this not too long ago... check it out over on msdn (see the first answer)
in summary:
.cer - certificate stored in the X.509 standard format. This certificate contains information about the certificate's owner... along with public and private keys.
.pvk - files are used to store private keys for code signing. You can also create a certificate based on .pvk private key file.
.pfx - stands for personal exchange format. It is used to exchange public and private objects in a single file. A pfx file can be created from .cer file. Can also be used to create a Software Publisher Certificate.
I summarized the info from the page based on the suggestion from the comments.
Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:
db.person.find().forEach(
function (elem) {
db.person.update(
{
_id: elem._id
},
{
$set: {
name: elem.firstname + ' ' + elem.lastname
}
}
);
}
);
I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.
input[type="checkbox"] {
// Unchecked Styles
}
input[type="checkbox"]:checked {
// Checked Styles
}
I apologize for bringing up an old thread but felt like it could have used a better answer.
EDIT (3/3/2016):
W3C Specs state that :not(:checked)
as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"]
selector. See example below for clarification.
input[type="checkbox"] {
/* Base Styles aka unchecked */
font-weight: 300; // Will be overwritten by :checked
font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
/* Explicit Unchecked Styles */
border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
/* Checked Styles */
font-weight: 900; // Use a bold font when checked
}
Without using :not(:checked)
in the example above the :checked
selector would have needed to use a border: none;
to achieve the same affect.
Use the input[type="checkbox"]
for base styling to reduce duplication.
Use the input[type="checkbox"]:not(:checked)
for explicit unchecked styles that you do not want to apply to the checked state.
You can directly define a char type vector as below.
vector<char> c = {'a', 'b', 'c'};
vector < vector<char> > t = {{'a','a'}, 'b','b'};
std::getline( stream, where to?, delimiter ie
std::string in;
std::getline(std::cin, in, ' '); //will split on space
or you can read in a line, then tokenize it based on whichever delimiter you wish.
On the version posted by sunshinekitty called "Version < 3.0" , you may need to specify apscheduler 2.1.2 . I accidentally had version 3 on my 2.7 install, so I went:
pip uninstall apscheduler
pip install apscheduler==2.1.2
It worked correctly after that. Hope that helps.
Using a char when the variable is a string won't work. Using
switch (hello.charAt(0))
you will extract the first character of the hello variable instead of trying to use the variable as it is, in string form. You also need to get rid of your space inside
case 'a '
This is how it works in my understanding:
Here's an example: picture the entire table as a series of buckets. Suppose you have an implementation with alpha-numeric hash-codes and have one bucket for each letter of the alphabet. This implementation puts each item whose hash code begins with a particular letter in the corresponding bucket.
Let's say you have 200 objects, but only 15 of them have hash codes that begin with the letter 'B.' The hash table would only need to look up and search through the 15 objects in the 'B' bucket, rather than all 200 objects.
As far as calculating the hash code, there is nothing magical about it. The goal is just to have different objects return different codes and for equal objects to return equal codes. You could write a class that always returns the same integer as a hash-code for all instances, but you would essentially destroy the usefulness of a hash-table, as it would just become one giant bucket.
If you are using angular, check that the tsconfig.json
does not contain errors. (in the problems terminal)
For some reason I doubled these lines, and it didn't work for me
{
"module": "esnext",
"moduleResolution": "node",
}
Swift 4.2
let data = yourString.data(using: .utf8, allowLossyConversion: true)
Give connection URL as jdbc:mysql://localhost:3306/hb_student_tracker?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
To execute your program from the command line, you have to call the python interpreter, like this :
C:\Python27>python hello.py 1 1
If you code resides in another directory, you will have to set the python binary path in your PATH environment variable, to be able to run it, too. You can find detailed instructions here.
If none of the solutions works, please check if you have more than one version of java installed on your machine. Please keep only one version which you prefer and everything should work fine.
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
Android Studio now comes bundled with OpenJDK 8 . Legacy projects can still use JDK7 or JDK8
Reference: https://developer.android.com/studio/releases/index.html
As the error message says in the last line: the module models
in the file c:\projects\mysite..\mysite\polls\models.py
contains no class model
. This error occurs in the definition of the Poll
class:
class Poll(models.model):
Either the class model
is misspelled in the definition of the class Poll
or it is misspelled in the module models
. Another possibility is that it is completely missing from the module models
. Maybe it is in another module or it is not yet implemented in models
.
If you run in linux, open file netbeans.conf using nano or anything else.
nano netbeans-8.2/etc/netbeans.conf
and edit jdkhome or directory for jdk
netbeans_jdkhome="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
you can check your jdk version with
java -version
or
ls /usr/lib/jvm
You can use git stash
to save the current repository before doing the commit you want to make (after merging the changes from the upstream repo with git stash pop
). I had to do this yesterday when I had the same problem.
So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:
val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x
But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:
val x: Any = 5
def f[T](v: T) = v match {
case _: Int => "Int"
case _: String => "String"
case _ => "Unknown"
}
f(x)
Here it doesn't matter what is the type of the variable, Any
. What matters, what is checked is the type of 5
, the value. In fact, T
is useless -- you might as well have written it def f(v: Any)
instead. Also, this uses either ClassTag
or a value's Class
, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_]
(List
of something), but not whether it is, for example, a List[Int]
or List[String]
.
Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag
or a TypeTag
. For example:
val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"
A ClassTag
will also let you use type parameters you received on match
. This won't work:
def f[A, B](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
But this will:
val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)
Here I'm using the context bounds syntax, B : ClassTag
, which works just like the implicit parameter in the previous ClassTag
example, but uses an anonymous variable.
One can also get a ClassTag
from a value's Class
, like this:
val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
val B = ClassTag(b.getClass)
ClassTag(a.getClass) match {
case B => "a is the same class as b"
case _ => "a is not the same class as b"
}
}
f(x, y) == f(y, x) // true, a is the same class as b
A ClassTag
is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag
for List[Int]
and List[String]
is the same, List
. If you need type parameters, then you must use a TypeTag
instead. A TypeTag
however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.
Examples with TypeTag
can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:
import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int
Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag
, so I'll stop here.
Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:
val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it
It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools
In August 2020
No more regular expression stuff
const str = "Test abc test test abc test test test abc test test abc";
const modifiedStr = str.replaceAll('abc', '');
console.log(modifiedStr);
_x000D_
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
import os
destdir = '/var/tmp/testdir'
files = [ f for f in os.listdir(destdir) if os.path.isfile(os.path.join(destdir,f)) ]
Old question I know, but for the curious:
Believe it or not, this issue was solved ~2 decades ago with HTTP BASIC, which passes the value as base64 encoded username:password. (See http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side)
You could do the same, so that the example above would become:
Authorization: FIRE-TOKEN MFBONUoxN0hCR1pIVDdKSjNYODI6ZnJKSVVOOERZcEtEdE9MQ3dvLy95bGxxRHpnPQ==
Session_unset();
only destroys the session variables. To end the session there is another function called session_destroy();
which also destroys the session .
update :
In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie()
may be used for that
adbd
has a compilation flag/option to enable root access: ALLOW_ADBD_ROOT=1
.
Up to Android 9: If adbd
on your device is compiled without that flag, it will always drop privileges when starting up and thus "adb root" will not help at all.
I had to patch the calls to setuid()
, setgid()
, setgroups()
and the capability drops out of the binary myself to get a permanently rooted adbd on my ebook reader.
With Android 10 this changed; when the phone/tablet is unlocked (ro.boot.verifiedbootstate == "orange"
), then adb root mode is possible in any case.
You can't serialize a class that implements IDictionary. Check out this link.
Q: Why can't I serialize hashtables?
A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.
So I think you need to create your own version of the Dictionary for this. Check this other question.
They dropped XS because Bootstrap is considered a mobile-first development tool. It's default is considered xs and so doesn't need to be defined.
You can use a lookahead:
/(?=\S)[^\\]/
window.location.hash = 'something';
That is just plain JavaScript.
Your comment...
Hi, what I really need is to add only the hash... something like this:
window.location.hash = '#';
but in this way nothing is added.
Try this...
window.location = '#';
Also, don't forget about the window.location.replace()
method.
I'm just dropping in to say that using a soft link to accomplish this is a terrible, no-good, horrible idea.
One of the key things about writing software is reproduceability - you want to be able to get the same results every time. These systems are so complex that you want to reduce all invisible sources of error.
Having a soft link is an invisible source of error. It's the sort of thing you'll forget in a month, then move to a different machine, and wonder why you are getting different results - or, you'll try to upgrade your system, and you'll get weird errors because it's not expecting a softlink there.
Moreover, this isn't guaranteed to work - in particular, it's not clear that you will get the correct system include files, which have certainly changed between iterations of gcc.
gcc_select is a systematic way of doing the same thing which will work predictably, or in the very worst case you can file a bug report and get an eventual fix or fix it yourself.
Unfortunately :-( gcc_select does not affect which compiler XCode uses so it's not the way to go if you need to work in XCode (which I do). I still don't know what that way might be.
Here you go. Just specify the chars you want to allow on the first line.
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead. Values produced byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.
Did you tried JQuery's scrollTo
method? http://demos.flesler.com/jquery/scrollTo/
Or you can extend JQuery and add your custom mentod:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 400);
}});
Then you can call this method like:
$("#header").scrollToMe();
SQL Server 2012 introduces the eomonth
function:
select eomonth('2013-05-31 00:00:00:000')
-->
2013-05-31
Try in html:
style="display: inline-block; margin-top: 50px;"
or in css:
display: inline-block;
margin-top: 50px;
The current root password must be empty. Then under "new root password" enter your password and confirm.
This answer uses
git-filter-branch
, for which the docs now give this warning:git filter-branch has a plethora of pitfalls that can produce non-obvious manglings of the intended history rewrite (and can leave you with little time to investigate such problems since it has such abysmal performance). These safety and performance issues cannot be backward compatibly fixed and as such, its use is not recommended. Please use an alternative history filtering tool such as git filter-repo. If you still need to use git filter-branch, please carefully read SAFETY (and PERFORMANCE) to learn about the land mines of filter-branch, and then vigilantly avoid as many of the hazards listed there as reasonably possible.
Changing the author (or committer) would require re-writing all of the history. If you're okay with that and think it's worth it then you should check out git filter-branch. The man page includes several examples to get you started. Also note that you can use environment variables to change the name of the author, committer, dates, etc. -- see the "Environment Variables" section of the git man page.
Specifically, you can fix all the wrong author names and emails for all branches and tags with this command (source: GitHub help):
#!/bin/sh
git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
The easiest way to stream video via IP Camera !
I just edit your example. You must replace your IP and add /video
on your link. And go ahead with your project
import cv2
cap = cv2.VideoCapture('http://192.168.18.37:8090/video')
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
You may try this (using jQuery
)
$(function(){_x000D_
$('#MainPopupIframe').load(function(){_x000D_
$(this).show();_x000D_
console.log('iframe loaded successfully')_x000D_
});_x000D_
_x000D_
$('#click').on('click', function(){_x000D_
$('#MainPopupIframe').attr('src', 'https://heera.it'); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
Update: Using plain javascript
window.onload=function(){_x000D_
var ifr=document.getElementById('MainPopupIframe');_x000D_
ifr.onload=function(){_x000D_
this.style.display='block';_x000D_
console.log('laod the iframe')_x000D_
};_x000D_
var btn=document.getElementById('click'); _x000D_
btn.onclick=function(){_x000D_
ifr.src='https://heera.it'; _x000D_
};_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
Update: Also you can try this (dynamic iframe)
$(function(){_x000D_
$('#click').on('click', function(){_x000D_
var ifr=$('<iframe/>', {_x000D_
id:'MainPopupIframe',_x000D_
src:'https://heera.it',_x000D_
style:'display:none;width:320px;height:400px',_x000D_
load:function(){_x000D_
$(this).show();_x000D_
alert('iframe loaded !');_x000D_
}_x000D_
});_x000D_
$('body').append(ifr); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
You can call the scp
bash command (it copies files over SSH) with subprocess.run
:
import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "[email protected]:/path/to/foo.bar"])
If you're creating the file that you want to send in the same Python program, you'll want to call subprocess.run
command outside the with
block you're using to open the file (or call .close()
on the file first if you're not using a with
block), so you know it's flushed to disk from Python.
You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).
The solution I came up with is basically the same solution used before the introduction of storyboards.
Create a new, empty interface class file. Drag a UIView on to the canvas, layout as desired.
Load the nib manually, assign to the appropriate header/footer section in viewForHeaderInSection or viewForFooterInSection delegate methods.
I had hope that Apple simplified this scenario with storyboards and kept looking for a better or simpler solution. For example custom table headers and footers are straight forward to add.
When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication.
By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs:
To fix this issue add following lines After Return and Before Begin statement:
READS SQL DATA
DETERMINISTIC
For Example :
CREATE FUNCTION f2()
RETURNS CHAR(36) CHARACTER SET utf8
/*ADD HERE */
READS SQL DATA
DETERMINISTIC
BEGIN
For more detail about this issue please read Here
You can use html2canvas plugin and jsPDF both. Process order: html to png & png to pdf
Example code:
jQuery('#part1').html2canvas({
onrendered: function( canvas ) {
var img1 = canvas.toDataURL('image/png');
}
});
jQuery('#part2').html2canvas({
onrendered: function( canvas ) {
var img2 = canvas.toDataURL('image/png');
}
});
jQuery('#part3').html2canvas({
onrendered: function( canvas ) {
var img3 = canvas.toDataURL('image/png');
}
});
var doc = new jsPDF('p', 'mm');
doc.addImage( img1, 'PNG', 0, 0, 210, 297); // A4 sizes
doc.addImage( img2, 'PNG', 0, 90, 210, 297); // img1 and img2 on first page
doc.addPage();
doc.addImage( img3, 'PNG', 0, 0, 210, 297); // img3 on second page
doc.save("file.pdf");
An adaptation of the above answer...
$('input[type=radio][name=bedStatus]').on('change', function() {_x000D_
switch ($(this).val()) {_x000D_
case 'allot':_x000D_
alert("Allot Thai Gayo Bhai");_x000D_
break;_x000D_
case 'transfer':_x000D_
alert("Transfer Thai Gayo");_x000D_
break;_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot_x000D_
<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer
_x000D_
Just having final
will have the intended effect.
final int x = 5;
...
x = 10; // this will cause a compilation error because x is final
Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x
You can use the static method Enum.GetNames
which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum
var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;
How are the "NULL" and "empty varchar" values stored in SQL Server. Why would you want to know that? Or in other words, if you knew the answer, how would you use that information?
And in case I have no user entry for a string field on my UI, should I store a NULL or a ''? It depends on the nature of your field. Ask yourself whether the empty string is a valid value for your field.
If it is (for example, house name in an address) then that might be what you want to store (depending on whether or not you know that the address has no house name).
If it's not (for example, a person's name), then you should store a null, because people don't have blank names (in any culture, so far as I know).
If you are working with Swift 5+ you have to use UserDefaults.standard.setValue(value, forKey: key)
and to get saved data you have to use UserDefaults.standard.dictionary(forKey: key)
.
Instead of LIKE
(which does work as other commenters have suggested), you can alternatively use CHARINDEX
:
declare @full varchar(100) = 'abcdefg'
declare @find varchar(100) = 'cde'
if (charindex(@find, @full) > 0)
print 'exists'
You can enable pretty-printing by setting the SerializationFeature.INDENT_OUTPUT
on your ObjectMapper
like so:
mapper.enable(SerializationFeature.INDENT_OUTPUT);
findViewById<Button>(R.id.signUp)?.setOnClickListener(
Toast.makeText(mActivity, "Button Clicked", Toast.LENGTH_LONG).show()
)
As an alternative approach to trying to parse the string and catching NumberFormatException
, you could use a regex; e.g.
if (Pattern.compile("-?[0-9]+").matches(str)) {
// its an integer
}
This is likely to be faster, especially if you precompile and reuse the regex.
However, the problem with this approach is that Integer.parseInt(str)
will also fail if str
represents a number that is outside range of legal int
values. While it is possible to craft a regex that only matches integers in the range Integer.MIN_INT
to Integer.MAX_INT
, it is not a pretty sight. (And I am not going to try it ...)
On the other hand ... it may be acceptable to treat "not an integer" and "integer too large" separately for validation purposes.
One situation I've run into was when dealing with milliseconds. FF and IE will not parse this date string correctly when trying to create a new date.
"2014/11/24 17:38:20.177Z"
They do not know how to handle .177Z
. Chrome will work though.
You will need to add handlers in Apache to handle php code.
Edit by command sudo vi /etc/httpd/conf/httpd.conf
Add these two handlers
AddType application/x-httpd-php .php
AddType application/x-httpd-php .php3
at position specified below
<IfModule mime_module>
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
--Add Here--
</IfModule>
for more details on AddType handlers
http://httpd.apache.org/docs/2.2/mod/mod_mime.html
FYI you can sometimes use SYSTEM or Trustedinstaller to kill tasks ;)
google quickkill_3_0.bat
sc config TrustedInstaller binPath= "cmd /c TASKKILL /F /IM notepad.exe
sc start "TrustedInstaller"
In my case it was due to 'lower_case_table_names' parameter.
The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.
This is fixed by reverting back the lower case parameter changes to the previous state.
The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.
You want HttpRuntime.AppDomainAppPath
.
If you're in an HTTP request, you can also call Server.MapPath("~/Whatever")
.
Method 1
public static void increaseFontSizeForPath(Spannable spannable, String path, float increaseTime) {
int startIndexOfPath = spannable.toString().indexOf(path);
spannable.setSpan(new RelativeSizeSpan(increaseTime), startIndexOfPath,
startIndexOfPath + path.length(), 0);
}
using
Utils.increaseFontSizeForPath(spannable, "big", 3); // make "big" text bigger 3 time than normal text
Method 2
public static void setFontSizeForPath(Spannable spannable, String path, int fontSizeInPixel) {
int startIndexOfPath = spannable.toString().indexOf(path);
spannable.setSpan(new AbsoluteSizeSpan(fontSizeInPixel), startIndexOfPath,
startIndexOfPath + path.length(), 0);
}
using
Utils.setFontSizeForPath(spannable, "big", (int) textView.getTextSize() + 20); // make "big" text bigger 20px than normal text
use window.event
- it contains last event
and as any event
contains pageX
, pageY
etc. Works for Chrome, Safari, IE but not FF.
You cannot call orElse
after ifPresent
, the reason is, orElse
is called on an optiional but ifPresent
returns void. So the best approach to achieve is ifPresentOrElse
.
It could be like this:
op.ifPresentOrElse(
(value)
-> { System.out.println(
"Value is present, its: "
+ value); },
()
-> { System.out.println(
"Value is empty"); });
This is what you need:
=NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0))) ## pseudo code
For the first cell of A, this would be:
=NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))
Enter formula (and drag down) as follows:
You will get:
this worked for me , in this way we setting the default value to empty string
@Html.TextBoxFor(m => m.Id, new { @Value = "" })
You can use pandas.Series.map :
df['col'].map('str{}'.format)
It will apply the word "str" before all your values.
Here's one more answer that I've found to be pretty concise and doesn't use external packages:
import datetime as dt
import calendar
# Today, in `dt.date` type
day = dt.datetime.now().date()
one_year_delta = dt.timedelta(days=366 if ((day.month >= 3 and calendar.isleap(day.year+1)) or
(day.month < 3 and calendar.isleap(day.year))) else 365)
# Add one year to the current date
print(day + one_year_delta)
You can use following command -
LENGTH(TRIM(TRANSLATE(string1, '+-.0123456789', '')))
This will return NULL if your string1
is Numeric
your query would be -
select * from tablename
where LENGTH(TRIM(TRANSLATE(X, '+-.0123456789', ''))) is null
How about:
select salesid from AXDelNotesNoTracking group by salesid having count(*) > 1;
Goto Properties -> maven Remove the pom.xml from the activate profiles and follow the below steps.
Steps :
EXCLUDE="foo bar blah jah"
DEST=$1
for i in *
do
for x in $EXCLUDE
do
if [ $x != $i ]; then
cp -a $i $DEST
fi
done
done
Untested...
First of all go to apache/bin/conf/httpd.conf and make sure that mod_deflate.so is enabled.
Then go to the .htaccess file and add this line:
SetOutputFilter DEFLATE
This should output all the content served as gzipped, i have tried it and it works.
Use :
$(PROJECT_DIR)/Project name/PrefixHeader.pch
For larger s&r tasks it's better and faster to use grep and xargs, so, for example;
grep -rl 'apples' /dir_to_search_under | xargs sed -i 's/apples/oranges/g'
Try the following configuration:
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false
log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false
Then configure the loggers in the Java code accordingly:
static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");
Do you want output to go to stdout
? If not, change the first line of log4j.properties
to:
log4j.rootLogger=OFF
and get rid of the stdout
lines.
a.sort(function(a,b){return a - b})
These can be confusing.... check this link out.
I have a Windows service, and I added the following line to the constructor for my service:
using System.Diagnostics;
try {
Process p = Process.Start(@"C:\Windows\system32\calc.exe");
} catch {
Debugger.Break();
}
When I tried to run this, the Process.Start() call was made, and no exception occurred. However, the calc.exe application did not show up. In order to make it work, I had edit the properties for my service in the Service Control Manager to enable interaction with the desktop. After doing that, the Process.Start() opened calc.exe as expected.
But as others have said, interaction with the desktop is frowned upon by Microsoft and has essentially been disabled in Vista. So even if you can get it to work in XP, I don't know that you'll be able to make it work in Vista.
I have to pass two parameters like:
/Controller/Action/Param1Value/Param2Value
This way:
@Html.ActionLink(
linkText,
actionName,
controllerName,
routeValues: new {
Param1Name= Param1Value,
Param2Name = Param2Value
},
htmlAttributes: null
)
will generate this url
/Controller/Action/Param1Value?Param2Name=Param2Value
I used a workaround method by merging parameter two in parameter one and I get what I wanted:
@Html.ActionLink(
linkText,
actionName,
controllerName,
routeValues: new {
Param1Name= "Param1Value / Param2Value" ,
},
htmlAttributes: null
)
And I get :
/Controller/Action/Param1Value/Param2Value
Here are a few ways:
1) sub
sub(".*:", "", string)
## [1] "E001" "E002" "E003"
2) strsplit
sapply(strsplit(string, ":"), "[", 2)
## [1] "E001" "E002" "E003"
3) read.table
read.table(text = string, sep = ":", as.is = TRUE)$V2
## [1] "E001" "E002" "E003"
4) substring
This assumes second portion always starts at 4th character (which is the case in the example in the question):
substring(string, 4)
## [1] "E001" "E002" "E003"
4a) substring/regex
If the colon were not always in a known position we could modify (4) by searching for it:
substring(string, regexpr(":", string) + 1)
5) strapplyc
strapplyc
returns the parenthesized portion:
library(gsubfn)
strapplyc(string, ":(.*)", simplify = TRUE)
## [1] "E001" "E002" "E003"
6) read.dcf
This one only works if the substrings prior to the colon are unique (which they are in the example in the question). Also it requires that the separator be colon (which it is in the question). If a different separator were used then we could use sub
to replace it with a colon first. For example, if the separator were _
then string <- sub("_", ":", string)
c(read.dcf(textConnection(string)))
## [1] "E001" "E002" "E003"
7) separate
7a) Using tidyr::separate
we create a data frame with two columns, one for the part before the colon and one for after, and then extract the latter.
library(dplyr)
library(tidyr)
library(purrr)
DF <- data.frame(string)
DF %>%
separate(string, into = c("pre", "post")) %>%
pull("post")
## [1] "E001" "E002" "E003"
7b) Alternately separate
can be used to just create the post
column and then unlist
and unname
the resulting data frame:
library(dplyr)
library(tidyr)
DF %>%
separate(string, into = c(NA, "post")) %>%
unlist %>%
unname
## [1] "E001" "E002" "E003"
8) trimws We can use trimws
to trim word characters off the left and then use it again to trim the colon.
trimws(trimws(string, "left", "\\w"), "left", ":")
## [1] "E001" "E002" "E003"
The input string
is assumed to be:
string <- c("G1:E001", "G2:E002", "G3:E003")
If you were interested in the function not just the answer here is how it is done:
int ipToInt(int first, int second,
int third, int fourth)
{
return Convert.ToInt32((first * Math.Pow(256, 3))
+ (second * Math.Pow(256, 2)) + (third * 256) + fourth);
}
with first
through fourth
being the segments of the IPv4 address.
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
I needed a way to do this in an AJAX return, so I wrote this piece:
<p id="num_results">Number of results: <span></span></p>
<div id="results"></div>
<script type="text/javascript">
$(function(){
ajax();
})
//Function that makes Ajax call out to receive search results
var ajax = function() {
//Setup Ajax
$.ajax({
url: '/path/to/url', //URL to load
type: 'GET', //Type of Ajax call
dataType: 'html', //Type of data to be expected on return
success: function(data) { //Function that manipulates the returned AJAX'ed data
$('#results').html(data); //Load the data into a HTML holder
var $el = $('#results'); //jQuery Object that is holding the results
setTimeout(function(){ //Custom callback function to count the number of results
callBack($el);
});
}
});
}
//Custom Callback function to return the number of results
var callBack = function(el) {
var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
$('#num_results span').text(length); //Write the counted results to the DOM
}
</script>
Obviously this is a quick example, but it may be helpful.
Here is an example of what I made to created ID's with my JavaScript.
function abs_demo_DemandeEnvoyee_absence(){
var iDateInitiale = document.getElementById("abs_t_date_JourInitial_absence").value; /* On récupère la date initiale*/
var iDateFinale = document.getElementById("abs_t_date_JourFinal_absence").value; /*On récupère la date finale*/
var sMotif = document.getElementById("abs_txt_motif_absence").value; /*On récupère le motif*/
var iCompteurDivNumero = 1; /*Le compteur est initialisé à 1 parce que la div 1 existe*/
var TestDivVide = document.getElementById("abs_Autorisation_"+iCompteurDivNumero+"_absence") == undefined; //Boléenne, renvoie false si la div existe déjà
var NewDivCreation = ""; /*Initialisée en string vide pour concaténation*/
var NewIdCreation; /*Utilisée pour créer l'id d'une div dynamiquement*/
var NewDivVersHTML; /*Utilisée pour insérer la nouvelle div dans le html*/
while(TestDivVide == false){ /*Tant que la div pointée existe*/
iCompteurDivNumero++; /*On incrémente le compteur de 1*/
TestDivVide = document.getElementById("abs_Autorisation_"+iCompteurDivNumero+"_absence") == undefined; /*Abs_autorisation_1_ est écrite en dur.*/
}
NewIdCreation = "abs_Autorisation_"+iCompteurDivNumero+"_absence" /*On crée donc la nouvelle ID de DIV*/
/*On crée la nouvelle DIV avec l'ID précédemment créée*/
NewDivCreation += "<div class=\"abs_AutorisationsDynamiques_absence\" id=\""+NewIdCreation+"\">Votre demande d'autorisation d'absence du <b>"+iDateInitiale+"</b> au <b>"+iDateFinale+"</b>, pour le motif suivant : <i>\""+sMotif+"\"</i> a bien été <span class=\"abs_CouleurTexteEnvoye_absence\">envoyée</span>.</div>";
document.getElementById("abs_AffichagePanneauDeControle_absence").innerHTML+=NewDivCreation; /*Et on concatenne la nouvelle div créée*/
document.getElementById("abs_Autorisation_1_absence").style.display = 'none'; /*On cache la première div qui contient le message "vous n'avez pas de demande en attente" */
}
Will provide text translation if asked. :)
If you are using windows xp and eclipse juno then it should be like this in order
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Dhelp.lucene.tokenizer=standard
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar
-Xms40m
-Xmx512m
Let me give an example for Including express module with require & import
-require
var express = require('express');
-import
import * as express from 'express';
So after using any of the above statement we will have a variable called as 'express' with us. Now we can define 'app' variable as,
var app = express();
So we use 'require' with 'CommonJS' and 'import' with 'ES6'.
For more info on 'require' & 'import', read through below links.
require - Requiring modules in Node.js: Everything you need to know
import - An Update on ES6 Modules in Node.js
A curried function is a function of several arguments rewritten such that it accepts the first argument and returns a function that accepts the second argument and so on. This allows functions of several arguments to have some of their initial arguments partially applied.
Try this if you don't want to use the UDF function.
SELECT COLUMN1, TRY_CONVERT(xml, COLUMN2).value('.', 'nvarchar(max)') as COL2, COLUMN3
FROM DBO.TABLENAME
This is v. easy, have been doing work on this for the past few weeks.
You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.
Open the terminal, and run this command:
java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg
That should output a JPEG of the SVG file. Really easy. You can even just place it in a loop and convert loads of SVGs,
import os
svgs = ('test1.svg', 'test2.svg', 'etc.svg')
for svg in svgs:
os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg')
I suggest you use curses.h or ncurses.h these implement keyboard management routines including getch(). You have several options to change the behavior of getch (i.e. wait for keypress or not).
Transaction Isolation and Transaction Propagation although related but are clearly two very different concepts. In both cases defaults are customized at client boundary component either by using Declarative transaction management or Programmatic transaction management. Details of each isolation levels and propagation attributes can be found in reference links below.
For given two or more running transactions/connections to a database, how and when are changes made by queries in one transaction impact/visible to the queries in a different transaction. It also related to what kind of database record locking will be used to isolate changes in this transaction from other transactions and vice versa. This is typically implemented by database/resource that is participating in transaction.
.
In an enterprise application for any given request/processing there are many components that are involved to get the job done. Some of this components mark the boundaries (start/end) of a transaction that will be used in respective component and it's sub components. For this transactional boundary of components, Transaction Propogation specifies if respective component will or will not participate in transaction and what happens if calling component already has or does not have a transaction already created/started. This is same as Java EE Transaction Attributes. This is typically implemented by the client transaction/connection manager.
Reference:
Maybe you can do something with
get-process -includeusername
Have you tried height: auto;
on your .container
div?
Here is a fiddle, if you change img height, container height will adjust to it.
EDIT
So if you "can't" change the inline min-height
, you can overwrite the inline style with an !important
parameter. It's not the cleanest way, but it solves your problem.
add to your .container
class this line
min-height:0px !important;
I've updated my fiddle to give you an example.
Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.
Use ffmpeglib to connect to the stream.
These functions may be useful. But take a look in the docs
av_open_input_stream(...);
av_find_stream_info(...);
avcodec_find_decoder(...);
avcodec_open(...);
avcodec_alloc_frame(...);
You would need a little algo to get a complete frame, which is available here
http://www.dranger.com/ffmpeg/tutorial01.html
Once you get a frame you could copy the video data (for each plane if needed) into a IplImage which is an OpenCV image object.
You can create an IplImage using something like...
IplImage *p_gray_image = cvCreateImage(size, IPL_DEPTH_8U, 1);
Once you have an IplImage, you could perform all sorts of image operations available in the OpenCV lib
To create HTML table using JSON, we will use ngRepeat
directive of AngularJS.
Example
HTML
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table border="1">
<tr ng-repeat="x in names">
<td>{{x.Name}}</td>
<td>{{x.City}}</td>
<td>{{x.Country}}</td></tr>
</table>
</div>
</body>
</html>
JavaScript
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
$scope.names = [
{ "Name" : "Max Joe", "City" : "Lulea", "Country" : "Sweden" },
{ "Name" : "Manish", "City" : "Delhi", "Country" : "India" },
{ "Name" : "Koniglich", "City" : "Barcelona", "Country" : "Spain" },
{ "Name" : "Wolski", "City" : "Arhus", "Country" : "Denmark" }
];
});
In above example I have created table from json. I have taken reference from http://www.tutsway.com/create-html-table-using-json-in-angular-js.php
I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);
$http.jsonp(url, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});
You can cheat a little with OPENROWSET :
SELECT ...fieldlist...
FROM OPENROWSET('SQLNCLI', 'connection string', 'name of sp')
WHERE ...
This would still run the entire SP every time, of course.
The JDK installation instructions explain exactly how to set the PATH
, for different versions of Windows.
Normally you should not set the CLASSPATH
environment variable. If you leave it unset, Java will look in the current directory to find classes. You can use the -cp
or -classpath
command line switch with java
or javac
.
I tried all the stuff I found on the net (npm cache clear
and rm -rf ~/.npm
), but nothing seems to work. What solved the issue was updating node (and npm) to the latest version. Try that.
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
Quoting from the Conda blog:
Having been involved in the python world for so long, we are all aware of pip, easy_install, and virtualenv, but these tools did not meet all of our specific requirements. The main problem is that they are focused around Python, neglecting non-Python library dependencies, such as HDF5, MKL, LLVM, etc., which do not have a setup.py in their source code and also do not install files into Python’s site-packages directory.
So Conda is a packaging tool and installer that aims to do more than what pip
does; handle library dependencies outside of the Python packages as well as the Python packages themselves. Conda also creates a virtual environment, like virtualenv
does.
As such, Conda should be compared to Buildout perhaps, another tool that lets you handle both Python and non-Python installation tasks.
Because Conda introduces a new packaging format, you cannot use pip
and Conda interchangeably; pip
cannot install the Conda package format. You can use the two tools side by side (by installing pip
with conda install pip
) but they do not interoperate either.
Since writing this answer, Anaconda has published a new page on Understanding Conda and Pip, which echoes this as well:
This highlights a key difference between conda and pip. Pip installs Python packages whereas conda installs packages which may contain software written in any language. For example, before using pip, a Python interpreter must be installed via a system package manager or by downloading and running an installer. Conda on the other hand can install Python packages as well as the Python interpreter directly.
and further on
Occasionally a package is needed which is not available as a conda package but is available on PyPI and can be installed with pip. In these cases, it makes sense to try to use both conda and pip.
I face same issue with sts 3.8.4, so I tried different settings but not luck, I reinstall jdk again n tried but same problem. Finally I downloaded sts 3.8.2 n it runs with out any issue. Using windows 8, 64 bit os. thanks
If you're trying this with GitHub, you can do this with your SSH entered:
git clone https://[email protected]/username/repository
I found this to be small and complete https://github.com/auth0/java-jwt
Per this comment (and I checked that this is true), rado's answer is very close but leaves git in a detached head state. Instead, remove HEAD
and use this to remove <commit-id>
from the branch you're on:
git rebase --onto <commit-id>^ <commit-id>
@AHegde - To get the tab delimited output use separator sep='\t'.
For df.to_csv:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')
For np.savetxt:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')
I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/
var _rmod = _rmod || {}; //require module namespace
_rmod.on_ready_fn_stack = [];
_rmod.libpath = '';
_rmod.imported = {};
_rmod.loading = {
scripts: {},
length: 0
};
_rmod.findScriptPath = function(script_name) {
var script_elems = document.getElementsByTagName('script');
for (var i = 0; i < script_elems.length; i++) {
if (script_elems[i].src.endsWith(script_name)) {
var href = window.location.href;
href = href.substring(0, href.lastIndexOf('/'));
var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);
return url.substring(href.length+1, url.length);
}
}
return '';
};
_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library
_rmod.injectScript = function(script_name, uri, callback, prepare) {
if(!prepare)
prepare(script_name, uri);
var script_elem = document.createElement('script');
script_elem.type = 'text/javascript';
script_elem.title = script_name;
script_elem.src = uri;
script_elem.async = true;
script_elem.defer = false;
if(!callback)
script_elem.onload = function() {
callback(script_name, uri);
};
document.getElementsByTagName('head')[0].appendChild(script_elem);
};
_rmod.requirePrepare = function(script_name, uri) {
_rmod.loading.scripts[script_name] = uri;
_rmod.loading.length++;
};
_rmod.requireCallback = function(script_name, uri) {
_rmod.loading.length--;
delete _rmod.loading.scripts[script_name];
_rmod.imported[script_name] = uri;
if(_rmod.loading.length == 0)
_rmod.onReady();
};
_rmod.onReady = function() {
if (!_rmod.LOADED) {
for (var i = 0; i < _rmod.on_ready_fn_stack.length; i++){
_rmod.on_ready_fn_stack[i]();
});
_rmod.LOADED = true;
}
};
//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.
var require = function(script_name) {
var np = script_name.split('.');
if (np[np.length-1] === '*') {
np.pop();
np.push('_all');
}
script_name = np.join('.');
var uri = _rmod.libpath + np.join('/')+'.js';
if (!_rmod.loading.scripts.hasOwnProperty(script_name)
&& !_rmod.imported.hasOwnProperty(script_name)) {
_rmod.injectScript(script_name, uri,
_rmod.requireCallback,
_rmod.requirePrepare);
}
};
var ready = function(fn) {
_rmod.on_ready_fn_stack.push(fn);
};
// ----- USAGE -----
require('ivar.util.array');
require('ivar.util.string');
require('ivar.net.*');
ready(function(){
//do something when required scripts are loaded
});
Regular expression is the most effective way of checking for a domain validation. If you're dead set on not using a Regular Expression (which IMO is stupid), then you could split each part of a domain:
You would then have to check each character in some sort of a loop to see that it matches a valid domain.
Like I said, it's much more effective to use a regular expression.
$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected');
Check out working code here http://jsbin.com/ipewe/edit
The example shows that the people in the project you joined don't understand anonymous namespaces :)
namespace {
const int SIZE_OF_ARRAY_X;
const int SIZE_OF_ARRAY_Y;
These don't need to be in an anonymous namespace, since const
object already have static linkage and therefore can't possibly conflict with identifiers of the same name in another translation unit.
bool getState(userType*,otherUserType*);
}
And this is actually a pessimisation: getState()
has external linkage. It is usually better to prefer static linkage, as that doesn't pollute the symbol table. It is better to write
static bool getState(/*...*/);
here. I fell into the same trap (there's wording in the standard that suggest that file-statics are somehow deprecated in favour of anonymous namespaces), but working in a large C++ project like KDE, you get lots of people that turn your head the right way around again :)
In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:
so:
import sys
and when finished:
sys.exit()
int (t.strftime("%s"))
also works
Whether null char is allowed or not really depends on base64 codec in question. Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/
But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.
One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.