For OpenGL rendering with the Nvidia driver, use the following image:
https://github.com/thewtex/docker-opengl-nvidia
For other OpenGL implementations, make sure the image has the same implementation as the host.
Set 'center_horizontal' and 'center_vertical' or just 'center' of the layout_gravity attribute of the widget
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MovieActivity"
android:id="@+id/mainContainerMovie"
>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3a3f51b5"
/>
<ProgressBar
android:id="@+id/movieprogressbar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
</FrameLayout>
Regular Expression that can be used:
Find: \w.+
Replace: able:"$&"
As, $&
will give you the string you search for.
Refer: regexr
Here is my solution similar to some others can wrap a function, but allows you to get the functions return value, if it suceeds.
/**
* Wraps a function with retry logic allowing exceptions to be caught and retires made.
*
* @param function the function to retry
* @param maxRetries maximum number of retires before failing
* @param delay time to wait between each retry
* @param allowedExceptionTypes exception types where if caught a retry will be performed
* @param <V> return type of the function
* @return the value returned by the function if successful
* @throws Exception Either an unexpected exception from the function or a {@link RuntimeException} if maxRetries is exceeded
*/
@SafeVarargs
public static <V> V runWithRetriesAndDelay(Callable<V> function, int maxRetries, Duration delay, Class<? extends Exception>... allowedExceptionTypes) throws Exception {
final Set<Class<? extends Exception>> exceptions = new HashSet<>(Arrays.asList(allowedExceptionTypes));
for(int i = 1; i <= maxRetries; i++) {
try {
return function.call();
} catch (Exception e) {
if(exceptions.contains(e.getClass())){
// An exception of an expected type
System.out.println("Attempt [" + i + "/" + maxRetries + "] Caught exception [" + e.getClass() + "]");
// Pause for the delay time
Thread.sleep(delay.toMillis());
}else {
// An unexpected exception type
throw e;
}
}
}
throw new RuntimeException(maxRetries + " retries exceeded");
}
import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
At this point you have a color and a gray image. We are dealing with 8-bit
, uint8
images here. That means the images can have pixel values in the range of [0, 255]
and the values have to be integers.
Let's do a binary thresholding operation. It creates a black and white masked image. The black regions have value 0
and the white regions 255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
The mask can be seen below on the left. The image on it's right is the result of applying bitwise_and
operation between the gray image and the mask. What happened is, the spatial locations where the mask had a pixel value zero (black), became pixel value zero in the result image. The locations where the mask had pixel value 255 (white), the resulting image retained it's original gray value.
To apply this mask to our original color image, we need to convert the mask into a 3 channel image as the original color image is a 3 channel image.
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
Then, we can apply this 3 channel mask to our color image using the same bitwise_and
function.
im_thresh_color = cv.bitwise_and(im_color, mask3)
mask3
from the code is the image below on the left, and im_thresh_color
is on its right.
You can plot the results and see for yourself.
cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
The original image is lenacolor.png
that I found here.
The first time you run the page, the query_age index doesn't exist because it hasn't been sent over from the form.
When you submit the form it will then exist, and it won't complain about it.
#so change
$_GET['query_age'];
#to:
(!empty($_GET['query_age']) ? $_GET['query_age'] : null);
For me this is the simplest way:
switch (["afshin","saeed","larry"].includes(varName) ? 1 : 2) {
case 1:
alert('Hey');
break;
default:
alert('Default case');
break;
}
You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.
If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.
Accept: application/xml
You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1
EDIT: based on your edited question with code:
Simple return list of string, instead of converting it to XML. try it using Fiddler.
public List<string> Get(int tenantID, string dataType, string ActionName)
{
List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
return SQLResult;
}
For example if your list is like:
List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;
and you specify Accept: application/xml
the output will be:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>Test1</string>
<string>Test2</string>
<string>Test3</string>
</ArrayOfstring>
and if you specify 'Accept: application/json' in the request then the output will be:
[
"Test1",
"Test2",
"Test3"
]
So let the client request the content type, instead of you sending the customized xml.
My 2 cents
I was getting this in a docker image using alpine. The django settings referenced /dev/log
for logging to syslog. The django app and celery worker were both based on the same image. The entrypoint of the django app image was launching syslogd
on start, but the one for the celery worker was not. This was causing things like ./manage.py shell
to fail because there wouldn't be any /dev/log
. The celery worker was not failing. Instead, it was silently just ignoring the rest of the app launch, which included loading shared_task
entries from applications in the django project
Is there an easy way to convert jQuery code to regular javascript?
No, especially if:
understanding the examples of javascript solutions written in jQuery [is] hard.
JQuery and all the frameworks tend to make understanding the code easier. If that's difficult to understand, then vanilla javascript will be torture :)
Using python 64 bit solves lot of problems.
A JIT compiler runs after the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently.
This is in contrast to a traditional compiler that compiles all the code to machine language before the program is first run.
To paraphrase, conventional compilers build the whole program as an EXE file BEFORE the first time you run it. For newer style programs, an assembly is generated with pseudocode (p-code). Only AFTER you execute the program on the OS (e.g., by double-clicking on its icon) will the (JIT) compiler kick in and generate machine code (m-code) that the Intel-based processor or whatever will understand.
Alternatively you can install the cx_Oracle module without the PIP using the following steps
Extract the tar using the following commands (Linux)
gunzip cx_Oracle-6.1.tar.gz
tar -xf cx_Oracle-6.1.tar
cd cx_Oracle-6.1
Build the module
python setup.py build
Install the module
python setup.py install
//Code to encrypt Data :
public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)
{
AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();
//Block size : Gets or sets the block size, in bits, of the cryptographic operation.
dataencrypt.BlockSize = 128;
//KeySize: Gets or sets the size, in bits, of the secret key
dataencrypt.KeySize = 128;
//Key: Gets or sets the symmetric key that is used for encryption and decryption.
dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
//IV : Gets or sets the initialization vector (IV) for the symmetric algorithm
dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
//Padding: Gets or sets the padding mode used in the symmetric algorithm
dataencrypt.Padding = PaddingMode.PKCS7;
//Mode: Gets or sets the mode for operation of the symmetric algorithm
dataencrypt.Mode = CipherMode.CBC;
//Creates a symmetric AES encryptor object using the current key and initialization vector (IV).
ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);
//TransformFinalBlock is a special function for transforming the last block or a partial block in the stream.
//It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of
//information returned at the end might be larger than a single block when padding is added.
byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);
crypto1.Dispose();
//return the encrypted data
return encrypteddata;
}
//code to decrypt data
private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)
{
AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();
keydecrypt.BlockSize = 128;
keydecrypt.KeySize = 128;
keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
keydecrypt.Padding = PaddingMode.PKCS7;
keydecrypt.Mode = CipherMode.CBC;
ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);
byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);
crypto1.Dispose();
return returnbytearray;
}
In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file">
tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.
function onFileLoad(elementId, event) {_x000D_
document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
if (typeof window.FileReader !== 'function')_x000D_
throw ("The file API isn't supported on this browser.");_x000D_
let input = event.target;_x000D_
if (!input)_x000D_
throw ("The browser does not properly implement the event object");_x000D_
if (!input.files)_x000D_
throw ("This browser does not support the `files` property of the file input.");_x000D_
if (!input.files[0])_x000D_
return undefined;_x000D_
let file = input.files[0];_x000D_
let fr = new FileReader();_x000D_
fr.onload = onLoadFileHandler;_x000D_
fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
First set position
of the parent DIV to relative
(specifying the offset, i.e. left
, top
etc. is not necessary) and then apply position: absolute
to the child DIV with the offset you want.
It's simple and should do the trick well.
My guess is that you've got something in method1
which wraps one exception in another, and uses the toString()
of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage()
behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message
I am wondering if you are after something like Squiggle. Also something very useful is jDBI. It won't help you with the queries though.
for (int j = 0; j < 5; j++) //inner loop
should be replaced with
for (int j = 0; j < 5 && !exitloops; j++)
.
Here, in this case complete nested loops should be exit if condition is True
. But if we use exitloops
only to the upper loop
for (int i = 0; i < 5 && !exitloops; i++) //upper loop
Then inner loop will continues, because there is no extra flag that notify this inner loop to exit.
Example : if
i = 3
andj=2
then condition isfalse
. But in next iteration of inner loopj=3
then condition(i*j)
become9
which istrue
but inner loop will be continue tillj
become5
.
So, it must use exitloops
to the inner loops too.
boolean exitloops = false;
for (int i = 0; i < 5 && !exitloops; i++) { //here should exitloops as a Conditional Statement to get out from the loops if exitloops become true.
for (int j = 0; j < 5 && !exitloops; j++) { //here should also use exitloops as a Conditional Statement.
if (i * j > 6) {
exitloops = true;
System.out.println("Inner loop still Continues For i * j is => "+i*j);
break;
}
System.out.println(i*j);
}
}
This would be a clean, readable and reusable solution using grep
and echo
to add a line to a file only if it doesn't already exist:
LINE='include "/configs/projectname.conf"'
FILE='lighttpd.conf'
grep -qF -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
If you need to match the whole line use grep -xqF
Add -s
to ignore errors when the file does not exist, creating a new file with just that line.
I think it's meant to mean nothing. The wiki says:
"Foo is commonly used with the metasyntactic variables bar and foobar."
While base64 encoding is safe and one could argue "the right answer", I arrived here looking for a way to convert a Java byte array to/from a Java String as-is. That is, where each member of the byte array remains intact in its String counterpart, with no extra space required for encoding/transport.
This answer describing 8bit transparent encodings was very helpful for me. I used ISO-8859-1
on terabytes of binary data to convert back and forth successfully (binary <-> String) without the inflated space requirements needed for a base64 encoding, so is safe for my use-case - YMMV.
This was also helpful in explaining when/if you should experiment.
For images if your using Web Pages v2 use the WebImage Class
var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
byte[] imgByteArray = webImage.GetBytes();
The file opened by codecs.open
is a file that takes unicode
data, encodes it in iso-8859-1
and writes it to the file. However, what you try to write isn't unicode
; you take unicode
and encode it in iso-8859-1
yourself. That's what the unicode.encode
method does, and the result of encoding a unicode string is a bytestring (a str
type.)
You should either use normal open()
and encode the unicode yourself, or (usually a better idea) use codecs.open()
and not encode the data yourself.
It's much easier if you use Response.raw
and shutil.copyfileobj()
:
import requests
import shutil
def download_file(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
This streams the file to disk without using excessive memory, and the code is simple.
You could use find along with the -exec flag in a single command line to do the job
find . -name "*.zip" -exec unzip {} \;
Just set the TextBox.PasswordChar property to '*'.
FYI - none of the above worked for me in 2012 SP1...simple solution was to embed credentials in the shared data source and then tell Safari to trust the SSRS server site. Then it worked great! Took days chasing down supposed solutions like above only to find out integrated security won't work reliably on Safari - you have to mess with the keychain on the mac and then still wouldn't work reliably.
You can convert your string to a DateTime
value like this:
DateTime date = DateTime.Parse(something);
You can convert a DateTime
value to a formatted string like this:
date.ToString("yyyyMMdd");
function chgAction( action_name )
{
if( action_name=="aaa" ) {
document.search-theme-form.action = "/AAA";
}
else if( action_name=="bbb" ) {
document.search-theme-form.action = "/BBB";
}
else if( action_name=="ccc" ) {
document.search-theme-form.action = "/CCC";
}
}
And your form needs to have name
in this case:
<form action="/" accept-charset="UTF-8" method="post" name="search-theme-form" id="search-theme-form">
Using Select2 4.0 with Meteor you can do something like this:
Template.TemplateName.rendered = ->
$("#select2-el").select2({
data : Session.get("select2Data")
})
@autorun ->
# Clear the existing list options.
$("#select2-el").select2().empty()
# Re-create with new options.
$("#select2-el").select2({
data : Session.get("select2Data")
})
What's happening:
This works for any reactive data source - such as a Collection.find().fetch() - not just Session.get().
NOTE: as of Select2 version 4.0 you must remove existing options before adding new onces. See this GitHub Issue for details. There is no method to 'update the options' without clearing the existing ones.
The above is coffeescript. Very similar for Javascript.
JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [42, 47, 139]
}
If you're doing a lot of string concatenation, use a StringBuilder. When you concatenate with a String, you create a new String each time, using up more memory.
Alex
I had a similar problem, with two jar libraries (app1 and app2) in one project. The bean "BeanName" is defined in app1 and is extended in app2 and the bean redefined with the same name.
In app1:
package com.foo.app1.pkg1;
@Component("BeanName")
public class Class1 { ... }
In app2:
package com.foo.app2.pkg2;
@Component("BeanName")
public class Class2 extends Class1 { ... }
This causes the ConflictingBeanDefinitionException
exception in the loading of the applicationContext due to the same component bean name.
To solve this problem, in the Spring configuration file applicationContext.xml
:
<context:component-scan base-package="com.foo.app2.pkg2"/>
<context:component-scan base-package="com.foo.app1.pkg1">
<context:exclude-filter type="assignable" expression="com.foo.app1.pkg1.Class1"/>
</context:component-scan>
So the Class1 is excluded to be automatically component-scanned and assigned to a bean, avoiding the name conflict.
sometimes, you can use regex
>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>
Simple Regular expression: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g
Check out the format, hope it works :
444-555-1234
f:246.555.8888
m:1235554567
You can also overload the Function prototype:
// partially applies the specified arguments to a function, returning a new function
Function.prototype.curry = function( ) {
var func = this;
var slice = Array.prototype.slice;
var appliedArgs = slice.call( arguments, 0 );
return function( ) {
var leftoverArgs = slice.call( arguments, 0 );
return func.apply( this, appliedArgs.concat( leftoverArgs ) );
};
};
// can do other fancy things:
// flips the first two arguments of a function
Function.prototype.flip = function( ) {
var func = this;
return function( ) {
var first = arguments[0];
var second = arguments[1];
var rest = Array.prototype.slice.call( arguments, 2 );
var newArgs = [second, first].concat( rest );
return func.apply( this, newArgs );
};
};
/*
e.g.
var foo = function( a, b, c, d ) { console.log( a, b, c, d ); }
var iAmA = foo.curry( "I", "am", "a" );
iAmA( "Donkey" );
-> I am a Donkey
var bah = foo.flip( );
bah( 1, 2, 3, 4 );
-> 2 1 3 4
*/
InnoDB has transaction support, you're not using explicit transactions so innoDB has to do a commit after each statement ("performs a log flush to disk for every insert").
Execute this command before your loop:
START TRANSACTION
and this after you loop
COMMIT
Use the modulo arithmetic operation found here in the PHP manual.
e.g.
$x = 3;
for($i=0; $i<10; $i++)
{
if($i % $x == 0)
{
// display image
}
}
For a more detailed understanding of modulus calculations, click here.
What about sed? That will work in a single command:
sed 's#.*/\([^:]*\).*#\1#' <<<$string
#
are being used for regex dividers instead of /
since the string has /
in it..*/
grabs the string up to the last backslash.\( .. \)
marks a capture group. This is \([^:]*\)
.
[^:]
says any character _except a colon, and the *
means zero or more..*
means the rest of the line.\1
means substitute what was found in the first (and only) capture group. This is the name.Here's the breakdown matching the string with the regular expression:
/var/cpanel/users/ joebloggs :DNS9=domain.com joebloggs
sed 's#.*/ \([^:]*\) .* #\1 #'
MSDN has a nice descriptive article on nulls and the three state logic that they engender.
In short, the SQL92 spec defines NULL as unknown, and NULL used in the following operators causes unexpected results for the uninitiated:
= operator NULL true false
NULL NULL NULL NULL
true NULL true false
false NULL false true
and op NULL true false
NULL NULL NULL false
true NULL true false
false false false false
or op NULL true false
NULL NULL true NULL
true true true true
false NULL true false
This might have changed since the original answer was written, but it looks like you can now use the Models populate function to do this without having to execute an extra findOne. See: http://mongoosejs.com/docs/api.html#model_Model.populate. You'd want to use this inside the save handler just like the findOne is.
Here's another way of doing the code above using the openpyxl
module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.
from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')
This is what lambda is for:
def perform(f):
f()
perform(lambda: action1())
perform(lambda: action2(p))
perform(lambda: action3(p, r))
You can convert the java.util.Date
object into a String
object, which will format the date as yyyy-mm-dd.
LocalDate has a parse
method that will convert it to a LocalDate
object. The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.
Date to LocalDate
LocalDate.parse(Date.toString())
when you have Failed to connect to remote VM Connection refused error, restart your eclipse
Something like:
clients.stream.filter(c->{
users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());
This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.
Comparator
provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable
allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator
.
Otherwise you can use Comparable
.
In 2020 I use the MoreLinq
Pipe
method. https://morelinq.github.io/2.3/ref/api/html/M_MoreLinq_MoreEnumerable_Pipe__1.htm
Under some circumstances (such as earlier versions of IE, Gecko, Webkit) and inheritance, elements with position:relative;
will prevent margin:0 auto;
from working, even if top
, right
, bottom
, and left
aren't set.
Setting the element to position:static;
(the default) may fix it under these circumstances. Generally, block level elements with a specified width will respect margin:0 auto;
using either relative
or static
positioning.
The canonical examples are __declspec(dllimport)
and __declspec(dllexport)
, which instruct the linker to import and export (respectively) a symbol from or to a DLL.
// header
__declspec(dllimport) void foo();
// code - this calls foo() somewhere in a DLL
foo();
(__declspec(..)
just wraps up Microsoft's specific stuff - to achieve compatibility, one would usually wrap it away with macros)
I had the same error caused by build errors. I ran ng build in the directory of my application which helped me correct my errors
Use mvn dependency:purge-local-repository -DactTransitively=false -Dskip=true
if you have maven plugins as one of the modules. Otherwise Maven will try to recompile them, thus downloading the dependencies again.
you can use mongo query like this yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}
HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}
If you don't have avahi installed then it's probably cups.
simple(?) way to do it from python (on mysql):
from django.db import connection
cursor = connection.cursor()
cursor.execute('show tables;')
parts = ('DROP TABLE IF EXISTS %s;' % table for (table,) in cursor.fetchall())
sql = 'SET FOREIGN_KEY_CHECKS = 0;\n' + '\n'.join(parts) + 'SET FOREIGN_KEY_CHECKS = 1;\n'
connection.cursor().execute(sql)
by typing yes it wont charge taxes, by typing no it will charge taxes.
=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))
This should also work (even in SQL-Server 2005):
SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
AND Created < DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))
I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)
But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this:
jdbc:sqlserver://localhost;integratedSecurity=true;
And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver)
MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL
Normal answer for this question if you really want to get something like content//media/external/video/media/18576
(e.g. for your video mp4 absolute path) and not just file///storage/emulated/0/DCIM/Camera/20141219_133139.mp4
:
MediaScannerConnection.scanFile(this,
new String[] { file.getAbsolutePath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("onScanCompleted", uri.getPath());
}
});
Accepted answer is wrong (cause it will not return content//media/external/video/media/*
)
Uri.fromFile(file).toString()
only returns something like file///storage/emulated/0/*
which is a simple absolute path of a file on the sdcard but with file//
prefix (scheme)
You can also get content
uri using MediaStore
database of Android
TEST (what returns Uri.fromFile
and what returns MediaScannerConnection
):
File videoFile = new File("/storage/emulated/0/video.mp4");
Log.i(TAG, Uri.fromFile(videoFile).toString());
MediaScannerConnection.scanFile(this, new String[] { videoFile.getAbsolutePath() }, null,
(path, uri) -> Log.i(TAG, uri.toString()));
Output:
I/Test: file:///storage/emulated/0/video.mp4
I/Test: content://media/external/video/media/268927
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
"Unlink" essentially means "delete file" in this case.
This error is not caused by git itself. You should have similar errors deleting those files manually, in a command line or file explorer.
Go to Tools > Options > Advanced "Tab"(?) > Encryption Tab
Click the "Validation" button, and uncheck the checkbox for checking validity
Be advised though that this is pretty unsecure as it leaves you wide open to accept any invalid certificate. I'd only do this if using the browser on an Intranet where the validity of the cert isn't a concern to you, or you aren't concerned in general.
Here is the configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)
file: /etc/hosts (non-windows)
127.0.0.1 example.local
file: /XAMPP/etc/httpd.conf
# Virtual hosts
Include etc/extra/httpd-vhosts.conf
file: XAMPP/etc/extra/httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/path_to_XAMPP/htdocs"
ServerName example.local
ServerAlias *.example.local
# SetEnv APP_ENVIRONMENT development
# ErrorLog "logs/example.local-error_log"
# CustomLog "logs/example.local-access_log" common
</VirtualHost>
restart apache
save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)
function FindProxyForURL(url, host) {
if (shExpMatch(host, "*example.local")) {
return "PROXY example.local";
}
return "DIRECT";
}
Define 2 overload functions.
virtual const ULONG Write(ULONG &State, bool sequence = true);
virtual const ULONG Write(bool sequence = true)
{
int State = 0;
return Write(State, sequence);
}
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
Basically, the third parameter in loggedIn
should not be an integer, it should be an object of some kind, but we can't know for sure because you did not name the parameters in the method call. Provide the method signature so we can see for sure. Perhaps it takes an NSNumber
or something.
I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).
Also in Logic Friday the expression A | B
just returns 3 entries in truth table; I expected 4.
I found a bug on Ankur answer and I've fixed it with this correction:
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Plz enter on Alphabets ')"
onchange="try{setCustomValidity('')}catch(e){}" />
The bug seen when you set an invalid input data, then correct the input and send the form. oops! you can't do this. I've tested it on firefox and chrome
If I remember correctly, and more often then not I do ... there is no END IF support in Transact-Sql. The BEGIN and END should do the job. Are you getting errors?
I have experienced the same issue before. In my case, I needed to install php-mbstring extension on GoDaddy VPS server. None of above solutions did work for me.
What I've found is to install PHP extensions using WHM (Web Hosting Manager) of GoDaddy. Anyone who use GoDaddy VPS server can access this page with the following address.
http://{Your_Server_IP_Address}:2087
On this page, you can easily find Easy Apache software that can help you to install/upgrade php components and extensions. You can select currently installed profile and customize and then provision the profile. Everything with Easy Apache is explanatory.
I remember that I did very similar things for HostGator server, but I don't remember how actually I did for profile update.
Edit: When you have got the server which supports Web Hosting Manager, then you can add/update/remove php extensions on WHM. On godaddy servers, it's even recommended to update PHP ini settings on WHM.
I needed to process the entire line as a whole. Here is what I found to work.
for /F "tokens=*" %%A in (myfile.txt) do [process] %%A
The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.
If there are spaces in your file path, you need to use usebackq
. For example.
for /F "usebackq tokens=*" %%A in ("my file.txt") do [process] %%A
You can use this function based on array_walk:
function mapToIDs($array, $id_field_name = 'id')
{
$result = [];
array_walk($array,
function(&$value, $key) use (&$result, $id_field_name)
{
$result[$value[$id_field_name]] = $value;
}
);
return $result;
}
$arr = [0 => ['id' => 'one', 'fruit' => 'apple'], 1 => ['id' => 'two', 'fruit' => 'banana']];
print_r($arr);
print_r(mapToIDs($arr));
It gives:
Array(
[0] => Array(
[id] => one
[fruit] => apple
)
[1] => Array(
[id] => two
[fruit] => banana
)
)
Array(
[one] => Array(
[id] => one
[fruit] => apple
)
[two] => Array(
[id] => two
[fruit] => banana
)
)
A terse solution using plain Javascript (thanks to Sygmoral for suggested improvements):
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 39:
alert('right');
break;
}
};
First make sure that the folder in which your .mdf file resides is not read only. If it is, un-check that option and make sure it reflects to folders and files within that folder.
Once that is done, Open Management Studio, in the Object Explorer right click on the Database which is read only and select Properties. In the Options Menu, check that the Read-Only property is false.
You need add Firebase Gradle buildscript dependency in build.gradle (project-level)
classpath 'com.google.gms:google-services:3.1.0'
and add Firebase plugin for Gradle in app/build.gradle
apply plugin: 'com.google.gms.google-services'
build.gradle will include these new dependencies:
compile 'com.google.firebase:firebase-database:11.0.4'
Source: Android Studio Assistant
While selecting library it's also important to see if it supports modern frameworks such as Bower, passes jslint, supports plugin model for JQuery or module systems such as AMD/RequireJS in addition to being in active development and have more than 1 contributors. There are couple of options that satisfies some or all of these additional criteria:
Example from CryptoJS:
//just include md5.js from the CryptoJS rollups folder
var hash = CryptoJS.MD5("Message");
console.log(hash.toString());
There is a performance comparison between above libraries at http://jsperf.com/md5-shootout/7. On my machine current tests (which are admittedly old) shows that if you are looking for speed Spark MD5 is your best bet (and so is plain JKM code). However if you looking for more comprehensive library then CryptoJS is your best bet although it is 79% slower than Spark MD5. However I would imagine CryptoJS would eventually achieve same speed as it is bit more active project.
I liked the Xembly syntax, but it is not a statically typed API. You can get this with XMLBeam:
// Declare a projection
public interface Projection {
@XBWrite("/root/order/@id")
Projection setID(int id);
@XBWrite("/root/order")
Projection setValue(String value);
}
public static void main(String[] args) {
// create a projector
XBProjector projector = new XBProjector();
// use it to create a projection instance
Projection projection = projector.projectEmptyDocument(Projection.class);
// You get a fluent API, with java types in parameters
projection.setID(553).setValue("$140.00");
// Use the projector again to do IO stuff or create an XML-string
projector.toXMLString(projection);
}
My experience is that this works great even when the XML gets more complicated. You can just decouple the XML structure from your java code structure.
If you want to automate the steps, the suggestions here will work only to an extent.
I came across this tool called fetch
and it worked quite fine for me. You can even specify the release. So, it takes a step to download and set it as executable, then fetch the required folder:
curl -sSLfo ./fetch \
https://github.com/gruntwork-io/fetch/releases/download/v0.3.12/fetch_linux_amd64
chmod +x ./fetch
./fetch --repo="https://github.com/foo/bar" --tag="${VERSION}" --source-path="/baz" /tmp/baz
You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}
The following will remove all the objects from your console
rm(list = ls())
A quick solution in eclipse to resolve when Tomcat could not load as per the following error:
Just refresh the Tomcat folder should do the trick. If it still does not work, delete all files in eclipse under the Tomcat folder, re-copy the server files then refresh the Tomcat folder. Tomcat should restart correctly after that.
In my case I got this error when I had mistakenly named a class the same as the class it was inheriting from.
/* for chrome */
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;}
/* for mozilla */
input[type=number] {-moz-appearance: textfield;}
No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:
const requestUrl = url.parse(url.format({
protocol: 'https',
hostname: 'yoursite.com',
pathname: '/the/path',
query: {
key: value
}
}));
Then make the request with the formatted url. requestUrl.path
will include the query parameters.
const req = https.get({
hostname: requestUrl.hostname,
path: requestUrl.path,
}, (res) => {
// ...
})
One simple but elegant way is to create a config.php
file (or whatever you call it) that just returns an array:
<?php
return array(
'host' => 'localhost',
'username' => 'root',
);
And then:
$configs = include('config.php');
request.user.get_username()
or request.user.username
, former is preferred.
Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.
P.S. For templates, use {{ user.get_username }}
Didn't wan to mess with carbon. So here's my solution
$start = new \DateTime('now');
$start->modify('first day of this month');
$end = new \DateTime('now');
$end->modify('last day of this month');
$new_releases = Game::whereBetween('release', array($start, $end))->get();
For future Google'rs that use Laravel 5, you can now also use it with includes,
@include('views.otherView', ['variable' => 1])
-Windows+r
open cmd.
-sc YourSeviceName
this code remove your service.
-Uninstal "YourService Path"
this code uninstall your service.
You can loop through the cells of any column in a table by knowing just its name and not its position. If the table is in sheet1 of the workbook:
Dim rngCol as Range
Dim cl as Range
Set rngCol = Sheet1.Range("TableName[ColumnName]")
For Each cl in rngCol
cl.Value = "PHEV"
Next cl
The code above will loop through the data values only, excluding the header row and the totals row. It is not necessary to specify the number of rows in the table.
Use this to find the location of any column in a table by its column name:
Dim colNum as Long
colNum = Range("TableName[Column name to search for]").Column
This returns the numeric position of a column in the table.
I realize this is an old question but for those reading, I would recommend against using recursion for problems such as this - lists are much faster and avoid recursion entirely. I would implement this as:
def fibonacci(n):
f = [0,1,1]
for i in xrange(3,n):
f.append(f[i-1] + f[i-2])
return 'The %.0fth fibonacci number is: %.0f' % (n,f[-1])
(Use n+1 in xrange if you start counting your fibonacci sequence from 0 instead of 1.)
It's declared inside a closure, which means it can only be accessed there. If you want a variable accessible globally, you can remove the var
:
$(function(){
value = "10";
});
value; // "10"
This is equivalent to writing window.value = "10";
.
I have already update my node to Version 5.0.0 And I work work with this:
function toArrayBuffer(buffer){
var array = [];
var json = buffer.toJSON();
var list = json.data
for(var key in list){
array.push(fixcode(list[key].toString(16)))
}
function fixcode(key){
if(key.length==1){
return '0'+key.toUpperCase()
}else{
return key.toUpperCase()
}
}
return array
}
I use it to check my vhd disk image.
Very old but I have just struggled with this, this is how I solved it in pure xml. In res/values/colors.xml I added three colours (the colour_...);
<resources>
<color name="black_overlay">#66000000</color>
<color name="colour_highlight_grey">#ff666666</color>
<color name="colour_dark_blue">#ff000066</color>
<color name="colour_dark_green">#ff006600</color>
</resources>
In the res/drawable folder I created listview_colours.xml which contained;
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/colour_highlight_grey" android:state_pressed="true"/>
<item android:drawable="@color/colour_dark_blue" android:state_selected="true"/>
<item android:drawable="@color/colour_dark_green" android:state_activated="true"/>
<item android:drawable="@color/colour_dark_blue" android:state_focused="true"/>
</selector>
In the main_activity.xml find the List View and add the drawable to listSelector;
<ListView
android:id="@+id/menuList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@drawable/listview_colours"
android:background="#ff222222"/>
</LinearLayout>
Play with the state_... items in the listview_colours.xml to get the effect you want.
There is also a method where you can set the style of the List View but I never managed to get it to work
To get only the name of the directory where script executed:
//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"
The stat module will do this as well as obtain a lot of other information for files. From the example documentation:
- stat: path=/path/to/something
register: p
- debug: msg="Path exists and is a directory"
when: p.stat.isdir is defined and p.stat.isdir
Let me to recommend you a jQuery plugin for nice modal alers. It doesn't requires jquery UI.
Demo: http://www.webmasters.by/images/articles/jquery.alerts/index.html
Having $line
as it is now, you can simply split the string based on at least one whitespace separator
my @answer = split(' ', $line); # creates an @answer array
then
print("@answer\n"); # print array on one line
or
print("$_\n") for (@answer); # print each element on one line
I prefer using ()
for split
, print
and for
.
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">
Try This
.content {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 250px;_x000D_
width: 200px;_x000D_
border: solid;_x000D_
word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.content h1 , .content h2 {_x000D_
margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
.content p {_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="content">_x000D_
<h1>heading 1</h1>_x000D_
<h2>heading 2</h2>_x000D_
<p>Some more or less text</p>_x000D_
<a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
Check DateDiff out on Books Online.
suppose you're posting a html form with this:
<input type="text" name="username">
If using raw cgi:
import cgi
form = cgi.FieldStorage()
print form["username"]
If using Django, Pylons, Flask or Pyramid:
print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method
Using Turbogears, Cherrypy:
from cherrypy import request
print request.params['username']
form = web.input()
print form.username
print request.form['username']
If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:
def index(self, username):
print username
class SomeHandler(webapp2.RequestHandler):
def post(self):
name = self.request.get('username') # this will get the value from the field named username
self.response.write(name) # this will write on the document
So you really will have to choose one of those frameworks.
Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.
Here's some sample code:
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController () {
MPMoviePlayerController *moviePlayerController;
}
@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Instantiate a movie player controller and add it to your view
NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[moviePlayerController.view setFrame:self.movieView.bounds]; // player's frame must match parent's
[self.movieView addSubview:moviePlayerController.view];
// Configure the movie player controller
moviePlayerController.controlStyle = MPMovieControlStyleNone;
[moviePlayerController prepareToPlay];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Start the movie
[moviePlayerController play];
}
@end
You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
com.nhaarman.mockitokotlin2.mock {}
This error occurs when, for example, we create a mock inside another mock
mock {
on { x() } doReturn mock {
on { y() } doReturn z()
}
}
The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.
val liveDataMock = mock {
on { y() } doReturn z()
}
mock {
on { x() } doReturn liveDataMock
}
GL
Try using online generator css3.me
Change the value and get the code, pretty simple.
I got the same error in the "Spring Tool Suite" software.
In my case, I have Java 8 installed and I created a project of Java 11. And when I run the project I got the same error, like " can not find main class ".
Then I created a project in Java 8 and the problem resolved.
I was going to ask if you would not want to just use a List<Pair<T, U>>
? but then, of course, the JDK doesn't have a Pair<> class. But a quick Google found one on both Wikipedia, and forums.sun.com. Cheers
Does allowing people to say
myTeam.subList(3, 5);
make any sense at all? If not then it shouldn't be a List.
I'm running under .NET 4.5.2, and I wasn't happy with any of these answers. As I'm talking to a system which supports TLS 1.2, and seeing as SSL3, TLS 1.0, and TLS 1.1 are all broken and unsafe for use, I don't want to enable these protocols. Under .NET 4.5.2, the SSL3 and TLS 1.0 protocols are both enabled by default, which I can see in code by inspecting ServicePointManager.SecurityProtocol
. Under .NET 4.7, there's the new SystemDefault
protocol mode which explicitly hands over selection of the protocol to the OS, where I believe relying on registry or other system configuration settings would be appropriate. That doesn't seem to be supported under .NET 4.5.2 however. In the interests of writing forwards-compatible code, that will keep making the right decisions even when TLS 1.2 is inevitably broken in the future, or when I upgrade to .NET 4.7+ and hand over more responsibility for selecting an appropriate protocol to the OS, I adopted the following code:
SecurityProtocolType securityProtocols = ServicePointManager.SecurityProtocol;
if (securityProtocols.HasFlag(SecurityProtocolType.Ssl3) || securityProtocols.HasFlag(SecurityProtocolType.Tls) || securityProtocols.HasFlag(SecurityProtocolType.Tls11))
{
securityProtocols &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11);
if (securityProtocols == 0)
{
securityProtocols |= SecurityProtocolType.Tls12;
}
ServicePointManager.SecurityProtocol = securityProtocols;
}
This code will detect when a known insecure protocol is enabled, and in this case, we'll remove these insecure protocols. If no other explicit protocols remain, we'll then force enable TLS 1.2, as the only known secure protocol supported by .NET at this point in time. This code is forwards compatible, as it will take into consideration new protocol types it doesn't know about being added in the future, and it will also play nice with the new SystemDefault
state in .NET 4.7, meaning I won't have to re-visit this code in the future. I'd strongly recommend adopting an approach like this, rather than hard-coding any particular security protocol states unconditionally, otherwise you'll have to recompile and replace your client with a new version in order to upgrade to a new security protocol when TLS 1.2 is inevitably broken, or more likely you'll have to leave the existing insecure protocols turned on for years on your server, making your organisation a target for attacks.
How about this? I needed the exact same thing, I had to create one from scratch. It's PURE CSS, and works in IE9+ Feel-free to improve upon it.
Demo: http://www.d-k-j.com/Articles/Web_Development/Pure_CSS_5_Star_Rating_System_with_Radios/
<ul class="form">
<li class="rating">
<input type="radio" name="rating" value="0" checked /><span class="hide"></span>
<input type="radio" name="rating" value="1" /><span></span>
<input type="radio" name="rating" value="2" /><span></span>
<input type="radio" name="rating" value="3" /><span></span>
<input type="radio" name="rating" value="4" /><span></span>
<input type="radio" name="rating" value="5" /><span></span>
</li>
</ul>
CSS:
.form {
margin:0;
}
.form li {
list-style:none;
}
.hide {
display:none;
}
.rating input[type="radio"] {
position:absolute;
filter:alpha(opacity=0);
-moz-opacity:0;
-khtml-opacity:0;
opacity:0;
cursor:pointer;
width:17px;
}
.rating span {
width:24px;
height:16px;
line-height:16px;
padding:1px 22px 1px 0; /* 1px FireFox fix */
background:url(stars.png) no-repeat -22px 0;
}
.rating input[type="radio"]:checked + span {
background-position:-22px 0;
}
.rating input[type="radio"]:checked + span ~ span {
background-position:0 0;
}
My version...
I named it "Needle in the haystack" for obvious reasons.
It searches for a specific value in each row and each column, not for column names, etc.
Execute search (replace values for the first two variables of course):
DECLARE @SEARCH_DB VARCHAR(100)='REPLACE_WITH_YOUR_DB_NAME'
DECLARE @SEARCH_VALUE_LIKE NVARCHAR(100)=N'%REPLACE_WITH_SEARCH_STRING%'
SET NOCOUNT ON;
DECLARE col_cur CURSOR FOR
SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM information_schema.columns WHERE TABLE_CATALOG=@SEARCH_DB AND DATA_TYPE NOT IN ('timestamp', 'datetime');
DECLARE @TOTAL int = (SELECT COUNT(*)
FROM information_schema.columns WHERE TABLE_CATALOG=@SEARCH_DB AND DATA_TYPE NOT IN ('timestamp', 'datetime'));
DECLARE @TABLE_CATALOG nvarchar(500), @TABLE_SCHEMA nvarchar(500), @TABLE_NAME nvarchar(500), @COLUMN_NAME nvarchar(500), @DATA_TYPE nvarchar(500);
DECLARE @SQL nvarchar(4000)='';
PRINT '-------- BEGIN SEARCH --------';
OPEN col_cur;
FETCH NEXT FROM col_cur INTO @TABLE_CATALOG, @TABLE_SCHEMA, @TABLE_NAME, @COLUMN_NAME, @DATA_TYPE;
BEGIN TRY DROP TABLE ##RESULTS; END TRY BEGIN CATCH END CATCH
CREATE TABLE ##RESULTS( TABLE_CATALOG nvarchar(500), TABLE_SCHEMA nvarchar(500), TABLE_NAME nvarchar(500), COLUMN_NAME nvarchar(500), DATA_TYPE nvarchar(500), RECORDS int)
DECLARE @SHOULD_CAST bit=0
DECLARE @i int =0
DECLARE @progress_sum bigint=0
WHILE @@FETCH_STATUS = 0
BEGIN
-- PRINT '' + CAST(@i as varchar(100)) +' of ' + CAST(@TOTAL as varchar(100)) + ' ' + @TABLE_CATALOG+'.'+@TABLE_SCHEMA+'.'+@TABLE_NAME+': '+@COLUMN_NAME+' ('+@DATA_TYPE+')';
SET @SHOULD_CAST = (SELECT CASE @DATA_TYPE
WHEN 'varchar' THEN 0
WHEN 'nvarchar' THEN 0
WHEN 'char' THEN 0
ELSE 1 END)
SET @SQL='SELECT '''+@TABLE_CATALOG+''' catalog_name, '''+@TABLE_SCHEMA+''' schema_name, '''+@TABLE_NAME+''' table_name, '''+@COLUMN_NAME+''' column_name, '''+@DATA_TYPE+''' data_type, ' +
+' COUNT(['+@COLUMN_NAME+']) records '+
+' FROM '+@TABLE_CATALOG+'.'+@TABLE_SCHEMA+'.'+@TABLE_NAME +
+' WHERE ' + CASE WHEN @SHOULD_CAST=1 THEN 'CAST(['+@COLUMN_NAME + '] as NVARCHAR(max)) ' ELSE ' ['+@COLUMN_NAME + '] ' END
+' LIKE '''+ @SEARCH_VALUE_LIKE + ''' '
-- PRINT @SQL;
IF @i % 100 = 0
BEGIN
SET @progress_sum = (SELECT SUM(RECORDS) FROM ##RESULTS)
PRINT CAST (@i as varchar(100)) +' of ' + CAST(@TOTAL as varchar(100)) +': '+ CAST (@progress_sum as varchar(100))
END
INSERT INTO ##RESULTS (TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, RECORDS)
EXEC(@SQL)
FETCH NEXT FROM col_cur INTO @TABLE_CATALOG, @TABLE_SCHEMA, @TABLE_NAME, @COLUMN_NAME, @DATA_TYPE;
SET @i=@i+1
-- IF @i > 1000
-- BREAK
END
CLOSE col_cur;
DEALLOCATE col_cur;
SELECT * FROM ##RESULTS WHERE RECORDS>0;
Then to view results, even while executing, from another window, execute:
DECLARE @SEARCH_VALUE_LIKE NVARCHAR(100)=N'%@FLEX@%'
SELECT * FROM ##RESULTS WHERE RECORDS>0;
SET NOCOUNT ON;
DECLARE col_cur CURSOR FOR
SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM ##RESULTS WHERE RECORDS>0;
DECLARE @TABLE_CATALOG nvarchar(500), @TABLE_SCHEMA nvarchar(500), @TABLE_NAME nvarchar(500), @COLUMN_NAME nvarchar(500), @DATA_TYPE nvarchar(500);
DECLARE @SQL nvarchar(4000)='';
OPEN col_cur;
FETCH NEXT FROM col_cur INTO @TABLE_CATALOG, @TABLE_SCHEMA, @TABLE_NAME, @COLUMN_NAME, @DATA_TYPE;
DECLARE @i int =0
DECLARE @SHOULD_CAST bit=0
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SHOULD_CAST = (SELECT CASE @DATA_TYPE
WHEN 'varchar' THEN 0
WHEN 'nvarchar' THEN 0
WHEN 'char' THEN 0
ELSE 1 END)
SET @SQL='SELECT '''+@TABLE_CATALOG+''' catalog_name, '''+@TABLE_SCHEMA+''' schema_name, '''+@TABLE_NAME+''' table_name, '''+@COLUMN_NAME+''' column_name, '''+@DATA_TYPE+''' data_type, ' +
+' ['+@COLUMN_NAME+']'+
+', * '
+' FROM '+@TABLE_CATALOG+'.'+@TABLE_SCHEMA+'.'+@TABLE_NAME +
+' WHERE ' + CASE WHEN @SHOULD_CAST=1 THEN 'CAST(['+@COLUMN_NAME + '] as NVARCHAR(max)) ' ELSE ' ['+@COLUMN_NAME + '] ' END
+' LIKE '''+ @SEARCH_VALUE_LIKE + ''' '
PRINT @SQL;
EXEC(@SQL)
FETCH NEXT FROM col_cur INTO @TABLE_CATALOG, @TABLE_SCHEMA, @TABLE_NAME, @COLUMN_NAME, @DATA_TYPE;
SET @i=@i+1
-- IF @i > 10
-- BREAK
END
CLOSE col_cur;
DEALLOCATE col_cur;
Few mentions about it:
DISCLAIMERS:
You'll need to allocate memory for the new string otherString. In general for a substring of length n, something like this may work for you (don't forget to do bounds checking...)
char *subString(char *someString, int n)
{
char *new = malloc(sizeof(char)*n+1);
strncpy(new, someString, n);
new[n] = '\0';
return new;
}
This will return a substring of the first n characters of someString. Make sure you free the memory when you are done with it using free().
Stopwatch
measures time elapsed.
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
Threading.Thread.Sleep(500)
// Stop timing
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
Here is a DEMO
.
I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.
I had
return [];
where []
was Criminal[]
type.
Neither return: Criminal[] [];
nor return []: Criminal[];
worked for me.
At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.
For thoroughness I'll report this solution in my answer too:
let temp: Criminal[] = [];
return temp;
Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:
return <Criminal[]>[];
Hope this will help future readers!
faster way will require additional space .
For example:
put all items in one list into a HashSet ( you have to implement the hash function by yourself to use object.getAttributeSame() )
Go through the other list and check if any item is in the HashSet.
In this way each object is visited at most once. and HashSet is fast enough to check or insert any object in O(1).
Doing an static import of the GestureTypes and then using the valuesOf() method could make it look much cleaner:
enum GestureTypes{ROCK,PAPER,SCISSORS};
and
import static com.example.GestureTypes.*;
public class GestureFactory {
public static Gesture getInstance(final String gesture) {
if (ROCK == valueOf(gesture))
//do somthing
if (PAPER == valueOf(gesture))
//do somthing
}
}
Great Start to learning login forms. You are right, fieldset may not be the best tag.
However, I highly suggest you code it in HTML5 by using its robust form features.
HTML5 is actually easier to learn than older HTML for creating forms.
For example, read the following.
<section class="loginform cf">
<form name="login" action="index_submit" method="get" accept-charset="utf-8">
<ul>
<li><label for="usermail">Email</label>
<input type="email" name="usermail" placeholder="[email protected]" required></li>
<li><label for="password">Password</label>
<input type="password" name="password" placeholder="password" required></li>
<li>
<input type="submit" value="Login"></li>
</ul>
</form>
</section>
Wasn't that easy for you to understand?
Try this http://www.hongkiat.com/blog/html5-loginpage/ and let me know if you have any questions.
If textColorSecondary does not work for you, you might have defined colorControlNormal in your theme to be a different color. If so, just use
<style name="yourStyle" parent="Base.Theme.AppCompat">
<item name="colorAccent">your_color</item> <!-- for checked state -->
<item name="colorControlNormal">your color</item> <!-- for unchecked state -->
</style>
In C++,
static const int foo = 42;
is the preferred way to define & use constants. I.e. use this rather than
#define foo 42
because it doesn't subvert the type-safety system.
You should note that div tag behaves like nothing and just let you to put something in it. It means that if you insert a paragraph with 100 lines of text within a div tag, it shows all the text but its height won't change to contain all the text.
So you have to use a CSS & HTML trick to handle this issue. This trick is very simple. you must use an empty div tag with class="clear" and then you will have to add this class to your CSS. Also note that your have #wrap in your CSS file but you don't have any tag with this id. In summary you have to change you code to something like below:
HTML Code:
<!-- Change "id" from "container" to "wrap" -->
<div id="wrap">
<div id="header">
</div>
<div id="navigation">
<a href="/" class="navigation">home</a>
<a href="about.php" class="navigation">about</a>
<a href="fanlisting.php" class="navigation">fanlisting</a>
<a href="reasons.php" class="navigation">100 reasons</a>
<a href="letter.php" class="navigation">letter</a>
</div>
<div id="content" >
<h1>Update Information</h1>
<iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>
<!-- Add this line -->
<div class="clear"></div>
</div>
<div id="footer">
</div>
<!-- Add this line -->
<div class="clear"></div>
</div>
And also add this line to your CSS file:
.clear{ display: block; clear: both;}
No, there is no such type. But there are some choices:
None of these are really elegant, but that's the best there is.
Yeah it suck to get stuck in Scale View.
Host+Home will popup the Virtual machine settings. (by default Host is Right Control)
From there you can change the view settings, as the Menu bar is hidden in Scale View.
Had the same issue, especially when you checked the box not to show the 'Switch to Scale view' dialog.
This you can do while the VM is running.
Dont need to reverse your steps. As you increased your VersionCode, it means your application has upgraded already. The VersionName is just a string which is presented to user for user readability. Google play does not take any action depending on VersionName.
this is very old question, but since I came here while searching worth putting my answer.
SELECT DATEPART(ISO_WEEK,'2020-11-13') AS ISO_8601_WeekNr
If you want to match the two words in either order, use:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'
If Failed always comes after VendorEnquiry on the line, just use:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'
For the record, I had this same problem, but none of the solutions worked. I had upgraded my computer and migrated my PC. I had a a mixed locale english and spanish:
$ locale
LANG=en_US.utf8
LANGUAGE=
LC_CTYPE="en_US.utf8"
LC_NUMERIC=es_ES.utf8
LC_TIME=es_ES.utf8
LC_COLLATE="en_US.utf8"
LC_MONETARY=es_ES.utf8
LC_MESSAGES="en_US.utf8"
LC_PAPER=es_ES.utf8
LC_NAME="en_US.utf8"
LC_ADDRESS="en_US.utf8"
LC_TELEPHONE="en_US.utf8"
LC_MEASUREMENT=es_ES.utf8
LC_IDENTIFICATION="en_US.utf8"
LC_ALL=
But, on my new Debian installation, I just selected english as locale. Which finally worked was to reconfigure locales package to add and generate spanish too.
$ grep -v "#" /etc/locale.gen
en_US.UTF-8 UTF-8
es_ES.UTF-8 UTF-8
An <input type=hidden>
element is not a hidden input box. It is simply a form field that has a value set via markup or via scripting, not via user input. You can use it for multi-line data too, e.g.
<input type=hidden name=stuff value=
"Hello
world, how
are you?">
If the value contains the Ascii quotation mark ("), then, as for any HTML attribute, you need to use Ascii apostrophes (') as attribute value delimites or escape the quote as "
, e.g.
<input type=hidden name=stuff value="A "funny" example">
Simple, without any other API:
To add 8 days:
Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);
Yes, C# supports that. There are several syntaxes available.
Anonymous methods were added in C# 2.0:
Func<int, int, int> add = delegate(int x, int y)
{
return x + y;
};
Action<int> print = delegate(int x)
{
Console.WriteLine(x);
}
Action<int> helloWorld = delegate // parameters can be elided if ignored
{
Console.WriteLine("Hello world!");
}
Lambdas are new in C# 3.0 and come in two flavours.
Expression lambdas:
Func<int, int, int> add = (int x, int y) => x + y; // or...
Func<int, int, int> add = (x, y) => x + y; // types are inferred by the compiler
Statement lambdas:
Action<int> print = (int x) => { Console.WriteLine(x); };
Action<int> print = x => { Console.WriteLine(x); }; // inferred types
Func<int, int, int> add = (x, y) => { return x + y; };
Local functions have been introduced with C# 7.0:
int add(int x, int y) => x + y;
void print(int x) { Console.WriteLine(x); }
There are basically two different types for these: Func
and Action
. Func
s return values but Action
s don't. The last type parameter of a Func
is the return type; all the others are the parameter types.
There are similar types with different names, but the syntax for declaring them inline is the same. An example of this is Comparison<T>
, which is roughly equivalent to Func<T, T, int>
.
Func<string, string, int> compare1 = (l,r) => 1;
Comparison<string> compare2 = (l, r) => 1;
Comparison<string> compare3 = compare1; // this one only works from C# 4.0 onwards
These can be invoked directly as if they were regular methods:
int x = add(23, 17); // x == 40
print(x); // outputs 40
helloWorld(x); // helloWorld has one int parameter declared: Action<int>
// even though it does not make any use of it.
For those of you looking for a solution for Oracle, I made a method from the code of Log4Jdbc. You will need to provide the query and the parameters passed to the preparedStatement since retrieving them from it is a bit of a pain:
private String generateActualSql(String sqlQuery, Object... parameters) {
String[] parts = sqlQuery.split("\\?");
StringBuilder sb = new StringBuilder();
// This might be wrong if some '?' are used as litteral '?'
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
sb.append(part);
if (i < parameters.length) {
sb.append(formatParameter(parameters[i]));
}
}
return sb.toString();
}
private String formatParameter(Object parameter) {
if (parameter == null) {
return "NULL";
} else {
if (parameter instanceof String) {
return "'" + ((String) parameter).replace("'", "''") + "'";
} else if (parameter instanceof Timestamp) {
return "to_timestamp('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS").
format(parameter) + "', 'mm/dd/yyyy hh24:mi:ss.ff3')";
} else if (parameter instanceof Date) {
return "to_date('" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").
format(parameter) + "', 'mm/dd/yyyy hh24:mi:ss')";
} else if (parameter instanceof Boolean) {
return ((Boolean) parameter).booleanValue() ? "1" : "0";
} else {
return parameter.toString();
}
}
}
Just enable parsing of the autoexec.bat in the registry, using these instructions.
:: works only on windows vista and earlier
Run REGEDT32.EXE.
Modify the following value within HKEY_CURRENT_USER:
Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ParseAutoexec
1 = autoexec.bat is parsed
0 = autoexec.bat is not parsed
If you don't know the number of columns ahead of time, add each column to a list and cbind
at the end.
List <- list()
for(i in 1:n)
{
normF <- #something
List[[i]] <- normF
}
Matrix = do.call(cbind, List)
Try this
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle==$value['uid'] OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Execute your Java program using java -d . HelloWorld
command.
This command works when you have declared package.
.
represent current directory/.
I faced the same issue in Android Studio version 3.5.3. This is how i fixed it.
I updated the dependecy com.android.tools.build:gradle in my project level build.gradle file from a lower version to 3.5.3 as below.
classpath 'com.android.tools.build:gradle:3.5.3'
I then went ahead and edited the value of distributionUrl in gradle-wrapper.properties file as below. This file is in the directory /gradle/wrapper/ from the root of your project folder.
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
As far as i know this seems out of scope of an IDE. Copyin ,you can copy the string and then try to format it using ctrl+shift+ F Most often these multiline strings are not used hard coded,rather they shall be used from property or xml files.which can be edited at later point of time without the need for code change
Instead of using <source>
tag, use <src>
attribute of <video>
as below and you will see the action.
<video width="320" height="240" src="mov1.mov"></video>
or
you can give multiple tags within the tag, each with a different video source. The browser will automatically go through the list and pick the first one it’s able to play. For example:
<video id="sampleMovie" width="640" height="360" preload controls>
<source src="HTML5Sample_H264.mov" />
<source src="HTML5Sample_Ogg.ogv" />
<source src="HTML5Sample_WebM.webm" />
</video>
If you test that code in Chrome, you’ll get the H.264 video. Run it in Firefox, though, and you’ll see the Ogg video in the same place.
line.strip() == ''
Or, if you don't want to "eat up" lines consisting of spaces:
line in ('\n', '\r\n')
I experienced this error when I was installing Android Studio with too little memory to install everything needed. It didn't help freeing up memory or installing Android SDK my self. Re-installing Android studio with sufficient memory, made the download start when I first opened up Android Studio.
In your comment on @Kenneth's answer you're saying that ReadAsStringAsync()
is returning empty string.
That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.
What you can do is this:
public static string GetRequestBody()
{
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
return bodyText;
}
You need to use the ajax-cross-origin plugin: http://www.ajax-cross-origin.com/
Just add the option crossOrigin: true
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});
If you're using PDO don't forget to initiate it with UTF8:
$con = new PDO('mysql:host=' . $server . ';dbname=' . $db . ';charset=UTF8', $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
(just spent 5 hours to figure this out, hope it will save someone precious time...)
Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
Gmail requires port 465, and also it's the code from phpmailer :)
I wanted to be able to specify which tab was shown by class rather than index as I thought it made for a robust solution that was less dependant on how you wire up IB. I didn't find either Disco's or Joped's solutions to work so i created this method:
-(void)setTab:(Class)class{
int i = 0;
for (UINavigationController *controller in self.tabBarContontroller.viewControllers){
if ([controller isKindOfClass:class]){
break;
}
i++;
}
self.tabBarContontroller.selectedIndex = i;
}
you call it like this:
[self setTab:[YourClass class]];
Hope this is helpful to someone
I had the same error code when I was running npm run build inside node docker container.
Locally it was working while inside a container I had set option to throw error when there is a warning during compilation while locally it wasn't set. So this error can mean anything that is connected with stopping the process being done by NPM
The variable arguments must be the last of the parameters specified in your function declaration. If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument.
void print(final String format, final String... arguments) {
System.out.format( format, arguments );
}
Count the Letters provided in string
function countTheElements(){
var str = "ssdefrcgfrdesxfdrgs";
var arr = [];
var count = 0;
for(var i=0;i<str.length;i++){
arr.push(str[i]);
}
arr.sort();
for(var i=0;i<arr.length;i++){
if(arr[i] == arr[i-1]){
count++;
}else{
count = 1;
}
if(arr[i] != arr[i+1]){
console.log(arr[i] +": "+(count));
}
}
}
countTheElements()
There is a very good case for using "adding existing file links" when reusing code across projects, and that is when you need to reference and support different versions of dependent libraries.
Making multiple assemblies with references to different external assemblies isn't easy to do otherwise without duplicating your code, or utilizing tricks with source code control.
I believe that it's easiest to maintain one project for development and unit test, then to create 'build' projects using existing file links when you need to create the assemblies which reference different versions of those external assemblies.
I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.
Put the testdata.xml file inside the assets directory.
Write the following code to get the testdata document parsed.
InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
// create a new DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// use the factory to create a documentbuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// create a new document from input stream
Document doc = builder.parse(inputStream);
I ran into a similar issue today - my ruby version didn't match my rvm installs.
> ruby -v
ruby 2.0.0p481
> rvm list
rvm rubies
ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
ruby-2.2.3 [ x86_64 ]
Also, rvm current
failed.
> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...
The error message recommended this useful command, which resolved the issue for me:
> rvm get stable --auto-dotfiles
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime()
to get the UTC time from your local time or myDateTime.ToLocalTime()
to convert the UTC time to the local machine's time.
// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();
// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();
If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime()
or TimeZoneInfo.ConvertTimeFromUtc()
.
// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);
// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
Many of the answerers spotted the issue and already gave the solution.
I just want to suggest another solution, which is changing the Glogal variable value from within the tool Mysql Workbench. That is ofcourse IF you use Workbench running locally on server (or via SSH connection)
You just connect to your instance and go on menu:
Server -> Options File -> Networking -> max_allowed_packed
You set the desired value and then you need to restart MySql Service.
I was frustrated with this problem for days. Nothing worked on ubuntu. If I put the call in /etc/profile it all crashed at login attempt. I couldn't use "Startup Applications" as that was not what I wanted. That only sets the script for that current user.
Finally I found this little article: http://standards.freedesktop.org/autostart-spec/autostart-spec-0.5.html
The solution would be:
find out the $XDG_CONFIG_DIRS path:
echo $XDG_CONFIG_DIRS
put your script in that directory
As mentioned by @Khaneddy2013, the cmd SQLCMD -L returns no server name when I run. Bcz I only have installed the SSMS (local db and server were not installed). After tried installing SqlLocaLDB and SQLEXPR32_x86_ENU(32 bit OS) I was able to connect. And now the cmd window shows the server names too.
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
A jQuery solution: Add this button inside any element you want to be able to close:
<button type='button' class='close' onclick='$(this).parent().remove();'>×</button>
or to 'just' hide it:
<button type='button' class='close' onclick='$(this).parent().hide();'>×</button>
This answer was made pre-JPA2 implementations, if you're using JPA2, see the ElementCollection answer above:
Lists of objects inside a model object are generally considered "OneToMany" relationships with another object. However, a String is not (by itself) an allowable client of a One-to-Many relationship, as it doesn't have an ID.
So, you should convert your list of Strings to a list of Argument-class JPA objects containing an ID and a String. You could potentially use the String as the ID, which would save a little space in your table both from removing the ID field and by consolidating rows where the Strings are equal, but you would lose the ability to order the arguments back into their original order (as you didn't store any ordering information).
Alternatively, you could convert your list to @Transient and add another field (argStorage) to your class that is either a VARCHAR() or a CLOB. You'll then need to add 3 functions: 2 of them are the same and should convert your list of Strings into a single String (in argStorage) delimited in a fashion that you can easily separate them. Annotate these two functions (that each do the same thing) with @PrePersist and @PreUpdate. Finally, add the third function that splits the argStorage into the list of Strings again and annotate it @PostLoad. This will keep your CLOB updated with the strings whenever you go to store the Command, and keep the argStorage field updated before you store it to the DB.
I still suggest doing the first case. It's good practice for real relationships later.
Tried everything but didn't work. All the above methods did nothing. At last I was able to delete via VSCode.
node_modules
folder and delete.few milliseconds
to delete.)Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';
In case you have to replace multiple values and if you don't mind "refactoring" your variable with as.factor(as.character(...)) you could try the following:
replace.values <- function(search, replace, x){
stopifnot(length(search) == length(replace))
xnew <- replace[ match(x, search) ]
takeOld <- is.na(xnew) & !is.na(x)
xnew[takeOld] <- x[takeOld]
return(xnew)
}
iris$Species <- as.factor(search=c("oldValue1","oldValue2"),
replace=c("newValue1","newValue2"),
x=as.character(iris$Species))
Like that:
SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'
The accepted answer correctly describes how the list should be declared and is highly recommended for most scenarios.
But I came across a different scenario, which also covers the question asked.
What if you have to use an existing object list, like ViewData["htmlAttributes"]
in MVC? How can you access its properties (they are usually created via new { @style="width: 100px", ... }
)?
For this slightly different scenario I want to share with you what I found out.
In the solutions below, I am assuming the following declaration for nodes
:
List<object> nodes = new List<object>();
nodes.Add(
new
{
Checked = false,
depth = 1,
id = "div_1"
});
In C# 4.0 and higher versions, you can simply cast to dynamic and write:
if (nodes.Any(n => ((dynamic)n).Checked == false))
Console.WriteLine("found a not checked element!");
Note: This is using late binding, which means it will recognize only at runtime if the object doesn't have a Checked
property and throws a RuntimeBinderException
in this case - so if you try to use a non-existing Checked2
property you would get the following message at runtime: "'<>f__AnonymousType0<bool,int,string>' does not contain a definition for 'Checked2'"
.
The solution with reflection works both with old and new C# compiler versions. For old C# versions please regard the hint at the end of this answer.
Background
As a starting point, I found a good answer here. The idea is to convert the anonymous data type into a dictionary by using reflection. The dictionary makes it easy to access the properties, since their names are stored as keys (you can access them like myDict["myProperty"]
).
Inspired by the code in the link above, I created an extension class providing GetProp
, UnanonymizeProperties
and UnanonymizeListItems
as extension methods, which simplify access to anonymous properties. With this class you can simply do the query as follows:
if (nodes.UnanonymizeListItems().Any(n => (bool)n["Checked"] == false))
{
Console.WriteLine("found a not checked element!");
}
or you can use the expression nodes.UnanonymizeListItems(x => (bool)x["Checked"] == false).Any()
as if
condition, which filters implicitly and then checks if there are any elements returned.
To get the first object containing "Checked" property and return its property "depth", you can use:
var depth = nodes.UnanonymizeListItems()
?.FirstOrDefault(n => n.Contains("Checked")).GetProp("depth");
or shorter: nodes.UnanonymizeListItems()?.FirstOrDefault(n => n.Contains("Checked"))?["depth"];
Note: If you have a list of objects which don't necessarily contain all properties (for example, some do not contain the "Checked" property), and you still want to build up a query based on "Checked" values, you can do this:
if (nodes.UnanonymizeListItems(x => { var y = ((bool?)x.GetProp("Checked", true));
return y.HasValue && y.Value == false;}).Any())
{
Console.WriteLine("found a not checked element!");
}
This prevents, that a KeyNotFoundException
occurs if the "Checked" property does not exist.
The class below contains the following extension methods:
UnanonymizeProperties
: Is used to de-anonymize the properties contained in an object. This method uses reflection. It converts the object into a dictionary containing the properties and its values.UnanonymizeListItems
: Is used to convert a list of objects into a list of dictionaries containing the properties. It may optionally contain a lambda expression to filter beforehand.GetProp
: Is used to return a single value matching the given property name. Allows to treat not-existing properties as null values (true) rather than as KeyNotFoundException (false)For the examples above, all that is required is that you add the extension class below:
public static class AnonymousTypeExtensions
{
// makes properties of object accessible
public static IDictionary UnanonymizeProperties(this object obj)
{
Type type = obj?.GetType();
var properties = type?.GetProperties()
?.Select(n => n.Name)
?.ToDictionary(k => k, k => type.GetProperty(k).GetValue(obj, null));
return properties;
}
// converts object list into list of properties that meet the filterCriteria
public static List<IDictionary> UnanonymizeListItems(this List<object> objectList,
Func<IDictionary<string, object>, bool> filterCriteria=default)
{
var accessibleList = new List<IDictionary>();
foreach (object obj in objectList)
{
var props = obj.UnanonymizeProperties();
if (filterCriteria == default
|| filterCriteria((IDictionary<string, object>)props) == true)
{ accessibleList.Add(props); }
}
return accessibleList;
}
// returns specific property, i.e. obj.GetProp(propertyName)
// requires prior usage of AccessListItems and selection of one element, because
// object needs to be a IDictionary<string, object>
public static object GetProp(this object obj, string propertyName,
bool treatNotFoundAsNull = false)
{
try
{
return ((System.Collections.Generic.IDictionary<string, object>)obj)
?[propertyName];
}
catch (KeyNotFoundException)
{
if (treatNotFoundAsNull) return default(object); else throw;
}
}
}
Hint: The code above is using the null-conditional operators, available since C# version 6.0 - if you're working with older C# compilers (e.g. C# 3.0), simply replace ?.
by .
and ?[
by [
everywhere (and do the null-handling traditionally by using if
statements or catch NullReferenceExceptions), e.g.
var depth = nodes.UnanonymizeListItems()
.FirstOrDefault(n => n.Contains("Checked"))["depth"];
As you can see, the null-handling without the null-conditional operators would be cumbersome here, because everywhere you removed them you have to add a null check - or use catch statements where it is not so easy to find the root cause of the exception resulting in much more - and hard to read - code.
If you're not forced to use an older C# compiler, keep it as is, because using null-conditionals makes null handling much easier.
Note: Like the other solution with dynamic, this solution is also using late binding, but in this case you're not getting an exception - it will simply not find the element if you're referring to a non-existing property, as long as you keep the null-conditional operators.
What might be useful for some applications is that the property is referred to via a string in solution 2, hence it can be parameterized.
You can code atoi()
for fun:
int my_getnbr(char *str)
{
int result;
int puiss;
result = 0;
puiss = 1;
while (('-' == (*str)) || ((*str) == '+'))
{
if (*str == '-')
puiss = puiss * -1;
str++;
}
while ((*str >= '0') && (*str <= '9'))
{
result = (result * 10) + ((*str) - '0');
str++;
}
return (result * puiss);
}
You can also make it recursive, which can fold in 3 lines.
You can just set the onClick of an ImageView and also set it to be clickable, Or set the drawableBottom property of a regular button.
ImageView iv = (ImageView)findViewById(R.id.ImageView01);
iv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
controlName.CssClass="CSS Class Name";
working example follows below
txtBank.CssClass = "csError";
Use hypertext reference and the ID tag,
Some paragraph text
Target Text<h1><a href="#target">Target Text Title</a></h1>
<p id="target">Target Text</p>
The best way to login to a guest Linux VirtualBox VM is port forwarding. By default, you should have one interface already which is using NAT. Then go to the Network settings and click the Port Forwarding button. Add a new Rule. As the rule name, insert "ssh". As "Host port", insert 3022. As "Guest port", insert 22. Everything else of the rule can be left blank.
or from the command line
VBoxManage modifyvm myserver --natpf1 "ssh,tcp,,3022,,22"
where 'myserver' is the name of the created VM. Check the added rules:
VBoxManage showvminfo myserver | grep 'Rule'
That's all! Please be sure you don't forget to install an SSH server in the VM:
sudo apt-get install openssh-server
To SSH into the guest VM, write:
ssh -p 3022 [email protected]
Where user
is your username within the VM.
Replace the line in htpasswd file:
go to: http://www.htaccesstools.com/htpasswd-generator-windows/
(if the link is expired, search another generator from google.com)
Enter your username and password. The site will generate encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".
You might also need to 'clear' the 'Authentication data' from tortoisSVN -> settings -> saved data
I run into this frequently for some reason, and I can't fathom why this solution hasn't been mentioned:
Click View ? Output (or just hold Ctrl and hit W > O)
Console output then appears where your Error List, Locals, and Watch windows are.
Note: I'm using Visual Studio 2015.
This can easily warp a normal human brain, so I've found a visual approach to be easier to understand:
If two ranges are "too fat" to fit in a slot that is exactly the sum of the width of both, then they overlap.
For ranges [a1, a2]
and [b1, b2]
this would be:
/**
* we are testing for:
* max point - min point < w1 + w2
**/
if max(a2, b2) - min(a1, b1) < (a2 - a1) + (b2 - b1) {
// too fat -- they overlap!
}
As an addendum to the existing answers, none of which worked for me I found my solution HERE:
https://bundletransformer.codeplex.com/discussions/429707
The solution was to
Build Action
as Content
I did NOT need to remove extensionless handlers (as can be found in other solutions on the internet)
I did NOT have to add the <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
web.config setting.
Hope this helps!
Calendar.getInstance().get(Calendar.MONTH);
is zero based, 10 is November. From the javadoc;
public static final int MONTH Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Calendar.getInstance().get(Calendar.JANUARY);
is not a sensible thing to do, the value for JANUARY
is 0, which is the same as ERA
, you are effectively calling;
Calendar.getInstance().get(Calendar.ERA);
The real limits for the alert text are not documented anywhere. The only thing the documentation says is:
In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification Service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)
This is what I could find doing some experiments.
Just as a reminder here is a very good note from the official documentation:
If necessary, iOS truncates your message so that it fits well in each notification delivery style; for best results, you shouldn’t truncate your message.
If you're already using SwiftyJSON:
https://github.com/SwiftyJSON/SwiftyJSON
You can do this:
// this works with dictionaries too
let paramsDictionary = [
"title": "foo",
"description": "bar"
]
let paramsArray = [ "one", "two" ]
let paramsJSON = JSON(paramsArray)
let paramsString = paramsJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)
SWIFT 3 UPDATE
let paramsJSON = JSON(paramsArray)
let paramsString = paramsJSON.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.prettyPrinted)!
JSON strings, which are good for transport, don't come up often because you can JSON encode an HTTP body. But one potential use-case for JSON stringify is Multipart Post, which AlamoFire nows supports.
The solution provided by Joe Steanelli works, but making a list of columns is inconvenient when dozens or hundreds of columns are involved. Here's how to get column list of table my_table in my_schema.
-- override GROUP_CONCAT limit of 1024 characters to avoid a truncated result
set session group_concat_max_len = 1000000;
select GROUP_CONCAT(CONCAT("'",COLUMN_NAME,"'"))
from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'my_table'
AND TABLE_SCHEMA = 'my_schema'
order BY ORDINAL_POSITION
Now you can copy & paste the resulting row as first statement in Joe's method.
If you would use asp:dropdownlist
you could select it easier by testSelect.Text
.
Now you'd have to do a Request.Form["testSelect"]
to get the value after pressed btnTes
.
Hope it helps.
EDIT: You need to specify a name
of the select (not only ID) to be able to Request.Form["testSelect"]
Solution: Use unix command find
The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the 'primaries' and 'operands') in terms of each file in the tree.
The Traditional Formula would be :
find <path> -flag <valueOfFlag>
Easy Examples
1.Find by Name - Find all package.json
from my current location subtree hierarchy.
find . -name "package.json"
2.Find by Name and Type - find all node_modules
directories from ALL file system (starting from root hierarchy )
sudo find / -name "node_modules" -type d
Complex Examples:
More Useful examples which can demonstrate the power of flag options and operators:
3.Regex and File Type - Find all javascript controllers variation names (using regex) javascript Files only in my app location.
find /user/dev/app -name "*contoller-*\.js" -type f
-type
f means file -name
related to regular expression to any variation of controller string and dash with .js
at the end
4.Depth - Find all routes patterns directories in app directory no more than 3 dimensions ( app/../../.. only and no more deeper)
find app -name "*route*" -type d -maxdepth 3
-type
d means directory -name
related to regular expression to any variation of route string -maxdepth
making the finder focusing on 3 subtree depth and no more <yourSearchlocation>/depth1/depth2/depth3
)
5.File Size , Ownership and OR Operator - Find all files with names 'sample' or 'test' under ownership of root user that greater than 1 Mega and less than 5 Mega.
find . \( -name "test" -or -name "sample" \) -user root -size +1M -size -5M
-size
threshold representing the range between more than (+) and less than (-) -user
representing the file owner -or
operator filters query for both regex matches
6.Empty Files - find all empty directories in file system
find / -type d -empty
7.Time Access, Modification and creation of files - find all files that were created/modified/access in directory in 10 days
# creation (c)
find /test -name "*.groovy" -ctime -10d
# modification (m)
find /test -name "*.java" -mtime -10d
# access (a)
find /test -name "*.js" -atime -10d
8.Modification Size Filter - find all files that were modified exactly between a week ago to 3 weeks ago and less than 500kb and present their sizes as a list
find /test -name "*.java" -mtime -3w -mtime +1w -size -500k | xargs du -h
You need to escape those but don't just replace it by %2F
manually. You can use URLEncoder
for this.
Eg URLEncoder.encode(url, "UTF-8")
Then you can say
yourUrl = "www.musicExplained/index.cfm/artist/" + URLEncoder.encode(VariableName, "UTF-8")
listview.setOnItemClickListener(new OnItemClickListener(){
//setting onclick to items in the listview.
@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){
// case 0 is the first item in the listView.
case 0:
intent = new Intent(Activity.this,firstActivity.class);
break;
//case 1 is the second item in the listView.
case 1:
intent = new Intent(Activity.this,secondActivity.class);
break;
case 2:
intent = new Intent(Activity.this,thirdActivity.class);
break;
//add more if you have more items in listView
startActivity(intent);
}
});
String extends Object, which means an Object. Object o = a;
If you really want to get as Object, you may do like below.
String s = "Hi";
Object a =s;
Use a Temp Table or a Table variable, e.g.
select 'A' as [value]
into #tmp
union
select 'B'
union
select 'C'
and then
SELECT
blah
FROM foo
WHERE myField IN (select [value] from #tmp)
or
SELECT
f.blah
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]
Actually, Ruby does have an in-place editing feature. Like Perl, you can say
ruby -pi.bak -e "gsub(/oldtext/, 'newtext')" *.txt
This will apply the code in double-quotes to all files in the current directory whose names end with ".txt". Backup copies of edited files will be created with a ".bak" extension ("foobar.txt.bak" I think).
NOTE: this does not appear to work for multiline searches. For those, you have to do it the other less pretty way, with a wrapper script around the regex.
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
WhatsApp Inc. does not provide an open API but a reverse-engineered library is made available on GitHub by the team Venomous on the GitHub. This however according to my knowledge is made possible in PHP. You can check the link here: https://github.com/venomous0x/WhatsAPI
Hope this helps
I've encountered such issue recently. Though code was correct, I didn't turn on permissions in app settings. So, all permissions hasn't been set by default on emulators, so you should do it yourself.
The question doesn't address multiline strings, but here is how you would strip leading whitespace from a multiline string using python's standard library textwrap module. If we had a string like:
s = """
line 1 has 4 leading spaces
line 2 has 4 leading spaces
line 3 has 4 leading spaces
"""
if we print(s)
we would get output like:
>>> print(s)
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
and if we used textwrap.dedent
:
>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
I've adjusted Glenn Moss' answer to account for the fact that overflow div might not be at the top of the page.
parentDiv.scrollTop(parentDiv.scrollTop() + (innerListItem.position().top - parentDiv.position().top) - (parentDiv.height()/2) + (innerListItem.height()/2) )
I was using this on a google maps application with a responsive template. On resolution > 800px, the list was on the left side of the map. On resolution < 800 the list was below the map.
As noted above the problem is in specifying the path to your file. The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).
Or you can specify the path from the drive to your file in the filename:
path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName
You can also catch the File Not Found Error and give another response using try:
try:
with open(filename) as f:
sequences = pick_lines(f)
except FileNotFoundError:
print("File not found. Check the path variable and filename")
exit()
Seriously, question exists five years and no nice facade?
function is_dir(path) {
try {
var stat = fs.lstatSync(path);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
}
Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "
Ex:
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= #2013-04-12#
I found other answers to be inaccurate/outdated. Best is to refer to the actual documentation.
Short version: in most cases gem update --system
will suffice.
You should not blindly use sudo
. In fact if you're not required to do so you most likely should not use it.
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
If you turn db.js
into a module you can require it from db_init.js
and just: node db_init.js
.
db.js:
module.exports = {
method1: function () { ... },
method2: function () { ... }
}
db_init.js:
var db = require('./db');
db.method1();
db.method2();