With Windows 2012 R2 (Win 8.1) and up, you also have the "official" Import-PfxCertificate cmdlet
Here are some essential parts of code (an adaptable example):
Invoke-Command -ComputerName $Computer -ScriptBlock {
param(
[string] $CertFileName,
[string] $CertRootStore,
[string] $CertStore,
[string] $X509Flags,
$PfxPass)
$CertPath = "$Env:SystemRoot\$CertFileName"
$Pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
# Flags to send in are documented here: https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509keystorageflags%28v=vs.110%29.aspx
$Pfx.Import($CertPath, $PfxPass, $X509Flags) #"Exportable,PersistKeySet")
$Store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $CertStore, $CertRootStore
$Store.Open("MaxAllowed")
$Store.Add($Pfx)
if ($?)
{
"${Env:ComputerName}: Successfully added certificate."
}
else
{
"${Env:ComputerName}: Failed to add certificate! $($Error[0].ToString() -replace '[\r\n]+', ' ')"
}
$Store.Close()
Remove-Item -LiteralPath $CertPath
} -ArgumentList $TempCertFileName, $CertRootStore, $CertStore, $X509Flags, $Password
Based on mao47's code and some research, I wrote up a little article and a simple cmdlet for importing/pushing PFX certificates to remote computers.
Here's my article with more details and complete code that also works with PSv2 (default on Server 2008 R2 / Windows 7), so long as you have SMB enabled and administrative share access.
NGINX SOLUTION
file
/etc/nginx/mime.types
or
/usr/local/nginx/conf/mime.types
add
font/ttf ttf;
font/opentype otf;
font/woff woff;
font/woff2 woff2;
application/vnd.ms-fontobject eot;
remove
application/octet-stream eot;
REFERENCES
RFC @02.2017
https://tools.ietf.org/html/rfc8081#page-15
https://www.iana.org/assignments/media-types/media-types.xhtml
Thanks to Mike Fulcher
The simplest way is to map over the DataFrame's RDD and use mkString:
df.rdd.map(x=>x.mkString(","))
As of Spark 1.5 (or even before that)
df.map(r=>r.mkString(","))
would do the same
if you want CSV escaping you can use apache commons lang for that. e.g. here's the code we're using
def DfToTextFile(path: String,
df: DataFrame,
delimiter: String = ",",
csvEscape: Boolean = true,
partitions: Int = 1,
compress: Boolean = true,
header: Option[String] = None,
maxColumnLength: Option[Int] = None) = {
def trimColumnLength(c: String) = {
val col = maxColumnLength match {
case None => c
case Some(len: Int) => c.take(len)
}
if (csvEscape) StringEscapeUtils.escapeCsv(col) else col
}
def rowToString(r: Row) = {
val st = r.mkString("~-~").replaceAll("[\\p{C}|\\uFFFD]", "") //remove control characters
st.split("~-~").map(trimColumnLength).mkString(delimiter)
}
def addHeader(r: RDD[String]) = {
val rdd = for (h <- header;
if partitions == 1; //headers only supported for single partitions
tmpRdd = sc.parallelize(Array(h))) yield tmpRdd.union(r).coalesce(1)
rdd.getOrElse(r)
}
val rdd = df.map(rowToString).repartition(partitions)
val headerRdd = addHeader(rdd)
if (compress)
headerRdd.saveAsTextFile(path, classOf[GzipCodec])
else
headerRdd.saveAsTextFile(path)
}
Your pattern is fine. But you shouldn't be split()
ting it away, you should find()
it. Following code gives the output you are looking for:
String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
dojo.query(document.body).connect('mouseup',function (e)
{
var obj = dojo.position(dojo.query('div#divselector')[0]);
if (!((e.clientX > obj.x && e.clientX <(obj.x+obj.w)) && (e.clientY > obj.y && e.clientY <(obj.y+obj.h))) ){
MyDive.Hide(id);
}
});
Use time.sleep()
from time import sleep
sleep(0.05)
You can Use INFORMATION_SCHEMA.KEY_COLUMN_USAGE and sys.foreign_key_columns in order to get the foreign key metadata for a table i.e. Constraint name, Reference table and Reference column etc.
Below is the query:
SELECT CONSTRAINT_NAME, COLUMN_NAME, ParentTableName, RefTableName,RefColName FROM
(SELECT CONSTRAINT_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = '<tableName>') constraint_details
INNER JOIN
(SELECT ParentTableName, RefTableName,name ,COL_NAME(fc.referenced_object_id,fc.referenced_column_id) RefColName FROM (SELECT object_name(parent_object_id) ParentTableName,object_name(referenced_object_id) RefTableName,name,OBJECT_ID FROM sys.foreign_keys WHERE parent_object_id = object_id('<tableName>') ) f
INNER JOIN
sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id ) foreign_key_detail
on foreign_key_detail.name = constraint_details.CONSTRAINT_NAME
Using the == operator will compare the references to the strings not the string themselves.
Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.
String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();
if (passwd1Text.equals(passwd2Text))
{
}
I had the same issue in Android studio 2.3 when I tried to test the app using Xiaomi's Mi5 and Mi4 phones. Disabling instant run didn't help me. So here is what I did.
Turn Off MIUI optimization in the Developer Options in the phone.
Then the device will be rebooted and then you'll be able to test the app over the phone.
Using this method you can still use instant run option in android studio. So this will fix your problem at least temporary. Hope that we'll be able to use MIUI optimization in the near future updates :)
A modern stdlib way is using sysconfig
module, available in version 2.7 and 3.2+. Unlike the current accepted answer, this method still works regardless of whether or not you have a virtual environment active.
Note: sysconfig
(source) is not to be confused with the distutils.sysconfig
submodule (source) mentioned in several other answers here. The latter is an entirely different module and it's lacking the get_paths
function discussed below.
Python currently uses eight paths (docs):
- stdlib: directory containing the standard Python library files that are not platform-specific.
- platstdlib: directory containing the standard Python library files that are platform-specific.
- platlib: directory for site-specific, platform-specific files.
- purelib: directory for site-specific, non-platform-specific files.
- include: directory for non-platform-specific header files.
- platinclude: directory for platform-specific header files.
- scripts: directory for script files.
- data: directory for data files.
In most cases, users finding this question would be interested in the 'purelib' path (in some cases, you might be interested in 'platlib' too). The purelib path is where ordinary Python packages will be installed by tools like pip
.
At system level, you'll see something like this:
# Linux
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/lib/python3.8/site-packages
# macOS (brew installed python3.8)
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/Cellar/[email protected]/3.8.3/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages
# Windows
C:\> py -c "import sysconfig; print(sysconfig.get_path('purelib'))"
C:\Users\wim\AppData\Local\Programs\Python\Python38\Lib\site-packages
With a venv, you'll get something like this
# Linux
/tmp/.venv/lib/python3.8/site-packages
# macOS
/private/tmp/.venv/lib/python3.8/site-packages
# Windows
C:\Users\wim\AppData\Local\Temp\.venv\Lib\site-packages
The function sysconfig.get_paths()
returns a dict of all of the relevant installation paths, example on Linux:
>>> import sysconfig
>>> sysconfig.get_paths()
{'stdlib': '/usr/local/lib/python3.8',
'platstdlib': '/usr/local/lib/python3.8',
'purelib': '/usr/local/lib/python3.8/site-packages',
'platlib': '/usr/local/lib/python3.8/site-packages',
'include': '/usr/local/include/python3.8',
'platinclude': '/usr/local/include/python3.8',
'scripts': '/usr/local/bin',
'data': '/usr/local'}
A shell script is also available to display these details, which you can invoke by executing sysconfig
as a module:
python -m sysconfig
window.location
adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.
window.location.replace
replaces the current history item so you can't go back to it.
See window.location
:
assign(url)
: Load the document at the provided URL.
replace(url)
:Replace the current document with the one at the provided URL. The difference from theassign()
method is that after usingreplace()
the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
Oh and generally speaking:
window.location.href = url;
is favoured over:
window.location = url;
Use Memoize
The op's derivation of state is a direct manipulation of props, with no true derivation needed. In other words, if you have a prop which can be utilized or transformed directly there is no need to store the prop on state.
Given that the state value of start_time
is simply the prop start_time.format("HH:mm")
, the information contained in the prop is already in itself sufficient for updating the component.
However if you did want to only call format on a prop change, the correct way to do this per latest documentation would be via Memoize: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization
This is the case because the pointer you have for the submodule isn’t what is actually in the submodule directory. To fix this, you must run git submodule update
again:
There are a few yet to be mentioned techniques available for you. Start with setting the contentType property in your ajax params.
Building on pradeek's example:
$('form').submit(function (e) {
var data;
data = new FormData();
data.append('file', $('#file')[0].files[0]);
$.ajax({
url: 'http://hacheck.tel.fer.hr/xml.pl',
data: data,
processData: false,
type: 'POST',
// This will override the content type header,
// regardless of whether content is actually sent.
// Defaults to 'application/x-www-form-urlencoded'
contentType: 'multipart/form-data',
//Before 1.5.1 you had to do this:
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
// Now you should be able to do this:
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
In some cases when forcing jQuery ajax to do non-expected things, the beforeSend
event is a great place to do it. For a while people were using beforeSend
to override the mimeType before that was added into jQuery in 1.5.1. You should be able to modify just about anything on the jqXHR object in the before send event.
You can better achieve it by using the DrawableCompat like this:
Drawable backgroundDrawable = view.getBackground();
DrawableCompat.setTint(backgroundDrawable, newColor);
As a response to your question: "i want to reset all the data and keep last 30 days inside the table."
you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html
For example:
CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);
Will run a daily cleanup in your table, keeping the last 30 days data available
I ran into this same issue when using anchors for an angular bootstrap drop down. The only solution I found that avoided unwanted side effects (ie. the drop down not closing because of using preventDefault()) was to use the following:
<a href="javascript:;" ng-click="do()">Click</a>
Please look at the following situation:
ab@cd-x:$ cat test_overflow.c
#include <stdio.h>
#include <string.h>
int check_password(char *password){
int flag = 0;
char buffer[20];
strcpy(buffer, password);
if(strcmp(buffer, "mypass") == 0){
flag = 1;
}
if(strcmp(buffer, "yourpass") == 0){
flag = 1;
}
return flag;
}
int main(int argc, char *argv[]){
if(argc >= 2){
if(check_password(argv[1])){
printf("%s", "Access granted\n");
}else{
printf("%s", "Access denied\n");
}
}else{
printf("%s", "Please enter password!\n");
}
}
ab@cd-x:$ gcc -g -fno-stack-protector test_overflow.c
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out wepassssssssssssssssss
Access granted
ab@cd-x:$ gcc -g -fstack-protector test_overflow.c
ab@cd-x:$ ./a.out wepass
Access denied
ab@cd-x:$ ./a.out mypass
Access granted
ab@cd-x:$ ./a.out yourpass
Access granted
ab@cd-x:$ ./a.out wepassssssssssssssssss
*** stack smashing detected ***: ./a.out terminated
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x48)[0xce0ed8]
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x0)[0xce0e90]
./a.out[0x8048524]
./a.out[0x8048545]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0xc16b56]
./a.out[0x8048411]
======= Memory map: ========
007d9000-007f5000 r-xp 00000000 08:06 5776 /lib/libgcc_s.so.1
007f5000-007f6000 r--p 0001b000 08:06 5776 /lib/libgcc_s.so.1
007f6000-007f7000 rw-p 0001c000 08:06 5776 /lib/libgcc_s.so.1
0090a000-0090b000 r-xp 00000000 00:00 0 [vdso]
00c00000-00d3e000 r-xp 00000000 08:06 1183 /lib/tls/i686/cmov/libc-2.10.1.so
00d3e000-00d3f000 ---p 0013e000 08:06 1183 /lib/tls/i686/cmov/libc-2.10.1.so
00d3f000-00d41000 r--p 0013e000 08:06 1183 /lib/tls/i686/cmov/libc-2.10.1.so
00d41000-00d42000 rw-p 00140000 08:06 1183 /lib/tls/i686/cmov/libc-2.10.1.so
00d42000-00d45000 rw-p 00000000 00:00 0
00e0c000-00e27000 r-xp 00000000 08:06 4213 /lib/ld-2.10.1.so
00e27000-00e28000 r--p 0001a000 08:06 4213 /lib/ld-2.10.1.so
00e28000-00e29000 rw-p 0001b000 08:06 4213 /lib/ld-2.10.1.so
08048000-08049000 r-xp 00000000 08:05 1056811 /dos/hacking/test/a.out
08049000-0804a000 r--p 00000000 08:05 1056811 /dos/hacking/test/a.out
0804a000-0804b000 rw-p 00001000 08:05 1056811 /dos/hacking/test/a.out
08675000-08696000 rw-p 00000000 00:00 0 [heap]
b76fe000-b76ff000 rw-p 00000000 00:00 0
b7717000-b7719000 rw-p 00000000 00:00 0
bfc1c000-bfc31000 rw-p 00000000 00:00 0 [stack]
Aborted
ab@cd-x:$
When I disabled the stack smashing protector no errors were detected, which should have happened when I used "./a.out wepassssssssssssssssss"
So to answer your question above, the message "** stack smashing detected : xxx" was displayed because your stack smashing protector was active and found that there is stack overflow in your program.
Just find out where that occurs, and fix it.
is there a problem with:
Rectangle box1 = new Rectangle(100,100,100,100);
Rectangle box2 = new Rectangle(200,200,100,100);
// what this means is if any pixel in box2 enters (hits) box1
if (box1.contains(box2))
{
// collision occurred
}
// your code for moving the boxes
this can also be applied to circles:
Ellipse2D.Double ball1 = new Ellipse2D.Double(100,100,200,200);
Ellipse2D.Double ball2 = new Ellipse2D.Double(400,100,200,200);
// what this means is if any pixel on the circumference in ball2 touches (hits)
// ball1
if (ball1.contains(ball2))
{
// collision occurred
}
// your code for moving the balls
to check whether youve hit the edge of a screen you could use the following:
Rectangle screenBounds = jpanel.getBounds();
Ellipse2D.Double ball = new Ellipse2D.Double(100,100,200,200); // diameter 200
Rectangle ballBounds = ball.getBounds();
if (!screenBounds.contains(ballBounds))
{
// the ball touched the edge of the screen
}
if [ ! -d directory ]; then
mkdir directory
fi
or
mkdir -p directory
-p
ensures creation if directory
does not exist
If you are doing what I believe you are trying to do, you'll need something a little more like this:
table {
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
}
table tr:first-child th {
border-top: 0;
}
table tr:last-child td {
border-bottom: 0;
}
table tr td:first-child,
table tr th:first-child {
border-left: 0;
}
table tr td:last-child,
table tr th:last-child {
border-right: 0;
}
The problem is that you are setting a 'full border' around all the cells, which make it appear as if you have a border around the entire table.
Cheers.
EDIT: A little more info on those pseudo-classes can be found on quirksmode, and, as to be expected, you are pretty much S.O.L. in terms of IE support.
Try the below code -
playButton.setVisibility(View.INVISIBLE);
or -
playButton.setVisibility(View.GONE);
show it again with -
playButton.setVisibility(View.VISIBLE);
for quick one time use this works, npm install --python="c:\python27"
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
You need to remember that IQueryable queries are not actually executed against the data store until you enumerate them.
using (var dataContext = new dataContext())
{
This line of code doesn't actually do anything other than build the SQL statement
users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);
.Any() is an operation that enumerates the IQueryable, so the SQL is sent to the data source (through dataContext), and then the .Any() operations is executed against it
if(users.Any() == false)
{
return null;
}
}
Your "problem" line is reusing the sql built above, and then doing an additional operation (.Select()), which just adds to the query. If you left it here, no exception, except your problem line
return users.Select(x => x.ToInfo()).ToList(); // this line is the problem
calls .ToList(), which enumerates the IQueryable, which causes the SQL to be sent to the datasource through the dataContext that was used in the original LINQ query. Since this dataContext has been disposed, it is no longer valid, and .ToList() throws an exception.
That is the "why it doesn't work". The fix is to move this line of code inside the scope of your dataContext.
How to use it properly is another question with a few arguably correct answers that depend on your application (Forms vs. ASP.net vs. MVC, etc.). The pattern that this implements is the Unit of Work pattern. There is almost no cost to creating a new context object, so the general rule is to create one, do your work, and then dispose of it. In web apps, some people will create a Context per request.
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
I use a variation on JOP's answer. Using command line parameters you can set the debugging mode in the IDE with project properties or through the Windows service manager.
protected override void OnStart(string[] args)
{
if (args.Contains<string>("DEBUG_SERVICE"))
{
Debugger.Break();
}
...
}
You can't delete on an array ! This should work better :
for (File f : files) f.delete();
But it won't work if the folders are not empty. For this cases, you will need to recursively descend into the folder hierarchy and delete everything. Yes it's a shame Java can't do that by default...
You have to add Imports System.Runtime.InteropServices
to the top of your source file.
Alternatively, you can fully qualify attribute name:
<System.Runtime.InteropService.DllImport("user32.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _
Go to your net card. Go to properties and then "Add service", which? This: VirtualBox NDIS6 Bridged Networking Driver
Reopen Virtual Box
You can jump through hoops and convert your solution to a lapply
, sapply
or apply
call. (I see @jonw shows one way to do this.) Other than that what you have already is perfectly acceptable code.
If these are all a time series or similar then the following might be a suitable alternative, which plots each series in it's own panel on a single plotting region. We use the zoo
package as it handles ordered data like this very well indeed.
require(zoo)
set.seed(1)
## example data
dat <- data.frame(X = cumsum(rnorm(100)), Y = cumsum(rnorm(100)),
Z = cumsum(rnorm(100)))
## convert to multivariate zoo object
datz <- zoo(dat)
## plot it
plot(datz)
Which gives:
You are copying all files to a single file called TEST_BACKUP_FOLDER
try this:
md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER
var test = $('input[name="testing"]:hidden');
test.val('work!');
This will have the field take 50% of the width and be centered and resized properly
{ width: 50%; margin-left : 25% }
May also use "vw" (view width) units instead of "%"
open ST ( Sublime Text )
add your project root folder into ST : link : https://stackoverflow.com/a/18798528/1241980
show sidebar : Menu bar View
> Side Bar
> Show Side Bar
Try Ctrl + P to open a file someFileName.py
Does a navigation panel for openned files and project folders appear in the left of ST ?
Extra : Want view the other files that are in the same directory with someFileName.py
?
While I found ST side bar seems doesn't support this, but you can try Ctrl + O (Open) keyshort in ST to open your system file browser, in which the ST will help you to locate into the folder that contains someFileName.py
and it's sibling files.
In Python2, dictionary.iteritems()
is more efficient than dictionary.items()
so in Python3, the functionality of dictionary.iteritems()
has been migrated to dictionary.items()
and iteritems()
is removed. So you are getting this error.
Use dict.items()
in Python3 which is same as dict.iteritems()
of Python2.
DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
str = str + ", " + file.Name;
}
Hope this will help...
U can also use PoDoFo library. The main goal is that it published under LGPL. Since it is written in C++ you should cross-compile it using NDK and write C-side and Java wrapper. Some of third-party libraries can be used from OpenCV project. Also in OpenCV project U can find android.toolchain.cmake
file, which will help you with generating Makefile
.
Just call the onBackPressed()
method in the activity you want to show the dialog and inside it show your dialog.
Researching this topic myself and having read the answers I recommend using the path.py library since it provides a context manager for changing the current working directory.
You then have something like
import path
if path.Path('../lib').isdir():
with path.Path('..'):
import lib
Although, you might just omit the isdir
statement.
Here I'll add print statements to make it easy to follow what's happening
import path
import pandas
print(path.Path.getcwd())
print(path.Path('../lib').isdir())
if path.Path('../lib').isdir():
with path.Path('..'):
print(path.Path.getcwd())
import lib
print('Success!')
print(path.Path.getcwd())
which outputs in this example (where lib is at /home/jovyan/shared/notebooks/by-team/data-vis/demos/lib
):
/home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart
/home/jovyan/shared/notebooks/by-team/data-vis/demos
/home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart
Since the solution uses a context manager, you are guaranteed to go back to your previous working directory, no matter what state your kernel was in before the cell and no matter what exceptions are thrown by importing your library code.
Try setting a height so the block cannot grow to accommodate your text, and keep the overflow: hidden
parameter
EDIT: Here is an example of what you might like if you need to display 2 lines high:
div {
border: 1px solid black;
width: 70px;
height: 2.2em;
overflow: hidden;
}
A much simpler way nowadays is to use the jquery filter() as follows:
var options = $('select option');
var query = $('input').val();
options.filter(function() {
$(this).toggle($(this).val().toLowerCase().indexOf(query) > -1);
});
There's a cool tool made by @kovart called the dashed border generator.
It uses an svg as a background image to allow setting the stroke dash array you desire, and is pretty convenient.
You would then simply use it as the background property on your element in place of the border:
div {
background-image: url("data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' stroke='black' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e");
padding: 20px;
display: inline-block;
}
In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.
In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.
In those few rare cases when you need to share a variable between files, do like this:
// file.h
extern int my_var;
// file.c
#include "file.h"
int my_var = something;
// main.c
#include "file.h"
use(my_var);
Never put any form of variable definition in a h-file.
For future Oracle Linux users trying to solve this, below is what worked for me. First install missing libs:
yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel
readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel
Then cd to your Python3.X library and run:
make
make install
Instead of using the conditions
syntax from Rails 2, use Rails 4's where
method instead:
def self.search(search, page = 1 )
wildcard_search = "%#{search}%"
where("name ILIKE :search OR postal_code LIKE :search", search: wildcard_search)
.page(page)
.per_page(5)
end
NOTE: the above uses parameter syntax instead of ? placeholder: these both should generate the same sql.
def self.search(search, page = 1 )
wildcard_search = "%#{search}%"
where("name ILIKE ? OR postal_code LIKE ?", wildcard_search, wildcard_search)
.page(page)
.per_page(5)
end
NOTE: using ILIKE
for the name - postgres case insensitive version of LIKE
Below code worked for me for getting a pdf file from an API service and response it out to the browser - hope it helps;
public async Task<FileResult> PrintPdfStatements(string fileName)
{
var fileContent = await GetFileStreamAsync(fileName);
var fileContentBytes = ((MemoryStream)fileContent).ToArray();
return File(fileContentBytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
}
A query (modification of https://stackoverflow.com/a/7892349/1737819) to find a custom name table size in GB. You might try this, replace 'YourTableName' with the name of your table.
SELECT
t.NAME AS TableName,
p.rows AS RowCounts,
CONVERT(DECIMAL,SUM(a.total_pages)) * 8 / 1024 / 1024 AS TotalSpaceGB,
SUM(a.used_pages) * 8 / 1024 / 1024 AS UsedSpaceGB ,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 / 1024 / 1024 AS UnusedSpaceGB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME = 'YourTable'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
UsedSpaceGB DESC, t.Name
Yes that is valid syntax but it may well not do what you want.
Execution will continue after your RAISERROR
except if you add a RETURN
. So you will need to add a block with BEGIN ... END
to hold the two statements.
Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.
Finally I'd simplify the conditions using IN
CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
@UserType TINYINT,
@UserName NVARCHAR(100),
@Password NVARCHAR(100))
AS
BEGIN
IF ( @TenantId IS NULL
AND @UserType IN ( 0, 1 ) )
BEGIN
RAISERROR('The value for @TenantID should not be null',15,1);
RETURN;
END
END
You can use CSS under legend.green-color a:hover
to do it.
legend.green-color a:hover {
color:green;
text-decoration:none;
}
That is a problem of security protocol. I am using TLSv1 but the host accept only TLSv1.1 and TLSv1.2 then I changed the protocol in Java with the instruction below:
System.setProperty("https.protocols", "TLSv1.1")
;
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
I got the same problem. I was sure that it was due to very small fault and yes it was!
I found the solution:
When generating the debug hash key in my computer, I entered the password of my system. But the password should be the following -
Enter keystore password: "android". This was the only problem in my case.
----- For generating Debug key hash, use this command -
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
Enter keystore password: 'android'
----- To Generate Release key hash, use this command -
keytool -exportcert -alias "alias of keystore" -keystore "Your path to the keystore when signing app" | openssl sha1 -binary | openssl base64
Provide your keystore password after executing this command.
You can use a pseudo-element to insert that character before each list item:
ul {_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
content: '?';_x000D_
}
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
Also If you want you result set data in list .please use below LOC:
public List<String> dbselect(String query)
{
List<String> dbdata=new ArrayList<String>();
try {
dbResult=statement.executeQuery(query);
ResultSetMetaData metadata=dbResult.getMetaData();
for(int i=0;i>=metadata.getColumnCount();i++)
{
dbdata.add(dbResult.getString(i));
}
return dbdata;
} catch (SQLException e) {
return null;
}
}
If you use "format-table" you can use -hidetableheaders
document.forms[ 'forms1' ].onsubmit = function() {
return [].some.call( this.elements, function( el ) {
return el.type === 'radio' ? el.checked : false
} )
}
Just something out of my head. Not sure the code is working.
<video width="320" height="240" controls autoplay>
<source src="movie.mp4" type="video/mp4"> Your browser does not support the video tag.
</video>
Remove autoplay
if you want to disable auto playing video.
If you need to rename not all but multiple column at once when you only know the old column names you can use colnames
function and %in%
operator. Example:
df = data.frame(bad=1:3, worse=rnorm(3), worst=LETTERS[1:3])
bad worse worst
1 1 -0.77915455 A
2 2 0.06717385 B
3 3 -0.02827242 C
Now you want to change "bad" and "worst" to "good" and "best". You can use
colnames(df)[which(colnames(df) %in% c("bad","worst") )] <- c("good","best")
This results in
good worse best
1 1 -0.6010363 A
2 2 0.7336155 B
3 3 0.9435469 C
npm fund [<pkg>]
This command retrieves information on how to fund the dependencies of a given project. If no package name is provided, it will list all dependencies that are looking for funding in a tree-structure in which are listed the type of funding and the url to visit.
The message can be disabled using: npm install --no-fund
There's one big difference between CLOCK_REALTIME and MONOTONIC. CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.
I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)
This is for reading images from Azure Cognative Services's Vision API
const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';
// Request parameters.
const params = {
'visualFeatures': 'Categories,Description,Adult,Faces',
'maxCandidates': '2',
'details': 'Celebrities,Landmarks',
'language': 'en'
};
const options = {
uri: uriBase,
qs: params,
body: fs.readFileSync(./my_local_image_path.jpg),
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, ' ');
body = JSON.parse(body);
if (body.code) // err
{
console.log("AZURE: " + body.message)
}
console.log('Response\n' + jsonString);
People who are struggling with uiscrollview not scrolling just set your content view's bottom constraint with your last view's bottom layout (which is inside of your content view). Do not forget to remove center Y constraint.
Rest all the constraints are same as defined above. Scrollview only concerned about getting maximum height from its content view, and we are setting it as last view's bottom constraint, which means scrollview automatically will change its content offset.
In my case last view was UILable with no of lines property = 0(which automatically adjust its height depending upon its content) so it dynamically increase uilable's height and eventually our scrollable area increases because of uilable's bottom layout is aligned with our content view's bottom, which forces scrollview to increase it's content offset.
One recommendation I've gotten is Hex Fiend.
A few times now, I've experienced various instances MS SQL Server to fail with this error after a Windows update. Most of the quick fixes above did not work for me.
What did:
For me, this was the fastest solution. Trying to find the cause of the error and fixing it is an afternoon of googling misty error messages. But YMMV.
You can use the ObjectOutputStream
class to write objects to an underlying stream.
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);
And read the Object
back like -
inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()
There is two easy way to set the alias.
Using Bash
Open bash terminal and type git command. For instance:
$ git config --global alias.a add
$ git config --global alias.aa 'add .'
$ git config --global alias.cm 'commit -m'
$ git config --global alias.s status
---
---
It will eventually add those aliases on .gitconfig file.
Updating .gitconfig file
Open .gitconfig file located at 'C:\Users\username\.gitconfig' in Windows environment. Then add following lines:
[alias]
a = add
aa = add .
cm = commit -m
gau = add --update
au = add --update
b = branch
---
---
driver Asus for Windows: http://www.asus.com/sa-en/support/Download/39/1/0/2/32/
Choose target device: USB device
If you use DB Browser for SQLite, you can copy the table from one db to another in following steps:
If you want to avoid having to use a form or an input and you're looking for a button-looking link, you can create good-looking button links with a div wrapper, an anchor and an h1
tag. You'd potentially want this so you can freely place the link-button around your page. This is especially useful for horizontally centering buttons and having vertically-centered text inside of them. Here's how:
Your button will be comprised of three nested pieces: a div wrapper, an anchor, and an h1, like so:
.link-button-wrapper {_x000D_
width: 200px;_x000D_
height: 40px;_x000D_
box-shadow: inset 0px 1px 0px 0px #ffffff;_x000D_
border-radius: 4px;_x000D_
background-color: #097BC0;_x000D_
box-shadow: 0px 2px 4px gray;_x000D_
display: block;_x000D_
border:1px solid #094BC0;_x000D_
}_x000D_
.link-button-wrapper > a {_x000D_
display: inline-table;_x000D_
cursor: pointer;_x000D_
text-decoration: none;_x000D_
height: 100%;_x000D_
width:100%;_x000D_
}_x000D_
.link-button-wrapper > a > h1 {_x000D_
margin: 0 auto;_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
color: #f7f8f8;_x000D_
font-size: 18px;_x000D_
font-family: cabinregular;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="link-button-wrapper">_x000D_
<a href="your/link/here">_x000D_
<h1>Button!</h1>_x000D_
</a>_x000D_
</div>
_x000D_
Here's a jsFiddle to check it out and play around with it.
Benefits of this setup: 1. Making the div wrapper display: block makes it easy to center (using margin: 0 auto) and position (while an <a> is inline and harder to positionand not possible to center).
You could just make the <a> display:block, move it around, and style it as a button, but then vertically aligning text inside of it becomes hard.
This allows you to make the <a> display: inline-table and the <h1> display: table-cell, which allows you to use vertical-align: middle on the <h1> and center it vertically (which is always nice on a button). Yes, you could use padding, but if you want your button to dynamically resize, that won't be as clean.
Sometimes when you embed an <a> within a div, only the text is clickable, this setup makes the whole button clickable.
You don't have to deal with forms if you're just trying to move to another page. Forms are meant for inputting information, and they should be reserved for that.
Allows you to cleanly separte the button styling and text styling from each other (stretch advantage? Sure, but CSS can get nasty-looking so it's nice to decompose it).
It definitely made my life easier styling a mobile website for variable-sized screens.
As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.
After 9.2.x. IOS remove this tag check on its' browser.
You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html
I hope you have installed the required drivers for debugging android programs on your machine. If that is the case, when you run an application from android studio in an actual device, it will pop up a message asking to enable logcat. If you have disabled that option, then you can enable the logcat view from Window menu -> Show view -> Logcat. Next time when you run your application on actual device or in an emulator, you can see the logcat is active.
If you are not able to view it with the above solution, you can view the logcat from command line by typing
adb logcat
You can view more information from here http://developer.android.com/tools/help/logcat.html
These are the two options I managed to build, not having the luxury of working with var
type, nor with additional variables on the line:
string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);
string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);
This is what it gets:
If you have a std::wstring object, you can call c_str()
on it to get a wchar_t*
:
std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar
routine. That will give you an LPWSTR
, which is equivalent to wchar_t*
.
try like this
css
*{
box-sizing: border-box;
-webkit-box-sizing: border-box;
-msbox-sizing: border-box;
}
body{
overflow-x: hidden;
}
img{
max-width:100%;
}
Raymond Hettinger (one of the Python core developers) had this to say about tuples in a recent tweet:
#python tip: Generally, lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.
This (to me) supports the idea that if the items in a sequence are related enough to be generated by a, well, generator, then it should be a list. Although a tuple is iterable and seems like simply a immutable list, it's really the Python equivalent of a C struct:
struct {
int a;
char b;
float c;
} foo;
struct foo x = { 3, 'g', 5.9 };
becomes in Python
x = (3, 'g', 5.9)
CURL client supports FTP protocol and works for passive mode. Get Download WITHOUT SSL version and you don't need any openssl.dll libraries. Just one curl.exe command line application.
http://www.paehl.com/open_source/?CURL_7.35.0
curl.exe -T c:\test\myfile.dat ftp://ftp.server.com/some/folder/myfile.dat --user myuser:mypwd
Another one is Putty psftp.exe but server key verification prompt requires a trick. This command line inputs NO for prompt meaning key is not stored in registry just this time being used. You need an external script file but sometimes its good if you copy multiple files up and down.
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
echo n | psftp.exe ftp.server.com -l myuser -pw mypwd -b script.txt
script.txt (any ftp command may be typed)
put "C:\test\myfile.dat" "/some/folder/myfile.dat"
quit
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
Can you try this,
var ajaxSubmit = function(formE1) {
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
async: "false",
url: "checkpass.php",
data: "password="+password,
success: function(html) {
var arr=$.parseJSON(html);
if(arr == "Successful")
{
**$("form[name='form']").submit();**
return true;
}
else
{ return false;
}
}
});
**return false;**
}
What about:
const n = 123456;
Array.from(n.toString()).map(Number);
// [1, 2, 3, 4, 5, 6]
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)
I did only one thing and it worked for me .. check your code is this method there ..
setResizable(false);
if it false make it true and it will work just fine .. I hope it helped ..
Use import test1
for the 1st use - it will execute the script. For later invocations, treat the script as an imported module, and call the reload(test1)
method.
When
reload(module)
is executed:
- Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called
A simple check of sys.modules
can be used to invoke the appropriate action. To keep referring to the script name as a string ('test1'
), use the 'import()' builtin.
import sys
if sys.modules.has_key['test1']:
reload(sys.modules['test1'])
else:
__import__('test1')
The following steps worked on Pop!_OS 20.10 & ubuntu 20.04
The Github application for Windows shows all remote branches of a repository. If you have deleted the branch locally with $ git branch -d [branch_name]
, the remote branch still exists in your Github repository and will appear regardless in the Windows Github application.
If you want to delete the branch completely (remotely as well), use the above command in combination with $ git push origin :[name_of_your_new_branch]
. Warning: this command erases all existing branches and may cause loss of code. Be careful, I do not think this is what you are trying to do.
However every time you delete the local branch changes, the remote branch will still appear in the application. If you do not want to keep making changes, just ignore it and do not click, otherwise you may clone the repository. If you had any more questions, please let me know.
What about following line:
awk '{$1=$2=$3=""; print}' file
Based on @ghostdog74 suggestion. Mine should behave better when you filter lines, i.e.:
awk '/^exim4-config/ {$1=""; print }' file
If one needs to use famous \n in string literals that can be passed to a variable, may write a code like in the Hello.bat script below:
@echo off
set input=%1
if defined input (
set answer=Hi!\nWhy did you call me a %input%?
) else (
set answer=Hi!\nHow are you?\nWe are friends, you know?\nYou can call me by name.
)
setlocal enableDelayedExpansion
set newline=^
rem Two empty lines above are essential
echo %answer:\n=!newline!%
This way multiline output may by prepared in one place, even in other scritpt or external file, and printed in another.
The line break is held in newline variable. Its value must be substituted after the echo line is expanded so I use setlocal enableDelayedExpansion to enable exclamation signs which expand variables on execution. And the execution substitutes \n with newline contents (look for syntax at help set). We could of course use !newline! while setting the answer but \n is more convenient. It may be passed from outside (try Hello R2\nD2), where nobody knows the name of variable holding the line break (Yes, Hello C3!newline!P0 works the same way).
Above example may be refined to a subroutine or standalone batch, used like call:mlecho Hi\nI'm your comuter
:
:mlecho
setlocal enableDelayedExpansion
set text=%*
set nl=^
echo %text:\n=!nl!%
goto:eof
Please note, that additional backslash won't prevent the script from parsing \n substring.
A great blog describing 14 address finders: https://www.conversion-uplift.co.uk/free-address-lookup-tools/
Many address autocomplete services, including Google's Places API, appears to offer international address support but it has limited accuracy.
For example, New Zealand address and geolocation data are free to download from Land Information New Zealand (LINZ). When a user search for an address such as 76 Francis St Hauraki from Google or Address Doctor, a positive match is returned. The land parcel was matched but not the postal/delivery address, which is either 76A or 76B. The problem is amplified with apartments and units on a single land parcel.
For 100% accuracy, use a country-specific address finder instead such as https://www.addy.co.nz for NZ address autocomplete.
one
has not been assigned so points to an unpredictable location. You should either place it on the stack:
Vector one;
one.a = 12;
one.b = 13;
one.c = -11
or dynamically allocate memory for it:
Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);
Note the use of free
in this case. In general, you'll need exactly one call to free
for each call made to malloc
.
Below Kotlin code will help
Bottom to Top or Slide to Up
private fun slideUp() {
isMapInfoShown = true
views!!.layoutMapInfo.visible()
val animate = TranslateAnimation(
0f, // fromXDelta
0f, // toXDelta
views!!.layoutMapInfo.height.toFloat(), // fromYDelta
0f // toYDelta
)
animate.duration = 500
animate.fillAfter = true
views!!.layoutMapInfo.startAnimation(animate)
}
Top to Bottom or Slide to Down
private fun slideDown() {
if (isMapInfoShown) {
isMapInfoShown = false
val animate = TranslateAnimation(
0f, // fromXDelta
0f, // toXDelta
0f, // fromYDelta
views!!.layoutMapInfo.height.toFloat() // toYDelta
)
animate.duration = 500
animate.fillAfter = true
views!!.layoutMapInfo.startAnimation(animate)
views!!.layoutMapInfo.gone()
}
}
Kotlin Extensions for Visible and Gone
fun View.visible() {
this.visibility = View.VISIBLE
}
fun View.gone() {
this.visibility = View.GONE
}
I had the same problem a month ago on Windows 10. Whenever I tried to access http://localhost/ it led me to the IIS page. I tried removing the IIS feature from windows features. Once I was sure it was gone, I tried running XAMPP, but it still did not work. I did not want to mess with the configuration files. But from this, I was quite sure it had something to do with my web browser. So, deleted the cache from the web browser I was using (Google Chrome).
To do so, I went to:
Chrome > Settings > Show Advanced Settings > Privacy > Clear browsing data > Clear Cached images and files.
Its almost the same process for any web browsers. Right after that, I was able to run XAMPP without any problem!
Hope it helps!
This might be a little off the question, but for those interested in the randomness of the generated string, my answer would be:
import os
import string
def _pwd_gen(size=16):
chars = string.letters
chars_len = len(chars)
return str().join(chars[int(ord(c) / 256. * chars_len)] for c in os.urandom(size))
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
You need to close the XML with </web-app>
, not with <web-app>
.
from the page suggested by @Phrogz
for (var i=0,nums=[];i<49;i++) nums[i]={ n:i, rand:Math.random() };
nums.sort( function(a,b){ a=a.rand; b=b.rand; return a<b?-1:a>b?1:0 } );
Add the -X
option to theirs
. For example:
git checkout branchA
git merge -X theirs branchB
Everything will merge in the desired way.
The only thing I've seen cause problems is if files were deleted from branchB. They show up as conflicts if something other than git did the removal.
The fix is easy. Just run git rm
with the name of any files that were deleted:
git rm {DELETED-FILE-NAME}
After that, the -X theirs
should work as expected.
Of course, doing the actual removal with the git rm
command will prevent the conflict from happening in the first place.
Note: A longer form option also exists.
To use it, replace:
-X theirs
with:
--strategy-option=theirs
express.static()
expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html
and use that.
Serving static files in Express documentation, or more detailed serve-static
documentation, including the default behavior of serving index.html
:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
REST
RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
Reference: http://spf13.com/post/soap-vs-rest
And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/
I did some more research and found this place to give me what I needed - feels clean and relates to update data when refreshed from server: https://blog.angular-university.io/angular-material-data-table/
Most credits to the page above. Below is a sample of how a mat-selector can be used to update a mat-table bound to a datasource on change of selection. I am using Angular 7. Sorry for being extensive, trying to be complete but concise - I have ripped out as many non-needed parts as possible. With this hoping to help someone else getting forward faster!
organization.model.ts:
export class Organization {
id: number;
name: String;
}
organization.service.ts:
import { Observable, empty } from 'rxjs';
import { of } from 'rxjs';
import { Organization } from './organization.model';
export class OrganizationService {
getConstantOrganizations(filter: String): Observable<Organization[]> {
if (filter === "All") {
let Organizations: Organization[] = [
{ id: 1234, name: 'Some data' }
];
return of(Organizations);
} else {
let Organizations: Organization[] = [
{ id: 5678, name: 'Some other data' }
];
return of(Organizations);
}
// ...just a sample, other filterings would go here - and of course data instead fetched from server.
}
organizationdatasource.model.ts:
import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { catchError, finalize } from "rxjs/operators";
import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
export class OrganizationDataSource extends DataSource<Organization> {
private organizationsSubject = new BehaviorSubject<Organization[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
constructor(private organizationService: OrganizationService, ) {
super();
}
loadOrganizations(filter: String) {
this.loadingSubject.next(true);
return this.organizationService.getOrganizations(filter).pipe(
catchError(() => of([])),
finalize(() => this.loadingSubject.next(false))
).subscribe(organization => this.organizationsSubject.next(organization));
}
connect(collectionViewer: CollectionViewer): Observable<Organization[]> {
return this.organizationsSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.organizationsSubject.complete();
this.loadingSubject.complete();
}
}
organizations.component.html:
<div class="spinner-container" *ngIf="organizationDataSource.loading$ | async">
<mat-spinner></mat-spinner>
</div>
<div>
<form [formGroup]="formGroup">
<mat-form-field fxAuto>
<div fxLayout="row">
<mat-select formControlName="organizationSelectionControl" (selectionChange)="updateOrganizationSelection()">
<mat-option *ngFor="let organizationSelectionAlternative of organizationSelectionAlternatives"
[value]="organizationSelectionAlternative">
{{organizationSelectionAlternative.name}}
</mat-option>
</mat-select>
</div>
</mat-form-field>
</form>
</div>
<mat-table fxLayout="column" [dataSource]="organizationDataSource">
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let organization">{{organization.name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="number">
<mat-header-cell *matHeaderCellDef>Number</mat-header-cell>
<mat-cell *matCellDef="let organization">{{organization.number}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
organizations.component.scss:
.spinner-container {
height: 360px;
width: 390px;
position: fixed;
}
organization.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';
import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
import { OrganizationDataSource } from './organizationdatasource.model';
@Component({
selector: 'organizations',
templateUrl: './organizations.component.html',
styleUrls: ['./organizations.component.scss']
})
export class OrganizationsComponent implements OnInit {
public displayedColumns: string[];
public organizationDataSource: OrganizationDataSource;
public formGroup: FormGroup;
public organizationSelectionAlternatives = [{
id: 1,
name: 'All'
}, {
id: 2,
name: 'With organization update requests'
}, {
id: 3,
name: 'With contact update requests'
}, {
id: 4,
name: 'With order requests'
}]
constructor(
private formBuilder: FormBuilder,
private organizationService: OrganizationService) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
'organizationSelectionControl': []
})
const toSelect = this.organizationSelectionAlternatives.find(c => c.id == 1);
this.formGroup.get('organizationSelectionControl').setValue(toSelect);
this.organizationDataSource = new OrganizationDataSource(this.organizationService);
this.displayedColumns = ['name', 'number' ];
this.updateOrganizationSelection();
}
updateOrganizationSelection() {
this.organizationDataSource.loadOrganizations(this.formGroup.get('organizationSelectionControl').value.name);
}
}
In this situation I always use code like this (just make sure delimeter you've chosen is not a part of search range)
Dim tmp As String
Dim arr() As String
If Not Selection Is Nothing Then
For Each cell In Selection
If (cell <> "") And (InStr(tmp, cell) = 0) Then
tmp = tmp & cell & "|"
End If
Next cell
End If
If Len(tmp) > 0 Then tmp = Left(tmp, Len(tmp) - 1)
arr = Split(tmp, "|")
I find that the Browse With..
menu item only appears in Visual Studio 2010 when I Run as administrator
. And in that case it is available even while in debug mode.
Basically my code sends data to the next page like so:
**Referring Page**
$this = $_SERVER['PHP_SELF'];
echo "<a href='next_page.php?prev=$this'>Next Page</a>";
**Page with button**
$prev = $_GET['prev'];
echo "<a href='$prev'><button id='back'>Back</button></a>";
xs:boolean
is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:
<xs:simpleType name="my:boolean">
<xs:restriction base="xs:string">
<xs:enumeration value="True"/>
<xs:enumeration value="False"/>
</xs:restriction>
</xs:simpleType>
use these settings with oauth2 in Postman:
Access Token URL = https://accounts.google.com/o/oauth2/token
SCOPE = https: //www.googleapis.com/auth/admin.directory.userschema
{
"fields": [
{
"fieldName": "role",
"fieldType": "STRING",
"multiValued": true,
"readAccessType": "ADMINS_AND_SELF"
}
],
"schemaName": "SAML"
}
SCOPE = https://www.googleapis.com/auth/admin.directory.user
PATCH https://www.googleapis.com/admin/directory/v1/users/[email protected]
{
"customSchemas": {
"SAML": {
"role": [
{
"value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
"customType": "Admin"
}
]
}
}
}
Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp
for / you would escape with %2F
I pasted your code into test project, added about 20 items and I get usable scroll bars, no problem, and they work as expected. When I only add a couple items (such that scrolling is unnecessary) I get no usable scrollbar. Could this be the case? that you are not adding enough items?
If you remove the ScrollViewer.VerticalScrollBarVisibility="Visible"
then the scroll bars only appear when you have need of them.
simply running a git prune
fixed this issue for me
An alternative to CrackerJacks suggestion, if you want the HashMap to maintain order you could consider using a LinkedHashMap instead. As far as im aware it's functionality is identical to a HashMap but it is FIFO so it maintains the order in which items were added.
You can't use the API
using POST
or GET
if they are not build to call using these methods separetly. Like if your API say
/service/function?param1=value1¶m2=value2
is accessed by using GET
method. Then you can not call it using POST
method if it is not specified as POST
method by its creator. If you do that you may got 405 Method not allowed
status.
Generally in POST
method you need to send the content in body with specified format which is described in content-type
header for ex. application/json
for json data.
And after that the request body gets deserialized at server end. So you need to pass the serialized data from the client and it is decided by the service developer.
But in general terms GET
is used when server returns some data to the client and have not any impact on server whereas POST
is used to create some resource on server. So generally it should not be same.
You're missing an ending anchor.
if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
// ...
}
EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:
if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
// ...
}
Maybe the condition you are using is incorrect:
$str1 == "taste" && $str2 == "waste"
The program will enter into THEN
part only when both of the stated conditions are true.
You can try with $str1 == "taste" || $str2 == "waste"
. This will execute the THEN
part if anyone of the above conditions are true.
Unfortunatelly, for IIS installed on Windows 7/8 machines, there is no option to create users only for IIS authentification. For Windows Server there is that option where you can add users from IIS Manager UI. These users have roles only on IIS, but not for the rest of the system. In this article it shows how you add users, but it is incorrect stating that is also appliable to standard OS, it only applies to server versions.
If you know you don't have any whitespace in the input:
xargs chmod 755 < file.txt
If there might be whitespace in the paths, and if you have GNU xargs:
tr '\n' '\0' < file.txt | xargs -0 chmod 755
var matches = [];
$(".className:checked").each(function() {
matches.push(this.value);
});
That's one of the few legitimate jobs for cat
:
openssl verify -verbose -CAfile <(cat Intermediate.pem RootCert.pem) UserCert.pem
Update:
As Greg Smethells points out in the comments, this command implicitly trusts Intermediate.pem. I recommend reading the first part of the post Greg references (the second part is specifically about pyOpenSSL and not relevant to this question).
In case the post goes away I'll quote the important paragraphs:
Unfortunately, an "intermediate" cert that is actually a root / self-signed will be treated as a trusted CA when using the recommended command given above:
$ openssl verify -CAfile <(cat geotrust_global_ca.pem rogue_ca.pem) fake_sometechcompany_from_rogue_ca.com.pem fake_sometechcompany_from_rogue_ca.com.pem: OK
It seems openssl will stop verifying the chain as soon as a root certificate is encountered, which may also be Intermediate.pem if it is self-signed. In that case RootCert.pem is not considered. So make sure that Intermediate.pem is coming from a trusted source before relying on the command above.
To avoid this error you could either:
You will find instructions on signing third-party assemblies in .NET-fu: Signing an Unsigned Assembly (Without Delay Signing).
The basic principle to sign a thirp-party is to
Disassemble the assembly using ildasm.exe
and save the intermediate language (IL):
ildasm /all /out=thirdPartyLib.il thirdPartyLib.dll
Rebuild and sign the assembly:
ilasm /dll /key=myKey.snk thirdPartyLib.il
The above steps work fine unless your third-party assembly (A.dll) references another library (B.dll) which also has to be signed. You can disassemble, rebuild and sign both A.dll and B.dll using the commands above, but at runtime, loading of B.dll will fail because A.dll was originally built with a reference to the unsigned version of B.dll.
The fix to this issue is to patch the IL file generated in step 1 above. You will need to add the public key token of B.dll to the reference. You get this token by calling
sn -Tp B.dll
which will give you the following output:
Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.33440
Copyright (c) Microsoft Corporation. All rights reserved.
Public key (hash algorithm: sha1):
002400000480000094000000060200000024000052534131000400000100010093d86f6656eed3
b62780466e6ba30fd15d69a3918e4bbd75d3e9ca8baa5641955c86251ce1e5a83857c7f49288eb
4a0093b20aa9c7faae5184770108d9515905ddd82222514921fa81fff2ea565ae0e98cf66d3758
cb8b22c8efd729821518a76427b7ca1c979caa2d78404da3d44592badc194d05bfdd29b9b8120c
78effe92
Public key token is a8a7ed7203d87bc9
The last line contains the public key token. You then have to search the IL of A.dll for the reference to B.dll and add the token as follows:
.assembly extern /*23000003*/ MyAssemblyName
{
.publickeytoken = (A8 A7 ED 72 03 D8 7B C9 )
.ver 10:0:0:0
}
The easiest way to create daemon with Python is to use the Twisted event-driven framework. It handles all of the stuff necessary for daemonization for you. It uses the Reactor Pattern to handle concurrent requests.
Laravel raw sql – Insert query:
lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .
put below code in your web.php file inside routes directory :
Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});
Now fire above insert query from browser link below :
localhost/yourprojectname/insertintodb
You can see output of above insert query by going into your database table .you will find a record with id 1 .
Laravel raw sql – Read query :
Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .
put below code in your web.php file inside routes directory :
Route::get('/readfromdb',function() {
$result = DB::select('select * from posts where id = ?', [1]);
var_dump($result);
});
now fire above read query from browser link below :
localhost/yourprojectname/readfromdb
EDIT: The correct way to do this is in @LiviuT's answer!
You can always extend Angular's scope to allow you to remove such listeners like so:
//A little hack to add an $off() method to $scopes.
(function () {
var injector = angular.injector(['ng']),
rootScope = injector.get('$rootScope');
rootScope.constructor.prototype.$off = function(eventName, fn) {
if(this.$$listeners) {
var eventArr = this.$$listeners[eventName];
if(eventArr) {
for(var i = 0; i < eventArr.length; i++) {
if(eventArr[i] === fn) {
eventArr.splice(i, 1);
}
}
}
}
}
}());
And here's how it would work:
function myEvent() {
alert('test');
}
$scope.$on('test', myEvent);
$scope.$broadcast('test');
$scope.$off('test', myEvent);
$scope.$broadcast('test');
echo "Enter Drive letter"
set /p driveletter=
attrib -s -h -a /s /d %driveletter%:\*.*
Your script seems incorrect in several places.
Try this
var timetemp = document.getElementsByTagName('input');
for (var i = 0; i < timetemp.length; i++){
if (timetemp[i].value == ""){
alert ('No value');
}
else{
alert (timetemp[i].value);
}
}
Example: http://jsfiddle.net/jasongennaro/FSzT2/
Here's what I changed:
input
s via TagName
. This makes an arrayi
with a var
and then looped through the timetemp
array using the timetemp.length
property.timetemp[i]
to reference each input
in the for statement
The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:
if(x.isEmpty()) return;
int last = x.size() - 1;
for(Integer i : x.subList(0, last)) out.println(i);
out.println("last " + x.get(last));
This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).
You have to convert string formate to required date format as following and then you can get your required result.
hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2011-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1 3 13-10-2010 Low 6.0 261.54 0.04 Regular Air -213.25 38.94
80 483 10-07-2011 High 30.0 4965.7593 0.08 Regular Air 1198.97 195.99
97 613 17-06-2011 High 12.0 93.54 0.03 Regular Air -54.04 7.3
98 613 17-06-2011 High 22.0 905.08 0.09 Regular Air 127.7 42.76
103 643 24-03-2011 High 21.0 2781.82 0.07 Express Air -695.26 138.14
127 807 23-11-2010 Medium 45.0 196.85 0.01 Regular Air -166.85 4.28
128 807 23-11-2010 Medium 32.0 124.56 0.04 Regular Air -14.33 3.95
160 995 30-05-2011 Medium 46.0 1815.49 0.03 Regular Air 782.91 39.89
229 1539 09-03-2011 Low 33.0 511.83 0.1 Regular Air -172.88 15.99
230 1539 09-03-2011 Low 38.0 184.99 0.05 Regular Air -144.55 4.89
Time taken: 0.166 seconds, Fetched: 10 row(s)
hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2010-12-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1 3 13-10-2010 Low 6.0 261.54 0.04 Regular Air -213.25 38.94
127 807 23-11-2010 Medium 45.0 196.85 0.01 Regular Air -166.85 4.28
128 807 23-11-2010 Medium 32.0 124.56 0.04 Regular Air -14.33 3.95
256 1792 08-11-2010 Low 28.0 370.48 0.04 Regular Air -5.45 13.48
381 2631 23-09-2010 Low 27.0 1078.49 0.08 Regular Air 252.66 40.96
656 4612 19-09-2010 Medium 9.0 89.55 0.06 Regular Air -375.64 4.48
769 5506 07-11-2010 Critical 22.0 129.62 0.05 Regular Air 4.41 5.88
1457 10499 16-11-2010 Not Specified 29.0 6250.936 0.01 Delivery Truck 31.21 262.11
1654 11911 10-11-2010 Critical 25.0 397.84 0.0 Regular Air -14.75 15.22
2323 16741 30-09-2010 Medium 6.0 157.97 0.01 Regular Air -42.38 22.84
Time taken: 0.17 seconds, Fetched: 10 row(s)
You should not use title attribute for the img element. The reasoning behind this is quite simple:
Presumably caption information is important information that should be available to all users by default. If so present this content as text next to the image.
Source: http://blog.paciellogroup.com/2010/11/using-the-html-title-attribute/
HTML 5.1 includes general advice on use of the title attribute:
Relying on the title attribute is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g. requiring a pointing device such as a mouse to cause a tooltip to apear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet).
Source: http://www.w3.org/html/wg/drafts/html/master/dom.html#the-title-attribute
When it comes to accessibility and different screen readers:
Hence, as Denis Boudreau adequately put it: clearly not a recommended practice.
<input
value={get(data, "api_key")}
styleName="input-wrap"
title={get(data, "api_key")}
ref={apikeyObjRef}
/>
<div
onClick={() => {
apikeyObjRef.current.select();
if (document.execCommand("copy")) {
document.execCommand("copy");
}
}}
styleName="copy"
>
??
</div>
You can use jquery function.
<form name='add'>
<input type='text' name='stud_name' id="stud_name" value=""/>
Age: <select name='age' id="age">
<option value='1' stud_name='sre'>23</option>
<option value='2' stud_name='sam'>24</option>
<option value='5' stud_name='john'>25</option>
</select>
<input type='submit' name='submit'/>
</form>
jquery code :
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function() {
$("#age").change(function(){
var option = $('option:selected', this).attr('stud_name');
$('#stud_name').val(option);
});
});
</script>
Note that neither DBCC DROPCLEANBUFFERS;
nor DBCC FREEPROCCACHE;
is supported in SQL Azure / SQL Data Warehouse.
However, if you need to reset the plan cache in SQL Azure, you can alter one of the tables in the query (for instance, just add then remove a column), this will have the side-effect of removing the plan from the cache.
I personally do this as a way of testing query performance without having to deal with cached plans.
There are no sleep()
functions in the pre-C11 C Standard Library, but POSIX does provide a few options.
The POSIX function sleep()
(unistd.h) takes an unsigned int
argument for the number of seconds desired to sleep. Although this is not a Standard Library function, it is widely available, and glibc appears to support it even when compiling with stricter settings like --std=c11
.
The POSIX function nanosleep()
(time.h) takes two pointers to timespec
structures as arguments, and provides finer control over the sleep duration. The first argument specifies the delay duration. If the second argument is not a null pointer, it holds the time remaining if the call is interrupted by a signal handler.
Programs that use the nanosleep()
function may need to include a feature test macro in order to compile. The following code sample will not compile on my linux system without a feature test macro when I use a typical compiler invocation of gcc -std=c11 -Wall -Wextra -Wpedantic
.
POSIX once had a usleep()
function (unistd.h) that took a useconds_t
argument to specify sleep duration in microseconds. This function also required a feature test macro when used with strict compiler settings. Alas, usleep()
was made obsolete with POSIX.1-2001 and should no longer be used. It is recommended that nanosleep()
be used now instead of usleep()
.
#define _POSIX_C_SOURCE 199309L // feature test macro for nanosleep()
#include <stdio.h>
#include <unistd.h> // for sleep()
#include <time.h> // for nanosleep()
int main(void)
{
// use unsigned sleep(unsigned seconds)
puts("Wait 5 sec...");
sleep(5);
// use int nanosleep(const struct timespec *req, struct timespec *rem);
puts("Wait 2.5 sec...");
struct timespec ts = { .tv_sec = 2, // seconds to wait
.tv_nsec = 5e8 }; // additional nanoseconds
nanosleep(&ts, NULL);
puts("Bye");
return 0;
}
C11 does have the header threads.h
providing thrd_sleep()
, which works identically to nanosleep()
. GCC did not support threads.h
until 2018, with the release of glibc 2.28. It has been difficult in general to find implementations with support for threads.h
(Clang did not support it for a long time, but I'm not sure about the current state of affairs there). You will have to use this option with care.
yourNode.Toggle();
//use that function on your node, it toggles it
$1
, $2
, $3
, ... are the positional parameters."$@"
is an array-like construct of all positional parameters, {$1, $2, $3 ...}
."$*"
is the IFS expansion of all positional parameters, $1 $2 $3 ...
.$#
is the number of positional parameters.$-
current options set for the shell.$$
pid of the current shell (not subshell).$_
most recent parameter (or the abs path of the command to start the current shell immediately after startup).$IFS
is the (input) field separator.$?
is the most recent foreground pipeline exit status.$!
is the PID of the most recent background command.$0
is the name of the shell or shell script.Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.
For a comprehensive index, please see the Reference Manual Variable Index.
Expanding on "splattered bits" answer, here is a complete script that does it:
@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
SET _baseDirQuery=SELECT SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1) ^
FROM master.sys.master_files WHERE database_id = 1 AND file_id = 1;
ECHO.
SQLCMD.EXE -b -E -S localhost -d master -Q "%_baseDirQuery%" -W >data_dir.tmp
IF ERRORLEVEL 1 ECHO Error with automatically determining SQL data directory by querying your server&ECHO using Windows authentication.
CALL :getBaseDir data_dir.tmp _baseDir
IF "%_baseDir:~-1%"=="\" SET "_baseDir=%_baseDir:~0,-1%"
DEL /Q data_dir.tmp
echo DataDir: %_baseDir%
GOTO :END
::---------------------------------------------
:: Functions
::---------------------------------------------
:simplePrompt 1-question 2-Return-var 3-default-Val
SET input=%~3
IF "%~3" NEQ "" (
:askAgain
SET /p "input=%~1 [%~3]:"
IF "!input!" EQU "" (
GOTO :askAgain
)
) else (
SET /p "input=%~1 [null]: "
)
SET "%~2=%input%"
EXIT /B 0
:getBaseDir fileName var
FOR /F "tokens=*" %%i IN (%~1) DO (
SET "_line=%%i"
IF "!_line:~0,2!" == "c:" (
SET "_baseDir=!_line!"
EXIT /B 0
)
)
EXIT /B 1
:END
PAUSE
IIF
is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END
. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.
CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.
try below code, it works for me in Mac10.10.2:
import subprocess
if __name__ == "__main__":
result = subprocess.check_output('ifconfig en0 |grep -w inet', shell=True) # you may need to use eth0 instead of en0 here!!!
print 'output = %s' % result.strip()
# result = None
ip = ''
if result:
strs = result.split('\n')
for line in strs:
# remove \t, space...
line = line.strip()
if line.startswith('inet '):
a = line.find(' ')
ipStart = a+1
ipEnd = line.find(' ', ipStart)
if a != -1 and ipEnd != -1:
ip = line[ipStart:ipEnd]
break
print 'ip = %s' % ip
You can use $.map()
(or even the .map()
function that operates on a jQuery object) to get an array of checked values. The unary (+) operator will cast the string to a number
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
console.log(arr);
Here's an example
Most of the other answers point to eager loading, but I found another solution.
In my case I had an EF object InventoryItem
with a collection of InvActivity
child objects.
class InventoryItem {
...
// EF code first declaration of a cross table relationship
public virtual List<InvActivity> ItemsActivity { get; set; }
public GetLatestActivity()
{
return ItemActivity?.OrderByDescending(x => x.DateEntered).SingleOrDefault();
}
...
}
And since I was pulling from the child object collection instead of a context query (with IQueryable
), the Include()
function was not available to implement eager loading. So instead my solution was to create a context from where I utilized GetLatestActivity()
and attach()
the returned object:
using (DBContext ctx = new DBContext())
{
var latestAct = _item.GetLatestActivity();
// attach the Entity object back to a usable database context
ctx.InventoryActivity.Attach(latestAct);
// your code that would make use of the latestAct's lazy loading
// ie latestAct.lazyLoadedChild.name = "foo";
}
Thus you aren't stuck with eager loading.
document.getElementById('link-id').href = "new-href";
I know this is an old post, but here's a one-liner that might be more suitable for some folks.
I had this problem with no detectable lock files. I found the solution here: http://schooner.uwaterloo.ca/twiki/bin/view/MAG/HgLockError
Here is a transcript from Tortoise Hg Workbench console
% hg debuglocks
lock: user None, process 7168, host HPv32 (114213199s)
wlock: free
[command returned code 1 Sat Jan 07 18:00:18 2017]
% hg debuglocks --force-lock
[command completed successfully Sat Jan 07 18:03:15 2017]
cmdserver: Process crashed
PaniniDev% hg debuglocks
% hg debuglocks
lock: free
wlock: free
[command completed successfully Sat Jan 07 18:03:30 2017]
After this the aborted pull ran sucessfully.
The lock had been set more than 2 years ago, by a process on a machine that is no longer on the LAN. Shame on the hg developers for a) not documenting locks adequately; b) not timestamping them for automatic removal when they get stale.
Use this :
<div style="width:700px; background:#F2F2F2">
<table style="width:100%;padding: 25px; margin: 0 auto; font-family:'Open Sans', 'Helvetica', 'Arial';">
<tr align="center" style="margin: 0; padding: 0;">
<td>
<table style="width:100%;border-style:solid; border-width:2px; border-color: #c3d2d9;" cellspacing="0">
<tr style="background-color: white;">
<td style=" padding: 10px 15px 10px 15px; color: #000000;">
<p>Some content here</p>
<span style="font-weight: bold;">My Signature</span><br/>
My Title<br/>
My Company<br/>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
If you sometimes run different versions of your application, make sure you delete 'Bla' from the application bin directory if the version running doesn't need it.
$ git submodule status --recursive
Is also a life saver in this situation. You can use it and gitk --all
to keep track of your sha1's and verify your sub-modules are pointing at what you think they are.
Another possible solution:
sek=[]
L=[1,2,3,4,5,6,7,8,9,0]
for i in [2, 4, 7, 0, 3]:
a=[L[i]]
sek=sek+a
print (sek)
I had the same problem and this is my solution. I had the following code:
se.GiftDescription = rs.getString(1);
se.GiftAmount = rs.getInt(2);
And I changed it to:
se.GiftDescription = rs.getString("DESCRIPTION");
se.GiftAmount = rs.getInt("AMOUNT");
And the problem was, after I restarted my PC, the column positions changed. That's why I got this error.
I recommend you to checkout @angular-material-components/datetime-picker. This is a DatetimePicker like @angular/material Datepicker by adding support for choosing time.
System.setProperty("gate.home", "/some/directory");
For more information, see:
System.setProperty( String key , String value )
.There is a free python tool called YouTube transcript API
You can use it in scripts or as a command line tool:
pip install youtube_transcript_api
If the close dismiss button is working but the problem occurs when using dynamic code such as modal('hide') you can use this code. forcing the backdrop to totally remove.
for Bootstrap 3
$modal.on('hidden.bs.modal', function(){
//remove the backdrop
jQuery('[data-dismiss="modal"]').click();
});
yourbutton.click(function() {
$modal.modal('hide');
});
yes, sql server doesn't allow to insert single quote in table field due to the sql injection attack. so we must replace single appostrophe by double while saving.
(he doesn't work for me) must be => (he doesn''t work for me)
Works for IE, Mozzila, Chrome
document.getElementById('YOUR IFRAME').contentDocument.location.reload(true);
I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.
set codedirectory=C:\Users\code
for /r %codedirectory% %%i in (*.c) do
( some GCC commands )
$('textarea').val();
textarea.value
would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value
).
document.getElementById('test').options[document.getElementById('test').selectedIndex].text;
To get properties from dynamic doc
when .GetType()
returns null
, try this:
var keyValuePairs = ((System.Collections.Generic.IDictionary<string, object>)doc);
var val = keyValuePairs["propertyName"].ToObject<YourModel>;
This paragraph from the FptWebRequest class reference might be of interest to you:
The URI may be relative or absolute. If the URI is of the form "ftp://contoso.com/%2fpath" (%2f is an escaped '/'), then the URI is absolute, and the current directory is /path. If, however, the URI is of the form "ftp://contoso.com/path", first the .NET Framework logs into the FTP server (using the user name and password set by the Credentials property), then the current directory is set to /path.
In my case with Android 8.0(Oreo), no one of this solutions worked! If you have more than 1 user, then you should go to Settings->Applications->All Applications->Find the application and uninstall for all users! After this steps, it worked!
So, something like the $_POST
array?
You can use http_build_query($_POST)
to get them in a var=xxx&var2=yyy
string again. Or just print_r($_POST)
to see what's there.
On my G2 I had to select PTP instead of MTP mode to get the connection to work.
Your title question and your example are completely different. I'll start by answering the title question:
$("a").removeAttr("href");
And as far as not requiring an href, the generally accepted way of doing this is:
<a href"#" onclick="doWork(); return false;">link</a>
The return false is necessary so that the href doesn't actually go anywhere.
Built-in Helpers
#if
You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.
template
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{else}}
<h1>Unknown Author</h1>
{{/if}}
</div>
When you pass the following input to the above template
{
author: true,
firstName: "Yehuda",
lastName: "Katz"
}
None of the suggested solutions worked for me when cloning a repository via ssh
. However, I was able to clone using https
, then later changed the remote to ssh
via:
git remote set-url origin [email protected]:USERNAME/REPOSITORY.git
If it's fixed layout you can do like that:
public void onClick(View v) {
ViewGroup parent = (ViewGroup) IdNumber.this.getParent();
EditText firstName = (EditText) parent.findViewById(R.id.display_name);
firstName.setText("Some Text");
}
If you want find the EditText in flexible layout, I will help you later. Hope this help.
You should access frames from window
and not document
window.frames['myIFrame'].document.getElementById('myIFrameElemId')
If column is not NOT NULL
(nullable).
You just put NULL
instead of value in INSERT
statement.
In eclipse you can use the old but still usable plugin jarsearch
Yet another solution with another algorithm without using collections:
def countFreq(A):
n=len(A)
count=[0]*n # Create a new list initialized with '0'
for i in range(n):
count[A[i]]+= 1 # increase occurrence for value A[i]
return [x for x in count if x] # return non-zero count
For anyone who needs to set up the title through the Toolbar some time after setting the SupportActionBar (@sorianiv) AND your Toolbar
is inside a CollapsingToolbarLayout
, read this:
mToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
//toolbar.setTitle(""); // no need to do this
//mToolbarLayout.setTitle("Title"); // if you need an initial title, do this instead
setSupportActionBar(toolbar);
Then later,
mToolbarLayout.setTitle("New Title");
You can modify the formData by catching the 'sending' event from your dropzone.
dropZone.on('sending', function(data, xhr, formData){
formData.append('fieldname', 'value');
});
I'll talk about the HashMap and TreeMap implementation in Java:
HashMap -- implement basic map interface
Map m = Collections.synchronizedMap(new HashMap(...));
TreeMap -- implement navigable map interface
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
To sum, the biggest difference between HashMap and TreeMap is that TreeMap implements NavigableMap<K,V>
, which provide the feature of ordered iteration. Besides, both HashMap and TreeMap are members of Java Collection framework. You can investigate the source code of Java to know more about their implementations.
This will work on SQL SERVER...
SELECT COL_LENGTH('Table', 'Column')
For the UITextField text comparison I am using below code and working fine for me, let me know if you find any error.
if(txtUsername.text.isEmpty || txtPassword.text.isEmpty)
{
//Do some stuff
}
else if(txtUsername.text == "****" && txtPassword.text == "****")
{
//Do some stuff
}
Five problems:
"$(...)"
to get the output of a command as text.[
is a command. Put a space between it and the arguments.echo
.rm "$folderToBeMoved"
The question was about Detecting which radio button is clicked, this is how you can get which button is clicked
final RadioGroup radio = (RadioGroup) dialog.findViewById(R.id.radioGroup1);
radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
View radioButton = radio.findViewById(checkedId);
int index = radio.indexOfChild(radioButton);
// Add logic here
switch (index) {
case 0: // first button
Toast.makeText(getApplicationContext(), "Selected button number " + index, 500).show();
break;
case 1: // secondbutton
Toast.makeText(getApplicationContext(), "Selected button number " + index, 500).show();
break;
}
}
});
In activity1
String easyPuzzle = "630208010200050089109060030"+
"008006050000187000060500900"+
"09007010681002000502003097";
Intent i = new Intent (this, activity2.class);
i.putExtra("puzzle", easyPuzzle);
startActivity(i);
In activity2
Intent i = getIntent();
String easyPuzzle = i.getStringExtra("puzzle");
You need to use following construction
InputStream in = getClass().getResourceAsStream("/yourFile");
Please note that you have to add this slash before your file name.
I've tweaked LostCajun's excellent post above to exclude system stored procedures. I also removed "Extract." from the code because I couldn't figure out what it's for and it gave me errors. The "fetch next" statement inside the loop also needed an "into" clause.
use <<databasename>>
go
declare @aQuery nvarchar(1024);
declare @spName nvarchar(64);
declare allSP cursor for
select p.name
from sys.procedures p
where p.type_desc = 'SQL_STORED_PROCEDURE'
and LEFT(p.name,3) NOT IN ('sp_','xp_','ms_')
order by p.name;
open allSP;
fetch next from allSP into @spName;
while (@@FETCH_STATUS = 0)
begin
set @aQuery = 'sp_helptext [' + @spName + ']';
exec sp_executesql @aQuery;
fetch next from allSP into @spName;
end;
close allSP;
deallocate allSP;
Design support library for androidX is implementation 'com.google.android.material:material:1.0.0'
My 2cents, in a single system user you can set the port also on /etc/ssh/ssh_config then rsync will use the port set here
Override method authenticationManagerBean
in WebSecurityConfigurerAdapter
to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder)
as a Spring bean:
For example:
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
This works:
location.href.split(location.pathname)[0];
Here is the official FAQ on installing Python Modules: http://docs.python.org/install/index.html
There are some tips which might help you.
I guess you are actually using Amazon Linux AMI 2013.03.1 instead of Ubuntu Server 12.x reason why you don't have apt-get tool installed.
I have improved on the solution above by providing support for different log levels and by changing the log levels automatically depending on if the code is being run on a live device or on the emulator.
public class Log {
final static int WARN = 1;
final static int INFO = 2;
final static int DEBUG = 3;
final static int VERB = 4;
static int LOG_LEVEL;
static
{
if ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)) {
LOG_LEVEL = VERB;
} else {
LOG_LEVEL = INFO;
}
}
/**
*Error
*/
public static void e(String tag, String string)
{
android.util.Log.e(tag, string);
}
/**
* Warn
*/
public static void w(String tag, String string)
{
android.util.Log.w(tag, string);
}
/**
* Info
*/
public static void i(String tag, String string)
{
if(LOG_LEVEL >= INFO)
{
android.util.Log.i(tag, string);
}
}
/**
* Debug
*/
public static void d(String tag, String string)
{
if(LOG_LEVEL >= DEBUG)
{
android.util.Log.d(tag, string);
}
}
/**
* Verbose
*/
public static void v(String tag, String string)
{
if(LOG_LEVEL >= VERB)
{
android.util.Log.v(tag, string);
}
}
}
In .ts :
today: Date;
constructor() {
this.today =new Date();
}
.html:
<input type="date"
[ngModel]="today | date:'yyyy-MM-dd'"
(ngModelChange)="today = $event"
name="dt"
class="form-control form-control-rounded" #searchDate
>
You can alternatively use recv(x_bytes, socket.MSG_WAITALL)
, which seems to work only on Unix, and will return exactly x_bytes
.
First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....
You need to specify the column in both expressions.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
While executing the job we need to pass Job parameters as follows:
JobParameters jobParameters= new JobParametersBuilder().addString("file.name", "filename.txt").toJobParameters();
JobExecution execution = jobLauncher.run(job, jobParameters);
by using the expression language we can import the value as follows:
#{jobParameters['file.name']}
innerHTML
sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.
For your case you want to set the value of an input element. So you should use the value
attribute.
Change innerHTML
to value
document.getElementById('add').value = sum;
this can be used inside some method or constructor.
It returns the reference to the current object.
Generally speaking, jQuery plugins are namespaces on the jQuery scope. You could run a simple check to see if the namespace exists:
if(jQuery().pluginName) {
//run plugin dependent code
}
dateJs however is not a jQuery plugin. It modifies/extends the javascript date object, and is not added as a jQuery namespace. You could check if the method you need exists, for example:
if(Date.today) {
//Use the dateJS today() method
}
But you might run into problems where the API overlaps the native Date API.
Here's a workaround. If you want to copy everything from A that does not already exist in B:
Copy A to a new directory C. Copy B to C, overwriting anything that overlaps with A. Copy C to B.
You missed in specifying the intent filter elements in your manifest file.Manifest file is:
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="Your Activity Name"
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>
Add and check this correctly. Hope this will help..
If after the *, you alias the id column that is breaking the query a secondtime... and give it a new name... it magically starts working.
select IDENTITY( int ) as TempID, *, SectionID as Fix2IDs
into #TempSections
from Files_Sections
Here's a category on SequenceType
which preserves the original order of the array, but uses a Set
to do the contains
lookups to avoid the O(n)
cost on Array's contains(_:)
method.
public extension Sequence where Element: Hashable {
/// Return the sequence with all duplicates removed.
///
/// i.e. `[ 1, 2, 3, 1, 2 ].uniqued() == [ 1, 2, 3 ]`
///
/// - note: Taken from stackoverflow.com/a/46354989/3141234, as
/// per @Alexander's comment.
func uniqued() -> [Element] {
var seen = Set<Element>()
return self.filter { seen.insert($0).inserted }
}
}
If you aren't Hashable or Equatable, you can pass in a predicate to do the equality check:
extension Sequence {
/// Return the sequence with all duplicates removed.
///
/// Duplicate, in this case, is defined as returning `true` from `comparator`.
///
/// - note: Taken from stackoverflow.com/a/46354989/3141234
func uniqued(comparator: @escaping (Element, Element) throws -> Bool) rethrows -> [Element] {
var buffer: [Element] = []
for element in self {
// If element is already in buffer, skip to the next element
if try buffer.contains(where: { try comparator(element, $0) }) {
continue
}
buffer.append(element)
}
return buffer
}
}
Now, if you don't have Hashable, but are Equatable, you can use this method:
extension Sequence where Element: Equatable {
/// Return the sequence with all duplicates removed.
///
/// i.e. `[ 1, 2, 3, 1, 2 ].uniqued() == [ 1, 2, 3 ]`
///
/// - note: Taken from stackoverflow.com/a/46354989/3141234
func uniqued() -> [Element] {
return self.uniqued(comparator: ==)
}
}
Finally, you can add a key path version of uniqued like this:
extension Sequence {
/// Returns the sequence with duplicate elements removed, performing the comparison usinig the property at
/// the supplied keypath.
///
/// i.e.
///
/// ```
/// [
/// MyStruct(value: "Hello"),
/// MyStruct(value: "Hello"),
/// MyStruct(value: "World")
/// ].uniqued(\.value)
/// ```
/// would result in
///
/// ```
/// [
/// MyStruct(value: "Hello"),
/// MyStruct(value: "World")
/// ]
/// ```
///
/// - note: Taken from stackoverflow.com/a/46354989/3141234
///
func uniqued<T: Equatable>(_ keyPath: KeyPath<Element, T>) -> [Element] {
self.uniqued { $0[keyPath: keyPath] == $1[keyPath: keyPath] }
}
}
You can stick both of these into your app, Swift will choose the right one depending on your sequence's Iterator.Element
type.
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
I would prefer to keep the "Show Whitespace" button on the toolbar, so that in one click you can toggle it.
Go to Window -> Perspective -> Customize Perspective and enable to show the button on toolbar.
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to @Thisguyhastwothumbs
If your using a new version of larval 7 >= you can use from your homested directory vagrant provision
Using the menus, open
In the "Installed software" tab click on the software that you wish to uninstall, then click the "Uninstall..." button below.
If you installed the plug-in by dropping into the dropins
folder, then just delete it from the dropins
folder and restart Eclipse.
See the answer of @Cogentleman for more recent versions of Eclipse.