You can detect and specify variables for several operating systems like that:
if(WIN32)
# for Windows operating system in general
endif()
Or:
if(MSVC OR MSYS OR MINGW)
# for detecting Windows compilers
endif()
if(APPLE)
# for MacOS X or iOS, watchOS, tvOS (since 3.10.3)
endif()
if(UNIX AND NOT APPLE)
# for Linux, BSD, Solaris, Minix
endif()
To solve your issue with the Windows-specific wsock32
library, just remove it from other systems, like that:
if(WIN32)
target_link_libraries(${PROJECT_NAME} bioutils wsock32)
else
target_link_libraries(${PROJECT_NAME} bioutils)
endif()
The thing on the right of <-
is a formula
object. It is often used to denote a statistical model, where the thing on the left of the ~
is the response and the things on the right of the ~
are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".
The myFormula <-
part of that line stores the formula in an object called myFormula
so you can use it in other parts of your R code.
Other common uses of formula objects in R
The lattice
package uses them to specify the variables to plot.
The ggplot2
package uses them to specify panels for plotting.
The dplyr
package uses them for non-standard evaulation.
String input = "0101";
BigInteger x = new BigInteger ( input , 2 );
String output = x.toString(2);
If your browser supports CSS3, try using the CSS element Calc()
height: calc(100% - 65px);
you might also want to adding browser compatibility options:
height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */
also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622
$(".hit").click(function(){
var values = [];
var table = $(this).closest("table");
table.find("tr").each(function() {
values.push($(this).find("td:first").html());
});
alert(values);
});
You should avoid $(".hit")
it's really inefficient. Try using event delegation instead.
how to determine if a commit with particular hash have been pushed to the origin already?
# list remote branches that contain $commit
git branch -r --contains $commit
I adapted Raymond Hettinger's solution to python 3.
Here is what has changed:
unicode
disappeareddefault
with super()
base64
to serialize the bytes
type into str
(because it seems that bytes
in python 3 can't be converted to JSON)from decimal import Decimal
from base64 import b64encode, b64decode
from json import dumps, loads, JSONEncoder
import pickle
class PythonObjectEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, (list, dict, str, int, float, bool, type(None))):
return super().default(obj)
return {'_python_object': b64encode(pickle.dumps(obj)).decode('utf-8')}
def as_python_object(dct):
if '_python_object' in dct:
return pickle.loads(b64decode(dct['_python_object'].encode('utf-8')))
return dct
data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]
j = dumps(data, cls=PythonObjectEncoder)
print(loads(j, object_hook=as_python_object))
# prints: [1, 2, 3, {'knights', 'who', 'say', 'ni'}, {'key': 'value'}, Decimal('3.14')]
Another approach to draw a line programatically using ImageView
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.ImageView;
public class Test extends Activity {
ImageView drawingImageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawingImageView.setImageBitmap(bitmap);
// Line
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(10);
int startx = 50;
int starty = 100;
int endx = 150;
int endy = 210;
canvas.drawLine(startx, starty, endx, endy, paint);
}
}
it's android:button="@drawable/selector_checkbox"
to make it work
To all those who know more than me, rather than marking it unhelpful or misleading, read it one more time. I had issues with my Virtual Machine (VM) becoming unresponsive due to all resources being consumed by locked threads, so killing threads is the only option I had. I am not recommending this to anyone who are running long queries but may help to those who are stuck with unresponsive VM or something. Its up-to individuals to take the call. Yes it will kill your query but it saved my VM machine being destroyed.
Serverstack already answered similar question. It solved my issue with SQL on VM machine. Please check here
You need to run following command to fix issues with indexes.
exec sp_updatestats
Use glob. There are comprehensive guide how to open all files from dir: PHP: Using functional programming for listing files and directories
Because it's all just about memory, in the end all the numerical values are stored in binary.
A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.
When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.
The code that does what I need could be this:
# test
aux=[[0 for n in range(3)] for i in range(4)]
print('aux:',aux)
# initialization
a,b,c,d=[[0 for n in range(3)] for i in range(4)]
# changing values
a[0]=1
d[2]=5
print('a:',a)
print('b:',b)
print('c:',c)
print('d:',d)
Result:
('aux:', [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
('a:', [1, 0, 0])
('b:', [0, 0, 0])
('c:', [0, 0, 0])
('d:', [0, 0, 5])
Interestingly, base R aggregate
's data.frame
method is not showcased here, above the formula interface is used, so for completeness:
aggregate(
x = df1[c("x1", "x2")],
by = df1[c("year", "month")],
FUN = sum, na.rm = TRUE
)
More generic use of aggregate's data.frame method:
Since we are providing a
data.frame
as x
and list
(data.frame
is also a list
) as by
, this is very useful if we need to use it in a dynamic manner, e.g. using other columns to be aggregated and to aggregate by is very simpleFor example like so:
colsToAggregate <- c("x1")
aggregateBy <- c("year", "month")
dummyaggfun <- function(v, na.rm = TRUE) {
c(sum = sum(v, na.rm = na.rm), mean = mean(v, na.rm = na.rm))
}
aggregate(df1[colsToAggregate], by = df1[aggregateBy], FUN = dummyaggfun)
Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:
find . -name "*.sess" -mtime +100
and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)
You can use it like union(array1, array2, array3, ...)
/**
* Merges two or more arrays keeping unique items. This method does
* not change the existing arrays, but instead returns a new array.
*/
function union<T>(...arrays: T[]) {
return [...new Set([...arrays].flat())];
}
It is ES2019 because of the flat()
function, but you can use core-js to get it as a polyfill. The T
here is TypeScript generic type, that you can remove if you are not using TypeScript. If you are using TypeScript, make sure to add "lib": ["es2019.array"]
to compiler options in tsconfig.json
.
just use lodash _.union
using can be used to call IDisposable. It can also be used to alias types.
using (SqlConnection cnn = new SqlConnection()) { /*code*/}
using f1 = System.Windows.Forms.Form;
If you get an error 1044 (42000) when you try to run SQL commands in MySQL (which installed along XAMPP server) cmd prompt, then here's the solution:
Close your MySQL command prompt.
Open your cmd prompt (from Start menu -> run -> cmd) which will show: C:\Users\User>_
Go to MySQL.exe by Typing the following commands:
C:\Users\User>cd\
C:\>cd xampp
C:\xampp>cd mysql
C:\xxampp\mysql>cd bin
C:\xampp\mysql\bin>mysql -u root
Now try creating a new database by typing:
mysql> create database employee;
if it shows:
Query OK, 1 row affected (0.00 sec)
mysql>
Then congrats ! You are good to go...
You can use either of the two statements below:
numpy.mean(df['col_name'])
# or
df['col_name'].mean()
You need to add CSS to .active
instead of .active a
.
Fiddle: http://jsfiddle.net/T5X6h/2/
Something like this:
.navbar-default .navbar-nav > .active{
color: #000;
background: #d65c14;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #000;
background: #d65c14;
}
I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:
gcc -o exec main.o add.o
But my program is a C++ program. Using the g++
compiler solved my issue:
g++ -o exec main.o add.o
I was always under the impression that gcc
could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.
I hope this help. Haven't tried it out yet, will post again once I tested it.
http://blog.appideas.net/using-iphone-video-output-to-demo-your-apps-o
In my understanding, the way Android handles the MVC pattern is like:
You have an Activity, which serves as the controller. You have a class which responsibility is to get the data - the model, and then you have the View class which is the view.
When talking about the view most people think only for its visual part defined in the xml. Let's not forget that the View also has a program part with its constructors, methods and etc, defined in the java class.
If you are using Oracle 10g, you can use the DECODE
function to pivot the rows into columns:
CREATE TABLE doc_tab (
loan_number VARCHAR2(20),
document_type VARCHAR2(20),
document_id VARCHAR2(20)
);
INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');
COMMIT;
SELECT
loan_number,
MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
FROM
doc_tab
GROUP BY loan_number
ORDER BY loan_number;
Output:
LOAN_NUMBER VOTERS_ID PAN_CARD DRIVERS_LICENCE ------------- -------------------- -------------------- -------------------- 992452533663 XPD0355636 CHXPS5522D DL-0420110141769
You can achieve the same using Oracle PIVOT
clause, introduced in 11g:
SELECT *
FROM doc_tab
PIVOT (
MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);
SQLFiddle example with both solutions: SQLFiddle example
Read more about pivoting here: Pivot In Oracle by Tim Hall
For me i was getting this error because i needed to put the arrays in paratheses. The error is a bit tricky in this case...
ie. concatenate((a, b))
is right
not concatenate(a, b)
hope that helps.
I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
Factory pattern is also used for loading beans through BeanFactory and Application context.
In C++, a structure's inheritance is the same as a class except the following differences:
When deriving a struct from a class/struct, the default access-specifier for a base class/struct is public. And when deriving a class, the default access specifier is private.
For example, program 1 fails with a compilation error and program 2 works fine.
// Program 1
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // Is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // Compiler error because inheritance is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Base {
public:
int x;
};
struct Derived : Base { }; // Is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // Works fine because inheritance is public
getchar();
return 0;
}
I was using above command but it was not working. This command worked for me:
python -m pip uninstall pip setuptools
Open a good text editor (I'd recommend TextMate, but the free TextWrangler or vi or nano will do too), and open:
/etc/apache2/httpd.conf
Find the line:
"#LoadModule php5_module libexec/apache2/libphp5.so"
And uncomment it (remove the #).
Download and install the latest MySQL version from mysql.com. Choose the x86_64 version for Intel (unless your Intel Mac is the original Macbook Pro or Macbook, which are not 64 bit chips. In those cases, use the 32 bit x86 version).
Install all the MySQL components. Using the pref pane, start MySQL.
In the Sharing System Pref, turn on (or if it was already on, turn off/on) Web Sharing.
You should now have Apache/PHP/MySQL running.
In 10.4 and 10.5 it was necessary to modify the php.ini file to point to the correct location of mysql.sock. There are reports that this is fixed in 10.6, but that doesn't appear to be the case for all of us, given some of the comments below.
Below is the easiest way in case if Anaconda is already installed.
1) Under "Files", there is an option called,"Upload".
2) Click on "Upload" button and it asks for the path of the file and select the file and click on upload button present beside the file.
Having a single exit point reduces Cyclomatic Complexity and therefore, in theory, reduces the probability that you will introduce bugs into your code when you change it. Practice however, tends to suggest that a more pragmatic approach is needed. I therefore tend to aim to have a single exit point, but allow my code to have several if that is more readable.
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
I have similar solution, but allows to use locales:
let date = moment(someDate);
if (moment().diff(date, 'days') >= 1) {
return date.fromNow(); // '2 days ago' etc.
}
return date.calendar().split(' ')[0]; // 'Today', 'yesterday', 'tomorrow'
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
The only thing that assisted me was to set margin:0px
on the topmost <div class="row">
in my html DOM.
This again wasn't the most appealing way to solve the issue, but as it is only in one place I put it inline.
As an fyi the container-fluid and apparent bootstrap fixes only introduced an increased whitespace on either side of the visible page... :( Although I came across my solution by reading through the back and forth on the github issue - so worthwhile reading.
DateTime.MinValue and DateTime.MaxValue
DateTime.MinValue = 1/1/0001 12:00:00 AM
DateTime.MaxValue = 23:59:59.9999999, December 31, 9999,
exactly one 100-nanosecond tick
before 00:00:00, January 1, 10000
This has worked for me. At first I've created only the database, no predefined table I created.
from platform import python_version
print(python_version())
3.7.3
path='glass.data'
df=pd.read_csv(path)
df.head()
!conda install sqlalchemy
!conda install pymysql
pd.__version__
'0.24.2'
sqlalchemy.__version__
'1.3.20'
restarted the Kernel after installation.
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://USER:PASSWORD@HOST:PORT/DATABASE_NAME', echo=False)
try:
df.to_sql(name='glasstable',con=engine,index=False, if_exists='replace')
print('Sucessfully written to Database!!!')
except Exception as e:
print(e)
Try this:
Swift 4.1 , 4.2:
let stringData = "Black board"
//swift quick way and case sensitive
if stringData.contains("bla") {
print("data contains string");
}
//case sensitive
if stringData.range(of: "bla",options: .caseInsensitive) != nil {
print("data contains string");
}else {
print("data does not contains string");
}
For Objective-C:
NSString *stringData = @"Black board";
//Quick way and case sensitive
if ([stringData containsString:@"bla"]) {
NSLog(@"data contains string");
}
//Case Insensitive
if ([stringData rangeOfString:@"bla" options:NSCaseInsensitiveSearch].location != NSNotFound) {
NSLog(@"data contains string");
}else {
NSLog(@"data does not contain string");
}
Open the App signing section in Google Play Console, and get the SHA-1 hash under App signing certificate. Then convert it to Base64, for example with this tool: Hexadecimal -> base64 string decoder
Angular6 using the renderer2 without any variables and a clean template:
template:
<div (click)="toggleClass($event,'testClass')"></div>
in ts:
toggleClass(event: any, class: string) {
const hasClass = event.target.classList.contains(class);
if(hasClass) {
this.renderer.removeClass(event.target, class);
} else {
this.renderer.addClass(event.target, class);
}
}
One could put this in a directive too ;)
One alternative would be to use the NULLIF operator other than <>
or !=
which returns NULL if the two arguments are equal NULLIF in Microsoft Docs. So I believe WHERE clause can be modified for <>
and !=
as follows:
NULLIF(arg1, arg2) IS NOT NULL
As I found that, using <>
and !=
doesn't work for date in some cases. Hence using the above expression does the needful.
First follow this procedure:
Log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:
a@A:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa):
Created directory '/home/a/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A
Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):
a@A:~> ssh b@B mkdir -p .ssh
b@B's password:
Finally append a's new public key to b@B:.ssh/authorized_keys and enter b's password one last time:
a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'
b@B's password:
From now on you can log into B as b from A as a without password:
a@A:~> ssh b@B
then this will work without entering a password
ssh b@B "cd /some/directory; program-to-execute &"
This warning generated for default ASP.NET MVC 4 beta see here
In, any cast this Warning can be eliminated by manually editing the .csproj file for your project.
modify........: Reference Include="System.Net.Http"
to read ......: Reference Include="System.Net.Http, Version=4.0.0.0"
You can use "netstat" to check whether a port is available or not.
Use the netstat -anp | find "port number"
command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.
You have to put : before port number to get the actual output
Ex
netstat -anp | find ":8080"
For a semantic web approach, you could run a sparql query against WordNet in RDF format. Basically just use urllib module to issue GET request and return results in JSON format, parse using python 'json' module. If it's not English word you'll get no results.
As another idea, you could query Wiktionary's API.
I was Working with Elastic SQL plugin. Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
Most likely you need to use this trick:
dbms_output.put_line('Hi' || chr(10) ||
'good' || chr(10) ||
'morning' || chr(10) ||
'friends' || chr(10));
Code coverage has been explained well in the previous answers. So this is more of an answer to the second part of the question.
We've used three tools to determine code coverage.
We use these tools to
I suspect you don't actually have that problem - I suspect you've really got:
double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0
// Now cast
int b = (int) a;
// Now a is 3668
What makes me say that is that although it's true that many decimal values cannot be stored exactly in float
or double
, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)
I strongly suspect that your double
value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.
Assuming your double
type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly
3668.99999999999954525264911353588104248046875
So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.
The original answer is no longer working as written:
<%=Html.TextBox("test", new { style="width:50px" })%>
will get you a text box with "{ style="width:50px" }" as its text content.
To adjust this for the current release of MVC 1.0, use the following script (note the addition of the second parameter - I have mine starting as blank, adjust accordingly based on your needs):
<%=Html.TextBox("test", "", new { style="width:50px" })%>
Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS
$(function() {
$("#employeeLink").on("click",function(e) {
e.preventDefault(); // cancel the link itself
$.post(this.href,function(data) {
$("#someContainer").html(data);
});
});
});
If you insist on using frames which I strongly discourage, have a form and submit it with the link
<form action="employee.action" method="post" target="myFrame" id="myForm"></form>
and use (in plain JS)
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the link
document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
});
});
Without a form we need to make one
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the actual link
var myForm = document.createElement("form");
myForm.action=this.href;// the href of the link
myForm.target="myFrame";
myForm.method="POST";
myForm.submit();
});
});
I have seen some solutions here worth noting, as Omer Eldan posted. but here follows. ASP C#
using System.Data;
using System.Web.UI.HtmlControls;
public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
Table tbl = new Table();
TableRow tr = null;
TableCell cell = null;
int rows = dt.Rows.Count;
int cols = dt.Columns.Count;
if (includeHeaders)
{
TableHeaderRow htr = new TableHeaderRow();
TableHeaderCell hcell = null;
for (int i = 0; i < cols; i++)
{
hcell = new TableHeaderCell();
hcell.Text = dt.Columns[i].ColumnName.ToString();
htr.Cells.Add(hcell);
}
tbl.Rows.Add(htr);
}
for (int j = 0; j < rows; j++)
{
tr = new TableRow();
for (int k = 0; k < cols; k++)
{
cell = new TableCell();
cell.Text = dt.Rows[j][k].ToString();
tr.Cells.Add(cell);
}
tbl.Rows.Add(tr);
}
return tbl;
}
why this solution? Because you can easily just add this to a panel ie:
panel.Controls.Add(DataTableToHTMLTable(dtExample,true));
Second question , why do you have one column datatables and not just array's? Are you sure that these DataTables are uniform, because if the data is jagged then it's no use. If You really have to join these DataTables, there is many examples of Linq operations, or just use (beware though of same name columns as this will conflict in both linq operations and this solution if not handled):
public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
int dt2ColsCount = dt2.Columns.Count;
int dt1lRowsCount = dt1.Rows.Count;
DataColumn column;
for (int i = 0; i < dt2ColsCount; i++)
{
column = new DataColumn();
string colName = dt2.Columns[i].ColumnName;
System.Type colType = dt2.Columns[i].DataType;
column.ColumnName = colName;
column.DataType = colType;
dt1.Columns.Add(column);
for (int j = 0; j < dt1lRowsCount; j++)
{
dt1.Rows[j][colName] = dt2.Rows[j][colName];
}
}
return dt1;
}
and your solution would look something like:
panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));
interpret the rest, and have fun.
The latest specification allows line feed character, so a simple line break inside the attribute or entity
(note that characters #
and ;
are required) are OK.
Maintain a list of nodes you can travel to, sorted by the distance from your start node. In the beginning only your start node will be in the list.
While you haven't reached your destination: Visit the node closest to the start node, this will be the first node in your sorted list. When you visit a node, add all its neighboring nodes to your list except the ones you have already visited. Repeat!
I was receiving the same error when not specifying the app
name before pattern name.
In my case:
app-name
: Blog
pattern-name
: post-delete
reverse_lazy('Blog:post-delete')
worked.
You can do npm list | grep typescript
if it's installed through npm.
did the same here needed to show "success" twice response is data from PHP
String res=response.toString().trim;
Toast.makeText(sign_in.this,res,Toast.LENGTH_SHORT).show();
if ( res.compareTo("success")==0){
Toast.makeText(this,res,Toast.LENGTH_SHORT).show();
}
this code will help you, in that there is two button one for Camera and another for Gallery, and Image will be displayed in ImageView
https://github.com/siddhpuraamitr/Choose-Image-From-Gallery-Or-Camera
CSS Level 3 specifies the unset
property value. From MDN:
The unset CSS keyword is the combination of the initial and inherit keywords. Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not. In other words, it behaves like the inherit keyword in the first case and like the initial keyword in the second case.
Unfortunately this value is currently not supported in all browsers, including IE, Safari and Opera. I suggest using transparent
for the time being.
Try this steps:
You need to allow Allow USB debugging in your device when popup.
I'm assuming cross-domain iFrame since presumably the risk would be lower if you controlled it yourself.
protected void lbAddtoDestination_Click(object sender, EventArgs e)
{
AddRemoveItemsListBox(lstSourceSkills, lstDestinationSkills);
}
protected void lbRemovefromDestination_Click(object sender, EventArgs e)
{
AddRemoveItemsListBox(lstDestinationSkills, lstSourceSkills);
}
private void AddRemoveItemsListBox(ListBox source, ListBox destination)
{
List<ListItem> toBeRemoved = new List<ListItem>();
foreach (ListItem item in source.Items)
{
if (item.Selected)
{
toBeRemoved.Add(item);
destination.Items.Add(item);
}
}
foreach (ListItem item in toBeRemoved) source.Items.Remove(item);
}
Beginning with C# 7.1, you can use default literal to produce the default value of a type when the compiler can infer the expression type.
Console.Writeline(default(Guid));
// ouptut: 00000000-0000-0000-0000-000000000000
Console.WriteLine(default(int)); // output: 0
Console.WriteLine(default(object) is null); // output: True
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default
Try
Dim connectionString AS String = "Server=my_server;Database=name_of_db;User Id=user_name;Password=my_password"
And replace my_server, name_of_db, user_name and my_password with your values.
then Using sqlCon = New SqlConnection(connectionString)
should work
also I think your SQL is wrong, it should be SET clickCount= clickCount + 1
I think.
And on a general note, the page you link to has a link called Connection String which shows you how to do this.
Problem is when you already have an outline. Chrome still changes something and it's a real pain. I cannot find what to change :
.search input {
outline: .5em solid black;
width:41%;
background-color:white;
border:none;
font-size:1.4em;
padding: 0 0.5em 0 0.5em;
border-radius:3px;
margin:0;
height:2em;
}
.search input:focus, .search input:hover {
outline: .5em solid black !important;
box-shadow:none;
border-color:transparent;;
}
.search button {
border:none;
outline: .5em solid black;
color:white;
font-size:1.4em;
padding: 0 0.9em 0 0.9em;
border-radius: 3px;
margin:0;
height:2em;
background: -webkit-gradient(linear, left top, left bottom, from(#4EB4F8), to(#4198DE));
background: -webkit-linear-gradient(#4EB4F8, #4198DE);
background: -moz-linear-gradient(top, #4EB4F8, #4198DE);
background: -ms-linear-gradient(#4EB4F8, #4198DE);
background: -o-linear-gradient(#4EB4F8, #4198DE);
background: linear-gradient(#4EB4F8, #4198DE);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#4EB4F8', endColorstr='#4198DE');
zoom: 1;
}
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null
to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
Alternatively, if you are not concerned with the possible exception raised, you could change TryParse for Parse:
DateTime? d = DateTime.Parse("some valid text");
Although there won't be a boolean indicating success either, it could be practical in some situations where you know that the input text will always be valid.
import org.apache.commons.io.FileUtils;
List<File> htmFileList = new ArrayList<File>();
for (File file : (List<File>) FileUtils.listFiles(new File(srcDir), new String[]{"txt", "TXT"}, true)) {
htmFileList.add(file);
}
This is my latest code to add all text files from a directory
If you have Prototype installed, you can tighten up the code to generate and submit the hidden form like this:
var form = new Element('form',
{method: 'post', action: 'http://example.com/'});
form.insert(new Element('input',
{name: 'q', value: 'a', type: 'hidden'}));
$(document.body).insert(form);
form.submit();
>>> from packaging import version
>>> version.parse("2.3.1") < version.parse("10.1.2")
True
>>> version.parse("1.3.a4") < version.parse("10.1.2")
True
>>> isinstance(version.parse("1.3.a4"), version.Version)
True
>>> isinstance(version.parse("1.3.xy123"), version.LegacyVersion)
True
>>> version.Version("1.3.xy123")
Traceback (most recent call last):
...
packaging.version.InvalidVersion: Invalid version: '1.3.xy123'
packaging.version.parse
is a third-party utility but is used by setuptools (so you probably already have it installed) and is conformant to the current PEP 440; it will return a packaging.version.Version
if the version is compliant and a packaging.version.LegacyVersion
if not. The latter will always sort before valid versions.
Note: packaging has recently been vendored into setuptools.
An ancient alternative still used by a lot of software is distutils.version
, built in but undocumented and conformant only to the superseded PEP 386;
>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
True
>>> StrictVersion("2.3.1") < StrictVersion("10.1.2")
True
>>> StrictVersion("1.3.a4")
Traceback (most recent call last):
...
ValueError: invalid version number '1.3.a4'
As you can see it sees valid PEP 440 versions as “not strict” and therefore doesn’t match modern Python’s notion of what a valid version is.
As distutils.version
is undocumented, here's the relevant docstrings.
This isn't a bad structure; it will work just fine. However, you do have to have functions in a function to do commands when someone clicks on a button or something
So what you could do is write classes for these then have methods in the class that handle commands for the button clicks and such.
Here's an example:
import tkinter as tk
class Window1:
def __init__(self, master):
pass
# Create labels, entries,buttons
def button_click(self):
pass
# If button is clicked, run this method and open window 2
class Window2:
def __init__(self, master):
#create buttons,entries,etc
def button_method(self):
#run this when button click to close window
self.master.destroy()
def main(): #run mianloop
root = tk.Tk()
app = Window1(root)
root.mainloop()
if __name__ == '__main__':
main()
Usually tk programs with multiple windows are multiple big classes and in the __init__
all the entries, labels etc are created and then each method is to handle button click events
There isn't really a right way to do it, whatever works for you and gets the job done as long as its readable and you can easily explain it because if you cant easily explain your program, there probably is a better way to do it.
Take a look at Thinking in Tkinter.
If you'd like to get the option with a value of 2, use
$("#list option[value='2']").text();
If you'd like to get whichever option is currently selected, use
$("#list option:selected").text();
I like the answers for this question. But to be creative, I would like to share one more way:
<script>if (document.URL.substring(0,5) == "http:") window.location.replace('https:' + document.URL.substring(5));</script>
@Giuseppe, you may want to consider this for a flexible specification of the plots arrangement (modified from here):
library(ggplot2)
library(gridExtra)
library(grid)
grid_arrange_shared_legend <- function(..., nrow = 1, ncol = length(list(...)), position = c("bottom", "right")) {
plots <- list(...)
position <- match.arg(position)
g <- ggplotGrob(plots[[1]] + theme(legend.position = position))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
gl <- lapply(plots, function(x) x + theme(legend.position = "none"))
gl <- c(gl, nrow = nrow, ncol = ncol)
combined <- switch(position,
"bottom" = arrangeGrob(do.call(arrangeGrob, gl),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight)),
"right" = arrangeGrob(do.call(arrangeGrob, gl),
legend,
ncol = 2,
widths = unit.c(unit(1, "npc") - lwidth, lwidth)))
grid.newpage()
grid.draw(combined)
}
Extra arguments nrow
and ncol
control the layout of the arranged plots:
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data = dsamp, colour = clarity)
p2 <- qplot(cut, price, data = dsamp, colour = clarity)
p3 <- qplot(color, price, data = dsamp, colour = clarity)
p4 <- qplot(depth, price, data = dsamp, colour = clarity)
grid_arrange_shared_legend(p1, p2, p3, p4, nrow = 1, ncol = 4)
grid_arrange_shared_legend(p1, p2, p3, p4, nrow = 2, ncol = 2)
Your change should work. However, there are potentially few php.ini configuration files with the 'xampp' stack. Try to identify whether or not there's an 'apache' specific php.ini. One potential location is:
C:\xampp\apache\bin\php.ini
What helped me was a look at the source code of the two functions.
Map - wraps the result in an Optional.
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value)); //<--- wraps in an optional
}
}
flatMap - returns the 'raw' object
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value)); //<--- returns 'raw' object
}
}
Use Google Search Operators to find it for you
search google with the below code..
inurl:domain.com filetype:xml click on this to view sitemap search example
change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)
A regular pipe can only connect two related processes. It is created by a process and will vanish when the last process closes it.
A named pipe, also called a FIFO for its behavior, can be used to connect two unrelated processes and exists independently of the processes; meaning it can exist even if no one is using it. A FIFO is created using the mkfifo()
library function.
writer.c
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write "Hi" to the FIFO */
fd = open(myfifo, O_WRONLY);
write(fd, "Hi", sizeof("Hi"));
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
reader.c
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
printf("Received: %s\n", buf);
close(fd);
return 0;
}
Note: Error checking was omitted from the above code for simplicity.
The exit()
and quit()
built in functions do just what you want. No import of sys needed.
Alternatively, you can raise SystemExit
, but you need to be careful not to catch it anywhere (which shouldn't happen as long as you specify the type of exception in all your try.. blocks).
Just a simplified version of @T.J. Crowder and @RegarBoy's answers.
Less is more in my opinion.
Check out onmousemove event for more info about the event.
There's a new value of posX
and posY
every time the mouse moves according to the horizontal and vertical coordinates.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example Mouse Tracker</title>
<style>
body {height: 3000px;}
.dot {width: 2px;height: 2px;background-color: black;position: absolute;}
</style>
</head>
<body>
<p>Mouse tracker</p>
<script>
onmousemove = function(e){
//Logging purposes
console.log("mouse location:", e.clientX, e.clientY);
//meat and potatoes of the snippet
var pos = e;
var dot;
dot = document.createElement('div');
dot.className = "dot";
dot.style.left = pos.x + "px";
dot.style.top = pos.y + "px";
document.body.appendChild(dot);
}
</script>
</body>
</html>
You can try using fast-export:
cd ~
git clone https://github.com/frej/fast-export.git
git init git_repo
cd git_repo
~/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
git checkout HEAD
Also have a look at this SO question.
If you're using Mercurial version below 4.6, adrihanu got your back:
As he stated in his comment: "In case you use Mercurial < 4.6 and you got "revsymbol not found" error. You need to update your Mercurial or downgrade fast-export by running git checkout tags/v180317 inside ~/fast-export directory.".
You can use a data-bound control like the Repeater
or ListView
, re-bind it to a list of control properties as needed, and let it generate the controls dynamically.
As an alternative, you can use Response.Redirect(".")
to re-load the same page.
I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path
But the main issue was not here. The problem was with these 2 lines of code
strFile = Dir(strPath & "*.csv")
Which should have written as
strFile = Dir(strPath & "\*.csv")
and
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Which should have written as
With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _
For those using Vue CLI 3 and the webpack-simple install, Aaron's answer did work for me however I wasn't keen on adding my environment variables to my webpack.config.js
as I wanted to commit it to GitHub. Instead I installed the dotenv-webpack plugin and this appears to load environment variables fine from a .env
file at the root of the project without the need to prepend VUE_APP_
to the environment variables.
Here my approach,it may be useful to others.
public static void compareArrays(int[] array1, int[] array2) {
if (array1.length != array2.length)
{
System.out.println("Not Equal");
}
else
{
int temp = 0;
for (int i = 0; i < array2.length; i++) { //Take any one of the array size
temp^ = array1[i] ^ array2[i]; //with help of xor operator to find two array are equal or not
}
if( temp == 0 )
{
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
}
}
I needed this same solution, but if you use the native ListObject.Add()
method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:
Sub AddDataRow(tableName As String, values() As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = ActiveWorkbook.Worksheets("Sheet1")
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
table.ListRows.Add
Exit For
End If
Next col
Else
table.ListRows.Add
End If
'Iterate through the last row and populate it with the entries from values()
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
Next col
End Sub
To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design
tab of the ribbon, in Excel 2013 at least:
Example code for a table with three columns:
Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x
exponent
is a 1D array. This means that exponent[0]
is a scalar, and exponent[0][i]
is trying to access it as if it were an array.
Did you mean to say:
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = exponent[i]
or even
L = diag(exponent)
?
In my case this format worked on latest version of jQuery:
$('img#post_image_preview').src;
You could do something along this lines:
def static_example():
if not hasattr(static_example, "static_var"):
static_example.static_var = 0
static_example.static_var += 1
return static_example.static_var
print static_example()
print static_example()
print static_example()
Given other answers are a few years old, currently here are my thoughts that may be helpful:
Simplest way
private async Task<string> PostAsync(Uri uri, HttpContent dataOut)
{
var client = new HttpClient();
var response = await client.PostAsync(uri, dataOut);
return await response.Content.ReadAsStringAsync();
// For non strings you can use other Content.ReadAs...() method variations
}
A More Practical Example
Often we are dealing with known types and JSON, so you can further extend this idea with any number of implementations, such as:
public async Task<T> PostJsonAsync<T>(Uri uri, object dtoOut)
{
var content = new StringContent(JsonConvert.SerializeObject(dtoOut));
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var results = await PostAsync(uri, content); // from previous block of code
return JsonConvert.DeserializeObject<T>(results); // using Newtonsoft.Json
}
An example of how this could be called:
var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);
Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat',
data = fake,
color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()
adjust his code:
Object.prototype.each = function(iterateFunc) {
var counter = 0,
keys = Object.keys(this),
currentKey,
len = keys.length;
var that = this;
var next = function() {
if (counter < len) {
currentKey = keys[counter++];
iterateFunc(currentKey, that[currentKey]);
next();
} else {
that = counter = keys = currentKey = len = next = undefined;
}
};
next();
};
({ property1: 'sdsfs', property2: 'chat' }).each(function(key, val) {
// do things
console.log(key);
});
Here's a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca. This one is using "DESede/ECB/PKCS7Padding" so I don't have to bother manually padding.
package com.zenimax.encryption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* @author Matthew H. Wagner
*/
public class TripleDesBouncyCastle {
private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";
private static String ALGORITHM = "DESede";
private static String BOUNCY_CASTLE_PROVIDER = "BC";
private static void init()
{
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] encode(byte[] input, byte[] key)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException {
init();
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
BOUNCY_CASTLE_PROVIDER);
encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
return encrypter.doFinal(input);
}
public static byte[] decode(byte[] input, byte[] key)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException {
init();
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
BOUNCY_CASTLE_PROVIDER);
decrypter.init(Cipher.DECRYPT_MODE, keySpec);
return decrypter.doFinal(input);
}
}
join
always return None
, i think you should subclass Thread
to handle return codes and so.
Here is my observation. I created a login (readonly) for a group windows(AD) user account but, its acting defiantly in different SQL servers. In the SQl servers that users can not see the databases I added view definition checked and also gave database execute permeation to the master database for avoiding error 229. I do not have this issue if I create a login for a user.
on ubuntu /etc/phpmyadmin/config-db.php
make sure the password matches your config.inc.php for the control user
also for the blowfish too short error
edit /var/lib/phpmyadmin/blowfish_secret.inc.php and make the key longer
You should use append("svg:svg")
, not append("svg")
so that D3 makes the element with the correct 'namespace' if you're using xhtml.
Pls, check if DataGridComboBoxColumn xaml below would work for you:
<DataGridComboBoxColumn
SelectedValueBinding="{Binding CompanyID}"
DisplayMemberPath="Name"
SelectedValuePath="ID">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
Here you can find another solution for the problem you're facing: Using combo boxes with the WPF DataGrid
If you want to return the altered document you need to set the option {new:true}
API reference you can use Cat.findOneAndUpdate(conditions, update, options, callback) // executes
Taken by the official Mongoose API http://mongoosejs.com/docs/api.html#findoneandupdate_findOneAndUpdate you can use the following parameters
A.findOneAndUpdate(conditions, update, options, callback) // executes
A.findOneAndUpdate(conditions, update, options) // returns Query
A.findOneAndUpdate(conditions, update, callback) // executes
A.findOneAndUpdate(conditions, update) // returns Query
A.findOneAndUpdate() // returns Query
Another implementation thats is not expressed in the official API page and is what I prefer to use is the Promise
base implementation that allow you to have .catch
where you can deal with all your various error there.
let cat: catInterface = {
name: "Naomi"
};
Cat.findOneAndUpdate({age:17}, cat,{new: true}).then((data) =>{
if(data === null){
throw new Error('Cat Not Found');
}
res.json({ message: 'Cat updated!' })
console.log("New cat data", data);
}).catch( (error) => {
/*
Deal with all your errors here with your preferred error handle middleware / method
*/
res.status(500).json({ message: 'Some Error!' })
console.log(error);
});
There is a bundled collection of Vim plugins for Python development: http://www.vim.org/scripts/script.php?script_id=3770
>>> list(x for x in string.letters if x in (y for y in "BigMan on campus"))
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']
I tried to adapt @Siddhart's code to a relative path to run my open_form
macro, but it didn't seem to work. Here was my first attempt. My working solution is below.
Option Explicit
Dim xlApp, xlBook
dim fso
dim curDir
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open(curDir & "Excels\CLIENTES.xlsb", 0, true)
xlApp.Run "open_form"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Echo "Finished."
EDIT
I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:
Issues I was facing:
1 - I did not want to use the Workbook_Open Event as the excel is locked in read only. 2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.
I first wrote a macro to launch my userform while hiding the application:
Sub open_form()
Application.Visible = False
frmAddClient.Show vbModeless
End Sub
I then created a vbs to launch this macro (doing it with a relative path has been tricky):
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"
And I finally did a batch file to execute the VBS...
@echo off
pushd %~dp0
cscript Add_Client.vbs
Note that I have also included the "Set back to visible" in my Userform_QueryClose
:
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
ThisWorkbook.Close SaveChanges:=True
Application.Visible = True
Application.Quit
End Sub
Anyway, thanks for your help, and I hope this will help if someone needs it
I found this on a Microsoft Support page http://support.microsoft.com/kb/2019698.
It works great! And since it came from Microsoft, I feel like it's pretty legit.
Basically there are two steps.
Schedule the backup from your task scheduler. You might want to put into a .bat or .cmd file first and then schedule that file.
sqlcmd -S YOUR_SERVER_NAME\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='C:\SQL_Backup\', @backupType='F'" 1>c:\SQL_Backup\backup.log
Obviously replace YOUR_SERVER_NAME with your computer name or optionally try .\SQLEXPRESS and make sure the backup folder exists. In this case it's trying to put it into c:\SQL_Backup
Try
UPDATE products SET former_date=20111218131717 WHERE id=1
Alternatively, you might want to look at using the STR_TO_DATE (see STR_TO_DATE(str,format)) function.
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
Server file only change name folder
etc/mysql
rename
mysql-
Paul's answer creates a new repository containing /ABC, but does not remove /ABC from within /XYZ. The following command will remove /ABC from within /XYZ:
git filter-branch --tree-filter "rm -rf ABC" --prune-empty HEAD
Of course, test it in a 'clone --no-hardlinks' repository first, and follow it with the reset, gc and prune commands Paul lists.
you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.
i.e:
datetime.Value
but check to see if it has a value first!
if (datetime.HasValue)
{
// work with datetime.Value
}
In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:
$ curl https://api.twitter.com/1/help/configuration.xml | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool
Tested on Ubuntu 11.0.4/11.10.
Another issue is the desired content type. Twitter uses .xml
/.json
extension, but more idiomatic REST would require Accept
header:
$ curl -H "Accept: application/json"
Use the following to jump to previous folder:
os.chdir(os.pardir)
If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.
The java.net.SocketException
is thrown when there is an error creating or accessing a socket (such as TCP). This usually can be caused when the server has terminated the connection (without properly closing it), so before getting the full response. In most cases this can be caused either by the timeout issue (e.g. the response takes too much time or server is overloaded with the requests), or the client sent the SYN, but it didn't receive ACK (acknowledgment of the connection termination). For timeout issues, you can consider increasing the timeout value.
The Socket Exception usually comes with the specified detail message about the issue.
Example of detailed messages:
Software caused connection abort: recv failed.
The error indicates an attempt to send the message and the connection has been aborted by your server. If this happened while connecting to the database, this can be related to using not compatible Connector/J JDBC driver.
Possible solution: Make sure you've proper libraries/drivers in your CLASSPATH.
Software caused connection abort: connect.
This can happen when there is a problem to connect to the remote. For example due to virus-checker rejecting the remote mail requests.
Possible solution: Check Virus scan service whether it's blocking the port for the outgoing requests for connections.
Software caused connection abort: socket write error.
Possible solution: Make sure you're writing the correct length of bytes to the stream. So double check what you're sending. See this thread.
Connection reset by peer: socket write error / Connection aborted by peer: socket write error
The application did not check whether keep-alive connection had been timed out on the server side.
Possible solution: Ensure that the HttpClient is non-null before reading from the connection.E13222_01
Connection reset by peer.
The connection has been terminated by the peer (server).
Connection reset.
The connection has been either terminated by the client or closed by the server end of the connection due to request with the request.
See: What's causing my java.net.SocketException: Connection reset?
In Windows 8.1 x64 bit os, Currently I am using MySQL
version :
Server version: 5.7.11-log MySQL Community Server (GPL)
For changing your MySQL
port number, Go to installation directory, my installation directory is :
C:\Program Files\MySQL\MySQL Server 5.7
open the my-default.ini
Configuration Setting file in any text editor.
search the line in the configuration file.
# port = .....
replace it with :
port=<my_new_port_number>
like my self changed to :
port=15800
To apply the changes don't forget to immediate either restart the MySQL Server or your OS.
Hope this would help many one.
I had the same problem on windows 10, IIS/10.0 was using port 80
To solve that:
French name is: "Service de publication World Wide Web"
English name is: "World Wide Web Publishing Service"
german name is: "WWW-Publishingdienst" – thanks @fiffy
Polish name is: "Usluga publikowania w sieci WWW" - thanks @KrzysDan
Russian name is "?????? ???-??????????" – thanks @Kreozot
Italian name is "Servizio Pubblicazione sul Web" – thanks @Claudio-Venturini
Español name is "Servicio de publicación World Wide Web" - thanks @Daniel-Santarriaga
Portuguese (Brazil) name is "Serviço de publicação da World Wide Web" - thanks @thiago-born
Alternatives :
sc stop W3SVC
Edit 07 oct 2015: For more details, see Matthew Stumphy's answer Apache Server (xampp) doesn't run on Windows 10 (Port 80)
There is one trick that can be used.The trick is to append a parameter/string to the file name in the script tag and change it when you file changes.
<script src="myfile.js?version=1.0.0"></script>
The browser interprets the whole string as the file path even though what comes after the "?" are parameters. So wat happens now is that next time when you update your file just change the number in the script tag on your website (Example <script src="myfile.js?version=1.0.1"></script>
) and each users browser will see the file has changed and grab a new copy.
For Scalar Function Syntax is
Select dbo.Function_Name(parameter_name)
Select dbo.Department_Employee_Count('HR')
<input data-ng-model="userInf.username" class="span12 editEmail" type="text" placeholder="[email protected]" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" required ng-disabled="true"/>
In Command Prompt, you can use the command telnet.. For Example, to connect to IP 192.168.10.1 with port 80,
telnet 192.168.10.1 80
To enable telnet in Windows 7 and above click. From the linked article, enable telnet through control panel -> programs and features -> windows features -> telnet client, or just run this in an admin prompt:
dism /online /Enable-Feature /FeatureName:TelnetClient
I usually create log table with a stored procedure to log to it. The call the logging procedure wherever needed from the procedure under development.
Looking at other posts on this same question, it seems like a common practice, although there are some alternatives.
On your existing button code, simply insert this line before the procedure:
If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub
This will force it to quit if the user presses no.
int size = (&arr)[1] - arr;
Check out this link for explanation
Sometimes, you just want to have a look at previous copies of files without the rigmarole of going through the diffs.
In such a case, it's just as easy to make a clone of a repository and checkout the specific commit that you are interested in and have a look at the subdirectory in that cloned repository. Because everything is local you can just delete this clone when you are done.
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
As the above people stated, select PostGIS_full_version(); will answer your question. On my machine, where I'm running PostGIS 2.0 from trunk, I get the following output:
postgres=# select PostGIS_full_version();
postgis_full_version
-------------------------------------------------------------------------------------------------------------------------------------------------------
POSTGIS="2.0.0alpha4SVN" GEOS="3.3.2-CAPI-1.7.2" PROJ="Rel. 4.7.1, 23 September 2009" GDAL="GDAL 1.8.1, released 2011/07/09" LIBXML="2.7.3" USE_STATS
(1 row)
You do need to care about the versions of PROJ and GEOS that are included if you didn't install an all-inclusive package - in particular, there's some brokenness in GEOS prior to 3.3.2 (as noted in the postgis 2.0 manual) in dealing with geometry validity.
Don't know if this is too late but you can use np.where to find the indices of non values as such:
indices = list(np.where(df['b'].isna()[0]))
I finally got this to work on my own hosted xampp windows 10 server web site. I.e. padlocks came up as ssl. I am using xampp version from November 2020.
Went to certbot.eff.org. Selected from their home page software [apache] and system [windows]. Then downloaded and installed certbot software found at the next page into my C drive.
Then from command line [cmd in Windows Start and then before you open cmd right click to run cmd as admin] I enhtered the command from Certbot page above. I.e. navigated to system32-- C:\WINDOWS\system32> certbot certonly --standalone
Then followed the prompts and enteredmy domain name. This created certs as cert1.pem and key1.pem in C:\Certbot yourwebsitedomain folder. the cmd windows tells you where these are.
Then took these and changed their names from cert1.pem to my domainname or shorter+cert.pem and same for domainname or shorter+key.key. Copied these into C:\xampp\apache\ssl.crt and ssl.key folders respectively.
Then for G:\xampp\apache\conf\extra\httpd-vhosts entered the following:
<VirtualHost *:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainname.hopto.org/public/" ###NB My document root is public. Yours may not be. Or could have an index.php page before /public###
ServerName yourwebsitedomainnamee.hopto.org
<Directory G:/xampp/htdocs/yourwebsitedomainname.hopto.org>
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
ErrorLog "G:/xampp/apache/logs/error.log"
CustomLog "G:/xampp/apache/logs/access.log" common
SSLEngine on
SSLCertificateFile "G:\xampp\apache\conf\ssl.crt\abscert.pem"
SSLCertificateKeyFile "G:\xampp\apache\conf\ssl.key\abskey.pem"
</VirtualHost>
<VirtualHost _default_:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainnamee.hopto.org/public/"
###NB My document root is public. Yours may not be. Or could have an index.php page before /public###
SSLEngine on
SSLCertificateFile "conf/ssl.crt/abscert.pem"
SSLCertificateKeyFile "conf/ssl.key/abskey.pem"
CustomLog "G:/xampp/apache/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
Note1. I used www.noip.com to register the domain name. Note2. Rather then try to get them to give me a ssl certificate, as I could not get it to work, the above worked instead. Note3 I use the noip DUC software to keep my personally hosted web site in sync with noip. Note4. Very important to stop and start xampp server after each change you make in xampp. If xampp fails for some reason instead of starting the xampp consol try the start xampp as this will give you problems you can bug fix. Copy these quickly and paste into note.txt.
Using your example, here are two ways to accomplish this:
Note that this code will work with or without mapping. If you turn off mapping on the entity, EF will generate an insert + select statement.
protected void btnSave_Click(object sender, EventArgs e)
{
using (var db = DepartmentContext() )
{
var department = new Department();
department.Name = txtDepartment.text.trim();
db.Departments.add(department);
db.SaveChanges();
// EF will populate department.DepartmentId
int departmentID = department.DepartmentId;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
using (var db = DepartmentContext() )
{
var name = new SqlParameter("@name", txtDepartment.text.trim());
//to get this to work, you will need to change your select inside dbo.insert_department to include name in the resultset
var department = db.Database.SqlQuery<Department>("dbo.insert_department @name", name).SingleOrDefault();
//alternately, you can invoke SqlQuery on the DbSet itself:
//var department = db.Departments.SqlQuery("dbo.insert_department @name", name).SingleOrDefault();
int departmentID = department.DepartmentId;
}
}
I recommend using the first approach, as you can work with the department object directly and not have to create a bunch of SqlParameter objects.
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
.on() is for jQuery version 1.7 and above. If you have an older version, use this:
$("#SomeId").live("click",function(){
//do stuff;
});
git log
's pickaxe will find commits with changes including "word" with git log -Sword
According to K&R 2nd edition the results are implementation-dependent for right shifts of signed values.
Wikipedia says that C/C++ 'usually' implements an arithmetic shift on signed values.
Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift.
Taking a guess at the results you want so maybe this is the query you want then
SELECT DISTINCT a FROM my_table
UNION
SELECT DISTINCT b FROM my_table
UNION
SELECT DISTINCT c FROM my_table
UNION
SELECT DISTINCT d FROM my_table
Should update the figure caption automatically.
My question is tho, how can one also 'assign' referenced figures '(Fig.4)' in the text to do the same thing - aka change when an image is added above it?
EDIT: Figured it out.. In word go to Insert and Cross-ref and assign the ref. Then Ctrl+A and F9 and everything should sort itself out.
For Windows 7, I just rename the python.exe
from the Python 3 folder to python3.exe
and add the path into the environment variables. Using that, I can execute python test_script.py
and the script runs with Python 2.7 and when I do python3 test_script.py
, it runs the script in Python 3.
To add Python 3
to the environment variables, follow these steps -
Properties
.Advanced System Settings
.Environment Variables
and edit PATH
and add the path to your Python 3 installation directory.For example,
For directions on creating a token, go here This is the command you will type (as of the date of this answer. (replace all CAPS keywords):
curl -u 'YOUR_USERNAME' -d '{"scopes":["repo"],"note":"YOUR_NOTE"}' https://api.github.com/authorizations
Once you enter your password you will see the following which contains your token.
{
"app": {
"name": "YOUR_NOTE (API)",
"url": "http://developer.github.com/v3/oauth/#oauth-authorizations-api"
},
"note_url": null,
"note": "YOUR_NOTE",
"scopes": [
"repo"
],
"created_at": "2012-10-04T14:17:20Z",
"token": "xxxxx",
"updated_at": "2012-10-04T14:17:20Z",
"id": xxxxx,
"url": "https://api.github.com/authorizations/697577"
}
You can revoke your token anytime by going here
More precise Kotlin code using handler :
Handler(Looper.getMainLooper()).post {
// your codes here run on main Thread
}
If, like me, you are trying to use GETDATE()
within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime
), then I found this expression to work:
@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-" + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-" + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)
I found this code snippet HERE
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field.
One solution would be this:
LOCK TABLES
favorite_food WRITE,
person WRITE;
ALTER TABLE favorite_food
DROP FOREIGN KEY fk_fav_food_person_id,
MODIFY person_id SMALLINT UNSIGNED;
Now you can change you person_id
ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
recreate foreign key
ALTER TABLE favorite_food
ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)
REFERENCES person (person_id);
UNLOCK TABLES;
EDIT: Added locks above, thanks to comments
You have to disallow writing to the database while you do this, otherwise you risk data integrity problems.
I've added a write lock above
All writing queries in any other session than your own ( INSERT, UPDATE, DELETE
) will wait till timeout or UNLOCK TABLES
; is executed
http://dev.mysql.com/doc/refman/5.5/en/lock-tables.html
EDIT 2: OP asked for a more detailed explanation of the line "The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field."
From MySQL 5.5 Reference Manual: FOREIGN KEY Constraints
Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.
Below query can be used to find the nth maximum value, just replace 2 from nth number
select * from emp e1 where 2 =(select count(distinct(salary)) from emp e2
where e2.emp >= e1.emp)
In Eclipse Photon navigate to Windows > Preferences > Maven > User Settings > User Setting
For "User settings" Browse to the settings.xml of the maven. ex. in my case maven it is located on the path C:\Program Files\Apache Software Distribution\apache-maven-3.5.4\conf\Settings.xml
Depending on the Settings.xml the Local Repository gets automatically configured to the specified location.
I had same problem with laravel and artisan, the solution:
php artisan key:generate
I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.
Have you tried compiling from the command line?
I have the exact same version:
Probably you're thinking the warning is an error.
UPDATE
It looks like you have a Arrays.class
file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class
From the YouTube help:
You will automatically be opted into showing ads on embedded videos if you've associated your YouTube and AdSense accounts and have enabled your videos for embedding.
If you don't want to show overlay ads on your embedded videos, you can opt your videos out of showing overlay ads, though this will also disable overlay ads on your videos on YouTube.com. You may also disable your videos for embedding.
https://support.google.com/youtube/answer/132596?hl=en
Another technical solution could be to use a custom video player, and streamline the youtube video with that one. Have not tried but guess that the ads cannot be displayed in a custom player. However, could be forbidden.
This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.
Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection
' This code only strips attachments from mail items.
' If objMsg.class=olMail Then
' Get the Attachments collection of the item.
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
strDeletedFiles = ""
If lngCount > 0 Then
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
' Save attachment before deleting from item.
' Get the file name.
strFile = objAttachments.Item(i).FileName
' Combine with the path to the Temp folder.
strFile = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
' Delete the attachment.
objAttachments.Item(i).Delete
'write the save as path to a string to add to the message
'check for html and use html tags in link
If objMsg.BodyFormat <> olFormatHTML Then
strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
Else
strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
strFile & "'>" & strFile & "</a>"
End If
'Use the MsgBox command to troubleshoot. Remove it from the final code.
'MsgBox strDeletedFiles
Next i
' Adds the filename string to the message body and save it
' Check for HTML body
If objMsg.BodyFormat <> olFormatHTML Then
objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
Else
objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
End If
objMsg.Save
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
I wrote a function for my own project to do this (it doesn't use numpy, though):
def partition(seq, chunks):
"""Splits the sequence into equal sized chunks and them as a list"""
result = []
for i in range(chunks):
chunk = []
for element in seq[i:len(seq):chunks]:
chunk.append(element)
result.append(chunk)
return result
If you want the chunks to be randomized, just shuffle the list before passing it in.
Shorter and dealing with a column (entire, not just a section of a column):
=COUNTA(A:A)
Beware, a cell containing just a space would be included in the count.
The way below will identify dupe columns to review what is going wrong building the dataframe originally.
dupes = pd.DataFrame(df.columns)
dupes[dupes.duplicated()]
What all should I know about web.xml apart from element name and their usage ?
The SINGLE most important JSP configuration parameter of ALL TIME is in your web.xml. Ladies and gentlemen, I give you... the TRIM-DIRECTIVE-WHITESPACES option!
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
</jsp-property-group>
</jsp-config>
This removes all the hundreds or thousands of lines of white space that you'll get in your generated HTML if you use any tag libraries (loops are particularly ugly & wasteful).
The other big one is the default web page (the page you get automatically sent to when you don't enter a web page in the URL):
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
For C++11, here is a simple wrapper:
#include <iostream>
#include <chrono>
class Timer
{
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const {
return std::chrono::duration_cast<second_>
(clock_::now() - beg_).count(); }
private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};
Or for C++03 on *nix,
class Timer
{
public:
Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }
double elapsed() {
clock_gettime(CLOCK_REALTIME, &end_);
return end_.tv_sec - beg_.tv_sec +
(end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
}
void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }
private:
timespec beg_, end_;
};
Example of usage:
int main()
{
Timer tmr;
double t = tmr.elapsed();
std::cout << t << std::endl;
tmr.reset();
t = tmr.elapsed();
std::cout << t << std::endl;
return 0;
}
Process Hacker has numerous ways of killing a process.
(Right-click the process, then go to Miscellaneous->Terminator.)
How about storing the alerts as records in an array instead of properties of a single object ?
var alerts = [
{num : 1, app:'helloworld',message:'message'},
{num : 2, app:'helloagain',message:'another message'}
]
And then to add one, just use push
:
alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});
This is my favorite approach...
_dataGrid.DataBindingComplete += (o, _) =>
{
var dataGridView = o as DataGridView;
if (dataGridView != null)
{
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView.Columns[dataGridView.ColumnCount-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
};
Assuming you're talking about round the value for printing, then Andrew Coleson and AraK's answer are correct:
printf("%.2f", 37.777779);
But note that if you're aiming to round the number to exactly 37.78 for internal use (eg to compare against another value), then this isn't a good idea, due to the way floating point numbers work: you usually don't want to do equality comparisons for floating point, instead use a target value +/- a sigma value. Or encode the number as a string with a known precision, and compare that.
See the link in Greg Hewgill's answer to a related question, which also covers why you shouldn't use floating point for financial calculations.
(I don't have enough reputation to comment this on the top post, so I hope someone else can do that for me.) There was a concern raised that the first method:
df.sample(frac=1)
made a deep copy or just changed the dataframe. I ran the following code:
print(hex(id(df)))
print(hex(id(df.sample(frac=1))))
print(hex(id(df.sample(frac=1).reset_index(drop=True))))
and my results were:
0x1f8a784d400
0x1f8b9d65e10
0x1f8b9d65b70
which means the method is not returning the same object, as was suggested in the last comment. So this method does indeed make a shuffled copy.
A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:
from tkinter import Frame, Tk
class MyApp():
def __init__(self):
self.root = Tk()
self.my_frame_red = Frame(self.root, bg='red')
self.my_frame_red.grid(row=0, column=0, sticky='nsew')
self.my_frame_blue = Frame(self.root, bg='blue')
self.my_frame_blue.grid(row=0, column=1, sticky='nsew')
self.root.grid_rowconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.root.mainloop()
if __name__ == '__main__':
app = MyApp()
But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.
for simple setups, you can provide ssh access to a central server, and set up each user's working directory to push/pull from this 'origin'. That would be the most simple and common setup for small teams.
You might also look into gitosis which gives you an http server and the ability to manage it remotely. That way you don't have to grant ssh access and all that entails to each committer.
For Android 7, Galaxy S6 Edge:
If Developer Options is not available then
Now perform step 1. Now it should work, if its still not working then perform these steps. It worked for me.
You should deploy "Client Profile" instead of "Full Framework" inside a corporation mostly in one case only: you want explicitly deny some .NET features are running on the client computers. The only real case is denying of ASP.NET on the client machines of the corporation, for example, because of security reasons or the existing corporate policy.
Saving of less than 8 MB on client computer can not be a serious reason of "Client Profile" deployment in a corporation. The risk of the necessity of the deployment of the "Full Framework" later in the corporation is higher than costs of 8 MB per client.
I was trying to use @class "Myclass.h"
.
When I changed it to #import "Myclass.h"
, it worked fine.
$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")
Use prepared statements, do not use mysql as it is deprecated.
// check if name is taken already
$stmt = $link->prepare("SELECT username FROM users WHERE username = :username");
$stmt->execute([
'username' => $username
]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (isset($user) && !empty($user)){
// Username already taken
}
DateTime.FromFileTime
should do the trick:
PS C:\> [datetime]::FromFileTime(129948127853609000)
Monday, October 15, 2012 3:13:05 PM
Then depending on how you want to format it, check out standard and custom datetime format strings.
PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('d MMMM')
15 October
PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('g')
10/15/2012 3:13 PM
If you want to integrate this into your one-liner, change your select
statement to this:
... | Select Name, manager, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}} | ...
EDIT: For a better description, see x86 Disassembly/Functions and Stack Frames in a WikiBook about x86 assembly. I try to add some info you might be interested in using Visual Studio.
Storing the caller EBP as the first local variable is called a standard stack frame, and this may be used for nearly all calling conventions on Windows. Differences exist whether the caller or callee deallocates the passed parameters, and which parameters are passed in registers, but these are orthogonal to the standard stack frame problem.
Speaking about Windows programs, you might probably use Visual Studio to compile your C++ code. Be aware that Microsoft uses an optimization called Frame Pointer Omission, that makes it nearly impossible to do walk the stack without using the dbghlp library and the PDB file for the executable.
This Frame Pointer Omission means that the compiler does not store the old EBP on a standard place and uses the EBP register for something else, therefore you have hard time finding the caller EIP without knowing how much space the local variables need for a given function. Of course Microsoft provides an API that allows you to do stack-walks even in this case, but looking up the symbol table database in PDB files takes too long for some use cases.
To avoid FPO in your compilation units, you need to avoid using /O2 or need to explicitly add /Oy- to the C++ compilation flags in your projects. You probably link against the C or C++ runtime, which uses FPO in the Release configuration, so you will have hard time to do stack walks without the dbghlp.dll.
Those who are using create-react-app
and trying to fetch local json files.
As in create-react-app
, webpack-dev-server
is used to handle the request and for every request it serves the index.html
. So you are getting
SyntaxError: Unexpected token < in JSON at position 0.
To solve this, you need to eject the app and modify the webpack-dev-server
configuration file.
You can follow the steps from here.
My answer is focused to a extended case derived from the one exposed at top.
Suppose you have group of elements from which you want to hide the child elements except first. As an example:
<html>
<div class='some-group'>
<div class='child child-0'>visible#1</div>
<div class='child child-1'>xx</div>
<div class='child child-2'>yy</div>
</div>
<div class='some-group'>
<div class='child child-0'>visible#2</div>
<div class='child child-1'>aa</div>
<div class='child child-2'>bb</div>
</div>
</html>
We want to hide all .child
elements on every group. So this will not help because will hide all .child
elements except visible#1
:
$('.child:not(:first)').hide();
The solution (in this extended case) will be:
$('.some-group').each(function(i,group){
$(group).find('.child:not(:first)').hide();
});
Try this one.
public static string GetFQDN()
{
string domainName = NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
string fqdn;
if (!hostName.Contains(domainName))
fqdn = hostName + "." +domainName;
else
fqdn = hostName;
return fqdn;
}
The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):
VARCHAR(65535) However, note that the limit is lower if you use a multi-byte character set:
VARCHAR(21844) CHARACTER SET utf8
Usually this is due to another directive in-between your ng-controller and your input that is creating a new scope. When the select writes out it value, it will write it up to the most recent scope, so it would write it to this scope rather than the parent that is further away.
The best practice is to never bind directly to a variable on the scope in an
ng-model
, this is also known as always including a "dot" in your ngmodel. For a better explanation of this, check out this video from John:
Solution from: https://groups.google.com/forum/#!topic/angular/7Nd_me5YrHU
yes you can use MapView in v2... for further details you can get help from this
https://gist.github.com/joshdholtz/4522551
SomeFragment.java
public class SomeFragment extends Fragment implements OnMapReadyCallback{
MapView mapView;
GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return v;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
/*
//in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
*/
// Updates the location and zoom of the MapView
/*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);*/
map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));
}
@Override
public void onResume() {
mapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_key"/>
<activity
android:name=".HomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
some_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Python's string
library has isdigit()
method:
string[0].isdigit()
In Rails 3.2 and Rails 4, Benjamin's popular answer has a slightly different syntax.
First in your terminal:
$ rails g migration change_date_format_in_my_table
Then in your migration file:
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def up
change_column :my_table, :my_column, :datetime
end
def down
change_column :my_table, :my_column, :date
end
end
CAST uses ANSI standard. In case of portability, this will work on other platforms. CONVERT is specific to sql server. But is very strong function. You can specify different styles for dates
I encountered the same problem when doing:
curl -L https://packagecloud.io/golang-migrate/migrate/gpgkey | apt-key add -
The above query needs to be executed using root privileges.
Writing it in following way solved the issue for me:
curl -L https://packagecloud.io/golang-migrate/migrate/gpgkey | sudo apt-key add -
If you write sudo
before curl
, you will get the Failed writing body
error.
Even though I am 3 years late, but to simplify Guffa's example, you don't even need to have the form on the page at all:
$('<form method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something">
...
</form>').submit();
Edited:
$('<form method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something">
...
</form>').appendTo('body').submit().remove();
Maybe a helpful tip for someone :)
I want to chime in here even though this question has already been answered correctly by @pscl in case anyone else runs into the same issue I did. Out of the 4 methods give I chose to use the es6 syntax with arrow functions due to it's conciseness and lack of dependence on external libraries:
Using Array.prototype.filter with ES6 Arrow Functions
removeItem(index) {
this.setState((prevState) => ({
data: prevState.data.filter((_, i) => i != index)
}));
}
As you can see I made a slight modification to ignore the type of index (!==
to !=
) because in my case I was retrieving the index from a string field.
Another helpful point if you're seeing weird behavior when removing an element on the client side is to NEVER use the index of an array as the key for the element:
// bad
{content.map((content, index) =>
<p key={index}>{content.Content}</p>
)}
When React diffs with the virtual DOM on a change, it will look at the keys to determine what has changed. So if you're using indices and there is one less in the array, it will remove the last one. Instead, use the id's of the content as keys, like this.
// good
{content.map(content =>
<p key={content.id}>{content.Content}</p>
)}
The above is an excerpt from this answer from a related post.
Happy Coding Everyone!
I've made some changes to the second most popular answer as i found this worked better for me. The changes use window.innerHeight as it is more dynamic than adding your own height for the nav (above used + 570). this allows the code to work on mobile, tablet and desktop dynamicly.
$(window).scroll(() => {
//Distance from top fo document to top of footer
topOfFooter = $('#footer').position().top;
// Distance user has scrolled from top + windows inner height
scrollDistanceFromTopOfDoc = $(document).scrollTop() + window.innerHeight;
// Difference between the two.
scrollDistanceFromTopOfFooter = scrollDistanceFromTopOfDoc - topOfFooter;
// If user has scrolled further than footer,
if (scrollDistanceFromTopOfDoc > topOfFooter) {
// add margin-bottom so button stays above footer.
$('#floating-button').css('margin-bottom', 0 + scrollDistanceFromTopOfFooter);
} else {
// remove margin-bottom so button goes back to the bottom of the page
$('#floating-button').css('margin-bottom', 0);
}
});
Just read the rabbitmq tutorial. You publish message to exchange, not to queue; it is then routed to appropriate queues. In your case, you should bind separate queue for each consumer. That way, they can consume messages completely independently.
I tried the solutions mentioned but still failed. I found the solution that finally worked for me here - removing then re-adding the remote link
The ++
class of operators are expressions with side effects. This is something generally not found in Python.
For the same reason an assignment is not an expression in Python, thus preventing the common if (a = f(...)) { /* using a here */ }
idiom.
Lastly I suspect that there operator are not very consistent with Pythons reference semantics. Remember, Python does not have variables (or pointers) with the semantics known from C/C++.
As others mentioned using epel
gives a really outdated version, here is a little script I just wrote instead to add to the CI pipeline or pass it to ec2 user-data
to install the latest version of node, simply replace the version
with what you want, and the appropriate distro
of Linux you are using.
The following example is for amazon-Linux-2-AMI
#!/bin/bash
version='v14.13.1'
distro='linux-x64'
package_name="node-$version-$distro"
package_location="/usr/local/lib/"
curl -O https://nodejs.org/download/release/latest/$package_name.tar.gz
tar -xvf $package_name.tar.gz -C $package_location
rm -rfv $package_name.tar.gz
echo "export PATH=$package_location/$package_name/bin:\$PATH" >> ~/.profile
if you want to test it in the same shell simply run
. ~/.profile
Since you have written a function named foo
and you know it is in myfile.js
why do you need to get this information dynamically?
That being said you can use arguments.callee.toString()
inside the function (this is a string representation of the entire function) and regex out the value of the function name.
Here is a function that will spit out its own name:
function foo() {
re = /^function\s+([^(]+)/
alert(re.exec(arguments.callee.toString())[1]);
}
From the Jquery docs (link):
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
Script and JSONP requests are not subject to the same origin policy restrictions.
So I would take it that you need to use jsonp for the request. But haven't tried this myself.
You can optionally actually use the get
method of a dict
:
x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2)
You don't need the get
method if one of the keys is guaranteed to evaluate to True
:
x = {i<0: -1, i==0: 0, i>0: 1}[True]
At most one of the keys should ideally evaluate to True
. If more than one key evaluates to True
, the results could seem unpredictable.
I see some of the above answers are now a bit out of date. From my perspective, and I work with both Solr(Cloud and non-Cloud) and ElasticSearch on a daily basis, here are some interesting differences:
For more thorough coverage of Solr vs. ElasticSearch topic have a look at https://sematext.com/blog/solr-vs-elasticsearch-part-1-overview/ . This is the first post in the series of posts from Sematext doing direct and neutral Solr vs. ElasticSearch comparison. Disclosure: I work at Sematext.
This is how the JDK does it (adapted from OpenJDK 8, String.java/regionMatches):
static boolean charactersEqualIgnoringCase(char c1, char c2) {
if (c1 == c2) return true;
// If characters don't match but case may be ignored,
// try converting both characters to uppercase.
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) return true;
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we need to make one last check before
// exiting.
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
I suppose that works for Turkish too.
You can use Local storage.
local storage is same as session. the data will be removed when you close the browser.
<script>
localStorage.setItem('lastname','Smith');
alert(localStorage.getItem('lastname'));
</script>
Edit: @Naveen comment below is correct. You can use session storage instead. (https://www.w3schools.com/jsref/prop_win_sessionstorage.asp) Thanks.
<script>
sessionStorage.setItem('lastname','Smith');
alert(sessionStorage.getItem('lastname'));
</script>
a. You can use environment variables via terminal:
$ docker run -d --name container_name \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
mongo
If you like to test if everything works:
// ssh into the running container
// Change container name if necessary
$ docker exec -it mongo /bin/bash
// Enter into mongo shell
$ mongo
// Caret will change when you enter successfully
// Switch to admin database
$> use admin
$> db.auth("admin", passwordPrompt())
// Show available databases
$> show dbs
If you like to instantiate a database on first run, check option b.
b. You can use environment variables in your docker stack deploy file or compose file for versions 3.4 through 4.1.
As it is explained on the quick reference section of the official mongo image set MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
in your yaml file:
mongo:
image: mongo
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
docker-entrypoint.sh file in mongo image checks for the existence of these two variables and sets --auth
flag accordingly.
c. You can also use docker secrets.
MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
is set indirectly by docker-entrypoint.sh from MONGO_INITDB_ROOT_USERNAME_FILE
and MONGO_INITDB_ROOT_PASSWORD_FILE
variables:
mongo:
image: mongo
environment:
- MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/db_root_username
- MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/db_root_password
secrets:
- db_root_username
- db_root_password
docker-entrypoint.sh converts MONGO_INITDB_ROOT_USERNAME_FILE
and MONGO_INITDB_ROOT_PASSWORD_FILE
to MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
.
You can use MONGO_INITDB_ROOT_USERNAME
and MONGO_INITDB_ROOT_PASSWORD
in your .sh
or .js
scripts in docker-entrypoint-initdb.d
folder while initializing database instance.
When a container is started for the first time it will execute files with extensions .sh
and .js
that are found in /docker-entrypoint-initdb.d
. Files will be executed in alphabetical order. .js
files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE
variable, if it is present, or test otherwise. You may also switch databases within the .js
script.
This last method is not in the reference docs, so it may not survive an update.
if you are using PyCharm, when you open or clone the project into the PyCharm it shows an alert and ask you for installing all necessary packages.
Since you didn't mention the version of Eclipse, I advice you to download the latest version of Eclipse Luna
which comes with Java 8 support by default.
I have solved this as follows:
Window > Customize Perspective... (you will see Android and AVD Manager are disabled)
Command Groups Availability > Android and AVD Manager > check
Tool Bar Visibility > Android and AVD Manager > check
A JavaScript Date has several methods allowing you to extract its parts:
getFullYear()
- Returns the 4-digit year
getMonth()
- Returns a zero-based integer (0-11) representing the month of the year.
getDate()
- Returns the day of the month (1-31).
getDay()
- Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours()
- Returns the hour of the day (0-23).
getMinutes()
- Returns the minute (0-59).
getSeconds()
- Returns the second (0-59).
getMilliseconds()
- Returns the milliseconds (0-999).
getTimezoneOffset()
- Returns the number of minutes between the machine local time and UTC.
There are no built-in methods allowing you to get localized strings like "Friday", "February", or "PM". You have to code that yourself. To get the string you want, you at least need to store string representations of days and months:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
Then, put it together using the methods above:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];_x000D_
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];_x000D_
var d = new Date();_x000D_
var day = days[d.getDay()];_x000D_
var hr = d.getHours();_x000D_
var min = d.getMinutes();_x000D_
if (min < 10) {_x000D_
min = "0" + min;_x000D_
}_x000D_
var ampm = "am";_x000D_
if( hr > 12 ) {_x000D_
hr -= 12;_x000D_
ampm = "pm";_x000D_
}_x000D_
var date = d.getDate();_x000D_
var month = months[d.getMonth()];_x000D_
var year = d.getFullYear();_x000D_
var x = document.getElementById("time");_x000D_
x.innerHTML = day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
_x000D_
<span id="time"></span>
_x000D_
I have a date format function I like to include in my standard library. It takes a format string parameter that defines the desired output. The format strings are loosely based on .Net custom Date and Time format strings. For the format you specified the following format string would work: "dddd h:mmtt d MMM yyyy"
.
var d = new Date();
var x = document.getElementById("time");
x.innerHTML = formatDate(d, "dddd h:mmtt d MMM yyyy");
Demo: jsfiddle.net/BNkkB/1
Here is my full date formatting function:
function formatDate(date, format, utc) {
var MMMM = ["\x00", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var MMM = ["\x01", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dddd = ["\x02", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var ddd = ["\x03", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function ii(i, len) {
var s = i + "";
len = len || 2;
while (s.length < len) s = "0" + s;
return s;
}
var y = utc ? date.getUTCFullYear() : date.getFullYear();
format = format.replace(/(^|[^\\])yyyy+/g, "$1" + y);
format = format.replace(/(^|[^\\])yy/g, "$1" + y.toString().substr(2, 2));
format = format.replace(/(^|[^\\])y/g, "$1" + y);
var M = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
format = format.replace(/(^|[^\\])MMMM+/g, "$1" + MMMM[0]);
format = format.replace(/(^|[^\\])MMM/g, "$1" + MMM[0]);
format = format.replace(/(^|[^\\])MM/g, "$1" + ii(M));
format = format.replace(/(^|[^\\])M/g, "$1" + M);
var d = utc ? date.getUTCDate() : date.getDate();
format = format.replace(/(^|[^\\])dddd+/g, "$1" + dddd[0]);
format = format.replace(/(^|[^\\])ddd/g, "$1" + ddd[0]);
format = format.replace(/(^|[^\\])dd/g, "$1" + ii(d));
format = format.replace(/(^|[^\\])d/g, "$1" + d);
var H = utc ? date.getUTCHours() : date.getHours();
format = format.replace(/(^|[^\\])HH+/g, "$1" + ii(H));
format = format.replace(/(^|[^\\])H/g, "$1" + H);
var h = H > 12 ? H - 12 : H == 0 ? 12 : H;
format = format.replace(/(^|[^\\])hh+/g, "$1" + ii(h));
format = format.replace(/(^|[^\\])h/g, "$1" + h);
var m = utc ? date.getUTCMinutes() : date.getMinutes();
format = format.replace(/(^|[^\\])mm+/g, "$1" + ii(m));
format = format.replace(/(^|[^\\])m/g, "$1" + m);
var s = utc ? date.getUTCSeconds() : date.getSeconds();
format = format.replace(/(^|[^\\])ss+/g, "$1" + ii(s));
format = format.replace(/(^|[^\\])s/g, "$1" + s);
var f = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
format = format.replace(/(^|[^\\])fff+/g, "$1" + ii(f, 3));
f = Math.round(f / 10);
format = format.replace(/(^|[^\\])ff/g, "$1" + ii(f));
f = Math.round(f / 10);
format = format.replace(/(^|[^\\])f/g, "$1" + f);
var T = H < 12 ? "AM" : "PM";
format = format.replace(/(^|[^\\])TT+/g, "$1" + T);
format = format.replace(/(^|[^\\])T/g, "$1" + T.charAt(0));
var t = T.toLowerCase();
format = format.replace(/(^|[^\\])tt+/g, "$1" + t);
format = format.replace(/(^|[^\\])t/g, "$1" + t.charAt(0));
var tz = -date.getTimezoneOffset();
var K = utc || !tz ? "Z" : tz > 0 ? "+" : "-";
if (!utc) {
tz = Math.abs(tz);
var tzHrs = Math.floor(tz / 60);
var tzMin = tz % 60;
K += ii(tzHrs) + ":" + ii(tzMin);
}
format = format.replace(/(^|[^\\])K/g, "$1" + K);
var day = (utc ? date.getUTCDay() : date.getDay()) + 1;
format = format.replace(new RegExp(dddd[0], "g"), dddd[day]);
format = format.replace(new RegExp(ddd[0], "g"), ddd[day]);
format = format.replace(new RegExp(MMMM[0], "g"), MMMM[M]);
format = format.replace(new RegExp(MMM[0], "g"), MMM[M]);
format = format.replace(/\\(.)/g, "$1");
return format;
};
I have same problem!
Found following in oracle site link text
As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.
If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.
Update in 2019:
This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.
Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!
the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e
cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>
i could then use mstsc /v:<server>
without getting prompted for the login.
One can rename indexes the same way:
alter index owner.index_name rename to new_name;
The fact that Angular allows DOM manipulation means that the input markup into the compilation process sometimes differ from the output. Particularly, some input markup may be cloned a few times (like with ng-repeat
) before being rendered to the DOM.
Angular terminology is a bit inconsistent, but it still distinguishes between two types of markups:
The following markup demonstrates this:
<div ng-repeat="i in [0,1,2]">
<my-directive>{{i}}</my-directive>
</div>
The source html defines
<my-directive>{{i}}</my-directive>
which serves as the source template.
But as it is wrapped within an ng-repeat
directive, this source template will be cloned (3 times in our case). These clones are instance template, each will appear in the DOM and be bound to the relevant scope.
Turn on Client Statistics by doing one of the following:
Then you get a new tab which records the timings, IO data and rowcounts etc for (up to) the last 10 exections (plus averages!):
I had this today, and in my case the issue was very odd:
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Host.SystemWeb" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0" newVersion="3.1.0.0" />
</dependentAssembly>0.
Note the stray characters at the end of the XML - somehow those had been moved from the version number to the end of this block of XML!
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Host.SystemWeb" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
Changed to the above and voila! Everything worked again.