Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
using this you can format date.
you can change the appearance in the way you want then
for more info you can visit here
The following parameter-mapping example passes all parameters, including path, querystring and header, through to the integration endpoint via a JSON payload
#set($allParams = $input.params())
{
"params" : {
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
"$paramName" : "$util.escapeJavaScript($params.get($paramName))"
#if($foreach.hasNext),#end
#end
}
#if($foreach.hasNext),#end
#end
}
}
In effect, this mapping template outputs all the request parameters in the payload as outlined as follows:
{
"parameters" : {
"path" : {
"path_name" : "path_value",
...
}
"header" : {
"header_name" : "header_value",
...
}
'querystring" : {
"querystring_name" : "querystring_value",
...
}
}
}
Copied from the Amazon API Gateway Developer Guide
For aspnetcore-3.1, you can also use Problem()
like below;
https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1
[Route("/error-local-development")]
public IActionResult ErrorLocalDevelopment(
[FromServices] IWebHostEnvironment webHostEnvironment)
{
if (webHostEnvironment.EnvironmentName != "Development")
{
throw new InvalidOperationException(
"This shouldn't be invoked in non-development environments.");
}
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
You have to set a reference to the workbook you're opening. Then you can do anything you want with that workbook by using its reference.
Dim wkb As Workbook
Set wkb = Workbooks.Open("Tire.xls") ' open workbook and set reference!
wkb.Sheets("Sheet1").Activate
wkb.Sheets("Sheet1").Cells(2, 1).Value = 123
Could even set a reference to the sheet, which will make life easier later:
Dim wkb As Workbook
Dim sht As Worksheet
Set wkb = Workbooks.Open("Tire.xls")
Set sht = wkb.Sheets("Sheet2")
sht.Activate
sht.Cells(2, 1) = 123
Others have pointed out that .Activate
may be superfluous in your case. You don't strictly need to activate a sheet before editing its cells. But, if that's what you want to do, it does no harm to activate -- except for a small hit to performance which should not be noticeable as long as you do it only once or a few times. However, if you activate many times e.g. in a loop, it will slow things down significantly, so activate should be avoided.
For printing I don't set any width and remove any obstacles which keep your print layout from having a dynamic width. Meaning if you make your browser window smaller and smaller, no content is cut/hidden but the document just gets longer. Like this, you can be sure that the rest will be handled by the printer/pdf-creator.
What about elements with a fixed width such as images or tables?
Options I can think of:
http://www.intensivstation.ch/en/css/print/
or any other google result for combinations of: CSS, print, media, layout
ECLIPSE PHOTON ON MAC
Get your current JAVA_HOME path /Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home
open /Users/you/eclipse/jee-photon/Eclipse.app/Contents/Eclipse/ and click on package content. Then open eclipse.ini file using any text file editor.
Edit your -VM argument as below( Make sure the Java Path is same as $JAVA_HOME)
-vm
/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/bin
One command and does not use the destructive git reset
command:
GIT_SEQUENCE_EDITOR="sed -i 's/pick/d/'" git rebase -i HEAD~ --autostash
It simply drops the commit, putting you back exactly in the state before the cherry-pick even if you had local changes.
Don't forget to add the schema name in case you have multiple schemas with the same table names.
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'your_table_name' AND table_schema = 'your_schema_name';
or using psql:
\d+ your_schema_name.your_table_name
function array_unique(array) {
var unique = [];
for ( var i = 0 ; i < array.length ; ++i ) {
if ( unique.indexOf(array[i]) == -1 )
unique.push(array[i]);
}
return unique;
}
Use DATE()
function:
select * from follow_queue group by DATE(follow_date)
In short, yes.
Suppose we are on a 32-bit machine.
If it is little endian, the x
in the memory will be something like:
higher memory
----->
+----+----+----+----+
|0x01|0x00|0x00|0x00|
+----+----+----+----+
A
|
&x
so (char*)(&x) == 1
, and *y+48 == '1'
.
If it is big endian, it will be:
+----+----+----+----+
|0x00|0x00|0x00|0x01|
+----+----+----+----+
A
|
&x
so this one will be '0'
.
If the numbers can be separated by more than one space, it is safest to split the string on one or more consecutive whitespace characters (which includes tabs and regular spaces). With a regular expression, this would be \s+
.
You can then map
each element using the Number
function to convert it. Note that parseInt
will not work (i.e. arr.map(parseInt)
) because map
passes three arguments to the mapping function: the element, the index, and the original array. parseInt
accepts the base or radix as the second parameter, so it will end up taking the index as the base, often resulting in many NaN
s in the result. However, Number
ignores any arguments other than the first, so it works directly.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(Number); //[1,2,3,4]
You could also use an anonymous function for the mapping callback with the unary plus operator to convert each element to a number.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(x => +x); //[1,2,3,4]
With an anonymous function for the callback, you can decide what parameters to use, so parseInt
can also work.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(x => parseInt(x)); //[1,2,3,4]
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(12, 18)
);
In addition to the accepted answer, one other check is to make sure that you have the right reference to your entity package in sessionFactory.setPackagesToScan(...) while setting up your session factory.
You need to allow transaction to your DAO method. Add,
@Transactional(readOnly = true, propagation=Propagation.NOT_SUPPORTED)
over your dao methods.
And @Transactional
should be from the package:
org.springframework.transaction.annotation.Transactional
It could also be as simple as the fact that your database is not actually MS SQL Server. If your database is actually MySql, for instance, and you try to connect to it with System.Data.SqlClient you will get this error.
By far most examples of ADO.Net will be for MSSQL and the inexperienced user may not know that you can't use SqlConnection
, SqlCommand
, etc., with MySql.
While all ADO.Net data providers conform to the same interface, you have to use the provider made for your database.
It does not sound like you imported the library right especially when you say at the point Add the library to your application project: I felt lost .. basically because I don't have the "add" option by itself .. however I clicked on "add library" and moved on ..
in eclipse you need to right click on the project, go to Properties, select Android in the list then Add to add the library
follow this tutorial in the docs
http://developer.android.com/tools/support-library/setup.html
This works for me.
void pause()
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
std::string dummy;
std::cout << "Press any key to continue . . .";
std::getline(std::cin, dummy);
}
What worked for me was downgrading from EF 6.1.3
to EF 6.1.1
.
In Visual Studios 2012+
head over to:
Tools - Nuget Package Manager - Package Manager Console`
Then enter:
Install-Package EntityFramework.SqlServerCompact -Version 6.1.1
I did not have to uninstall EF 6.1.3
first because the command above already does that.
In addition, I don't know if it did something, but I also installed SQL Server CE in my project.
Here's the link to the solution I found:
http://www.itorian.com/2014/11/no-entity-framework-provider-found-for.html
Extra info:
If you are using PhpStorm as IDE, after updating the path variable you need to restart PhpStorm so that it takes effect.
Restarting terminal window was not enough for me. (PhpStorm 2020.3.2)
1) Note that it is considered insecure to have the .htpasswd
file below the server root.
2) The docs say this about relative paths, so it looks you're out of luck:
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the ServerRoot.
3) While the answers recommending the use of environment variables work perfectly fine, I would prefer to put a placeholder in the .htaccess
file, or have different versions in my codebase, and have the deployment process set it all up (i. e. replace placeholders or rename / move the appropriate file).
On Java projects, I use Maven to do this type of work, on, say, PHP projects, I like to have a build.sh and / or install.sh shell script that tunes the deployed files to their environment. This decouples your codebase from the specifics of its target environment (i. e. its environment variables and configuration parameters). In general, the application should adapt to the environment, if you do it the other way around, you might run into problems once the environment also has to cater for different applications, or for completely unrelated, system-specific requirements.
All the different answers on this topic are very confusing, so I’m hoping to give a bit more clarity with this overview of the different bindings of libmagic. Previously mammadori gave a short answer listing the available option.
magic
When determining a files mime-type, the tool of choice is simply called file
and its back-end is called libmagic
. (See the Project home page.) The project is developed in a private cvs-repository, but there is a read-only git mirror on github.
Now this tool, which you will need if you want to use any of the libmagic bindings with python, already comes with its own python bindings called file-magic
. There is not much dedicated documentation for them, but you can always have a look at the man page of the c-library: man libmagic
. The basic usage is described in the readme file:
import magic
detected = magic.detect_from_filename('magic.py')
print 'Detected MIME type: {}'.format(detected.mime_type)
print 'Detected encoding: {}'.format(detected.encoding)
print 'Detected file type name: {}'.format(detected.name)
Apart from this, you can also use the library by creating a Magic
object using magic.open(flags)
as shown in the example file.
Both toivotuo and ewr2san use these file-magic
bindings included in the file
tool. They mistakenly assume, they are using the python-magic
package. This seems to indicate, that if both file
and python-magic
are installed, the python module magic
refers to the former one.
magic
This is the library that Simon Zimmermann talks about in his answer and which is also employed by Claude COULOMBE as well as Gringo Suave.
magic
Note: This project was last updated in 2013!
Due to being based on the same c-api, this library has some similarity with file-magic
included in libmagic
. It is only mentioned by mammadori and no other answer employs it.
After setting
actionBar.setHomeButtonEnabled(true);
You have to configure the parent activity in your AndroidManifest.xml
<activity
android:name="com.example.MainActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat" />
<activity
android:name="com.example.SecondActivity"
android:theme="@style/Theme.AppCompat" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.MainActivity" />
</activity>
Look here for more information http://developer.android.com/training/implementing-navigation/ancestral.html
Check out:
var crypto = require('crypto');
crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);
Use RGBA or if you hex code then change it into rgba. No need to do some presodu element css.
function hexaChangeRGB(hex, alpha) {
var r = parseInt(hex.slice(1, 3), 16),
g = parseInt(hex.slice(3, 5), 16),
b = parseInt(hex.slice(5, 7), 16);
if (alpha) {
return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
} else {
return "rgb(" + r + ", " + g + ", " + b + ")";
}
}
hexaChangeRGB('#FF0000', 0.2);
css ---------
background-color: #fff;
opacity: 0.8;
OR
mycolor = hexaChangeRGB('#FF0000', 0.2);
document.getElementById("myP").style.background-color = mycolor;
The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....
About the libraries you could use are.
And there could be many more, but that are what I've used
About the json I don't now maybe something like this
public class GetQuestions
{
public List<Student> Questions { get; set; }
}
public class Student
{
public string Code { get; set; }
public string Questions { get; set; }
}
void Main()
{
var gq = new GetQuestions
{
Questions = new List<Student>
{
new Student {Code = "s1", Questions = "Q1,Q2"},
new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
}
};
//Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
JsonConvert.SerializeObject(gq).Dump();
}
and the result is this
{
"Questions":[
{"Code":"s1","Questions":"Q1,Q2"},
{"Code":"s2","Questions":"Q1,Q2,Q3"},
{"Code":"s3","Questions":"Q1,Q2,Q4"},
{"Code":"s4","Questions":"Q1,Q2,Q5"}
]
}
Yes I know the json is different, but the json that you want with dictionary.
void Main()
{
var f = new Foo
{
GetQuestions = new Dictionary<string, string>
{
{"s1", "Q1,Q2"},
{"s2", "Q1,Q2,Q3"},
{"s3", "Q1,Q2,Q4"},
{"s4", "Q1,Q2,Q4,Q6"},
}
};
JsonConvert.SerializeObject(f).Dump();
}
class Foo
{
public Dictionary<string, string> GetQuestions { get; set; }
}
And with Dictionary is as you want it.....
{
"GetQuestions":
{
"s1":"Q1,Q2",
"s2":"Q1,Q2,Q3",
"s3":"Q1,Q2,Q4",
"s4":"Q1,Q2,Q4,Q6"
}
}
If you are using Android Lollipop i.e. SDK 21, then:
CookieManager.getInstance().setAcceptCookie(true);
won't work. You need to use:
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
I ran into same issue and the above line worked as a charm.
student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user,
'request':request, 'enrolled_subjects': enrolled_subjects})
In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.
Subject and Student User model is a Foreign Key to the SubjectGrade Model.
In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user
PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much
The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules. Use otool -hv some_file
to see the filetype of some_file
.
Mach-O shared libraries have the file type MH_DYLIB
and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo
for libfoo.dylib. They can be created by passing the -dynamiclib
flag to the compiler. (-fPIC
is the default and needn't be specified.)
Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE
. They can carry any extension; the extension .bundle
is recommended by Apple, but most ported software uses .so
for the sake of compatibility. Typically, you'll use bundles for plug-ins that extend an application; in such situations, the bundle will link against the application binary to gain access to the application’s exported API. They can be created by passing the -bundle
flag to the compiler.
Both dylibs and bundles can be dynamically loaded using the dl
APIs (e.g. dlopen
, dlclose
). It is not possible to link against bundles as if they were shared libraries. However, it is possible that a bundle is linked against real shared libraries; those will be loaded automatically when the bundle is loaded.
Historically, the differences were more significant. In Mac OS X 10.0, there was no way to dynamically load libraries. A set of dyld APIs (e.g. NSCreateObjectFileImageFromFile
, NSLinkModule
) were introduced with 10.1 to load and unload bundles, but they didn't work for dylibs. A dlopen
compatibility library that worked with bundles was added in 10.3; in 10.4, dlopen
was rewritten to be a native part of dyld and added support for loading (but not unloading) dylibs. Finally, 10.5 added support for using dlclose
with dylibs and deprecated the dyld APIs.
On ELF systems like Linux, both use the same file format; any piece of shared code can be used as a library and for dynamic loading.
Finally, be aware that in Mac OS X, "bundle" can also refer to directories with a standardized structure that holds executable code and the resources used by that code. There is some conceptual overlap (particularly with "loadable bundles" like plugins, which generally contain executable code in the form of a Mach-O bundle), but they shouldn't be confused with Mach-O bundles discussed above.
Additional references:
I would recommend virtualenvwrapper as well. It works wonders for me and how I always have problems with activating. http://virtualenvwrapper.readthedocs.org/en/latest/
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
SWIFT 4
view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage
i did this:
$("#myModal").modal({}).draggable();
and it make my very standard/basic modal draggable.
not sure how/why it worked, but it did.
Use DBNull.Value.Equals on the object without converting it to a string.
Here's an example:
if (! DBNull.Value.Equals(row[fieldName]))
{
//not null
}
else
{
//null
}
Try jQuery.map function, works pretty well with maps.
var mapArray = {_x000D_
"lastName": "Last Name cannot be null!",_x000D_
"email": "Email cannot be null!",_x000D_
"firstName": "First Name cannot be null!"_x000D_
};_x000D_
_x000D_
$.map(mapArray, function(val, key) {_x000D_
alert("Value is :" + val);_x000D_
alert("key is :" + key);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="one">1</option>
<option name="2"value="two">2</option>
<option name="3"value="three"></option>
</select>
</body>
</html>
Here you wanna make a pointer to the first element of the array
uint8_t (*matrix_ptr)[20] = l_matrix;
With typedef, this looks cleaner
typedef uint8_t array_of_20_uint8_t[20];
array_of_20_uint8_t *matrix_ptr = l_matrix;
Then you can enjoy life again :)
matrix_ptr[0][1] = ...;
Beware of the pointer/array world in C, much confusion is around this.
Reviewing some of the other answers here, because the comment fields are too short to do there. Multiple alternatives were proposed, but it wasn't shown how they behave. Here is how they do
uint8_t (*matrix_ptr)[][20] = l_matrix;
If you fix the error and add the address-of operator &
like in the following snippet
uint8_t (*matrix_ptr)[][20] = &l_matrix;
Then that one creates a pointer to an incomplete array type of elements of type array of 20 uint8_t. Because the pointer is to an array of arrays, you have to access it with
(*matrix_ptr)[0][1] = ...;
And because it's a pointer to an incomplete array, you cannot do as a shortcut
matrix_ptr[0][0][1] = ...;
Because indexing requires the element type's size to be known (indexing implies an addition of an integer to the pointer, so it won't work with incomplete types). Note that this only works in C
, because T[]
and T[N]
are compatible types. C++ does not have a concept of compatible types, and so it will reject that code, because T[]
and T[10]
are different types.
The following alternative doesn't work at all, because the element type of the array, when you view it as a one-dimensional array, is not uint8_t
, but uint8_t[20]
uint8_t *matrix_ptr = l_matrix; // fail
The following is a good alternative
uint8_t (*matrix_ptr)[10][20] = &l_matrix;
You access it with
(*matrix_ptr)[0][1] = ...;
matrix_ptr[0][0][1] = ...; // also possible now
It has the benefit that it preserves the outer dimension's size. So you can apply sizeof on it
sizeof (*matrix_ptr) == sizeof(uint8_t) * 10 * 20
There is one other answer that makes use of the fact that items in an array are contiguously stored
uint8_t *matrix_ptr = l_matrix[0];
Now, that formally only allows you to access the elements of the first element of the two dimensional array. That is, the following condition hold
matrix_ptr[0] = ...; // valid
matrix_ptr[19] = ...; // valid
matrix_ptr[20] = ...; // undefined behavior
matrix_ptr[10*20-1] = ...; // undefined behavior
You will notice it probably works up to 10*20-1
, but if you throw on alias analysis and other aggressive optimizations, some compiler could make an assumption that may break that code. Having said that, i've never encountered a compiler that fails on it (but then again, i've not used that technique in real code), and even the C FAQ has that technique contained (with a warning about its UB'ness), and if you cannot change the array type, this is a last option to save you :)
When I want to have docstrings for my bash functions, I use a solution similar to the suggestion of user12205 in a duplicate of this question.
See how I define USAGE for a solution that:
function foo {
# Docstring
read -r -d '' USAGE <<' END'
# This method prints foo to the terminal.
#
# Enter `foo -h` to see the docstring.
# It has indentations and multiple lines.
#
# Change the delimiter if you need hashtag for some reason.
# This can include $$ and = and eval, but won't be evaluated
END
if [ "$1" = "-h" ]
then
echo "$USAGE" | cut -d "#" -f 2 | cut -c 2-
return
fi
echo "foo"
}
So foo -h
yields:
This method prints foo to the terminal.
Enter `foo -h` to see the docstring.
It has indentations and multiple lines.
Change the delimiter if you need hashtag for some reason.
This can include $$ and = and eval, but won't be evaluated
Explanation
cut -d "#" -f 2
: Retrieve the second portion of the #
delimited lines. (Think a csv with "#" as the delimiter, empty first column).
cut -c 2-
: Retrieve the 2nd to end character of the resultant string
Also note that if [ "$1" = "-h" ]
evaluates as False
if there is no first argument, w/o error, since it becomes an empty string.
While the answers here are definately working, they are using a GET
request, which exposes your private key (even though https
is used). On Google Developers the specified method is POST
.
For a little bit more detail: https://stackoverflow.com/a/323286/1680919
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '[YOUR SECRET KEY]',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
Array Syntax: I use the "new" array syntax ( [
and ]
instead of array(..)
). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).
Return Values: This function returns true
if the user is valid, false
if not, and null
if an error occured. You can use it for example simply by writing if (isValid()) { ... }
You can execute bits of code once for a class before an object is constructed in the static blocks.
E.g.
class A {
static int var1 = 6;
static int var2 = 9;
static int var3;
static long var4;
static Date date1;
static Date date2;
static {
date1 = new Date();
for(int cnt = 0; cnt < var2; cnt++){
var3 += var1;
}
System.out.println("End first static init: " + new Date());
}
}
<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";
function docWrite(variable) {
document.write(variable);
}
</script>
</head>
<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>
<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
You can shorten document.write
but
can't avoid <script>
tag
You can ssh
directly from the Terminal on Mac, but you need to use a .PEM
key rather than the putty
.PPK
key. You can use PuttyGen on Windows to convert from .PEM
to .PPK
, I'm not sure about the other way around though.
You can also convert the key using putty
for Mac via port
or brew
:
sudo port install putty
or
brew install putty
This will also install puttygen
. To get puttygen
to output a .PEM
file:
puttygen privatekey.ppk -O private-openssh -o privatekey.pem
Once you have the key, open a terminal window and:
ssh -i privatekey.pem [email protected]
The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.
chmod go-rw privatekey.pem
You'll need to escape the (escaped) backslash in the first argument as it is a regular expression. Replacement (2nd argument - see Matcher#replaceAll(String)) also has it's special meaning of backslashes, so you'll have to replace those to:
theString.replaceAll("\\\\", "\\\\\\\\");
I did some more research and found this place to give me what I needed - feels clean and relates to update data when refreshed from server: https://blog.angular-university.io/angular-material-data-table/
Most credits to the page above. Below is a sample of how a mat-selector can be used to update a mat-table bound to a datasource on change of selection. I am using Angular 7. Sorry for being extensive, trying to be complete but concise - I have ripped out as many non-needed parts as possible. With this hoping to help someone else getting forward faster!
organization.model.ts:
export class Organization {
id: number;
name: String;
}
organization.service.ts:
import { Observable, empty } from 'rxjs';
import { of } from 'rxjs';
import { Organization } from './organization.model';
export class OrganizationService {
getConstantOrganizations(filter: String): Observable<Organization[]> {
if (filter === "All") {
let Organizations: Organization[] = [
{ id: 1234, name: 'Some data' }
];
return of(Organizations);
} else {
let Organizations: Organization[] = [
{ id: 5678, name: 'Some other data' }
];
return of(Organizations);
}
// ...just a sample, other filterings would go here - and of course data instead fetched from server.
}
organizationdatasource.model.ts:
import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { catchError, finalize } from "rxjs/operators";
import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
export class OrganizationDataSource extends DataSource<Organization> {
private organizationsSubject = new BehaviorSubject<Organization[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();
constructor(private organizationService: OrganizationService, ) {
super();
}
loadOrganizations(filter: String) {
this.loadingSubject.next(true);
return this.organizationService.getOrganizations(filter).pipe(
catchError(() => of([])),
finalize(() => this.loadingSubject.next(false))
).subscribe(organization => this.organizationsSubject.next(organization));
}
connect(collectionViewer: CollectionViewer): Observable<Organization[]> {
return this.organizationsSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.organizationsSubject.complete();
this.loadingSubject.complete();
}
}
organizations.component.html:
<div class="spinner-container" *ngIf="organizationDataSource.loading$ | async">
<mat-spinner></mat-spinner>
</div>
<div>
<form [formGroup]="formGroup">
<mat-form-field fxAuto>
<div fxLayout="row">
<mat-select formControlName="organizationSelectionControl" (selectionChange)="updateOrganizationSelection()">
<mat-option *ngFor="let organizationSelectionAlternative of organizationSelectionAlternatives"
[value]="organizationSelectionAlternative">
{{organizationSelectionAlternative.name}}
</mat-option>
</mat-select>
</div>
</mat-form-field>
</form>
</div>
<mat-table fxLayout="column" [dataSource]="organizationDataSource">
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let organization">{{organization.name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="number">
<mat-header-cell *matHeaderCellDef>Number</mat-header-cell>
<mat-cell *matCellDef="let organization">{{organization.number}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
organizations.component.scss:
.spinner-container {
height: 360px;
width: 390px;
position: fixed;
}
organization.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';
import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
import { OrganizationDataSource } from './organizationdatasource.model';
@Component({
selector: 'organizations',
templateUrl: './organizations.component.html',
styleUrls: ['./organizations.component.scss']
})
export class OrganizationsComponent implements OnInit {
public displayedColumns: string[];
public organizationDataSource: OrganizationDataSource;
public formGroup: FormGroup;
public organizationSelectionAlternatives = [{
id: 1,
name: 'All'
}, {
id: 2,
name: 'With organization update requests'
}, {
id: 3,
name: 'With contact update requests'
}, {
id: 4,
name: 'With order requests'
}]
constructor(
private formBuilder: FormBuilder,
private organizationService: OrganizationService) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
'organizationSelectionControl': []
})
const toSelect = this.organizationSelectionAlternatives.find(c => c.id == 1);
this.formGroup.get('organizationSelectionControl').setValue(toSelect);
this.organizationDataSource = new OrganizationDataSource(this.organizationService);
this.displayedColumns = ['name', 'number' ];
this.updateOrganizationSelection();
}
updateOrganizationSelection() {
this.organizationDataSource.loadOrganizations(this.formGroup.get('organizationSelectionControl').value.name);
}
}
If you have stopped the mongod.exe service from the task manager, you need to restart the service. In my case I stopped the service from task manager and on restart it doesn't automatically started.
This should work:
window.location.href = window.location.href.split( '#' )[0];
or
var x = window.location.href;
x = x.split( '#' );
window.location.href = x[0];
I prefer this for the following reasons:
Alternatively, you may use the most recent official method for this task
window.location.reload()
On Ubuntu 14.04, I found two parts to solving the problem:
/jre
from the environment variable. For me: export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/
sudo apt-get install default-jdk
In spark/scala, it's pretty easy to filter with varargs.
val d = spark.read...//data contains column named matid
val ids = Seq("BNBEL0608AH", "BNBEL00608H")
val filtered = d.filter($"matid".isin(ids:_*))
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
If your form is "outside" the MDI parent, then you most likely didn't set the MdiParent property:
Dim f As New Form
f.MdiParent = Me
f.Show()
Me, in this example, is a form that has IsMdiContainer = True
so that it can host child forms.
For re-arranging the child form layout, you just call the method from your MdiContainer form:
Me.LayoutMdi(MdiLayout.Cascade)
The MdiLayout enum also has tiling and arrange icons values.
You can use sklearn.preprocessing:
from sklearn.preprocessing import normalize
data = np.array([
[1000, 10, 0.5],
[765, 5, 0.35],
[800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1. 1. 1. ]
[ 0.765 0.5 0.7 ]
[ 0.8 0.7 0.18 ]]
Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:
L[0] += 1
is not guaranteed to actually increase L[0] by one if another thread does the same thing, because +=
is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.
There's code in one reply that spells it out, but you might find it easier to start from the bottom up, by asking and answering tiny questions (this is the approach in The Little Lisper):
public ListNode Reverse(ListNode list)
{
if (list == null) return null; // first question
if (list.next == null) return list; // second question
// third question - in Lisp this is easy, but we don't have cons
// so we grab the second element (which will be the last after we reverse it)
ListNode secondElem = list.next;
// bug fix - need to unlink list from the rest or you will get a cycle
list.next = null;
// then we reverse everything from the second element on
ListNode reverseRest = Reverse(secondElem);
// then we join the two lists
secondElem.next = list;
return reverseRest;
}
Using list comprehension:
>>> lst = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [item[0] for item in lst]
>>> lst2
['a', 1, 'x']
Here is an interesting article on Getting your C++ to the Web with Node.js
three general ways of integrating C++ code with a Node.js application - although there are lots of variations within each category:
- Automation - call your C++ as a standalone app in a child process.
- Shared library - pack your C++ routines in a shared library (dll) and call those routines from Node.js directly.
- Node.js Addon - compile your C++ code as a native Node.js module/addon.
TF2 runs Eager Execution by default, thus removing the need for Sessions. If you want to run static graphs, the more proper way is to use tf.function()
in TF2. While Session can still be accessed via tf.compat.v1.Session()
in TF2, I would discourage using it. It may be helpful to demonstrate this difference by comparing the difference in hello worlds:
TF1.x hello world:
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(msg))
TF2.x hello world:
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)
For more info, see Effective TensorFlow 2
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 have found the browser referer implementation to be really inconsistent.
For example, an anchor element with the "download" attribute works as expected in Safari and sends the referer, but in Chrome the referer will be empty or "-" in the web server logs.
<a href="http://foo.com/foo" download="bar">click to download</a>
Is broken in Chrome - no referer sent.
For Linux :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
For Mac :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip
For Windows:https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip
unzip it
for linux and mac users move file to /usr/local/bin
and execute ngrok http 80
command in the terminal
I don't have any idea about windows
This will give DISTINCT values across all the columns:
SELECT DISTINCT value
FROM (
SELECT DISTINCT a AS value FROM my_table
UNION SELECT DISTINCT b AS value FROM my_table
UNION SELECT DISTINCT c AS value FROM my_table
) AS derived
Samsung file explorer needs not only custom action (com.sec.android.app.myfiles.PICK_DATA), but also category part (Intent.CATEGORY_DEFAULT) and mime-type should be passed as extra.
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
You can also use this action for opening multiple files: com.sec.android.app.myfiles.PICK_DATA_MULTIPLE Anyway here is my solution which works on Samsung and other devices:
public void openFile(String mimeType) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(mimeType);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", mimeType);
sIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getPackageManager().resolveActivity(sIntent, 0) != null){
// it is device with Samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Open file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
} else {
chooserIntent = Intent.createChooser(intent, "Open file");
}
try {
startActivityForResult(chooserIntent, CHOOSE_FILE_REQUESTCODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
}
}
This solution works well for me, and maybe will be useful for someone else.
This works:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Form2.Show()
This works if you need only the application name without extension:
Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName);
It all depends on the type of classification problem you are dealing with. There are three main categories
In the first case, binary cross-entropy should be used and targets should be encoded as one-hot vectors.
In the second case, categorical cross-entropy should be used and targets should be encoded as one-hot vectors.
In the last case, binary cross-entropy should be used and targets should be encoded as one-hot vectors. Each output neuron (or unit) is considered as a separate random binary variable, and the loss for the entire vector of outputs is the product of the loss of single binary variables. Therefore it is the product of binary cross-entropy for each single output unit.
The binary cross-entropy is defined as
and categorical cross-entropy is defined as
where c
is the index running over the number of classes C
.
The SublimeText 3 Column-Select plugin should be all you need. Install that, then make sure you have something like the following in your 'Default (OSX).sublime-keymap' file:
// Column mode
{ "keys": ["ctrl+alt+up"], "command": "column_select", "args": {"by": "lines", "forward": false}},
{ "keys": ["ctrl+alt+down"], "command": "column_select", "args": {"by": "lines", "forward": true}},
{ "keys": ["ctrl+alt+pageup"], "command": "column_select", "args": {"by": "pages", "forward": false}},
{ "keys": ["ctrl+alt+pagedown"], "command": "column_select", "args": {"by": "pages", "forward": true}},
{ "keys": ["ctrl+alt+home"], "command": "column_select", "args": {"by": "all", "forward": false}},
{ "keys": ["ctrl+alt+end"], "command": "column_select", "args": {"by": "all", "forward": true}}
What exactly about it did not work for you?
Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.
VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"
With the following appended to android kernel cmd:
UVESA_MODE=440x680 DPI=120
If you need a cross-platform solution, try Boost's Program Options library.
The only way that worked for me was
gksudo nautilus
For anyone looking for a solution using React 16.8+ (hooks) and React Router 5:
You can change the route using a button with the following code:
<button onClick={() => props.history.push("path")}>
React Router provides some props to your components, including the push() function on history which works pretty much like the < Link to='path' > element.
You don't need to wrap your components with the Higher Order Component "withRouter" to get access to those props.
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer
class has variables called name
and sale
, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store
class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
I've seen this error in a similar situation to mentioned in Joe's answer:
description: Too high 5xx responses rate: {{ .Value }} > 0.05
We have a colon in description value. So, the problem is in missing quotes around description value. It can be resolved by adding quotes:
description: 'Too high 5xx responses rate: {{ .Value }} > 0.05'
The above answer only deal with DOM parser (that normally reads the entire file in memory and parse it, what for a big file is a problem), you could use a SAX parser that uses less memory and is faster (anyway that depends on your code).
SAX parser callback some functions when it find a start of element, end of element, attribute, text between elements, etc, so it can parse the document and at the same time you get what you need.
Some example code:
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
this is pretty old, but if you are using Python 3.4 or above use PathLib.
# using OS
import os
path=os.path.dirname("C:/folder1/folder2/filename.xml")
print(path)
print(os.path.basename(path))
# using pathlib
import pathlib
path = pathlib.PurePath("C:/folder1/folder2/filename.xml")
print(path.parent)
print(path.parent.name)
CORS
(Cross-Origin Resource Sharing) and SOP
(Same-Origin Policy) are server-side configurations that clients decide to enforce or not.
Related to clients
CSRF
attack.On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.
Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.
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;
}
int num = Integer.parseInt("binaryString",2);
IPv4 uses 32 bits, in the form of:
255.255.255.255
I suppose it depends on your datatype, whether you're just storing as a string with a CHAR type or if you're using a numerical type.
IPv6 uses 128 bits. You won't have IPs longer than that unless you're including other information with them.
IPv6 is grouped into sets of 4 hex digits seperated by colons, like (from wikipedia):
2001:0db8:85a3:0000:0000:8a2e:0370:7334
You're safe storing it as a 39-character long string, should you wish to do that. There are other shorthand ways to write addresses as well though. Sets of zeros can be truncated to a single 0, or sets of zeroes can be hidden completely by a double colon.
Presumably, if one wants to use an OnTouchListener
rather than an OnClickListener
, then the extra functionality of the OnTouchListener
is needed. This is a supplemental answer to show more detail of how an OnTouchListener
can be used.
Define the listener
Put this somewhere in your activity or fragment.
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
Set the listener
Set the listener in onCreate
(for an Activity) or onCreateView
(for a Fragment).
myView.setOnTouchListener(handleTouch);
Notes
getX
and getY
give you the coordinates relative to the view (that is, the top left corner of the view). They will be negative when moving above or to the left of your view. Use getRawX
and getRawY
if you want the absolute screen coordinates.x
and y
values to determine things like swipe direction.For those looking a concise answer,
If an assembly is compiled as a class library and provides types for other assemblies to use, then it has the ifle extension .dll
(dynamic link library), and it cannot be executed standalone.
Likewise, if an assembly is compiled as an application, then it has the file extension .exe
(executable) and can be executed standalone. Before .NET Core 3.0, console apps were compiled to .dll fles and had to be executed by the dotnet run command or a host executable. - Source
Images or binary data:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
or HTML:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
This answer is based on Yann's answer. It will set the aspect ratio for linear or log-log plots. I've used additional information from https://stackoverflow.com/a/16290035/2966723 to test if the axes are log-scale.
def forceAspect(ax,aspect=1):
#aspect is width/height
scale_str = ax.get_yaxis().get_scale()
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
if scale_str=='linear':
asp = abs((xmax-xmin)/(ymax-ymin))/aspect
elif scale_str=='log':
asp = abs((scipy.log(xmax)-scipy.log(xmin))/(scipy.log(ymax)-scipy.log(ymin)))/aspect
ax.set_aspect(asp)
Obviously you can use any version of log
you want, I've used scipy
, but numpy
or math
should be fine.
You should try this:
<b class="{{ Request::is('admin/login') ? 'active' : '' }}">Login Account Details</b>
how do i print HTML table. Header and footer on each page
Also Work in Webkit Browsers
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function PrintPage() {
document.getElementById('print').style.display = 'none';
window.resizeTo(960, 600);
document.URL = "";
window.location.href = "";
window.print();
}
</script>
<style type="text/css" media="print">
@page
{
size: auto; /* auto is the initial value */
margin: 2mm 4mm 0mm 0mm; /* this affects the margin in the printer settings */
}
thead
{
display: table-header-group;
}
tfoot
{
display: table-footer-group;
}
</style>
<style type="text/css" media="screen">
thead
{
display: block;
}
tfoot
{
display: block;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 500px; margin: 0 auto;">
<thead>
<tr>
<td>
header comes here for each page
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
1
</td>
</tr>
<tr>
<td>
2
</td>
</tr>
<tr>
<td>
3
</td>
</tr>
<tr>
<td>
4
</td>
</tr>
<tr>
<td>
5
</td>
</tr>
<tr>
<td>
6
</td>
</tr>
<tr>
<td>
7
</td>
</tr>
<tr>
<td>
8
</td>
</tr>
<tr>
<td>
9
</td>
</tr>
<tr>
<td>
10
</td>
</tr>
<tr>
<td>
11
</td>
</tr>
<tr>
<td>
12
</td>
</tr>
<tr>
<td>
13
</td>
</tr>
<tr>
<td>
14
</td>
</tr>
<tr>
<td>
15
</td>
</tr>
<tr>
<td>
16
</td>
</tr>
<tr>
<td>
17
</td>
</tr>
<tr>
<td>
18
</td>
</tr>
<tr>
<td>
19
</td>
</tr>
<tr>
<td>
20
</td>
</tr>
<tr>
<td>
21
</td>
</tr>
<tr>
<td>
22
</td>
</tr>
<tr>
<td>
23
</td>
</tr>
<tr>
<td>
24
</td>
</tr>
<tr>
<td>
25
</td>
</tr>
<tr>
<td>
26
</td>
</tr>
<tr>
<td>
27
</td>
</tr>
<tr>
<td>
28
</td>
</tr>
<tr>
<td>
29
</td>
</tr>
<tr>
<td>
30
</td>
</tr>
<tr>
<td>
31
</td>
</tr>
<tr>
<td>
32
</td>
</tr>
<tr>
<td>
33
</td>
</tr>
<tr>
<td>
34
</td>
</tr>
<tr>
<td>
35
</td>
</tr>
<tr>
<td>
36
</td>
</tr>
<tr>
<td>
37
</td>
</tr>
<tr>
<td>
38
</td>
</tr>
<tr>
<td>
39
</td>
</tr>
<tr>
<td>
40
</td>
</tr>
<tr>
<td>
41
</td>
</tr>
<tr>
<td>
42
</td>
</tr>
<tr>
<td>
43
</td>
</tr>
<tr>
<td>
44
</td>
</tr>
<tr>
<td>
45
</td>
</tr>
<tr>
<td>
46
</td>
</tr>
<tr>
<td>
47
</td>
</tr>
<tr>
<td>
48
</td>
</tr>
<tr>
<td>
49
</td>
</tr>
<tr>
<td>
50
</td>
</tr>
<tr>
<td>
51
</td>
</tr>
<tr>
<td>
52
</td>
</tr>
<tr>
<td>
53
</td>
</tr>
<tr>
<td>
54
</td>
</tr>
<tr>
<td>
55
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
footer comes here for each page
</td>
</tr>
</tfoot>
</table>
</div>
<br clear="all" />
<input type="button" id="print" name="print" value="Print" onclick="javascript:PrintPage();"
class="button" />
</form>
</body>
</html>
For folks who ended up here and are using CYGWIN
, install following packages in cygwin and re-run:
[examine all threads backtraces to find the culprit]
Even fully expanded call stack can still hide the actual offending line of code from you when you use more than one thread!
Example: One thread is iterating ruby Hash, other thread is trying to modify it. BOOM! Exception! And the problem with the stack trace you get while trying to modify 'busy' hash is that it shows you chain of functions down to the place where you're trying to modify hash, but it does NOT show who's currently iterating it in parallel (who owns it)! Here's the way to figure that out by printing stack trace for ALL currently running threads. Here's how you do this:
# This solution was found in comment by @thedarkone on https://github.com/rails/rails/issues/24627
rescue Object => boom
thread_count = 0
Thread.list.each do |t|
thread_count += 1
err_msg += "--- thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace begin \n"
# Lets see if we are able to pin down the culprit
# by collecting backtrace for all existing threads:
err_msg += t.backtrace.join("\n")
err_msg += "\n---thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace end \n"
end
# and just print it somewhere you like:
$stderr.puts(err_msg)
raise # always reraise
end
The above code snippet is useful even just for educational purposes as it can show you (like x-ray) how many threads you actually have (versus how many you thought you have - quite often those two are different numbers ;)
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their <html>
and <body>
tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.
Kdiff3 conflict resolution algorithm is really impressive.
Even when subversion indicates a conflict, Kdiff3 solves it automatically. There's versions for Windows and Linux with the same interface. It is possible to integrate it with Tortoise and with your linux shell.
It is in the list of my favorite open source software. One of the first tools I install in any machine.
You can configure it as the default diff tool in Subversion, Git, Mercurial, and ClearCase. It also solves almost all the ClearCase conflicts. In Windows, it has a nice integration with windows explorer: select two files and right click to compare them, or right click to 'save to later' a file, and then select another one to compare.
The merged file is editable. Has slick keyboard shortcuts.
You can also use it compare and merge directories. See:
An advanced feature is to use regular expressions for defining automatic merges.
My only annoyance is that it is a little difficult to compile if it isn't present in your favorite distro repository.
Spaces are horrible in filenames or directory names.
The correct syntax for this is to include every directory name that includes spaces, in double quotes
cmd /c C:\"Program Files"\"Microsoft Visual Studio 9.0"\Common7\IDE\devenv.com mysolution.sln /build "release|win32"
jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:
$("a.directions-link").attr("href", function(i, href) {
return href + '?q=testing';
});
That loops over all the elements too, so no need for $.each
For me reinstalling and then upgrading the pip worked.
Reinstall pip by using below command or following link How do I install pip on macOS or OS X?
curl https://bootstrap.pypa.io/get-pip.py -o - | python
Upgrade pip after it's installed
pip install -U pip
Note that you could as well plot directly from ce
(after the comma removing) using the column name :
hist(ce$Weight)
(As opposed to using hist(ce[1])
, which would lead to the same "must be numeric" error.)
This also works for a database query result.
There are a couple of ways of doing I first did the way Grendal2501 did it. I then did it similar to user15163, you can store the image URL in the firebase and host the image on your firebase host or also Amazon S3;
Actually, all the other answers have flaws. The most reliable way is:
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
Detailed Explanation:
Using "%1"=="-b"
will flat out crash if passing argument with spaces and quotes. This is the least reliable method.
IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "a b"
b""=="-b" was unexpected at this time.
Using [%1]==[-b]
is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.
IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "-b"
(does not match, and jumps to UNKNOWN instead of SPECIFIC)
Using "%~1"=="-b"
is the most reliable. %~1
will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"
(all of the above tests work correctly)
Whenever possible one should avoid culture specific date/time literals.
There are some secure formats to provide a date/time as literal:
All examples for 2016-09-15 17:30:00
{ts'2016-09-15 17:30:00'}
--Time Stamp{d'2016-09-15'}
--Date only{t'17:30:00'}
--Time only'2016-09-15T17:30:00'
--be aware of the T
in the middle!'20160915'
--only for pure dateSQL-Server is well know to do things in an order of execution one might not have expected. Your written statement looks like the conversion is done before some type related action takes place, but the engine decides - why ever - to do the conversion in a later step.
Here is a great article explaining this with examples: Rusano.com: "t-sql-functions-do-no-imply-a-certain-order-of-execution" and here is the related question.
hosts0 = open("C:path\\a.txt","r")
hosts1 = open("C:path\\b.txt","r")
lines1 = hosts0.readlines()
for i,lines2 in enumerate(hosts1):
if lines2 != lines1[i]:
print "line ", i, " in hosts1 is different \n"
print lines2
else:
print "same"
The above code is working for me. Can you please indicate what error you are facing?
On macOS Mojave 10.14.4, you can also try Command ? + Q in a terminal.
To remove all child elements from your div:
$('#mysweetdiv').empty();
.removeData()
and the corresponding .data()
function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:
var $li = $('<li>Joe</li>').data('id', 25);
To solve this:
All you need to do is to install Python certificates! A common issue on macOS.
Open these files:
Install Certificates.command
Update Shell Profile.command
Simply Run these two scripts and you wont have this issue any more.
Hope this helps!
If your list has fields/properties and you want to use a specific value (e.g. FirstName), then you can do this:
string combindedString = string.Join( ",", myList.Select(t=>t.FirstName).ToArray() );
This did the job for me,
import org.apache.commons.lang.StringEscapeUtils;
...
String decodedXML= StringEscapeUtils.unescapeHtml(encodedXML);
or
import org.apache.commons.lang3.StringEscapeUtils;
...
String decodedXML= StringEscapeUtils.unescapeHtml4(encodedXML);
I guess its always better to use the lang3
for obvious reasons.
Hope this helps :)
You can Use This One To get the selected ListItme Name ::
String selectedItem = ((ListBoxItem)ListBox.SelectedItem).Name.ToString();
Make sure that Your each ListBoxItem have a Name property
cp -r ./SourceFolder ./DestFolder
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>
Yet another reason may be that your entity class has several properties named somhow /.*id/i
- so ending with ID case insensitive AND elementary type AND there is no [Key]
attribute.
EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.
See my case:
public class MyTest, IMustHaveTenant
{
public long Id { get; set; }
public int TenantId { get; set; }
[MaxLength(32)]
public virtual string Signum{ get; set; }
public virtual string ID { get; set; }
public virtual string ID_Other { get; set; }
}
don't ask - lecacy code. The Id
was even inherited, so I could not use [Key]
(just simplifying the code here)
But here EF is totally confused.
What helped was using modelbuilder this in DBContext class.
modelBuilder.Entity<MyTest>(f =>
{
f.HasKey(e => e.Id);
f.HasIndex(e => new { e.TenantId });
f.HasIndex(e => new { e.TenantId, e.ID_Other });
});
the index on PK is implicit.
This can also be done in the GUI:
The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false
, then you can do this:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"
if(mymap[key]) {
println mymap[key]
}
However, if the value could potentially be Groovy-false
, you should use:
if(mymap.containsKey(key)) {
println mymap[key]
}
The easiest solution, though, if you know the value isn't going to be Groovy-false
(or you can ignore that), and want a default value, is like this:
def value = mymap[key] ?: "default"
All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap
(or LinkedHashMap
) design that makes direct key access nearly instantaneous.
Update for Swift 3.0 and higher
//
// Step 1:- Create a method in AppDelegate.swift
//
func someMethodInAppDelegate() {
print("someMethodInAppDelegate called")
}
calling above method from your controller by followings
//
// Step 2:- Getting a reference to the AppDelegate & calling the require method...
//
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.someMethodInAppDelegate()
}
Output:
Why do people use constants in classes instead of a variable?
readability and maintainability,
having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.
Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.
But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.
For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.
grep provides '-v' or '--invert-match' option to select non-matching lines.
e.g.
grep -v 'unwanted_pattern' file_name
This will output all the lines from file file_name, which does not have 'unwanted_pattern'.
If you are searching the pattern in multiple files inside a folder, you can use the recursive search option as follows
grep -r 'wanted_pattern' * | grep -v 'unwanted_pattern'
Here grep will try to list all the occurrences of 'wanted_pattern' in all the files from within currently directory and pass it to second grep to filter out the 'unwanted_pattern'. '|' - pipe will tell shell to connect the standard output of left program (grep -r 'wanted_pattern' *) to standard input of right program (grep -v 'unwanted_pattern').
You can do this with PARTITION
and RANK
:
select * from
(
select MyPK, fmgcms_cpeclaimid, createdon,
Rank() over (Partition BY fmgcms_cpeclaimid order by createdon DESC) as Rank
from Filteredfmgcms_claimpaymentestimate
where createdon < 'reportstartdate'
) tmp
where Rank = 1
I went ahead and wrote it in python since I think it's a lot more readable than in c++ for a problem like this. The function order is in order of operations for solving this by hand via this video. Just import this and call "print_invert" on your matrix.
def print_invert (matrix):
i_matrix = invert_matrix (matrix)
for line in i_matrix:
print (line)
return
def invert_matrix (matrix):
determinant = str (determinant_of_3x3 (matrix))
cofactor = make_cofactor (matrix)
trans_matrix = transpose_cofactor (cofactor)
trans_matrix[:] = [[str (element) +'/'+ determinant for element in row] for row in trans_matrix]
return trans_matrix
def determinant_of_3x3 (matrix):
multiplication = 1
neg_multiplication = 1
total = 0
for start_column in range (3):
for row in range (3):
multiplication *= matrix[row][(start_column+row)%3]
neg_multiplication *= matrix[row][(start_column-row)%3]
total += multiplication - neg_multiplication
multiplication = neg_multiplication = 1
if total == 0:
total = 1
return total
def make_cofactor (matrix):
cofactor = [[0,0,0],[0,0,0],[0,0,0]]
matrix_2x2 = [[0,0],[0,0]]
# For each element in matrix...
for row in range (3):
for column in range (3):
# ...make the 2x2 matrix in this inner loop
matrix_2x2 = make_2x2_from_spot_in_3x3 (row, column, matrix)
cofactor[row][column] = determinant_of_2x2 (matrix_2x2)
return flip_signs (cofactor)
def make_2x2_from_spot_in_3x3 (row, column, matrix):
c_count = 0
r_count = 0
matrix_2x2 = [[0,0],[0,0]]
# ...make the 2x2 matrix in this inner loop
for inner_row in range (3):
for inner_column in range (3):
if row is not inner_row and inner_column is not column:
matrix_2x2[r_count % 2][c_count % 2] = matrix[inner_row][inner_column]
c_count += 1
if row is not inner_row:
r_count += 1
return matrix_2x2
def determinant_of_2x2 (matrix):
total = matrix[0][0] * matrix [1][1]
return total - (matrix [1][0] * matrix [0][1])
def flip_signs (cofactor):
sign_pos = True
# For each element in matrix...
for row in range (3):
for column in range (3):
if sign_pos:
sign_pos = False
else:
cofactor[row][column] *= -1
sign_pos = True
return cofactor
def transpose_cofactor (cofactor):
new_cofactor = [[0,0,0],[0,0,0],[0,0,0]]
for row in range (3):
for column in range (3):
new_cofactor[column][row] = cofactor[row][column]
return new_cofactor
I just ran a Monte-Carlo simulation on both comparators on double heap sort min max and they both came to the same result:
These are the max comparators I have used:
(A) Collections built-in comparator
PriorityQueue<Integer> heapLow = new PriorityQueue<Integer>(Collections.reverseOrder());
(B) Custom comparator
PriorityQueue<Integer> heapLow = new PriorityQueue<Integer>(new Comparator<Integer>() {
int compare(Integer lhs, Integer rhs) {
if (rhs > lhs) return +1;
if (rhs < lhs) return -1;
return 0;
}
});
I had this issue and it looked like a bug in xcode's 10.x New build system.
Go to File > Project Settings
Change the Build system to use Legacy build system
.
Deep clean the project by holding Option(?)+Shift(?)+Command(?)+K or holding Option(?) and selecting Product > Clean Build Folder
Run on a device
For >= iOS8: (Simplified @EliBud's answer).
#define APP_STORE_ID 1108885113
- (void)rateApp{
static NSString *const iOSAppStoreURLFormat = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d";
NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:iOSAppStoreURLFormat, APP_STORE_ID]];
if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
[[UIApplication sharedApplication] openURL:appStoreURL];
}
}
Second approach is object initializer in C#
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
The first approach
var albumData = new Album("Albumius", "Artistus", 2013);
explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:
var albumData = new Album
{
Name = "Albumius",
};
Object initializer would translate into something like:
var albumData;
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;
Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.
As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.
select year(current_timestamp)
use this in code :
from selenium import webdriver
driver = webdriver.Firefox() # or Chrome()
driver.implicitly_wait(10) # seconds
driver.get("http://www.......")
or you can use this code if you are looking for a specific tag :
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox() #or Chrome()
driver.get("http://www.......")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "tag_id"))
)
finally:
driver.quit()
From about section of Reverse IP Domain Check tool on yougetsignal:
A reverse IP domain check takes a domain name or IP address pointing to a web server and searches for other sites known to be hosted on that same web server. Data is gathered from search engine results, which are not guaranteed to be complete.
Use the shell functions from http://cfajohnson.com/shell/ssr/ssr-scripts.tar.gz; they work in any standard Unix shell.
date1=2012-09-22
date2=2013-01-31
. date-funcs-sh
_date2julian "$date1"
jd1=$_DATE2JULIAN
_date2julian "$date2"
echo $(( _DATE2JULIAN - jd1 ))
See the documentation at http://cfajohnson.com/shell/ssr/08-The-Dating-Game.shtml
If you have more then one UITextField
s and you need to do something when (or before) keyboard appears or disappears, you can implement this approach.
Add UITextFieldDelegate
to your class. Assign integer counter, let's say:
NSInteger editCounter;
Set this counter to zero somewhere in viewDidLoad
.
Then, implement textFieldShouldBeginEditing
and textFieldShouldEndEditing
delegate methods.
In the first one add 1 to editCounter. If value of editCounter becomes 1 - this means that keyboard will appear (in case if you return YES). If editCounter > 1 - this means that keyboard is already visible and another UITextField holds the focus.
In textFieldShouldEndEditing
subtract 1 from editCounter. If you get zero - keyboard will be dismissed, otherwise it will remain on the screen.
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
I had the same issue in vscode. Just create a .prettierrc file in your root directory and add the following json. For single quotes add:
{
"singleQuote": true
}
For double quotes add:
{
"singleQuote": false
}
Unfortunately, there is no way to do this easily. Every solution has its drawbacks.
Use atof()
or strtof()
directly: this is what most people will tell you to do and it will work most of the time. However, if the program sets a locale or it uses a library that sets the locale (for instance, a graphics library that displays localised menus) and the user has their locale set to a language where the decimal separator is not .
(such as fr_FR
where the separator is ,
) these functions will stop parsing at the .
and you will stil get 4.0
.
Use atof()
or strtof()
but change the locale; it's a matter of calling setlocale(LC_ALL|~LC_NUMERIC, "");
before any call to atof()
or the likes. The problem with setlocale
is that it will be global to the process and you might interfer with the rest of the program. Note that you might query the current locale with setlocale()
and restore it after you're done.
Write your own float parsing routine. This might be quite quick if you do not need advanced features such as exponent parsing or hexadecimal floats.
Also, note that the value 4.08
cannot be represented exactly as a float; the actual value you will get is 4.0799999237060546875
.
As Umesh Patil answer have comment say that there is problem. I try to edit answer and get reject. And get suggest to post new answer. This code should solve problem they have (Shashi Roy, Gaven, John Higgins).
<html>
<head>
<script type="text/javascript">
function CheckColors(val){
var element=document.getElementById('othercolor');
if(val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</head>
<body>
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="othercolor" id="othercolor" style='display:none;'/>
</body>
</html>
Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.
Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.
old question but this is a pretty neat and clean fix, might come in use for people who are still wondering if it's possible :):
br{_x000D_
content: '.';_x000D_
display: inline-block;_x000D_
width: 100%;_x000D_
border-bottom: 1px dashed black;_x000D_
}
_x000D_
with this fix you can also remove BRs on websites ( just set the width to 0px )
The other answers are all correct, but don't forget you could also use collection operators, as follows:
var list = [1, 2, 3, 4]
var max: Int = (list as AnyObject).valueForKeyPath("@max.self") as Int
you can also find the average in the same way:
var avg: Double = (list as AnyObject).valueForKeyPath("@avg.self") as Double
This syntax might be less clear than some of the other solutions, but it's interesting to see that -valueForKeyPath:
can still be used :)
I accidentally ended up writing almost the same as provided by git-extras. So if you prefer a single custom command instead of installing a bunch of other extra commands, just place this git-pr
file somewhere in your $PATH
and then you can just write:
git pr 42
// or
git pr upstream 42
// or
git pr https://github.com/peerigon/phridge/pull/1
This can be achieved in a very simple way 1. Write this in the view.
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Height="30">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsHide}" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
The following is the Boolean property which holds the true/ false value. The following is the code snippet. In my example this property is in UserNote class.
public bool _isHide = false;
public bool IsHide
{
get { return _isHide; }
set
{
_isHide = value;
OnPropertyChanged("IsHide");
}
}
This is the way the IsHide property gets the value.
userNote.IsHide = userNote.IsNoteDeleted;
Douglas Crockford has some very good explanations of inheritance in JavaScript:
You need to use .each
:
var listItems = $("#productList li");
listItems.each(function(idx, li) {
var product = $(li);
// and the rest of your code
});
This is the correct way to loop through a jQuery selection.
In modern Javascript you can also use a for .. of
loop:
var listItems = $("#productList li");
for (let li of listItems) {
let product = $(li);
}
Be aware, however, that older browsers will not support this syntax, and you may well be better off with the jQuery syntax above.
You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.
The source comment added to NonLocalizedLabel
directs us now to:
return context.getPackageManager().getApplicationLabelFormatted(context.getApplicationInfo());
First add the following line to AndroidManifest.xml :
<uses-permission android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions" />
Then use the following code to install apk:
File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/MyApp";// + "app-release.apk";
File file = new File(fileStr, "TaghvimShamsi.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(promptInstall);
Dont use spaces:
SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE
dataGridView1.Columns
is probably of a length less than 5. Accessing dataGridView1.Columns[4]
then will be outside the list.
You can make it by one line:
mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
fmt.Println("k:", k, "v:", v)
}
Output is:
k: foo v: map[first:1]
k: boo v: map[second:2]
I'm using Oracle. If your sql returns numeric value, which is int, you need to use Convert.ToInt32(object). Here is the example below:
public int GetUsersCount(int userId)
{
using (var conn = new OracleConnection(...)){
conn.Open();
using(var command = conn.CreateCommand()){
command.CommandText = "select count(*) from users where userid = :userId";
command.AddParameter(":userId", userId);
var rowCount = command.ExecuteScalar();
return rowCount == null ? 0 : Convert.ToInt32(rowCount);
}
}
}
Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes
Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class
Example Code:
abstract class A {
public function test1() {
echo 'Hello World';
}
abstract protected function f1();
abstract public function f2();
protected function test2(){
echo 'Hello World test';
}
}
class B extends A {
public $a = 'India';
public function f1() {
echo "F1 Method Call";
}
public function f2() {
echo "F2 Method Call";
}
}
$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";
Output:
Hello World
India
Hello World test
F1 Method Call
F2 Method Call
INSERT...ON DUPLICATE KEY UPDATE
is prefered to prevent unexpected Exceptions management.
In my case I know that col1
and col2
make a unique composite index.
It keeps track of the error, but does not throw an exception on duplicate. Regarding the performance, the update by the same value is efficient as MySQL notices this and does not update it
INSERT INTO table
(col1, col2, col3, col4)
VALUES
(?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
col1 = VALUES(col1),
col2 = VALUES(col2)
The idea to use this approach came from the comments at phpdelusions.net/pdo.
======authorization====== MIDDLEWARE_x000D_
_x000D_
const jwt = require('../helpers/jwt')_x000D_
const User = require('../models/user')_x000D_
_x000D_
module.exports = {_x000D_
authentication: function(req, res, next) {_x000D_
try {_x000D_
const user = jwt.verifyToken(req.headers.token, process.env.JWT_KEY)_x000D_
User.findOne({ email: user.email }).then(result => {_x000D_
if (result) {_x000D_
req.body.user = result_x000D_
req.params.user = result_x000D_
next()_x000D_
} else {_x000D_
throw new Error('User not found')_x000D_
}_x000D_
})_x000D_
} catch (error) {_x000D_
console.log('langsung dia masuk sini')_x000D_
_x000D_
next(error)_x000D_
}_x000D_
},_x000D_
_x000D_
adminOnly: function(req, res, next) {_x000D_
let loginUser = req.body.user_x000D_
if (loginUser && loginUser.role === 'admin') {_x000D_
next()_x000D_
} else {_x000D_
next(new Error('Not Authorized'))_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
====error handler==== MIDDLEWARE_x000D_
const errorHelper = require('../helpers/errorHandling')_x000D_
_x000D_
module.exports = function(err, req, res, next) {_x000D_
// console.log(err)_x000D_
let errorToSend = errorHelper(err)_x000D_
// console.log(errorToSend)_x000D_
res.status(errorToSend.statusCode).json(errorToSend)_x000D_
}_x000D_
_x000D_
_x000D_
====error handling==== HELPER_x000D_
var nodeError = ["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]_x000D_
var mongooseError = ["MongooseError","DisconnectedError","DivergentArrayError","MissingSchemaError","DocumentNotFoundError","MissingSchemaError","ObjectExpectedError","ObjectParameterError","OverwriteModelError","ParallelSaveError","StrictModeError","VersionError"]_x000D_
var mongooseErrorFromClient = ["CastError","ValidatorError","ValidationError"];_x000D_
var jwtError = ["TokenExpiredError","JsonWebTokenError","NotBeforeError"]_x000D_
_x000D_
function nodeErrorMessage(message){_x000D_
switch(message){_x000D_
case "Token is undefined":{_x000D_
return 403;_x000D_
}_x000D_
case "User not found":{_x000D_
return 403;_x000D_
}_x000D_
case "Not Authorized":{_x000D_
return 401;_x000D_
}_x000D_
case "Email is Invalid!":{_x000D_
return 400;_x000D_
}_x000D_
case "Password is Invalid!":{_x000D_
return 400;_x000D_
}_x000D_
case "Incorrect password for register as admin":{_x000D_
return 400;_x000D_
}_x000D_
case "Item id not found":{_x000D_
return 400;_x000D_
}_x000D_
case "Email or Password is invalid": {_x000D_
return 400_x000D_
}_x000D_
default :{_x000D_
return 500;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
module.exports = function(errorObject){_x000D_
// console.log("===ERROR OBJECT===")_x000D_
// console.log(errorObject)_x000D_
// console.log("===ERROR STACK===")_x000D_
// console.log(errorObject.stack);_x000D_
_x000D_
let statusCode = 500; _x000D_
let returnObj = {_x000D_
error : errorObject_x000D_
}_x000D_
if(jwtError.includes(errorObject.name)){_x000D_
statusCode = 403;_x000D_
returnObj.message = "Token is Invalid"_x000D_
returnObj.source = "jwt"_x000D_
}_x000D_
else if(nodeError.includes(errorObject.name)){_x000D_
returnObj.error = JSON.parse(JSON.stringify(errorObject, ["message", "arguments", "type", "name"]))_x000D_
returnObj.source = "node";_x000D_
statusCode = nodeErrorMessage(errorObject.message);_x000D_
returnObj.message = errorObject.message;_x000D_
}else if(mongooseError.includes(errorObject.name)){_x000D_
returnObj.source = "database"_x000D_
returnObj.message = "Error from server"_x000D_
}else if(mongooseErrorFromClient.includes(errorObject.name)){_x000D_
returnObj.source = "database";_x000D_
errorObject.message ? returnObj.message = errorObject.message : returnObj.message = "Bad Request"_x000D_
statusCode = 400;_x000D_
}else{_x000D_
returnObj.source = "unknown error";_x000D_
returnObj.message = "Something error";_x000D_
}_x000D_
returnObj.statusCode = statusCode;_x000D_
_x000D_
return returnObj;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
===jwt====_x000D_
const jwt = require('jsonwebtoken')_x000D_
_x000D_
function generateToken(payload) {_x000D_
let token = jwt.sign(payload, process.env.JWT_KEY)_x000D_
return token_x000D_
}_x000D_
_x000D_
function verifyToken(token) {_x000D_
let payload = jwt.verify(token, process.env.JWT_KEY)_x000D_
return payload_x000D_
}_x000D_
_x000D_
module.exports = {_x000D_
generateToken, verifyToken_x000D_
}_x000D_
_x000D_
===router index===_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
// router.get('/', )_x000D_
router.use('/users', require('./users'))_x000D_
router.use('/products', require('./product'))_x000D_
router.use('/transactions', require('./transaction'))_x000D_
_x000D_
module.exports = router_x000D_
_x000D_
====router user ====_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
const User = require('../controllers/userController')_x000D_
const auth = require('../middlewares/auth')_x000D_
_x000D_
/* GET users listing. */_x000D_
router.post('/register', User.register)_x000D_
router.post('/login', User.login)_x000D_
router.get('/', auth.authentication, User.getUser)_x000D_
router.post('/logout', auth.authentication, User.logout)_x000D_
module.exports = router_x000D_
_x000D_
_x000D_
====app====_x000D_
require('dotenv').config()_x000D_
const express = require('express')_x000D_
const cookieParser = require('cookie-parser')_x000D_
const logger = require('morgan')_x000D_
const cors = require('cors')_x000D_
const indexRouter = require('./routes/index')_x000D_
const errorHandler = require('./middlewares/errorHandler')_x000D_
const mongoose = require('mongoose')_x000D_
const app = express()_x000D_
_x000D_
mongoose.connect(process.env.DB_URI, {_x000D_
useNewUrlParser: true,_x000D_
useUnifiedTopology: true,_x000D_
useCreateIndex: true,_x000D_
useFindAndModify: false_x000D_
})_x000D_
_x000D_
app.use(cors())_x000D_
app.use(logger('dev'))_x000D_
app.use(express.json())_x000D_
app.use(express.urlencoded({ extended: false }))_x000D_
app.use(cookieParser())_x000D_
_x000D_
app.use('/', indexRouter)_x000D_
app.use(errorHandler)_x000D_
_x000D_
module.exports = app
_x000D_
Specify it on the command line for javac:
javac -Xlint:unchecked
Or if you are using Ant modify your javac target
<javac ...>
<compilerarg value="-Xlint"/>
</javac>
If you are using Maven, configure this in the maven-compiler-plugin
<compilerArgument>-Xlint:unchecked</compilerArgument>
This code will dynamically generate the expression for you with the nested clauses. I have a scenario where the number of "OR" s was unknown, so I'm using the below. Usage:
private static void Main(string[] args)
{
var query = new PropertyString(@"<Query><Where>{{WhereClauses}}</Where></Query>");
var whereClause =
new PropertyString(@"<Eq><FieldRef Name='ID'/><Value Type='Counter'>{{NestClauseValue}}</Value></Eq>");
var andClause = new PropertyString("<Or>{{FirstExpression}}{{SecondExpression}}</Or>");
string[] values = {"1", "2", "3", "4", "5", "6"};
query["WhereClauses"] = NestEq(whereClause, andClause, values);
Console.WriteLine(query);
}
And here's the code:
private static string MakeExpression(PropertyString nestClause, string value)
{
var expr = nestClause.New();
expr["NestClauseValue"] = value;
return expr.ToString();
}
/// <summary>
/// Recursively nests the clause with the nesting expression, until nestClauseValue is empty.
/// </summary>
/// <param name="whereClause"> A property string in the following format: <Eq><FieldRef Name='Title'/><Value Type='Text'>{{NestClauseValue}}</Value></Eq>"; </param>
/// <param name="nestingExpression"> A property string in the following format: <And>{{FirstExpression}}{{SecondExpression}}</And> </param>
/// <param name="nestClauseValues">A string value which NestClauseValue will be filled in with.</param>
public static string NestEq(PropertyString whereClause, PropertyString nestingExpression, string[] nestClauseValues, int pos=0)
{
if (pos > nestClauseValues.Length)
{
return "";
}
if (nestClauseValues.Length == 1)
{
return MakeExpression(whereClause, nestClauseValues[0]);
}
var expr = nestingExpression.New();
if (pos == nestClauseValues.Length - 2)
{
expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
expr["SecondExpression"] = MakeExpression(whereClause, nestClauseValues[pos + 1]);
return expr.ToString();
}
else
{
expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
expr["SecondExpression"] = NestEq(whereClause, nestingExpression, nestClauseValues, pos + 1);
return expr.ToString();
}
}
public class PropertyString
{
private string _propStr;
public PropertyString New()
{
return new PropertyString(_propStr );
}
public PropertyString(string propStr)
{
_propStr = propStr;
_properties = new Dictionary<string, string>();
}
private Dictionary<string, string> _properties;
public string this[string key]
{
get
{
return _properties.ContainsKey(key) ? _properties[key] : string.Empty;
}
set
{
if (_properties.ContainsKey(key))
{
_properties[key] = value;
}
else
{
_properties.Add(key, value);
}
}
}
/// <summary>
/// Replaces properties in the format {{propertyName}} in the source string with values from KeyValuePairPropertiesDictionarysupplied dictionary.nce you've set a property it's replaced in the string and you
/// </summary>
/// <param name="originalStr"></param>
/// <param name="keyValuePairPropertiesDictionary"></param>
/// <returns></returns>
public override string ToString()
{
string modifiedStr = _propStr;
foreach (var keyvaluePair in _properties)
{
modifiedStr = modifiedStr.Replace("{{" + keyvaluePair.Key + "}}", keyvaluePair.Value);
}
return modifiedStr;
}
}
From the documentation get_or_create:
# get_or_create() a person with similar first names.
p, created = Person.objects.get_or_create(
first_name='John',
last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)},
)
# get_or_create() didn't have to create an object.
>>> created
False
Explanation:
Fields to be evaluated for similarity, have to be mentioned outside defaults
. Rest of the fields have to be included in defaults
. In case CREATE event occurs, all the fields are taken into consideration.
It looks like you need to be returning into a tuple, instead of a single variable, do like this:
customer.source,created = Source.objects.get_or_create(name="Website")
Please check http://jsfiddle.net/GEBrW/ for live test.
You can use similar method for dynamic arrays creation.
var i = 0;
var a = new Array();
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
The result:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
I am using Angular v11 and was facing this error while trying to lazy load a component (await import('./my-component.component')
) and even if import
and export
were correctly set.
I finally figured out that the solution was deleting the separate dedicated module's file and move the module content inside the component file itself.
rm -r my-component.module.ts
and add module inside my-component.ts
(same file)
@Component({
selector: 'app-my-component',
templateUrl: './my-component.page.html',
styleUrls: ['./my-component.page.scss'],
})
export class MyComponent {
}
@NgModule({
imports: [CommonModule],
declarations: [MyComponent],
})
export class MyComponentModule {}
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h"
to your main.cpp
file.
In second.h
you just declare like this void yourFunction();
In second.cpp
you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h"
also in the beginning of second.cpp
Hope this helps:)
I solved this in my env, without modify hadoop-env.sh
You'd be better using /bin/bash
as default shell not /bin/sh
Check these before:
echo $JAVA_HOME
)echo $SHELL
in every node, check if print /bin/bash
if not, vi /etc/passwd
, add /bin/bash
at tail of your username
ref
It's possible in ggplot and you can use scale_date for this task
library(ggplot2)
Lines <- "Date Visits
11/1/2010 696537
11/2/2010 718748
11/3/2010 799355
11/4/2010 805800
11/5/2010 701262
11/6/2010 531579
11/7/2010 690068
11/8/2010 756947
11/9/2010 718757
11/10/2010 701768
11/11/2010 820113
11/12/2010 645259"
dm <- read.table(textConnection(Lines), header = TRUE)
dm <- mutate(dm, Date = as.Date(dm$Date, "%m/%d/%Y"))
ggplot(data = dm, aes(Date, Visits)) +
geom_line() +
scale_x_date(format = "%b %d", major = "1 day")
The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:
Digest Password Support
The WSS 1.1 Username Token Profile allows digest passwords to be sent in a
wsse:UsernameToken
of a SOAP message. Two more optional elements are included in thewsse:UsernameToken
in this case:wsse:Nonce
andwsse:Created
. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period. The Password Digest in this case is calculated as:Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )
This is how a UsernameToken with Digest Password looks like:
<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c"> <wsse:Username>Alice</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password> <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce> <wsu:Created>2008-04-28T10:02:11Z</wsu:Created> </wsse:UsernameToken>
In my case, the .gitignore
file is somehow corrupted. It sometimes shows up OK but sometimes is gibberish. I guess the encoding might be to blame but cannot be sure. To solve the issue, I deleted the file (previously created through echo > .gitgore
in VS Code commandline) and created a new one manually in the file system (Explorer), then added my ignore rules. After the new .ignore
was in place, everything works fine.
You can do it by ordering to do the operation with a list of files with names equal to the name(s) you need. It is much easier and direct than to create a special target. And you needn't any additional tools, just pure Ant.
<delete>
<fileset includes="name or names of file or files you need to delete"/>
</delete>
See: FileSet.
The solution consists in a regex pattern matching open and closing parenthesis
String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis,
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
// I print first "Your", in the second round trip "String"
System.out.println(part);
}
Writing in Java 8's style, this can be solved in this way:
Arrays.asList("Your(String)".split("[\\(\\)]"))
.forEach(System.out::println);
I hope it is clear.
$ ssh-keygen -p
worked for me
Opened git bash. Pasted : $ ssh-keygen -p
Hit enter for default location.
Enter old passphrase
Enter new passphrase - BLANK
Confirm new passphrase - BLANK
BOOM the pain of entering passphrase for git push was gone.
Thanks!
In PowerShell 5 and PowerShell 5 ISE, it is also possible to use just Shift + Enter for multiline editing (instead of standard backticks `
at the end of each line):
PS> &"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" # Shift+Enter
>>> -verb:sync # Shift+Enter
>>> -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" # Shift+Enter
>>> -dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"
Have a look at what happens if you run javaws.exe directly from the command line.
You are looking for the DateTime.Parse()
method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime
typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact
(MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
You need to drop the table and then recreate it and then load it again
Set body css to :
body {
background: url(../img/background.jpg) no-repeat center center fixed #000;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
For git mv
the
manual page
says
The index is updated after successful completion, […]
So, at first, you have to update the index on your own
(by using git add mobile.css
). However
git status
will still show two different files
$ git status
# On branch master
warning: LF will be replaced by CRLF in index.html
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: index.html
# new file: mobile.css
#
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# deleted: iphone.css
#
You can get a different output by running
git commit --dry-run -a
, which results in what you
expect:
Tanascius@H181 /d/temp/blo (master)
$ git commit --dry-run -a
# On branch master
warning: LF will be replaced by CRLF in index.html
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: index.html
# renamed: iphone.css -> mobile.css
#
I can't tell you exactly why we see these differences
between git status
and
git commit --dry-run -a
, but
here is a hint from
Linus:
git really doesn't even care about the whole "rename detection" internally, and any commits you have done with renames are totally independent of the heuristics we then use to show the renames.
A dry-run
uses the real renaming mechanisms, while a
git status
probably doesn't.
After Add this to your web.config file and configure according to your service name and contract name.
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="MyService.MyService" behaviorConfiguration="metadataBehavior">
<endpoint
address="" <!-- don't put anything here - Cassini will determine address -->
binding="basicHttpBinding"
contract="MyService.IMyService"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
Please add this in your Service.svc
using System.ServiceModel.Description;
Hope it will helps you.
php artisan migrate:fresh
Should do the job, if you are in development and the desired outcome is to start all over.
In production, that maybe not the desired thing, so you should be adverted. (The migrate:fresh command will drop all tables from the database and then execute the migrate command).
See where each class is in the class hierarchy in the following diagram (bigger one). TreeMap implements SortedMap
and NavigableMap
while HashMap
doesn't.
HashTable
is obsolete and the corresponding ConcurrentHashMap
class should be used.
You are asking to replace the character "?" but for me that is coming through as three characters 'ï', '¿' and '½'. This might be your problem... If you are using Java prior to Java 1.5 then you only get the UCS-2 characters, that is only the first 65K UTF-8 characters. Based on other comments, it is most likely that the character that you are looking for is '?', that is the Unicode replacement character. This is the character that is "used to replace an incoming character whose value is unknown or unrepresentable in Unicode".
Actually, looking at the comment from Kathy, the other issue that you might be having is that javac is not interpreting your .java file as UTF-8, assuming that you are writing it in UTF-8. Try using:
javac -encoding UTF-8 xx.java
Or, modify your source code to do:
String.replaceAll("\uFFFD", "");
Are you keeping references to variables that you no longer need (e.g. data from the previous simulations)? If so, you have a memory leak. You just need to find where that is happening and make sure that you remove the references to the variables when they are no longer needed (this would automatically happen if they go out of scope).
If you actually need all that data from previous simulations in memory, you need to increase the heap size or change your algorithm.
You could do
alert(document.getElementById('table1').rows[0].cells.length)
fiddle here http://jsfiddle.net/TEZ73/
If there are large number of lines you want to comment out then it will be better if you can make multi line comments rather than commenting out every line.
See this post by Rob van der Woude on comment blocks:
The batch language doesn't have comment blocks, though there are ways to accomplish the effect.
GOTO EndComment1 This line is comment. And so is this line. And this one... :EndComment1
You can use
GOTO
Label and :Label for making block comments.Or, If the comment block appears at the end of the batch file, you can write
EXIT
at end of code and then any number of comments for your understanding.@ECHO OFF REM Do something • • REM End of code; use GOTO:EOF instead of EXIT for Windows NT and later EXIT Start of comment block at end of batch file This line is comment. And so is this line. And this one...
the command should be java -version
If you want MySQL server to decide character set, and not PHP as a client (old behaviour; preferred, in my opinion), try adding skip-character-set-client-handshake
to your my.cnf
, under [mysqld]
, and restart mysql
.
This may cause troubles in case you're using anything other than UTF8.
updated
might be what you're looking for. https://vuejs.org/v2/api/#updated
try "configuration properties -> debugging -> environment" and set the PATH variable in run-time
The following is a simple way to open the camera:
private void startCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath());
startActivityForResult(intent, 1);
}
See inspect.getmembers(object[, predicate])
.
Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.
>>> [name for name,thing in inspect.getmembers([])]
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__',
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__',
'__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
in java you can replace with
getChildFragmentManager()
in kotlin, make it simple by
childFragmentManager
hope it help :)
You can paste your code into LINQPad. Then copy from LINQPad into MS Word. LINQPad supports following programming languages: C#, VB, SQL, ESQL and F#
There's no legitimate way you can do it.
warning: LF will be replaced by CRLF.
Depending on the editor you are using, a text file with LF wouldn't necessary be saved with CRLF: recent editors can preserve eol style. But that git config setting insists on changing those...
Simply make sure that (as I recommend here):
git config --global core.autocrlf false
That way, you avoid any automatic transformation, and can still specify them through a .gitattributes
file and core.eol
directives.
windows git "LF will be replaced by CRLF"
Is this warning tail backward?
No: you are on Windows, and the git config
help page does mention
Use this setting if you want to have
CRLF
line endings in your working directory even though the repository does not have normalized line endings.
As described in "git replacing LF with CRLF", it should only occur on checkout (not commit), with core.autocrlf=true
.
repo
/ \
crlf->lf lf->crlf
/ \
As mentioned in XiaoPeng's answer, that warning is the same as:
warning: (If you check it out/or clone to another folder with your current
core.autocrlf
configuration,) LF will be replaced by CRLF
The file will have its original line endings in your (current) working directory.
As mentioned in git-for-windows/git
issue 1242:
I still feel this message is confusing, the message could be extended to include a better explanation of the issue, for example: "LF will be replaced by CRLF in
file.json
after removing the file and checking it out again".
Note: Git 2.19 (Sept 2018), when using core.autocrlf
, the bogus "LF
will be replaced by CRLF" warning is now suppressed.
As quaylar rightly comments, if there is a conversion on commit, it is to LF
only.
That specific warning "LF will be replaced by CRLF
" comes from convert.c#check_safe_crlf():
if (checksafe == SAFE_CRLF_WARN)
warning("LF will be replaced by CRLF in %s.
The file will have its original line endings
in your working directory.", path);
else /* i.e. SAFE_CRLF_FAIL */
die("LF would be replaced by CRLF in %s", path);
It is called by convert.c#crlf_to_git()
, itself called by convert.c#convert_to_git()
, itself called by convert.c#renormalize_buffer()
.
And that last renormalize_buffer()
is only called by merge-recursive.c#blob_unchanged()
.
So I suspect this conversion happens on a git commit
only if said commit is part of a merge process.
Note: with Git 2.17 (Q2 2018), a code cleanup adds some explanation.
See commit 8462ff4 (13 Jan 2018) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit 9bc89b1, 13 Feb 2018)
convert_to_git(): safe_crlf/checksafe becomes int conv_flags
When calling
convert_to_git()
, thechecksafe
parameter defined what should happen if the EOL conversion (CRLF --> LF --> CRLF
) does not roundtrip cleanly.
In addition, it also defined if line endings should be renormalized (CRLF --> LF
) or kept as they are.checksafe was an
safe_crlf
enum with these values:
SAFE_CRLF_FALSE: do nothing in case of EOL roundtrip errors
SAFE_CRLF_FAIL: die in case of EOL roundtrip errors
SAFE_CRLF_WARN: print a warning in case of EOL roundtrip errors
SAFE_CRLF_RENORMALIZE: change CRLF to LF
SAFE_CRLF_KEEP_CRLF: keep all line endings as they are
Note that a regression introduced in 8462ff4 ("convert_to_git()
:
safe_crlf/checksafe
becomes int conv_flags
", 2018-01-13, Git 2.17.0) back in Git 2.17 cycle caused autocrlf
rewrites to produce a warning message
despite setting safecrlf=false
.
See commit 6cb0912 (04 Jun 2018) by Anthony Sottile (asottile
).
(Merged by Junio C Hamano -- gitster
-- in commit 8063ff9, 28 Jun 2018)
Try this simple function to add an dictionary item if it does not exist or update when it exists:
public void AddOrUpdateDictionaryEntry(string key, int value)
{
if (dict.ContainsKey(key))
{
dict[key] = value;
}
else
{
dict.Add(key, value);
}
}
This is the same as dict[key] = value.
=(MOD(R[-1]C-1,100)*7+DATE(INT(R[-1]C/100+2000),1,1)-2)
yyww as the given week exp:week 51 year 2014 will be 1451
You can also use OPENROWSET to import excel file in sql server.
SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
'SELECT * FROM [Data$]')
Using ViewPager2
and FragmentStateAdapter
:
Updating data dynamically is supported by ViewPager2
.
There is an important note in the docs on how to get this working:
Note: The DiffUtil utility class relies on identifying items by ID. If you are using ViewPager2 to page through a mutable collection, you must also override getItemId() and containsItem(). (emphasis mine)
Based on ViewPager2
documentation and Android's Github sample project there are a few steps we need to take:
Set up FragmentStateAdapter
and override the following methods: getItemCount
, createFragment
, getItemId
, and containsItem
(note: FragmentStatePagerAdapter
is not supported by ViewPager2
)
Attach adapter to ViewPager2
Dispatch list updates to ViewPager2
with DiffUtil
(don't need to use DiffUtil
, as seen in sample project)
Example:
private val items: List<Int>
get() = viewModel.items
private val viewPager: ViewPager2 = binding.viewPager
private val adapter = object : FragmentStateAdapter(this@Fragment) {
override fun getItemCount() = items.size
override fun createFragment(position: Int): Fragment = MyFragment()
override fun getItemId(position: Int): Long = items[position].id
override fun containsItem(itemId: Long): Boolean = items.any { it.id == itemId }
}
viewPager.adapter = adapter
private fun onDataChanged() {
DiffUtil
.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize(): Int = viewPager.adapter.itemCount
override fun getNewListSize(): Int = viewModel.items.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
viewPager.adapter?.getItemId(oldItemPosition) == viewModel.items[newItemPosition].id
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
areItemsTheSame(oldItemPosition, newItemPosition)
}, false)
.dispatchUpdatesTo(viewPager.adapter!!)
}
Swift 4,
private func callNumber(phoneNumber:String) {
if let phoneCallURL = URL(string: "telprompt://\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
if #available(iOS 10.0, *) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
application.openURL(phoneCallURL as URL)
}
}
}
}
In my case, none of the code above with bundle-operate
works; Here is my decision (I don't know if it is proper code or not, but it works in my case):
public class DialogMessageType extends DialogFragment {
private static String bodyText;
public static DialogMessageType addSomeString(String temp){
DialogMessageType f = new DialogMessageType();
bodyText = temp;
return f;
};
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] choiseArray = {"sms", "email"};
String title = "Send text via:";
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title).setItems(choiseArray, itemClickListener);
builder.setCancelable(true);
return builder.create();
}
DialogInterface.OnClickListener itemClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
prepareToSendCoordsViaSMS(bodyText);
dialog.dismiss();
break;
case 1:
prepareToSendCoordsViaEmail(bodyText);
dialog.dismiss();
break;
default:
break;
}
}
};
[...]
}
public class SendObjectActivity extends FragmentActivity {
[...]
DialogMessageType dialogMessageType = DialogMessageType.addSomeString(stringToSend);
dialogMessageType.show(getSupportFragmentManager(),"dialogMessageType");
[...]
}
var spl = item.Split('/')[1];
var format =spl.Split(';')[0];
stringconvert=item.Replace($"data:image/{format};base64,",String.Empty);
The term overloading refers to having multiple versions of something with the same name, usually methods with different parameter lists
public int DoSomething(int objectId) { ... }
public int DoSomething(string objectName) { ... }
So these functions might do the same thing but you have the option to call it with an ID, or a name. Has nothing to do with inheritance, abstract classes, etc.
Overriding usually refers to polymorphism, as you described in your question
I think you want NUL
, at least within a command prompt or batch files.
For example:
type c:\autoexec.bat > NUL
doesn't create a file.
(I believe the same is true if you try to create a file programmatically, but I haven't tried it.)
In PowerShell, you want $null
:
echo 1 > $null
You could take a look at the DateTimeFormat property which contains the culture specific formats.
SELECT Activity, arat.Amount "Total Amount 2008", abull.Amount AS "Total Amount 2009"
FROM
Activities a
LEFT OUTER JOIN
(
SELECT ActivityId, SUM(Amount) AS Amount
FROM Incomes ibull
GROUP BY
ibull.ActivityId
) abull
ON abull.ActivityId = a.ActivityID
LEFT OUTER JOIN
(
SELECT ActivityId, SUM(Amount) AS Amount
FROM Incomes2008 irat
GROUP BY
irat.ActivityId
) arat
ON arat.ActivityId = a.ActivityID
WHERE a.UnitName = ?
ORDER BY Activity
For those who support iOS 8+ only, there is a new boolean property active. It will help to enable only needed constraints dynamically
P.S. Constraint outlet must be strong, not weak
Example:
@IBOutlet weak var optionalView: UIView!
@IBOutlet var viewIsVisibleConstraint: NSLayoutConstraint!
@IBOutlet var viewIsHiddenConstraint: NSLayoutConstraint!
func showView() {
optionalView.isHidden = false
viewIsVisibleConstraint.isActive = true
viewIsHiddenConstraint.isActive = false
}
func hideView() {
optionalView.isHidden = true
viewIsVisibleConstraint.isActive = false
viewIsHiddenConstraint.isActive = true
}
Also to fix an error in storyboard you'll need to uncheck Installed
checkbox for one of these constraints.
UIStackView (iOS 9+)
One more option is to wrap your views in UIStackView
. Once view is hidden UIStackView
will update layout automatically
You add a
float: left;
to the style of the 3 elements and make sure the parent container has
overflow: hidden; position: relative;
this makes sure the floats take up actual space.
<html>
<head>
<title>Website Title </title>
</head>
<body>
<div id="the-whole-thing" style="position: relative; overflow: hidden;">
<div id="leftThing" style="position: relative; width: 25%; background-color: blue; float: left;">
Left Side Menu
</div>
<div id="content" style="position: relative; width: 50%; background-color: green; float: left;">
Random Content
</div>
<div id="rightThing" style="position: relative; width: 25%; background-color: yellow; float: left;">
Right Side Menu
</div>
</div>
</body>
</html>
Also please note that the width: 100% and height: 100% need to be removed from the container, otherwise the 3rd block will wrap to a 2nd line.
The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.
As an example, let's say you have a person class:
class Person {
String name;
List<String> emailAddresses
}
How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses
in the new object. But if you modified the contents of the emailAddresses
list, you would be modifying the list in both copies (since that's how object references work).
A deep copy would mean that you recursively copy every member, so you would need to create a new List
for the new Person
, and then copy the contents from the old to the new object.
Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.
If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.
The innerHtml property did not work for me. So I experimented with ...
<div id=successAndErrorMessages-1>100% OK</div>
<div id=successAndErrorMessages-2>This is an error mssg!</div>
and toggled one of the two on/off ...
$("#successAndErrorMessages-1").css('display', 'none')
$("#successAndErrorMessages-2").css('display', '')
For some reason I had to fiddle around with the ordering before it worked in all types of browsers.
Most recent answer (for Angular 8+):
this.http.post("your-url",params,{responseType:'arraybuffer' as 'json'}).subscribe(
(res) => {
this.showpdf(res);
}
)};
public Content:SafeResourceUrl;
showpdf(response:ArrayBuffer) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
this.Content = this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
}
HTML :
<embed [src]="Content" style="width:200px;height:200px;" type="application/pdf" />
Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.texture);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
Shader.TileMode.REPEAT);
setBackground(bitmapDrawable);
}