try
window.frameElement.ownerDocument.domain
I have this function for this case ..
Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean
c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
Select Case Mid(c, x, 1)
Case ":": bNum = True
Case " ": Exit For
Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
End Select
Next
GetValue = val(nRet)
End Function
To fill cell BC .. (assumed that you check cell A1)
Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")
Spring dependency inject help you to remove coupling from your classes. Instead of creating object like this:
UserService userService = new UserServiceImpl();
You will be using this after introducing DI:
@Autowired
private UserService userService;
For achieving this you need to create a bean of your service in your ServiceConfiguration
file. After that you need to import that ServiceConfiguration
class to your WebApplicationConfiguration
class so that you can autowire that bean into your Controller like this:
public class AccController {
@Autowired
private UserService userService;
}
You can find a java configuration based POC here example.
The following program calculates nCr
in an efficient manner (compared to calculating factorials etc.)
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
As of Python 3.8, binomial coefficients are available in the standard library as math.comb
:
>>> from math import comb
>>> comb(10,3)
120
For some applications may be better:
string.Join(",", arr1) == string.Join(",", arr2)
clear()
will go through the underlying Array and set each entry to null;
removeAll(collection)
will go through the ArrayList checking for collection and remove(Object)
it if it exists.
I would imagine that clear()
is way faster then removeAll because it's not comparing, etc.
I know the question specified dplyr
. But, since others already posted solutions using other packages, I decided to have a go using other packages too:
Base package:
df <- df[with(df, order(id, stopSequence, stopId)), ]
merge(df[!duplicated(df$id), ],
df[!duplicated(df$id, fromLast = TRUE), ],
all = TRUE)
data.table:
df <- setDT(df)
df[order(id, stopSequence)][, .SD[c(1,.N)], by=id]
sqldf:
library(sqldf)
min <- sqldf("SELECT id, stopId, min(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId")
max <- sqldf("SELECT id, stopId, max(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId")
sqldf("SELECT * FROM min
UNION
SELECT * FROM max")
In one query:
sqldf("SELECT *
FROM (SELECT id, stopId, min(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId)
UNION
SELECT *
FROM (SELECT id, stopId, max(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId)")
Output:
id stopId StopSequence
1 1 a 1
2 1 c 3
3 2 b 1
4 2 c 4
5 3 a 3
6 3 b 1
Please try with just giving the path from where you want to pull the files I just got the files from sdcard like
adb pull sdcard/
do NOT give * like to broaden the search or to filter out. ex: adb pull sdcard/*.txt --> this is invalid.
just give adb pull sdcard/
This tutorial is a just step by step for installing Android SDK (Software Development Kit) assuming the user is starting from scratch.
There are just a couple of prerequisites to note:
I recommed using the offline SDK installer for installing the essential tools namely SDK and AVD manager: The last version of he installer is found here: SDK Installer_r24.4.1 (for windows), SDK Installer_r24.4.1 (for linux) or SDK Installer_r24.4.1 (for macos)
For this guide I was using windows:
Here is the workthrough:
%USERPROFILE%\android-sdk
):Now we're in business...
Note: I recommend downloading x86 images as they're much faster tham arm counterparts, also get intel HAXM (hardware accelerated execution manager) driver to significantly increase your emulator speed
All set, now you just need to create and configure an Android virtual device matching your target Android version and tweak desired settings.
To do this click on the Tools tab in SDK manager and select manage AVDs, then in the following window click Create you'll see a similar screen as below:
Most of the answers here are using inbuilt functions-
Here is my answer if you want to know the whole logic behind this ques:
import java.util.*;
public class SumOfArray {
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = inp.nextInt();
}
System.out.println("The sum of the array is :" + sum(arr));
}
static int sum(int[] arr){
int sum = 0;
for (int a = 0; a < arr.length; a++){
sum = sum + arr[a];
}
return sum;
}
}
Of course it is an old post but just for people how will find it through search engine.
Another solution is to run it like this for IE9 and later
iexplore.exe" -noframemerging http://google.com
iexplore.exe" -noframemerging http://gmail.com
-noframemerging means run IE independently. For example it you want to run 2 browser and login as different username it will not work if you just run 2 IE. but with -noframemerging it will work. -noframemerging works for IE9 and later, for early versions like IE8 it is -nomerge
usually I create 1 but file like this run_ie.bat
"c:\Program Files (x86)\Internet Explorer\iexplore.exe" -noframemerging %1
and I create another bat file like this run_2_ie.bat
start run_ie.bat http://google.com
start run_ie.bat http://yahoo.com
One of the easiest ways to check if the area formed by the vertices of triangle (x1,y1),(x2,y2),(x3,y3) is positive or not.
Area can by calculated by the formula:
1/2 [x1(y2–y3) + x2(y3–y1) + x3(y1–y2)]
or python code can be written as:
def triangleornot(p1,p2,p3):
return (1/ 2) [p1[0](p2[1]–p3[1]) + p2[0] (p3[1]–p1[1]) + p3[0] (p1[0]–p2[0])]
Pretty sure this solves what you're looking for:
HTML:
<table>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
</table>
Javascript (using jQuery):
$(document).ready(function(){
$('.editbtn').click(function(){
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
Edit:
Apparently I should have looked at your sample code first ;)
You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.
By using classes, you can apply the same logic to multiple elements without any conflicts.
If you change the classes and load the content within the same function you should be fine.
$(document).ready(function(){
$('.nav li').click(function(event){
//remove all pre-existing active classes
$('.active').removeClass('active');
//add the active class to the link we clicked
$(this).addClass('active');
//Load the content
//e.g.
//load the page that the link was pointing to
//$('#content').load($(this).find(a).attr('href'));
event.preventDefault();
});
});
In version 1.28 of Visual Studio Code "files.exclude"
must be placed within a settings
node.
Resulting in a workspace file that looks like:
{
"settings": {
"files.exclude": {
"**/node_modules": true
}
}
}
First, to address your first inquiry:
When you see this in .h file:
#ifndef FILE_H
#define FILE_H
/* ... Declarations etc here ... */
#endif
This is a preprocessor technique of preventing a header file from being included multiple times, which can be problematic for various reasons. During compilation of your project, each .cpp file (usually) is compiled. In simple terms, this means the compiler will take your .cpp file, open any files #included
by it, concatenate them all into one massive text file, and then perform syntax analysis and finally it will convert it to some intermediate code, optimize/perform other tasks, and finally generate the assembly output for the target architecture. Because of this, if a file is #included
multiple times under one .cpp file, the compiler will append its file contents twice, so if there are definitions within that file, you will get a compiler error telling you that you redefined a variable. When the file is processed by the preprocessor step in the compilation process, the first time its contents are reached the first two lines will check if FILE_H
has been defined for the preprocessor. If not, it will define FILE_H
and continue processing the code between it and the #endif
directive. The next time that file's contents are seen by the preprocessor, the check against FILE_H
will be false, so it will immediately scan down to the #endif
and continue after it. This prevents redefinition errors.
And to address your second concern:
In C++ programming as a general practice we separate development into two file types. One is with an extension of .h and we call this a "header file." They usually provide a declaration of functions, classes, structs, global variables, typedefs, preprocessing macros and definitions, etc. Basically, they just provide you with information about your code. Then we have the .cpp extension which we call a "code file." This will provide definitions for those functions, class members, any struct members that need definitions, global variables, etc. So the .h file declares code, and the .cpp file implements that declaration. For this reason, we generally during compilation compile each .cpp file into an object and then link those objects (because you almost never see one .cpp file include another .cpp file).
How these externals are resolved is a job for the linker. When your compiler processes main.cpp, it gets declarations for the code in class.cpp by including class.h. It only needs to know what these functions or variables look like (which is what a declaration gives you). So it compiles your main.cpp file into some object file (call it main.obj). Similarly, class.cpp is compiled into a class.obj file. To produce the final executable, a linker is invoked to link those two object files together. For any unresolved external variables or functions, the compiler will place a stub where the access happens. The linker will then take this stub and look for the code or variable in another listed object file, and if it's found, it combines the code from the two object files into an output file and replaces the stub with the final location of the function or variable. This way, your code in main.cpp can call functions and use variables in class.cpp IF AND ONLY IF THEY ARE DECLARED IN class.h.
I hope this was helpful.
You can initialize a Dictionary
(and other collections) inline. Each member is contained with braces:
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
{ 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
{ 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
{ 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};
See Microsoft Docs for details.
This code works. I have a date input field that has been set to read only which forces the user to select from the calendar.
for a start date:
var updateInput = "var input = document.getElementById('startDateInput');" +
"input.value = '18-Jan-2016';" +
"angular.element(input).scope().$apply(function(s) { s.$parent..searchForm[input.name].$setViewValue(input.value);})";
browser.executeScript(updateInput);
for an end date:
var updateInput = "var input = document.getElementById('endDateInput');" +
"input.value = '22-Jan-2016';" +
"angular.element(input).scope().$apply(function(s) { s.$parent.searchForm[input.name].$setViewValue(input.value);})";
browser.executeScript(updateInput);
For me, it was having display: none;
#spinner-success-text {
display: none;
transition: all 1s ease-in;
}
#spinner-success-text.show {
display: block;
}
Removing it, and using opacity
instead, fixed the issue.
#spinner-success-text {
opacity: 0;
transition: all 1s ease-in;
}
#spinner-success-text.show {
opacity: 1;
}
I do all this as normal user (not root)
Grab infos from dmesg
Using dmesg
is one of the 1st things to do for inquiring current state of system:
dmesg | sed '/eth.*Link is/h;${x;p};d'
could answer something like:
[936536.904154] e1000e: eth0 NIC Link is Down
or
[936555.596870] e1000e: eth0 NIC Link is Up 100 Mbps Full Duplex, Flow Control: Rx/Tx
depending on state, message could vary depending on hardware and drivers used.
Nota: this could by written dmesg|grep eth.*Link.is|tail -n1
but I prefer using sed
.
dmesg | sed '/eth.*Link is/h;${x;s/^.*Link is //;p};d'
Up 100 Mbps Full Duplex, Flow Control: Rx/Tx
dmesg | sed '/eth.*Link is/h;${x;s/^.*Link is //;p};d'
Down
Test around /sys
pseudo filesystem
Reading or writting under /sys
could break your system, especially if run as root! You've been warned ;-)
This is a pooling method, not a real event tracking.
cd /tmp
grep -H . /sys/class/net/eth0/* 2>/dev/null >ethstate
while ! read -t 1;do
grep -H . /sys/class/net/eth0/* 2>/dev/null |
diff -u ethstate - |
tee >(patch -p0) |
grep ^+
done
Could render something like (once you've unplugged and plugged back, depending ):
+++ - 2016-11-18 14:18:29.577094838 +0100
+/sys/class/net/eth0/carrier:0
+/sys/class/net/eth0/carrier_changes:9
+/sys/class/net/eth0/duplex:unknown
+/sys/class/net/eth0/operstate:down
+/sys/class/net/eth0/speed:-1
+++ - 2016-11-18 14:18:48.771581903 +0100
+/sys/class/net/eth0/carrier:1
+/sys/class/net/eth0/carrier_changes:10
+/sys/class/net/eth0/duplex:full
+/sys/class/net/eth0/operstate:up
+/sys/class/net/eth0/speed:100
(Hit Enter to exit loop)
Nota: This require patch
to be installed.
In fine, there must already be something about this...
Depending on Linux Installation, you could add if-up
and if-down
scripts to be able to react to this kind of events.
On Debian based (like Ubuntu), you could store your scripts into
/etc/network/if-down.d
/etc/network/if-post-down.d
/etc/network/if-pre-up.d
/etc/network/if-up.d
see man interfaces
for more infos.
In my case every time the Fragment entered onCreateView
I was restarting values so handle null or empty values like:
if (var == null) {
var = new Something();
}
if (list.isEmpty()) {
list = new ArrayList<MyItem>();
}
if (myAdapter == null) {
myAdapter = new CustomAdapter();
recyclerView.setAdapter(myAdapter);
}
// etc...
Fragment class could enter onCreateView
every time we change and get back to the view from the UI at runtime.
<div style="cursor:pointer" onclick="document.location='http://www.google.com'">Content Goes Here</div>
They are:
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0'); // for infinite time of execution
Place this at the top of your PHP script and let your script loose!
Taken from Increase PHP Script Execution Time Limit Using ini_set()
When I want to see a snapshot of a table(s), and/or view (in a read-only way)
You could also use operator.concat()
like this:
>>> from operator import concat
>>> a = ['a', 'b', 'c', 'd']
>>> reduce(concat, a)
'abcd'
If you're using Python 3 you need to prepend:
>>> from functools import reduce
since the builtin reduce()
has been removed from Python 3 and now lives in functools.reduce()
.
you to restart services PostgreSQL from task manager click ctrl+alt+delete then chose services the postgresql-[version] chose the option to run automatically then start and apply ->ok
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).
This worked for me (win10), place before you import keras:
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
You just have to write sudo
instead of su
.
Then just copy the PHP file to the var/www/ directory
.
Then go to the browser, and write local host/test.php
or whatever the .php
filename is.
This might help. It contains many examples which will be useful in understanding.
http://www.w3schools.com/bootstrap/bootstrap_ref_comp_glyphs.asp
I had a same issue on ubuntu 14.04 Here is a solution
sudo service docker start
or you can list images
docker images
Apple simply recommends declaring an isX
getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:
@property (nonatomic, assign) BOOL working;
[self setWorking:YES]; // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;
Or
@property (nonatomic, assign, getter=isWorking) BOOL working;
[self setWorking:YES]; // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above
If you want your CSS to be copied into the output without being processed, you can use the (inline)
directive. e.g.,
@import (inline) '../timepicker/jquery.ui.timepicker.css';
rpm -qa openssl
yum clean all && yum update "openssl*"
lsof -n | grep ssl | grep DEL
cd /usr/src
wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz
tar -zxf openssl-1.0.1g.tar.gz
cd openssl-1.0.1g
./config --prefix=/usr --openssldir=/usr/local/openssl shared
./config
make
make test
make install
cd /usr/src
rm -rf openssl-1.0.1g.tar.gz
rm -rf openssl-1.0.1g
and
openssl version
moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.
function momentTest() {
var varDate = "2018-01-19 18:05:01.423";
var myDate = moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
var todayDate = moment().format("DD-MM-YYYY");
var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");
var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");
alert(todayDate);
if (myDate == todayDate) {
alert("date is today");
} else if (myDate == yesterdayDate) {
alert("date is yesterday");
} else if (myDate == tomorrowDate) {
alert("date is tomorrow");
} else {
alert("It's not today, tomorrow or yesterday!");
}
}
Using the accepted answer you have to access each record by using Customers[i].customer
, and you need an extra CustomerJson
class, which is a little annoying. If you don't want to do that, you can use the following:
public class CustomerList
{
[JsonConverter(typeof(MyListConverter))]
public List<Customer> customer { get; set; }
}
Note that I'm using a List<>
, not an Array. Now create the following class:
class MyListConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Values())
{
var childToken = child.Children().First();
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(childToken.CreateReader(), newObject);
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
Working with the answers provided by Marco Lazzeri and Terre Porter (vote them up if this answer is useful), I came up with a slightly different solution that preserves the selected value (probably doesn't preserve event handlers or attached data, though) using jQuery.
// save the selected value for sorting
var v = jQuery("#id").val();
// sort the options and select the value that was saved
j$("#id")
.html(j$("#id option").sort(function(a,b){
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;}))
.val(v);
I know this post is a bit old, but thought I would add the functions I use that take into account any filters and any <![CDATA[some stuff]]>
content you want to safely exclude.
Simply add to your functions.php file and use anywhere you would like, such as:
content(53);
or
excerpt(27);
Enjoy!
//limit excerpt
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'...';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
return $excerpt;
}
//limit content
function content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('/\[.+\]/','', $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
If you are testing simple new Thread(runnable).run() You can mock Thread to run the runnable sequentially
For instance, if the code of the tested object invokes a new thread like this
Class TestedClass {
public void doAsychOp() {
new Thread(new myRunnable()).start();
}
}
Then mocking new Threads and run the runnable argument sequentially can help
@Mock
private Thread threadMock;
@Test
public void myTest() throws Exception {
PowerMockito.mockStatic(Thread.class);
//when new thread is created execute runnable immediately
PowerMockito.whenNew(Thread.class).withAnyArguments().then(new Answer<Thread>() {
@Override
public Thread answer(InvocationOnMock invocation) throws Throwable {
// immediately run the runnable
Runnable runnable = invocation.getArgumentAt(0, Runnable.class);
if(runnable != null) {
runnable.run();
}
return threadMock;//return a mock so Thread.start() will do nothing
}
});
TestedClass testcls = new TestedClass()
testcls.doAsychOp(); //will invoke myRunnable.run in current thread
//.... check expected
}
Suppose you have void method that prints many objects;
public static void print( Object... values){
for(Object c : values){
System.out.println(c);
}
}
Above example I used vararge as an argument that accepts values from 0 to N.
From comments: What if 2 strings and 5 integers ??
Answer:
print("string1","string2",1,2,3,4,5);
Be aware that you're currently testing for object identity (is
only returns True
if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==
). If you are doing this on purpose, then you could rewrite your code as
some_dict = {key: value for key, value in some_dict.items()
if value is not value_to_remove}
But this may not do what you want:
>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}
So you probably want !=
instead of is not
.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
This is my case: it's run Environment: AspNet Core 2.1 Controller:
public class MyController
{
// ...
[HttpPost]
public ViewResult Search([FromForm]MySearchModel searchModel)
{
// ...
return View("Index", viewmodel);
}
}
View:
<form method="post" asp-controller="MyController" asp-action="Search">
<input name="MySearchModelProperty" id="MySearchModelProperty" />
<input type="submit" value="Search" />
</form>
Make sure when executing Michael Krelin's solution you do the following
cat <your_public_key_file> >> ~/.ssh/authorized_keys
Note the double >
without the double >
the existing contents of authorized_keys will be over-written (nuked!) and that may not be desirable
$.ajax(), $.get(), $.post(), $.load()
functions of jQuery internally send XML HTTP
request.
among these the load()
is only dedicated for a particular DOM Element
. See jQuery Ajax Doc. A details Q.A. on these are Here .
@crobar, you are right that there is a dearth of multi-file examples, so I decided to share the following in the hopes that it helps others:
::::::::::::::
main.cpp
::::::::::::::
#include <iostream>
#include "UseSomething.h"
#include "Something.h"
int main()
{
UseSomething y;
std::cout << y.getValue() << '\n';
}
::::::::::::::
Something.h
::::::::::::::
#ifndef SOMETHING_H_
#define SOMETHING_H_
class Something
{
private:
static int s_value;
public:
static int getValue() { return s_value; } // static member function
};
#endif
::::::::::::::
Something.cpp
::::::::::::::
#include "Something.h"
int Something::s_value = 1; // initializer
::::::::::::::
UseSomething.h
::::::::::::::
#ifndef USESOMETHING_H_
#define USESOMETHING_H_
class UseSomething
{
public:
int getValue();
};
#endif
::::::::::::::
UseSomething.cpp
::::::::::::::
#include "UseSomething.h"
#include "Something.h"
int UseSomething::getValue()
{
return(Something::getValue());
}
I found it cleaner and more reusable to extend AlertDialog.Builder
to create a custom dialog class. This is for a dialog that asks the user to input a phone number. A preset phone number can also be supplied by calling setNumber()
before calling show()
.
InputSenderDialog.java
public class InputSenderDialog extends AlertDialog.Builder {
public interface InputSenderDialogListener{
public abstract void onOK(String number);
public abstract void onCancel(String number);
}
private EditText mNumberEdit;
public InputSenderDialog(Activity activity, final InputSenderDialogListener listener) {
super( new ContextThemeWrapper(activity, R.style.AppTheme) );
@SuppressLint("InflateParams") // It's OK to use NULL in an AlertDialog it seems...
View dialogLayout = LayoutInflater.from(activity).inflate(R.layout.dialog_input_sender_number, null);
setView(dialogLayout);
mNumberEdit = dialogLayout.findViewById(R.id.numberEdit);
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if( listener != null )
listener.onOK(String.valueOf(mNumberEdit.getText()));
}
});
setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if( listener != null )
listener.onCancel(String.valueOf(mNumberEdit.getText()));
}
});
}
public InputSenderDialog setNumber(String number){
mNumberEdit.setText( number );
return this;
}
@Override
public AlertDialog show() {
AlertDialog dialog = super.show();
Window window = dialog.getWindow();
if( window != null )
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return dialog;
}
}
dialog_input_sender_number.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="10dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:paddingBottom="20dp"
android:text="Input phone number"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/numberLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/title"
app:layout_constraintLeft_toLeftOf="parent"
android:text="Phone number" />
<EditText
android:id="@+id/numberEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/numberLabel"
app:layout_constraintLeft_toLeftOf="parent"
android:inputType="phone" >
<requestFocus />
</EditText>
</android.support.constraint.ConstraintLayout>
Usage:
new InputSenderDialog(getActivity(), new InputSenderDialog.InputSenderDialogListener() {
@Override
public void onOK(final String number) {
Log.d(TAG, "The user tapped OK, number is "+number);
}
@Override
public void onCancel(String number) {
Log.d(TAG, "The user tapped Cancel, number is "+number);
}
}).setNumber(someNumberVariable).show();
java.util.logging
keeps you from having to tote one more jar file around with your application, and it works well with a good Formatter.
In general, at the top of every class, you should have:
private static final Logger LOGGER = Logger.getLogger( ClassName.class.getName() );
Then, you can just use various facilities of the Logger class.
Use Level.FINE
for anything that is debugging at the top level of execution flow:
LOGGER.log( Level.FINE, "processing {0} entries in loop", list.size() );
Use Level.FINER
/ Level.FINEST
inside of loops and in places where you may not always need to see that much detail when debugging basic flow issues:
LOGGER.log( Level.FINER, "processing[{0}]: {1}", new Object[]{ i, list.get(i) } );
Use the parameterized versions of the logging facilities to keep from generating tons of String concatenation garbage that GC will have to keep up with. Object[]
as above is cheap, on the stack allocation usually.
With exception handling, always log the complete exception details:
try {
...something that can throw an ignorable exception
} catch( Exception ex ) {
LOGGER.log( Level.SEVERE, ex.toString(), ex );
}
I always pass ex.toString()
as the message here, because then when I "grep -n
" for "Exception
" in log files, I can see the message too. Otherwise, it is going to be on the next line of output generated by the stack dump, and you have to have a more advanced RegEx to match that line too, which often gets you more output than you need to look through.
Also, we use them for managing inheritance.
class Super( object ):
def __init__( self, this, that ):
self.this = this
self.that = that
class Sub( Super ):
def __init__( self, myStuff, *args, **kw ):
super( Sub, self ).__init__( *args, **kw )
self.myStuff= myStuff
x= Super( 2.7, 3.1 )
y= Sub( "green", 7, 6 )
This way Sub doesn't really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.
Another way of adding schema dynamically or if you want to change it to something else
DECLARE @schema AS VARCHAR(256) = 'dbo.'
--User can also use SELECT SCHEMA_NAME() to get the default schema name
DECLARE @ID INT
declare @SQL nvarchar(max) = 'EXEC ' + @schema +'spSelectCaseBookingDetails @BookingID = ' + CAST(@ID AS NVARCHAR(10))
No need to cast @ID if it is nvarchar or varchar
execute (@SQL)
The simplest way would be to use https://github.com/mitchellh/mapstructure
import "github.com/mitchellh/mapstructure"
mapstructure.Decode(myData, &result)
If you want to do it yourself, you could do something like this:
http://play.golang.org/p/tN8mxT_V9h
func SetField(obj interface{}, name string, value interface{}) error {
structValue := reflect.ValueOf(obj).Elem()
structFieldValue := structValue.FieldByName(name)
if !structFieldValue.IsValid() {
return fmt.Errorf("No such field: %s in obj", name)
}
if !structFieldValue.CanSet() {
return fmt.Errorf("Cannot set %s field value", name)
}
structFieldType := structFieldValue.Type()
val := reflect.ValueOf(value)
if structFieldType != val.Type() {
return errors.New("Provided value type didn't match obj field type")
}
structFieldValue.Set(val)
return nil
}
type MyStruct struct {
Name string
Age int64
}
func (s *MyStruct) FillStruct(m map[string]interface{}) error {
for k, v := range m {
err := SetField(s, k, v)
if err != nil {
return err
}
}
return nil
}
func main() {
myData := make(map[string]interface{})
myData["Name"] = "Tony"
myData["Age"] = int64(23)
result := &MyStruct{}
err := result.FillStruct(myData)
if err != nil {
fmt.Println(err)
}
fmt.Println(result)
}
// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;
int main()
{
pt::ptime current_date_microseconds = pt::microsec_clock::local_time();
long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();
pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);
pt::ptime current_date_milliseconds(current_date_microseconds.date(),
current_time_milliseconds);
std::cout << "Microseconds: " << current_date_microseconds
<< " Milliseconds: " << current_date_milliseconds << std::endl;
// Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}
I wanted an utility class which is not managed by spring, so no spring annotations like @Component
, @Configuration
etc. But I wanted the class to read from application.properties
I managed to get it working by getting the class to be aware of the Spring Context, hence is aware of Environment
, and hence environment.getProperty()
works as expected.
To be explicit, I have:
application.properties
mypath=somestring
Utils.java
import org.springframework.core.env.Environment;
// No spring annotations here
public class Utils {
public String execute(String cmd) {
// Making the class Spring context aware
ApplicationContextProvider appContext = new ApplicationContextProvider();
Environment env = appContext.getApplicationContext().getEnvironment();
// env.getProperty() works!!!
System.out.println(env.getProperty("mypath"))
}
}
ApplicationContextProvider.java (see Spring get current ApplicationContext)
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext CONTEXT;
public ApplicationContext getApplicationContext() {
return CONTEXT;
}
public void setApplicationContext(ApplicationContext context) throws BeansException {
CONTEXT = context;
}
public static Object getBean(String beanName) {
return CONTEXT.getBean(beanName);
}
}
You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?
If you're trying to add a psycopg2
dependency in your virtual environment that will allow your python project to connect to your docker or kubernetes pod that's running postgresql separately, on your Mac and are not really interested in installing postgresql on your Mac just so that you can get pg_config, here's what you do instead:
Install psycopg2_binary
as suggested in the error output from the pipenv install and everything will work out just fine.
Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506
I can't get that constructor to work either. This however seems to work:
# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)
You can also pass an integer in the constructor to set an initial capacity.
What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?
Edit:
It seems that you can use the array constructor like this:
$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.
To install specific version of laravel try this & simply command on terminal
composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}
Hope this will help a little more
import sys
varExcepHandling, varExcepHandlingZer = 2, 0
try:
print(varExcepHandling/varExcepHandlingZer)
except Exception as ex:
print(sys.exc_info())
'sys.exc_info()
' will return a tuple, if you only want the exception class name use 'sys.exc_info()[0]
'
Note:- if you want to see all the exception classes just write dir(__builtin__)
Facebook uses og:tags
and the Open Graph Protocol to decipher what information to display when previewing your URL in a share dialog
or in a news feed on facebook.
The og:tags
contain information such as :
Here is an example ( taken from the facebook documentation ) of some og:tags
<meta property="og:title" content="The Rock"/>
<meta property="og:type" content="movie"/>
<meta property="og:url" content="http://www.imdb.com/title/tt0117500/"/>
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
Once you have implemented the correct markup of the og:tags
and set their values, you can test how facebook will view your URL by using the Facebook Debugger. The debugger tool will also highlight any problems it finds with the og:tags
on the page or lack there-of.
One thing to keep in mind is that facebook does do some caching with regard to this information, so in order for changes to take effect your page will have t be scraped as stated in the documentation :
Editing Meta Tags
You can update the attributes of your page by updating your page's tags. Note that og:title and og:type are only editable initially - after your page receives 50 likes the title becomes fixed, and after your page receives 10,000 likes the type becomes fixed. These properties are fixed to avoid surprising users who have liked the page already. Changing the title or type tags after these limits are reached does nothing, your page retains the original title and type.
For the changes to be reflected on Facebook, you must force your page to be scraped. The page is scraped when an admin for the page clicks the Like button or when the URL is entered into the
Facebook URL LinterFacebook Debugger...
Use:
((Long) userService.getAttendanceList(currentUser)).intValue();
instead.
The .intValue()
method is defined in class Number
, which Long
extends.
Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:
str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');
The problem is that first code removes all the hyphens and then tries to replace them :) You should reverse the replace calls and also add hyphen to second replace regex. Like this:
str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');
For anyone stumbling across the same issue:
I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.
The poor mans compromise solution is to use a simplistic multi signature approach.
For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU
He or she give half the password to the application developer who then hard codes it into the java binary.
private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"
The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.
java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU
When the application starts it uses pass1 + pass2 and connects to the database.
This solution has many advantages with out the downfalls mentioned.
You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.
The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.
The source code can also be semi public as reading it and the password will not give you application access.
You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.
In angular.json
you can insert all css and js file in your template.
Other ways, you can use from Style.css in src folder for load stylesheets.
@import "../src/fonts/font-awesome/css/font-awesome.min.css";
@import "../src/css/bootstrap.min.css";
@import "../src/css/now-ui-kit.css";
@import "../src/css/plugins/owl.carousel.css";
@import "../src/css/plugins/owl.theme.default.min.css";
@import "../src/css/main.css";
Cleaning project, closing Eclipse, re-opening it and launching my project finally made my R.java to reappear... Hope it helps
I've tried a lot of things but finally, including uninstall with the automated tools. So, I've uninstalled manually scikit-learn.
sudo rm -R /home/ubuntu/.local/lib/python3.6/site-packages/sklearn
sudo rm -R /home/ubuntu/.local/lib/python3.6/site-packages/scikit_learn-0.20.0-py3.6.egg-info
And re-install using pip
sudo pip3.6 install -U scikit-learn
Hope that can help someone else!
It's better to use $(window).scroll()
rather than $('#Eframe').on("mousewheel")
$('#Eframe').on("mousewheel")
will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.
$(window).scroll(function(){
var scrollPos = $(document).scrollTop();
console.log(scrollPos);
});
If #Eframe
is an element with overflow:scroll
on it and you want it's scroll position. I think this should work (I haven't tested it though).
$('#Eframe').scroll(function(){
var scrollPos = $('#Eframe').scrollTop();
console.log(scrollPos);
});
If the place you're gonna paste have no problem with pasting a table formating (like the browser URL bar), I think the easiest way is this:
Sheets(1).Range("A1000").Value = string
Sheets(1).Range("A1000").Copy
MsgBox "Paste before closing this dialog."
Sheets(1).Range("A1000").Value = ""
The multiline flag tells regex to match the pattern to each line as opposed to the entire string for your purposes a wild card will suffice.
max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.
• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;
• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.
First Step you need to create a list instance through Arrays.asList();
String[] args = new String[]{"one","two","three"};
List<String> list = Arrays.asList(args);//it converts to immutable list
Then you need to pass 'list' instance to new ArrayList();
List<String> newList=new ArrayList<>(list);
template <typename T>
const T to(const string& sval)
{
T val;
stringstream ss;
ss << sval;
ss >> val;
if(ss.fail())
throw runtime_error((string)typeid(T).name() + " type wanted: " + sval);
return val;
}
And then you can use it like that:
double d = to<double>("4.3");
or
int i = to<int>("4123");
I used
diff -rqyl folder1 folder2 --exclude=node_modules
in my nodejs apps.
Your best bet is to throw
an Error
wrapping the value, which results in a rejected promise with an Error
wrapping the value:
} catch (error) {
throw new Error(400);
}
You can also just throw
the value, but then there's no stack trace information:
} catch (error) {
throw 400;
}
Alternately, return a rejected promise with an Error
wrapping the value, but it's not idiomatic:
} catch (error) {
return Promise.reject(new Error(400));
}
(Or just return Promise.reject(400);
, but again, then there's no context information.)
In your case, as you're using TypeScript
and foo
's return value is Promise<A>
, you'd use this:
return Promise.reject<A>(400 /*or Error*/ );
In an async
/await
situation, that last is probably a bit of a semantic mis-match, but it does work.
If you throw an Error
, that plays well with anything consuming your foo
's result with await
syntax:
try {
await foo();
} catch (error) {
// Here, `error` would be an `Error` (with stack trace, etc.).
// Whereas if you used `throw 400`, it would just be `400`.
}
It seems like react-native eject
is no more available. The only way I could find for recreating the ios folder was to generate it from scratch.
Take a backup of your ios folder
mv /path_to_your_old_project/ios /path_to_your_backup_dir/ios_backup
Navigate to a temporary directory and create a new project with the same name as your current project
react-native init project_name
mv project_name/ios /path_to_your_old_project/ios
Install the pod dependencies inside the ios folder within your project
cd /path_to_your_old_project/ios
pod install
For a time field, use:
import time
time.strftime('%Y-%m-%d %H:%M:%S')
I think strftime also applies to datetime.
If you want to easily know the screen density and size of an Android device, you can use this free app (no permission required): https://market.android.com/details?id=com.jotabout.screeninfo
I will add this information since I had a hard time figuring how to mock an async api call.
Here is what I did to mock an async call.
Here is the function I wanted to test
async def get_user_info(headers, payload):
return await httpx.AsyncClient().post(URI, json=payload, headers=headers)
You still need the MockResponse class
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
You add the MockResponseAsync class
class MockResponseAsync:
def __init__(self, json_data, status_code):
self.response = MockResponse(json_data, status_code)
async def getResponse(self):
return self.response
Here is the test. The important thing here is I create the response before since init function can't be async and the call to getResponse is async so it all checked out.
@pytest.mark.asyncio
@patch('httpx.AsyncClient')
async def test_get_user_info_valid(self, mock_post):
"""test_get_user_info_valid"""
# Given
token_bd = "abc"
username = "bob"
payload = {
'USERNAME': username,
'DBNAME': 'TEST'
}
headers = {
'Authorization': 'Bearer ' + token_bd,
'Content-Type': 'application/json'
}
async_response = MockResponseAsync("", 200)
mock_post.return_value.post.return_value = async_response.getResponse()
# When
await api_bd.get_user_info(headers, payload)
# Then
mock_post.return_value.post.assert_called_once_with(
URI, json=payload, headers=headers)
If you have a better way of doing that tell me but I think it's pretty clean like that.
This should work for every default repo:
git pull origin master
If your default branch is different than master
, you will need to specify the branch name:
git pull origin my_default_branch_name
You could use the {display: inline-flex;} this would produce this: inline-flex
You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.
If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:
-- dummy ITEM table as we don't know what the real ones looks like
create table item(
item_num number,
currency varchar2(9)
)
/
insert into item values(1,'GBP');
insert into item values(2,'AUD');
insert into item values(3,'GBP');
insert into item values(4,'AUD');
insert into item values(5,'CDN');
create package so_5165580 as
type exch_row is record(
exch_rt_eur number,
exch_rt_usd number);
type exch_tbl is table of exch_row index by varchar2(9);
exch_rt exch_tbl;
procedure show_items;
end so_5165580;
/
create package body so_5165580 as
procedure populate_rates is
rate exch_row;
begin
rate.exch_rt_eur := 0.614394;
rate.exch_rt_usd := 0.8494;
exch_rt('GBP') := rate;
rate.exch_rt_eur := 0.9817;
rate.exch_rt_usd := 1.3572;
exch_rt('AUD') := rate;
end;
procedure show_items is
cursor c0 is
select i.*
from item i;
begin
for r0 in c0 loop
if exch_rt.exists(r0.currency) then
dbms_output.put_line('Item ' || r0.item_num
|| ' Currency ' || r0.currency
|| ' EUR ' || exch_rt(r0.currency).exch_rt_eur
|| ' USD ' || exch_rt(r0.currency).exch_rt_usd);
else
dbms_output.put_line('Item ' || r0.item_num
|| ' Currency ' || r0.currency
|| ' ** no rates defined **');
end if;
end loop;
end;
begin
populate_rates;
end so_5165580;
/
So inside your loop, wherever you would have expected to use r0.exch_rt_eur
you instead use exch_rt(r0.currency).exch_rt_eur
, and the same for USD. Testing from an anonymous block:
begin
so_5165580.show_items;
end;
/
Item 1 Currency GBP EUR .614394 USD .8494
Item 2 Currency AUD EUR .9817 USD 1.3572
Item 3 Currency GBP EUR .614394 USD .8494
Item 4 Currency AUD EUR .9817 USD 1.3572
Item 5 Currency CDN ** no rates defined **
Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert
statement. Assuming EXCH
holds exchange rates of other currencies against the Euro, including USD with currency_key=1
:
insert into detail_items
with rt as (select c.currency_cd as currency_cd,
e.exch_rt as exch_rt_eur,
(e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
currency c,
(select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key)
select i.doc,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;
With items valued at 19.99 GBP and 25.00 AUD, you get detail_items
:
DOC DOC_CURRENCY NET_VALUE NET_VALUE_IN_USD NET_VALUE_IN_EURO
--- ------------ ----------------- ----------------- -----------------
1 GBP 19.99 32.53611 23.53426
2 AUD 25 25.46041 18.41621
If you want the currency stuff to be more re-usable you could create a view:
create view rt as
select c.currency_cd as currency_cd,
e.exch_rt as exch_rt_eur,
(e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
currency c,
(select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key;
And then insert using values from that:
insert into detail_items
select i.doc,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;
In my experience, working with Firebase is a huge advantage if you are trying to do user management, database, messaging sort of app since all of these features are already well integrated.
Like others have said, if you're just focused on the database/querying aspect, stick to mongo.
textBox1.Enabled = false;
"false" property will make the text box disable. and "true" will make it in regular form. Thanks.
You can use Apache LastModifiedFileComparator library
import org.apache.commons.io.comparator.LastModifiedFileComparator;
File[] files = directory.listFiles();
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
for (File file : files) {
Date lastMod = new Date(file.lastModified());
System.out.println("File: " + file.getName() + ", Date: " + lastMod + "");
}
I understand the demands. The thing is, there are WPF Methods for getting those values - but yes, one of the contributors is right, not directly. The Solution is not to get all those workarounds, but to change the initial approach according to clean Design and Development.
A) Set the initial Main Window to Screen
B) Get the Values for the ActualWindow including a ton of useful WPF Methods
C) You can add as many Windows as you like for the behaviour you want to have, like resizeable, minimized whatever… but now you always can access the Loaded and Rendered Screen
Please be careful with the following example, there is some Code around that makes it necessary to use that kind of approach, however it should work (It would give you the Points for each of the Corners of your Screen): Working Example on Single, Dual Monitor and different Resolutions (Within the Primal Main Window Class):
InitializeComponent();
[…]
ActualWindow.AddHandler(Window.LoadedEvent, new RoutedEventHandler(StartUpScreenLoaded));
Routed Event:
private void StartUpScreenLoaded(object sender, RoutedEventArgs e)
{
Window StartUpScreen = sender as Window;
// Dispatcher Format B:
Dispatcher.Invoke(new Action(() =>
{
// Get Actual Window on Loaded
StartUpScreen.InvalidateVisual();
System.Windows.Point CoordinatesTopRight = StartUpScreen.TranslatePoint(new System.Windows.Point((StartUpScreen.ActualWidth), (0d)), ActualWindow);
System.Windows.Point CoordinatesBottomRight = StartUpScreen.TranslatePoint(new System.Windows.Point((StartUpScreen.ActualWidth), (StartUpScreen.ActualHeight)), ActualWindow);
System.Windows.Point CoordinatesBottomLeft = StartUpScreen.TranslatePoint(new System.Windows.Point((0d), (StartUpScreen.ActualHeight)), ActualWindow);
// Set the Canvas Top Right, Bottom Right, Bottom Left Coordinates
System.Windows.Application.Current.Resources["StartUpScreenPointTopRight"] = CoordinatesTopRight;
System.Windows.Application.Current.Resources["StartUpScreenPointBottomRight"] = CoordinatesBottomRight;
System.Windows.Application.Current.Resources["StartUpScreenPointBottomLeft"] = CoordinatesBottomLeft;
}), DispatcherPriority.Loaded);
}
.env
and .env.production
VUE_APP_
eg: VUE_APP_WHATEVERYOUWANT
.env
and build uses .env.production
process.env.VUE_APP_WHATEVERYOUWANT
to call valueBe sure you are using vue-cli version 3 or above
For more information: https://cli.vuejs.org/guide/mode-and-env.html
For others who are experiencing with the same problem, here is the description of the bug in php + patch https://bugs.php.net/bug.php?id=44522
Pipe date format bug fixed in Angular 2.0.0-rc.2, this Pull Request.
Now we can do the conventional way:
{{valueDate | date: 'dd/MM/yyyy'}}
Current Version:
Old Versions:
for me, the pragmatic approach is class inside class, sample:
public class MSEModel
{
class WITS
{
public const string DATE = "5005";
public const string TIME = "5006";
public const string MD = "5008";
public const string ROP = "5075";
public const string WOB = "5073";
public const string RPM = "7001";
...
}
I found a way that works if I use JavaScript combined with TypeScript.
logging.d.ts:
declare var log: log4javascript.Logger;
log-declaration.js:
log = null;
initalize-app.ts
import './log-declaration.js';
// Call stuff to actually setup log.
// Similar to this:
log = functionToSetupLog();
This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.
NOTE: I think this only works because I have the allowJs
TypeScript option set to true.
If someone posts an pure TypeScript solution, I will accept that.
There is an .Offset property on a Range class which allows you to do just what you need
ActiveCell.Offset(numRows, numCols)
follow up on a comment:
Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))
and you can verify by MsgBox newRange.Address
What context/language? Some languages use /
as the pattern delimiter, so yes, you need to escape it, depending on which language/context. You escape it by putting a backward slash in front of it: \/
For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the /
has is it may be the designated pattern delimiter.
Since you're using bash, the fastest way would be:
shopt -s extglob # Allow extended globbing
var=" lakdjsf lkadsjf "
echo "${var//+([[:space:]])/}"
It's fastest because it uses built-in functions instead of firing up extra processes.
However, if you want to do it in a POSIX-compliant way, use sed
:
var=" lakdjsf lkadsjf "
echo "$var" | sed 's/[[:space:]]//g'
Try
sys.exit("message")
It is like the perl
die("message")
if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function
For example, here's a table that has a primary key but is not AUTO_INCREMENT
:
mysql> CREATE TABLE foo (
id INT NOT NULL,
PRIMARY KEY (id)
);
mysql> INSERT INTO foo VALUES (1), (2), (5);
You can MODIFY
the column to redefine it with the AUTO_INCREMENT
option:
mysql> ALTER TABLE foo MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;
Verify this has taken effect:
mysql> SHOW CREATE TABLE foo;
Outputs:
CREATE TABLE foo (
`id` INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
Note that you have modified the column definition in place, without requiring creating a second column and dropping the original column. The PRIMARY KEY
constraint is unaffected, and you don't need to mention in in the ALTER TABLE
statement.
Next you can test that an insert generates a new value:
mysql> INSERT INTO foo () VALUES (); -- yes this is legal syntax
mysql> SELECT * FROM foo;
Outputs:
+----+
| id |
+----+
| 1 |
| 2 |
| 5 |
| 6 |
+----+
4 rows in set (0.00 sec)
I tested this on MySQL 5.0.51 on Mac OS X.
I also tested with ENGINE=InnoDB
and a dependent table. Modifying the id
column definition does not interrupt referential integrity.
To respond to the error 150 you mentioned in your comment, it's probably a conflict with the foreign key constraints. My apologies, after I tested it I thought it would work. Here are a couple of links that may help to diagnose the problem:
Taken from the ReactKonvaCore.d.ts file:
onClick?(evt: Konva.KonvaEventObject<MouseEvent>): void;
So, I'd say your event type is Konva.KonvaEventObject<MouseEvent>
A canvas element with some JavaScript would work great.
In fact, Signature Pad (a jQuery plugin) already has this implemented.
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
Straightforward and easy solution is:
docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67
3000
- can be any port
a3e628814c68
- hash result given by success build command
NOTE: you should be within directory that contains Dockerfile.
I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'MyTable'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
some_col = Column(String(500))
def __init__(self, some_col):
self.some_col = some_col
engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
for class_instance in session.query(MyTable).all():
print(vars(class_instance))
session.close()
+-----------------------------------------------------------------------------+
¦ ¦ class ¦ module ¦
¦---------------+---------------------------+---------------------------------¦
¦ instantiation ¦ can be instantiated ¦ can *not* be instantiated ¦
¦---------------+---------------------------+---------------------------------¦
¦ usage ¦ object creation ¦ mixin facility. provide ¦
¦ ¦ ¦ a namespace. ¦
¦---------------+---------------------------+---------------------------------¦
¦ superclass ¦ module ¦ object ¦
¦---------------+---------------------------+---------------------------------¦
¦ methods ¦ class methods and ¦ module methods and ¦
¦ ¦ instance methods ¦ instance methods ¦
¦---------------+---------------------------+---------------------------------¦
¦ inheritance ¦ inherits behaviour and can¦ No inheritance ¦
¦ ¦ be base for inheritance ¦ ¦
¦---------------+---------------------------+---------------------------------¦
¦ inclusion ¦ cannot be included ¦ can be included in classes and ¦
¦ ¦ ¦ modules by using the include ¦
¦ ¦ ¦ command (includes all ¦
¦ ¦ ¦ instance methods as instance ¦
¦ ¦ ¦ methods in a class/module) ¦
¦---------------+---------------------------+---------------------------------¦
¦ extension ¦ can not extend with ¦ module can extend instance by ¦
¦ ¦ extend command ¦ using extend command (extends ¦
¦ ¦ (only with inheritance) ¦ given instance with singleton ¦
¦ ¦ ¦ methods from module) ¦
+-----------------------------------------------------------------------------+
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
Setting default choice for symfony2 radio button
$builder->add('range_options', 'choice', array(
'choices' => array('day'=>'Day', 'week'=>'Week', 'month'=>'Month'),
'data'=>'day', //set default value
'required'=>true,
'empty_data'=>null,
'multiple'=>false,
'expanded'=> true
))
Although both versions of the specific example are equivalent, as already mentioned in the other answers, there is still one small difference between them. The first version includes an unnecessary implicit barrier, encountered at the end of the "omp for". The other implicit barrier can be found at the end of the parallel region. Adding "nowait" to "omp for" would make the two codes equivalent, at least from an OpenMP perspective. I mention this because an OpenMP compiler could generate slightly different code for the two cases.
Make a bat file with the following in it:
copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt
However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:
C:\temp\test.bat > C:\temp\test.log
(assuming the first bat file was called test.bat and was located in that directory)
I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit javax.swing.AbstractButton
and create your own. Should be pretty simple to wire something together with their existing framework.
What you actually created with:
MyType[] list = []
Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:
MyType[] array = new MyType[4]
But there's no add method of course.
If you create list with def
it's something like creating this instance with Object
(You can read more about def
here). And []
creates empty ArrayList
in this case.
So using def list = []
you can then append new items with add()
method of ArrayList
list.add(new MyType())
Or more groovy way with overloaded left shift operator:
list << new MyType()
Maybe not THE answer, but it's definitely AN answer.
If nothing else is working for you, go the nuclear option: Close IDEA and delete the ".../.IntelliJIdea/system" directory using your local file system tools.
The .IntelliJIdea directory is usually found in your home directory. Your IDE configuration is in the ".../.IntelliJIdea/config" directory, so it should be fine.
Obviously, this is not the "IDEA" way to do it and would be completely unsupported by JetBrains. Also - I don't use Android Studio so I dunno if this will cause problems, but there you go.
It's worked for me before when I've had problems getting IDEA to start and nothing else works to get me going. Maybe back up your entire .IntelliJIdea directory if you have a morbid fear of losing all your work >.<
It looks like the github.com
host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts
. Jenkins runs on most distros as the user jenkins
and hence has its own .ssh
directory to store the list of public keys and known_hosts
.
The easiest solution I can think of to fix this problem is:
# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash
cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL
# Allow adding the SSH host key to your known_hosts
# Exit from su
exit
To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.
for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.
In firefox, this can be done from 'about:preferences' and searching for 'Certificates'
Take a look at sprintf()
and family.
I think if you try:
Sub Macro3()
a = ActiveSheet.UsedRange.Columns.Count - 3
End Sub
with a watch on a
you will see it does make a difference.
OSX User adjustments.
Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.
I put the cert.pem
file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.
Configure git to trust this certificate:
$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem
If you're rolling your own modules specific to your application, you can either:
Keep those (and only those) in your application's /node_modules
folder and move out all the other dependencies to parent ../node_modules
folder. This will work because of how NodeJS CommonJS modules system works by moving up to the parent directory, and so on, until the root of the tree is reached. See: https://nodejs.org/api/modules.html
Or gitignore all /node_modules/*
except your /node_modules/your-modules
. See: Make .gitignore ignore everything except a few files
This use case is pretty awesome. It lets you keep modules you created specifically for your application nicely with it and doesn't clutter with dependencies which can be installed later.
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
Only downside (it seems), is that the table cell widths are identical. Any way to get around this? – Josh Stodola Oct 12 at 15:53
Just define width of the table and width for each table cell
something like
table {border-collapse:collapse; table-layout:fixed; width:900px;}
th {background: yellow; }
td {overflow:hidden;white-space:nowrap; }
.cells1{width:300px;}
.cells2{width:500px;}
.cells3{width:200px;}
It works like a charm :o)
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
For me I had all of the namespaces on the pages and none of the solutions above fixed it. My problem was in:
<%@ Page Language="C#"
AutoEventWireup="true"
CodeBehind="xxx.aspx.cs"
Inherits="xxx.xxx.xxx"
MasterPageFile="~masterurl/default.master" %>
Then in my aspx.cs
file the namespace did not match the Inherits
tag. So it needed
namespace xxx.xxx.xxx
In the .cs
to match the Inherits
.
My Personal View of Gist and GitHub:
Gist: Gist is a simple way to share code snippets and pastes with others. It is used when you need to share a sample piece of code or technique with your co-workers or friends.
And
GitHub GitHub, on the other hand, provides a platform to share an entire project as a repo among a team(private repo) or to the whole world(public repo).
Both Will log version details.
Note:
$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody
$("table#myTable tr").last().after(newRow); // this will add new row outside tbody
//i.e. between thead and tbody
//.before() will also work similar
Try this code
private void clearAppData() {
try {
if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData();
} else {
Runtime.getRuntime().exec("pm clear " + getApplicationContext().getPackageName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
To have the exact same output as you need, you need to format the file like that :
a very long string..........\t 112232432\t anotherfield\n
a smaller string\t 123124343\t anotherfield\n
And then using :
$ column -t -s $'\t' FILE
a very long string.......... 112232432 anotherfield
a smaller string 123124343 anotherfield
It's worth mentioning that there is very useful chapter Testing Concurrent Programs
in Concurrency in Practice which describes some unit testing approaches and gives solutions for issues.
I would always encode in UTF-8. From the Wikipedia page on percent encoding:
The generic URI syntax mandates that new URI schemes that provide for the representation of character data in a URI must, in effect, represent characters from the unreserved set without translation, and should convert all other characters to bytes according to UTF-8, and then percent-encode those values. This requirement was introduced in January 2005 with the publication of RFC 3986. URI schemes introduced before this date are not affected.
It seems like because there were other accepted ways of doing URL encoding in the past, browsers attempt several methods of decoding a URI, but if you're the one doing the encoding you should use UTF-8.
The object of the exercise is to find the row that contains the information. When we get there, we can easily extract the required information.
$(".use-address").click(function() {
var $item = $(this).closest("tr") // Finds the closest row <tr>
.find(".nr") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$("#resultas").append($item); // Outputs the answer
});
Now let's focus on some frequently asked questions in such situations.
Using .closest()
:
var $row = $(this).closest("tr");
Using .parent()
:
You can also move up the DOM tree using .parent()
method. This is just an alternative that is sometimes used together with .prev()
and .next()
.
var $row = $(this).parent() // Moves up from <button> to <td>
.parent(); // Moves up from <td> to <tr>
<td>
valuesSo we have our $row
and we would like to output table cell text:
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td"); // Finds all children <td> elements
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
<td>
valueSimilar to the previous one, however we can specify the index of the child <td>
element.
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
.closest()
- get the first element that matches the selector.parent()
- get the parent of each element in the current set of matched elements.parents()
- get the ancestors of each element in the current set of matched elements.children()
- get the children of each element in the set of matched elements.siblings()
- get the siblings of each element in the set of matched elements.find()
- get the descendants of each element in the current set of matched elements.next()
- get the immediately following sibling of each element in the set of matched elements.prev()
- get the immediately preceding sibling of each element in the set of matched elementsAccording to cppreference, nullptr
is a keyword that:
denotes the pointer literal. It is a prvalue of type
std::nullptr_t
. There exist implicit conversions from nullptr to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of typestd::nullptr_t
as well as the macroNULL
.
So nullptr
is a value of a distinct type std::nullptr_t
, not int
. It implicitly converts to the null pointer value of any pointer type. This magic happens under the hood for you and you don't have to worry about its implementation. NULL
, however, is a macro and it is an implementation-defined null pointer constant. It's often defined like this:
#define NULL 0
i.e. an integer.
This is a subtle but important difference, which can avoid ambiguity.
For example:
int i = NULL; //OK
int i = nullptr; //error
int* p = NULL; //OK
int* p = nullptr; //OK
and when you have two function overloads like this:
void func(int x); //1)
void func(int* x); //2)
func(NULL)
calls 1) because NULL
is an integer.
func(nullptr)
calls 2) because nullptr
converts implicitly to a pointer of type int*
.
Also if you see a statement like this:
auto result = findRecord( /* arguments */ );
if (result == nullptr)
{
...
}
and you can't easily find out what findRecord
returns, you can be sure that result
must be a pointer type; nullptr
makes this more readable.
In a deduced context, things work a little differently. If you have a template function like this:
template<typename T>
void func(T *ptr)
{
...
}
and you try to call it with nullptr
:
func(nullptr);
you will get a compiler error because nullptr
is of type nullptr_t
. You would have to either explicitly cast nullptr
to a specific pointer type or provide an overload/specialization for func
with nullptr_t
.
if (ptr == nullptr)
instead of if (ptr == 0)
The m_
prefix is often used for member variables - I think its main advantage is that it helps create a clear distinction between a public property and the private member variable backing it:
int m_something
public int Something => this.m_something;
It can help to have a consistent naming convention for backing variables, and the m_
prefix is one way of doing that - one that works in case-insensitive languages.
How useful this is depends on the languages and the tools that you're using. Modern IDEs with strong refactor tools and intellisense have less need for conventions like this, and it's certainly not the only way of doing this, but it's worth being aware of the practice in any case.
With jquery (only tested in firefox):
function getScrollBarHeight() {
var jTest = $('<div style="display:none;width:50px;overflow: scroll"><div style="width:100px;"><br /><br /></div></div>');
$('body').append(jTest);
var h = jTest.innerHeight();
jTest.css({
overflow: 'auto',
width: '200px'
});
var h2 = jTest.innerHeight();
return h - h2;
}
function getScrollBarWidth() {
var jTest = $('<div style="display:none;height:50px;overflow: scroll"><div style="height:100px;"></div></div>');
$('body').append(jTest);
var w = jTest.innerWidth();
jTest.css({
overflow: 'auto',
height: '200px'
});
var w2 = jTest.innerWidth();
return w - w2;
}
But I actually like @Steve's answer better.
You must make your binding bidirectional :
<checkbox IsChecked="{Binding Path=MyProperty, Mode=TwoWay}"/>
If you have Gimp, I saw that exporting the image in .eps format would do the job.
convert to string and then use built-in functions
unsigned int i;
cout<< to_string(i).length()<<endl;
var data = {"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}
var parsedData = JSON.parse(data);
alert(parsedData.name);
alert(parsedData.skills);
alert(parsedData.jobtitel);
alert(parsedData.res_linkedin);
The Android support library can be imported within gradle in the dependencies :
compile 'com.android.support:design:22.2.0'
It should be included within GradlePlease! And as an example to use it:
<android.support.design.widget.TextInputLayout
android:id="@+id/to_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/autoCompleteTextViewTo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="To"
android:layout_marginTop="45dp"
/>
</android.support.design.widget.TextInputLayout>
Btw, the editor may not understand that AutoCompleteTextView is allowed within TextInputLayout.
Method call setSelectedIndex("item_value");
doesn't work because setSelectedIndex
use sequential index.
You technically have two options when speaking of ISO dates.
In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd
or y-m-d
. Which are both valid ISO formats.
Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.
Because of this, your safest bet is to persist/filter based on the always netural ymd
format.
The code:
select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)
If you want to solve it in a two-liner you can do it like this:
with open('data.json') as f:
data = [json.loads(line) for line in f]
Another way of getting the first row and preserving the index:
x = df.first('d') # Returns the first day. '3d' gives first three days.
Uncommenting the
always_populate_raw_post_data = -1
in php.ini ( line# 703 ) and restarting APACHE services help me get rid from the message anyway
; Always populate the $HTTP_RAW_POST_DATA variable. PHP's default behavior is
; to disable this feature and it will be removed in a future version.
; If post reading is disabled through enable_post_data_reading,
; $HTTP_RAW_POST_DATA is *NOT* populated.
; http://php.net/always-populate-raw-post-data
; always_populate_raw_post_data = -1
If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!
Here I have used jQuery function, it can be done by simple JavaScript also...
<form id="form_data">
<input type="anything" name="anything" />
<input type="anything" name="anything" />
<!-- Save and Reset button -->
<button type="button" id="btn_submit">Save</button>
<button type="reset" id="btn_reset" style="display: none;"></button>
</form>
<script type="text/javascript">
$(function(){
$('#btn_submit').click(function(){
// Do what ever you want
$('#btn_reset').click(); // Clicking reset button
});
});
</script>
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
#Kill command after 10 seconds
timeout 10 command
#If you don't have timeout installed, this is almost the same:
sh -c '(sleep 10; kill "$$") & command'
#The same as above, with muted duplicate messages:
sh -c '(sleep 10; kill "$$" 2>/dev/null) & command'
Refer This code:
public class sample
{
public static void main(String[] args)
{
Object obj=new Object();
int a=10,b=0;
obj=a;
b=(int)obj;
System.out.println("Object="+obj+"\nB="+b);
}
}
None of these methods worked for me, the only solution was to nuke the whole repo and re-clone it. This includes stashing, resetting, adding then resetting, clrf settings, case sensitivity etc. Sigh..
You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.
You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).
You should convert the shortened array back to a string with .join(",")
and then use it for the new cookie instead of using old_cookie
which is not shortened.
You may also not be using .splice()
correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice()
here.
you please open the Navigator view and following step
Having all the related projects in the same root directory.
This will create a empty project, with a .idea directory that will simply remember the module organisation we are about to do in the next step
The project will be imported as a new module.
By current official documentation there is a short cut that stops and removes containers, networks, volumes, and images created by up, if they are already stopped or partially removed and so on, then it will do the trick too:
docker-compose down
Then if you have new changes on your images or Dockerfiles use:
docker-compose build --no-cache
Finally:docker-compose up
In one command:
docker-compose down && docker-compose build --no-cache && docker-compose up
First you need to check which version of git you are running, the one installed with brew should be running on /usr/local/bin/git , you can verify this from a terminal using:
which git
In case git shows up on a different directory you need to run this from a terminal to add it to your path:
echo export PATH='/usr/local/bin:$PATH' >> ~/.bash_profile
After that you can close and open again your terminal or just run:
source ~/.bash_profile
And voila! In case you are running on OSX Mavericks you might need to install XQuartz.
Combine the SUBSTRING()
, LEFT()
, and CHARINDEX()
functions.
SELECT LEFT(SUBSTRING(YOUR_FIELD,
CHARINDEX(';', YOUR_FIELD) + 1, 100),
CHARINDEX('[', YOUR_FIELD) - 1)
FROM YOUR_TABLE;
This assumes your field length will never exceed 100, but you can make it smarter to account for that if necessary by employing the LEN()
function. I didn't bother since there's enough going on in there already, and I don't have an instance to test against, so I'm just eyeballing my parentheses, etc.
Here I found a tweak for this, without any third party tool. This will make the following shortcut to work:
fn + right: to go to the end of the line.
fn + left: to go to the beginning of the line.
cmd + ,
).EDIT: Refer to the comment by @Maurice Gilden below for more insights.
Drop-in Swift 3.0 extension that supports the new iOS 10.0 API & the previous method.
Note:
!
which could cause a crash.extension UIView
{
public func renderToImage(afterScreenUpdates: Bool = false) -> UIImage?
{
if #available(iOS 10.0, *)
{
let rendererFormat = UIGraphicsImageRendererFormat.default()
rendererFormat.scale = self.layer.contentsScale
rendererFormat.opaque = self.isOpaque
let renderer = UIGraphicsImageRenderer(size: self.bounds.size, format: rendererFormat)
return
renderer.image
{
_ in
self.drawHierarchy(in: self.bounds, afterScreenUpdates: afterScreenUpdates)
}
}
else
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, self.layer.contentsScale)
defer
{
UIGraphicsEndImageContext()
}
self.drawHierarchy(in: self.bounds, afterScreenUpdates: afterScreenUpdates)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
}
Refer this link Get Keycode from key press and char value for any key code
$('input#inp').keyup(function(e){
$(this).val(String.fromCharCode(e.keyCode));
$('div#output').html('Keycode : ' + e.keyCode);
});
And if you need authorized user in templates (e.g. JSP) use
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>
together with
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-security.version}</version>
</dependency>
we can access/pass arguments/variables from one class to another class using object reference.
#Class1
class Test:
def __init__(self):
self.a = 10
self.b = 20
self.add = 0
def calc(self):
self.add = self.a+self.b
#Class 2
class Test2:
def display(self):
print('adding of two numbers: ',self.add)
#creating object for Class1
obj = Test()
#invoking calc method()
obj.calc()
#passing class1 object to class2
Test2.display(obj)
If the string is
$STR = 'HELLO WORLD'
and you want to remove the empty space between 'HELLO' and 'WORLD'
$STR.replace(' ','')
replace
takes the string and replaces white space with empty string (of length 0), in other words the white space is just deleted.
I was still confused after reading the other answers and comments. But the answer now seems simpler, so here you go.
Since Pandas version 0.9 (from 2012), you can read your csv with empty cells interpreted as empty strings by simply setting keep_default_na=False
:
pd.read_csv('test.csv', keep_default_na=False)
This issue is more clearly explained in
That was fixed on on Aug 19, 2012 for Pandas version 0.9 in
The easiest and the most correct (and legal) way is to use graph api.
Just perform the request: http://graph.facebook.com/4
which returns
{
"id": "4",
"name": "Mark Zuckerberg",
"first_name": "Mark",
"last_name": "Zuckerberg",
"link": "http://www.facebook.com/zuck",
"username": "zuck",
"gender": "male",
"locale": "en_US"
}
and take the link
key.
You can also reduce the traffic by using fields
parameter: http://graph.facebook.com/4?fields=link to get only what you need:
{
"link": "http://www.facebook.com/zuck",
"id": "4"
}
Before you can fix anything you need to know which service has not started, Apache or MySQL.
As the TEST PORT 80 utility is saying Apache is running its probably the MySQL service that has not started. Unless you have another Apache running!
So which service has not started???
If the wampmanager icon is not GREEN then one of the services ( Apache/MySQL ) has not started properly.
How to tell which service is not running if the wampmanager icon is orange.
Left click the wampmanager icon to reveal the menu-> Apache -> Service If the Start/Resume service menu is Green then Apache IS NOT running.
Left click the wampmanager icon to reveal the menu-> MySQL -> Service If the Start/Resume service menu is Green then MySQL IS NOT running.
If Apache is the service that is not running it is normally, but not always, because something else has captured port 80.
Now do, Left click the wampmanager icon to reveal the menu-> Apache -> Service -> Test port 80 This will launch a command window and display some information about what, if anything is using port 80.
Whatever it is should be re-configured to not use port 80 or uninstalled if you are not using it.
If port 80 is not the problem look for errors in the appropriate error log ( use the wamp manager menus to view the error logs )
If these do not exists or show no errors then also check the Windows Event Viewer Start -> Administrative Tools -> Event Viewer And look in the 'Windows Logs' -> Application' section accessed from the menu on the left of the dialog for error messages from Apache and or MySQL.
Check the mysql error log by using the menus
wampmanager->MySQL->error log
Check the Windows Event log for messages from MYSQL
Check you dont have another MYSQL Server instance running.
How to Configure SKYPE so it does not require port 80 or 443
Run SKYPE then using the menus do this: Tools -> Options -> Advanced -> Connection Un-Check the checkbox next to 'Use port 80 and 443 as alternatives for incomming connections' Now restart SKYPE for these changes to take effect.
If you are running Windows 8 SKYPE comes as an app and this cannot ( as yet ) be configured in this way. However if you uninstall the SKYPE app and install SKYPE in the old way, you can reconfigure it, and it works just as well.
You need to set android:exported="true"
in your AndroidManifest.xml
file where you declare this Activity
:
<activity
android:name="com.example.lib.MainActivity"
android:label="LibMain"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" >
</action>
</intent-filter>
</activity>
I know this post is old but i want to add a few points to this!
you can try
vagrant ssh -c "ifconfig | grep inet" hostname
this will be easy if you have setup a name to your guests individually!
Another all-too-common reason for this problem is if you attempt to load a directory on a drive that is no longer connected. For example, Say you program in C:\Code\Java, but occasionally work off of a flash drive, H:\Code\Java. If you do not have the drive connected it can be easy to believe you are trying to load a valid directory without noticing your typo.
It depends which version of the .NET Framework you are using. .NET 4.0 made thread management a whole lot easier using Tasks:
class Program
{
static void Main(string[] args)
{
Task task1 = Task.Factory.StartNew(() => doStuff());
Task task2 = Task.Factory.StartNew(() => doStuff());
Task task3 = Task.Factory.StartNew(() => doStuff());
Task.WaitAll(task1, task2, task3);
Console.WriteLine("All threads complete");
}
static void doStuff()
{
//do stuff here
}
}
In previous versions of .NET you could use the BackgroundWorker
object, use ThreadPool.QueueUserWorkItem()
, or create your threads manually and use Thread.Join()
to wait for them to complete:
static void Main(string[] args)
{
Thread t1 = new Thread(doStuff);
t1.Start();
Thread t2 = new Thread(doStuff);
t2.Start();
Thread t3 = new Thread(doStuff);
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine("All threads complete");
}
You can't do this with Html.ActionLink
. You should use Url.RouteUrl
and use the URL to construct the element you want.
based on swift:
let alertCtr = UIAlertController(title:"Title", message:"Message", preferredStyle: .Alert)
let Cancel = AlertAction(title:"remove", style: .Default, handler: {(UIAlertAction) -> Void in })
let Remove = UIAlertAction(title:"remove", style: .Destructive, handler:{(UIAlertAction)-> Void
inself.colorLabel.hidden = true
})
alertCtr.addAction(Cancel)
alertCtr.addAction(Remove)
self.presentViewController(alertCtr, animated:true, completion:nil)}
Make sure to run 7zip in 'Administrator mode' for extracting to Program Files.
Also, temporarily turning off virus protection worked for some people in the past.
1) When to use include directive ?
To prevent duplication of same output logic across multiple jsp's of the web app ,include mechanism is used ie.,to promote the re-usability of presentation logic include directive is used
<%@ include file="abc.jsp" %>
when the above instruction is received by the jsp engine,it retrieves the source code of the abc.jsp and copy's the same inline in the current jsp. After copying translation is performed for the current page
Simply saying it is static instruction to jsp engine ie., whole source code of "abc.jsp" is copied into the current page
2) When to use include action ?
include tag doesn't include the source code of the included page into the current page instead the output generated at run time by the included page is included into the current page response
include tag functionality is similar to that of include mechanism of request dispatcher of servlet programming
include tag is run-time instruction to jsp engine ie., rather copying whole code into current page a method call is made to "abc.jsp" from current page
In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start
was called!). But PHP’s session handling is a little bit more complicated.
Because the session data is removed by a garbage collector that is only called by session_start
with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start
calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.
Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.
If you are adding the View programmatically, you can use yourLayout.addView(view, 1);
where 1 is the index
.
git ls-files -o --exclude-standard
gives untracked files, so you can do something like below ( or add an alias to it):
git add $(git ls-files -o --exclude-standard)
import subprocess
p = sub.Popen('file yourfile.txt', stdout=sub.PIPE, stderr=sub.PIPE)
output, errors = p.communicate()
print(output)
As Steven pointed out, subprocess
is the way. You can get the command output by the way above as this post said
This fix / solution worked for me: Device Manager --> Ports --> right click on Arduino Uno --> Update Driver Software --> Search automatically for updated driver software
To make the image move right:
float: right;
To make the text not wrapped:
clear: right;
For best practice, put the css code in your stylesheets file. Once you add more code, it will look messy and hard to edit.
If join does not work for you you may try this solution. It is for deleting orphan records from t1 when not using foreign keys + specific where condition. I.e. it deletes records from table1, that have empty field "code" and that do not have records in table2, matching by field "name".
delete table1 from table1 t1
where t1.code = ''
and 0=(select count(t2.name) from table2 t2 where t2.name=t1.name);
To get the absolute position of an UI element within the window you can use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
If you are within an User Control, and simply want relative position of the UI element within that control, simply use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));
position.X -= controlPosition.X;
position.Y -= controlPosition.Y;
Expanding on @gecco 's answer, the following is an example that'll show you the difference:
def foo(**kwargs):
for entry in kwargs.items():
print("Key: {}, value: {}".format(entry[0], entry[1]))
# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})
# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")
Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails
You are correct. Local variables are not allowed in a VIEW.
You can set a local variable in a table valued function, which returns a result set (like a view does.)
http://msdn.microsoft.com/en-us/library/ms191165.aspx
e.g.
CREATE FUNCTION dbo.udf_foo()
RETURNS @ret TABLE (col INT)
AS
BEGIN
DECLARE @myvar INT;
SELECT @myvar = 1;
INSERT INTO @ret SELECT @myvar;
RETURN;
END;
GO
SELECT * FROM dbo.udf_foo();
GO
In the first case you are creating the object on the heap
using new
.
In the second case you are creating the object on the stack
, so it will be disposed of when going out of scope.
In C++
you'll need to delete objects on the heap
explicitly using delete
when you don't Need them anymore.
To call a static method from a class, do
Singleton* singleton = Singleton::get_sample();
in your main-function or wherever.
Use the datetime
method and the operator <
and its kin.
>>> from datetime import datetime, timedelta
>>> past = datetime.now() - timedelta(days=1)
>>> present = datetime.now()
>>> past < present
True
>>> datetime(3000, 1, 1) < present
False
>>> present - datetime(2000, 4, 4)
datetime.timedelta(4242, 75703, 762105)
Just go to web.config file and add following
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="Path of your Page" />
</files>
</defaultDocument>
</system.webServer>
This should do the trick:
import pandas as pd
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy import create_engine
# Create engine
engine = create_engine('mysql://USER_NAME_HERE:PASS_HERE@HOST_ADRESS_HERE/DB_NAME_HERE')
# Create the connection and close it(whether successed of failed)
with engine.begin() as connection:
df.to_sql(name='INSERT_TABLE_NAME_HERE/INSERT_NEW_TABLE_NAME', con=connection, if_exists='append', index=False)
After reading through erickson's suggestions, and gleaning what I could from a couple other postings and this example here, I've attempted to update Doug's code with the recommended changes. Feel free to edit to make it better.
Some notes: This uses a 128 bit encryption key - java apparently won't do 256 bit encryption out-of-the-box. Implementing 256 requires installing some extra files into the java install directory.
Also, I'm not a crypto person. Take heed.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
public class Crypto
{
String mPassword = null;
public final static int SALT_LEN = 8;
byte [] mInitVec = null;
byte [] mSalt = null;
Cipher mEcipher = null;
Cipher mDecipher = null;
private final int KEYLEN_BITS = 128; // see notes below where this is used.
private final int ITERATIONS = 65536;
private final int MAX_FILE_BUF = 1024;
/**
* create an object with just the passphrase from the user. Don't do anything else yet
* @param password
*/
public Crypto (String password)
{
mPassword = password;
}
/**
* return the generated salt for this object
* @return
*/
public byte [] getSalt ()
{
return (mSalt);
}
/**
* return the initialization vector created from setupEncryption
* @return
*/
public byte [] getInitVec ()
{
return (mInitVec);
}
/**
* debug/print messages
* @param msg
*/
private void Db (String msg)
{
System.out.println ("** Crypt ** " + msg);
}
/**
* this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
* and generates the salt bytes using secureRandom(). The encryption secret key is created
* along with the initialization vectory. The member variable mEcipher is created to be used
* by the class later on when either creating a CipherOutputStream, or encrypting a buffer
* to be written to disk.
*
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidParameterSpecException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
*/
public void setupEncrypt () throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidParameterSpecException,
IllegalBlockSizeException,
BadPaddingException,
UnsupportedEncodingException,
InvalidKeyException
{
SecretKeyFactory factory = null;
SecretKey tmp = null;
// crate secureRandom salt and store as member var for later use
mSalt = new byte [SALT_LEN];
SecureRandom rnd = new SecureRandom ();
rnd.nextBytes (mSalt);
Db ("generated salt :" + Hex.encodeHexString (mSalt));
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
/* Derive the key, given password and salt.
*
* in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
* The end user must also install them (not compiled in) so beware.
* see here: http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
*/
KeySpec spec = new PBEKeySpec (mPassword.toCharArray (), mSalt, ITERATIONS, KEYLEN_BITS);
tmp = factory.generateSecret (spec);
SecretKey secret = new SecretKeySpec (tmp.getEncoded(), "AES");
/* Create the Encryption cipher object and store as a member variable
*/
mEcipher = Cipher.getInstance ("AES/CBC/PKCS5Padding");
mEcipher.init (Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = mEcipher.getParameters ();
// get the initialization vectory and store as member var
mInitVec = params.getParameterSpec (IvParameterSpec.class).getIV();
Db ("mInitVec is :" + Hex.encodeHexString (mInitVec));
}
/**
* If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
* We have the password from initializing the class. pass the iv and salt here which is
* obtained when encrypting the file initially.
*
* @param initvec
* @param salt
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws DecoderException
*/
public void setupDecrypt (String initvec, String salt) throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
DecoderException
{
SecretKeyFactory factory = null;
SecretKey tmp = null;
SecretKey secret = null;
// since we pass it as a string of input, convert to a actual byte buffer here
mSalt = Hex.decodeHex (salt.toCharArray ());
Db ("got salt " + Hex.encodeHexString (mSalt));
// get initialization vector from passed string
mInitVec = Hex.decodeHex (initvec.toCharArray ());
Db ("got initvector :" + Hex.encodeHexString (mInitVec));
/* Derive the key, given password and salt. */
// in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
// The end user must also install them (not compiled in) so beware.
// see here:
// http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(mPassword.toCharArray (), mSalt, ITERATIONS, KEYLEN_BITS);
tmp = factory.generateSecret(spec);
secret = new SecretKeySpec(tmp.getEncoded(), "AES");
/* Decrypt the message, given derived key and initialization vector. */
mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));
}
/**
* This is where we write out the actual encrypted data to disk using the Cipher created in setupEncrypt().
* Pass two file objects representing the actual input (cleartext) and output file to be encrypted.
*
* there may be a way to write a cleartext header to the encrypted file containing the salt, but I ran
* into uncertain problems with that.
*
* @param input - the cleartext file to be encrypted
* @param output - the encrypted data file
* @throws IOException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public void WriteEncryptedFile (File input, File output) throws
IOException,
IllegalBlockSizeException,
BadPaddingException
{
FileInputStream fin;
FileOutputStream fout;
long totalread = 0;
int nread = 0;
byte [] inbuf = new byte [MAX_FILE_BUF];
fout = new FileOutputStream (output);
fin = new FileInputStream (input);
while ((nread = fin.read (inbuf)) > 0 )
{
Db ("read " + nread + " bytes");
totalread += nread;
// create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
// and results in full blocks of MAX_FILE_BUF being written.
byte [] trimbuf = new byte [nread];
for (int i = 0; i < nread; i++)
trimbuf[i] = inbuf[i];
// encrypt the buffer using the cipher obtained previosly
byte [] tmp = mEcipher.update (trimbuf);
// I don't think this should happen, but just in case..
if (tmp != null)
fout.write (tmp);
}
// finalize the encryption since we've done it in blocks of MAX_FILE_BUF
byte [] finalbuf = mEcipher.doFinal ();
if (finalbuf != null)
fout.write (finalbuf);
fout.flush();
fin.close();
fout.close();
Db ("wrote " + totalread + " encrypted bytes");
}
/**
* Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
* to disk as (output) File.
*
* I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
* and still have a correctly decrypted file in the end. Seems to work so left it in.
*
* @param input - File object representing encrypted data on disk
* @param output - File object of cleartext data to write out after decrypting
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws IOException
*/
public void ReadEncryptedFile (File input, File output) throws
IllegalBlockSizeException,
BadPaddingException,
IOException
{
FileInputStream fin;
FileOutputStream fout;
CipherInputStream cin;
long totalread = 0;
int nread = 0;
byte [] inbuf = new byte [MAX_FILE_BUF];
fout = new FileOutputStream (output);
fin = new FileInputStream (input);
// creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
cin = new CipherInputStream (fin, mDecipher);
while ((nread = cin.read (inbuf)) > 0 )
{
Db ("read " + nread + " bytes");
totalread += nread;
// create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
byte [] trimbuf = new byte [nread];
for (int i = 0; i < nread; i++)
trimbuf[i] = inbuf[i];
// write out the size-adjusted buffer
fout.write (trimbuf);
}
fout.flush();
cin.close();
fin.close ();
fout.close();
Db ("wrote " + totalread + " encrypted bytes");
}
/**
* adding main() for usage demonstration. With member vars, some of the locals would not be needed
*/
public static void main(String [] args)
{
// create the input.txt file in the current directory before continuing
File input = new File ("input.txt");
File eoutput = new File ("encrypted.aes");
File doutput = new File ("decrypted.txt");
String iv = null;
String salt = null;
Crypto en = new Crypto ("mypassword");
/*
* setup encryption cipher using password. print out iv and salt
*/
try
{
en.setupEncrypt ();
iv = Hex.encodeHexString (en.getInitVec ()).toUpperCase ();
salt = Hex.encodeHexString (en.getSalt ()).toUpperCase ();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidParameterSpecException e)
{
e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
/*
* write out encrypted file
*/
try
{
en.WriteEncryptedFile (input, eoutput);
System.out.printf ("File encrypted to " + eoutput.getName () + "\niv:" + iv + "\nsalt:" + salt + "\n\n");
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
/*
* decrypt file
*/
Crypto dc = new Crypto ("mypassword");
try
{
dc.setupDecrypt (iv, salt);
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidAlgorithmParameterException e)
{
e.printStackTrace();
}
catch (DecoderException e)
{
e.printStackTrace();
}
/*
* write out decrypted file
*/
try
{
dc.ReadEncryptedFile (eoutput, doutput);
System.out.println ("decryption finished to " + doutput.getName ());
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
In the end after trying many of these complicated solutions as I only needed to save/restore a single value in my Fragment (the content of an EditText), and although it might not be the most elegant solution, creating a SharedPreference and storing my state there worked for me
You can use the for command:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
Type
for /?
at the command prompt. Also, you can parse ini files!
If you're using concatenate method then don't forget to trim the string if you're working with if else method.
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
var host = location.protocol + '//' + location.host + '/';
Inaccessible logs: Security
A new event source needs to have a unique name across all logs including Security (which needs admin privilege when it's being read).
So your app will need admin privilege to create a source. But that's probably an overkill.
I wrote this powershell script to create the event source at will. Save it as *.ps1
and run it with any privilege and it will elevate itself.
# CHECK OR RUN AS ADMIN
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
# CHECK FOR EXISTENCE OR CREATE
$source = "My Service Event Source";
$logname = "Application";
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
[System.Diagnostics.EventLog]::CreateEventSource($source, $logname);
Write-Host $source -f white -nonewline; Write-Host " successfully added." -f green;
}
else
{
Write-Host $source -f white -nonewline; Write-Host " already exists.";
}
# DONE
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:
var qry = Foos.GroupJoin(
Bars.OrderByDescending(b => b.Id),
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });
Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).
I use moment.js http://momentjs.com/
var start = moment(StartTimeString).toDate().getTime();
var end = moment(EndTimeString).toDate().getTime();
var timespan = end - start;
var duration = moment(timespan);
var output = duration.format("YYYY-MM-DDTHH:mm:ss");
For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.
For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.
JQuery:
$(function () {
$('.SendEmail').click(function (event) {
var email = '[email protected]';
var subject = 'Test';
var emailBody = 'Hi Sample,';
var attach = 'path';
document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody+
"?attach="+attach;
});
});
HTML:
<button class="SendEmail">Send Email</button>
1-to get your id go to your image profile and click right click and take copy link adress.
try {
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("fb://profile/id"));
startActivity(intent);
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("facebook url")));
}
}
});
Use .height()
like this:
var result = $("#myDiv").height();
There's also .innerHeight()
and .outerHeight()
depending on exactly what you want.
You can test it here, play with the padding/margins/content to see how it changes around.
Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild
ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers
parameter. Then each process will start 25 threads determined by ThreadsPerChild
parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit
parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients
is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients
. This also means that if I set MaxClients
to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient
parameter. In this case, we need to also increase ServerLimit
to 1000/25 i.e. MaxClients/ThreadsPerChild=40
So this is the optmized configuration to server 1000 clients
<IfModule mpm_worker_module>
ServerLimit 40
StartServers 2
MaxClients 1000
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
Standard (https://tools.ietf.org/html/rfc6750) says you can use:
So it's possible to pass many Bearer Token with URI, but doing this is discouraged (see section 5 in the standard).
Turns out, you can hide and show cells in a static UITableView - and with animation. And it is not that hard to accomplish.
The gist:
Use tableView:heightForRowAtIndexPath:
to specify cell heights dynamically based on some state.tableView.beginUpdates();tableView.endUpdates()
tableView.cellForRowAtIndexPath:
inside tableView:heightForRowAtIndexPath:
. Use cached indexPaths to differentiate the cells.For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:
CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END