You haven't specified any keyframes. I made it work here.
div {
margin: 20px;
width: 100px;
height: 100px;
background: #f00;
-webkit-animation: spin 4s infinite linear;
}
@-webkit-keyframes spin {
0% {-webkit-transform: rotate(0deg);}
100% {-webkit-transform: rotate(360deg);}
}
You can actually do lots of really cool stuff with this. Here is one I made earlier.
:)
N.B. You can skip having to write out all the prefixes if you use -prefix-free.
I wouldn't recommend this, but if you're really into it being one line and only writing 0 once, you can also do this:
int row, column, index = row = column = 0;
If you want, you can deactivate this feature in your git core config using
git config core.autocrlf false
But it would be better to just get rid of the warnings using
git config core.autocrlf true
Here's yet another alternative:
template<typename T>
void Remove( std::basic_string<T> & Str, const T * CharsToRemove )
{
std::basic_string<T>::size_type pos = 0;
while (( pos = Str.find_first_of( CharsToRemove, pos )) != std::basic_string<T>::npos )
{
Str.erase( pos, 1 );
}
}
std::string a ("(555) 555-5555");
Remove( a, "()-");
Works with std::string and std::wstring
DAO
is an abstraction of data persistence.
Repository
is an abstraction of a collection of objects.
DAO
would be considered closer to the database, often table-centric.
Repository
would be considered closer to the Domain, dealing only in Aggregate Roots.
Repository
could be implemented using DAO
's, but you wouldn't do the opposite.
Also, a Repository
is generally a narrower interface. It should be simply a collection of objects, with a Get(id)
, Find(ISpecification)
, Add(Entity)
.
A method like Update
is appropriate on a DAO
, but not a Repository
- when using a Repository
, changes to entities would usually be tracked by separate UnitOfWork.
It does seem common to see implementations called a Repository
that is really more of a DAO
, and hence I think there is some confusion about the difference between them.
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
Make a bat file with the following in it:
copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt
However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:
C:\temp\test.bat > C:\temp\test.log
(assuming the first bat file was called test.bat and was located in that directory)
They can be in separate containers, and indeed, if the application was also intended to run in a larger environment, they probably would be.
A multi-container system would require some more orchestration to be able to bring up all the required dependencies, though in Docker v0.6.5+, there is a new facility to help with that built into Docker itself - Linking. With a multi-machine solution, its still something that has to be arranged from outside the Docker environment however.
With two different containers, the two parts still communicate over TCP/IP, but unless the ports have been locked down specifically (not recommended, as you'd be unable to run more than one copy), you would have to pass the new port that the database has been exposed as to the application, so that it could communicate with Mongo. This is again, something that Linking can help with.
For a simpler, small installation, where all the dependencies are going in the same container, having both the database and Python runtime started by the program that is initially called as the ENTRYPOINT is also possible. This can be as simple as a shell script, or some other process controller - Supervisord is quite popular, and a number of examples exist in the public Dockerfiles.
You entered an alphanumeric and int, blank delimited in mystr
.
You then tried to convert the first token (blank delimited) into an int
.
The first token was RS which failed to convert to int
, leaving a zero for myprice, and we all know what zero times anything yields.
When you only entered int values the second time, everything worked as you expected.
It was the spurious RS that caused your code to fail.
No need to use grep. ps
in Android can filter by COMM
value (last 15 characters of the package name in case of java app)
Let's say we want to check if com.android.phone
is running:
adb shell ps m.android.phone
USER PID PPID VSIZE RSS WCHAN PC NAME
radio 1389 277 515960 33964 ffffffff 4024c270 S com.android.phone
Filtering by COMM
value option has been removed from ps
in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof
command:
adb shell pidof com.android.phone
It returns the PID if such process was found or an empty string otherwise.
blog_development doesn't exist
You can see this in sql by the 0 rows affected
message
create it in mysql with
mysql> create database blog_development
However as you are using rails you should get used to using
$ rake db:create
to do the same task. It will use your database.yml file settings, which should include something like:
development:
adapter: mysql2
database: blog_development
pool: 5
Also become familiar with:
$ rake db:migrate # Run the database migration
$ rake db:seed # Run thew seeds file create statements
$ rake db:drop # Drop the database
This should work
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)
XAMPP uses a file called mysql_start.bat to start MySQL and if you open that file with a text editor you can see what config file is trying to use, in the current version it is:
mysql\bin\mysqld --defaults-file=mysql\bin\my.ini --standalone --console
If you installed XAMPP on the default path it means it is on c:/xampp/mysql/bin/my.ini
If somehow the file doesn't exist you should open a console terminal (start-> type "cmd", press enter) and then write "mysql --help" and it prints a text mentioning the default locations, in the current version of XAMPP is:
C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf C:\xampp\mysql\my.ini C:\xampp\mysql\my.cnf
Here is another variant that uses a mix of the two above methods.
Combining the speed and correctness of Parcelable
with the simplicity of a Bundle
:
@Override
public Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
// The vars you want to save - in this instance a string and a boolean
String someString = "something";
boolean someBoolean = true;
State state = new State(super.onSaveInstanceState(), someString, someBoolean);
bundle.putParcelable(State.STATE, state);
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
State customViewState = (State) bundle.getParcelable(State.STATE);
// The vars you saved - do whatever you want with them
String someString = customViewState.getText();
boolean someBoolean = customViewState.isSomethingShowing());
super.onRestoreInstanceState(customViewState.getSuperState());
return;
}
// Stops a bug with the wrong state being passed to the super
super.onRestoreInstanceState(BaseSavedState.EMPTY_STATE);
}
protected static class State extends BaseSavedState {
protected static final String STATE = "YourCustomView.STATE";
private final String someText;
private final boolean somethingShowing;
public State(Parcelable superState, String someText, boolean somethingShowing) {
super(superState);
this.someText = someText;
this.somethingShowing = somethingShowing;
}
public String getText(){
return this.someText;
}
public boolean isSomethingShowing(){
return this.somethingShowing;
}
}
You could extend the "string" class to let you return a limited string.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// since specified strings are treated on the fly as string objects...
string limit5 = "The quick brown fox jumped over the lazy dog.".LimitLength(5);
string limit10 = "The quick brown fox jumped over the lazy dog.".LimitLength(10);
// this line should return us the entire contents of the test string
string limit100 = "The quick brown fox jumped over the lazy dog.".LimitLength(100);
Console.WriteLine("limit5 - {0}", limit5);
Console.WriteLine("limit10 - {0}", limit10);
Console.WriteLine("limit100 - {0}", limit100);
Console.ReadLine();
}
}
public static class StringExtensions
{
/// <summary>
/// Method that limits the length of text to a defined length.
/// </summary>
/// <param name="source">The source text.</param>
/// <param name="maxLength">The maximum limit of the string to return.</param>
public static string LimitLength(this string source, int maxLength)
{
if (source.Length <= maxLength)
{
return source;
}
return source.Substring(0, maxLength);
}
}
}
Result:
limit5 - The q
limit10 - The quick
limit100 - The quick brown fox jumped over the lazy dog.
The parent function needs the virtual
keyword, and the child function needs the override
keyword in front of the function definition.
To render SVG file you can use Macaw. Also Macaw supports transformations, user events, animation and various effects.
You can render SVG file with zero lines of code. For more info please check this article: Render SVG file with Macaw.
DISCLAIMER: I am affiliated with this project.
I had the same problem as the original poster but the quoted answer did not solve the problem for me. The query still ran really slow from a stored procedure.
I found another answer here "Parameter Sniffing", Thanks Omnibuzz. Boils down to using "local Variables" in your stored procedure queries, but read the original for more understanding, it's a great write up. e.g.
Slow way:
CREATE PROCEDURE GetOrderForCustomers(@CustID varchar(20))
AS
BEGIN
SELECT *
FROM orders
WHERE customerid = @CustID
END
Fast way:
CREATE PROCEDURE GetOrderForCustomersWithoutPS(@CustID varchar(20))
AS
BEGIN
DECLARE @LocCustID varchar(20)
SET @LocCustID = @CustID
SELECT *
FROM orders
WHERE customerid = @LocCustID
END
Hope this helps somebody else, doing this reduced my execution time from 5+ minutes to about 6-7 seconds.
Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.
We faced the same problem:
ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log
In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.
When you only need to check for equality, you can also simply use the in
operator to do a membership test in a sequence of accepted elements:
if message.value[0] in ('/', '\\'):
do_stuff()
I was puzzled by this also... didn't like the parentheses that windows puts in when you rename in bulk. In my research I decided to write a script with PowerShell instead. Super easy and worked like a charm. Now I can use it whenever I need to batch process file renaming... which is frequent. I take hundreds of photos and the camera names them IMG1234.JPG etc...
Here is the script I wrote:
# filename: bulk_file_rename.ps1
# by: subcan
# PowerShell script to rename multiple files within a folder to a
# name that increments without (#)
# create counter
$int = 1
# ask user for what they want
$regex = Read-Host "Regex for files you are looking for? ex. IMG*.JPG "
$file_name = Read-Host "What is new file name, without extension? ex. New Image "
$extension = Read-Host "What extension do you want? ex. .JPG "
# get a total count of the files that meet regex
$total = Get-ChildItem -Filter $regex | measure
# while loop to rename all files with new name
while ($int -le $total.Count)
{
# diplay where in loop you are
Write-Host "within while loop" $int
# create variable for concatinated new name -
# $int.ToString(000) ensures 3 digit number 001, 010, etc
$new_name = $file_name + $int.ToString(000)+$extension
# get the first occurance and rename
Get-ChildItem -Filter $regex | select -First 1 | Rename-Item -NewName $new_name
# display renamed file name
Write-Host "Renamed to" $new_name
# increment counter
$int++
}
I hope that this is helpful to someone out there.
subcan
I once solved this kind of problem by moving all inlines after the class definition and putting the #include
for the other classes just before the inlines in the header file. This way one make sure all definitions+inlines are set prior the inlines are parsed.
Doing like this makes it possible to still have a bunch of inlines in both(or multiple) header files. But it's necessary to have include guards.
Like this
// File: A.h
#ifndef __A_H__
#define __A_H__
class B;
class A
{
int _val;
B *_b;
public:
A(int val);
void SetB(B *b);
void Print();
};
// Including class B for inline usage here
#include "B.h"
inline A::A(int val) : _val(val)
{
}
inline void A::SetB(B *b)
{
_b = b;
_b->Print();
}
inline void A::Print()
{
cout<<"Type:A val="<<_val<<endl;
}
#endif /* __A_H__ */
...and doing the same in B.h
After some research on this topic, I found that the error is occured basically if you have an instance of db created previously on your local sql server express. So whenever you have updates on db and try to update the db/run some code on db without running Update Database
command using Package Manager Console
; first of all, you have to delete previous db on our local sql express manually.
Also, this solution works unless you have AutomaticMigrationsEnabled = false;
in your Configuration.
If you work with a version control system (git,svn,etc.) and some other developers update db objects in production phase then this error rises whenever you update your code base and run the application.
As stated above, there are some solutions for this on code base. However, this is the most practical one for some cases.
In case anyone wishes to do this with bootstrap, version 4 offers the following:
The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.
Where property is one of:
m - for classes that set margin
p - for classes that set padding
Where sides is one of:
t - for classes that set margin-top or padding-top
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom
blank - for classes that set a margin or padding on all 4 sides of the element
Where size is one of:
0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3
auto - for classes that set the margin to auto
For example:
.mt-0 {
margin-top: 0 !important;
}
.ml-1 {
margin-left: ($spacer * .25) !important;
}
.px-2 {
padding-left: ($spacer * .5) !important;
padding-right: ($spacer * .5) !important;
}
.p-3 {
padding: $spacer !important;
}
Reference: https://getbootstrap.com/docs/4.0/utilities/spacing/
bash doesn't know boolean variables, nor does test
(which is what gets called when you use [
).
A solution would be:
if $myVar ; then ... ; fi
because true
and false
are commands that return 0
or 1
respectively which is what if
expects.
Note that the values are "swapped". The command after if
must return 0
on success while 0
means "false" in most programming languages.
SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /
Change secret_string += str(chr(char + 7429146))
To secret_string += chr(ord(char) + 7429146)
ord()
converts the character to its Unicode integer equivalent. chr()
then converts this integer into its Unicode character equivalent.
Also, 7429146 is too big of a number, it should be less than 1114111
Flying Saucer xhtmlrenderer repeats the THEAD on every page of PDF output, if you add the following to your CSS:
table {
-fs-table-paginate: paginate;
}
(It works at least since the R8 release.)
There is a conflict between (Safari) and (Opera) and (Chrome) !!!
The above codes couldn't work properly
This is my code, and it works very well without any conflict:
function ExactBrowserName()
{
$ExactBrowserNameUA=$_SERVER['HTTP_USER_AGENT'];
if (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")) {
// OPERA
$ExactBrowserNameBR="Opera";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "chrome/")) {
// CHROME
$ExactBrowserNameBR="Chrome";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "msie")) {
// INTERNET EXPLORER
$ExactBrowserNameBR="Internet Explorer";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "firefox/")) {
// FIREFOX
$ExactBrowserNameBR="Firefox";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")==false and strpos(strtolower($ExactBrowserNameUA), "chrome/")==false) {
// SAFARI
$ExactBrowserNameBR="Safari";
} else {
// OUT OF DATA
$ExactBrowserNameBR="OUT OF DATA";
};
return $ExactBrowserNameBR;
}
You can put the script into a separate file, then use $.getScript
to load and run it.
Example:
$.getScript("test.js", function(){
alert("Running test.js");
});
please fill the @likeTablename param for search table.
now this parameter set to %tbltrans% for search all table contain tbltrans in name.
set @likeTablename to '%' to show all table.
declare @AllTableNames nvarchar(max);
select @AllTableNames=STUFF((select ' SELECT TABLE_CATALOG collate DATABASE_DEFAULT+''.''+TABLE_SCHEMA collate DATABASE_DEFAULT+''.''+TABLE_NAME collate DATABASE_DEFAULT as tablename FROM '+name+'.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE'' union '
FROM master.sys.databases
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
set @AllTableNames=left(@AllTableNames,len(@AllTableNames)-6)
declare @likeTablename nvarchar(200)='%tbltrans%';
set @AllTableNames=N'select tablename from('+@AllTableNames+N')at where tablename like '''+N'%'+@likeTablename+N'%'+N''''
exec sp_executesql @AllTableNames
You can use the start
command to do much the same thing as ShellExecute
. For example
start "" http://www.stackoverflow.com
This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.
If you're getting something like getElementById call returns null
, it's probably because the function is running, but the ID hasn't had time to load in the DOM.
Try using Will's answer (towards the top) with a delay. Example:
angular.module('MyApp', [])
.controller('MyCtrl', [function() {
$scope.sleep = (time) => {
return new Promise((resolve) => setTimeout(resolve, time));
};
angular.element(document).ready(function () {
$scope.sleep(500).then(() => {
//code to run here after the delay
});
});
}]);
To get the job done, use
<table cellspacing=12>
If you’d rather “be right” than get things done, you can instead use the CSS property border-spacing
, which is supported by some browsers.
This might be overkill, but it works for me.
Array.prototype.contains = function (item, prop) {
var arr = this.valueOf();
if (prop == undefined || prop == null) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == item) {
return true;
}
}
}
else {
for (var i = 0; i < arr.length; i++) {
if (arr[i][prop] == item) return true;
}
}
return false;
}
Array.prototype.distinct = function (prop) {
var arr = this.valueOf();
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (!ret.contains(arr[i][prop], prop)) {
ret.push(arr[i]);
}
}
arr = [];
arr = ret;
return arr;
}
The distinct function depends on the contains function defined above. It can be called as array.distinct(prop);
where prop is the property you want to be distinct.
So you could just say $scope.places.distinct("category");
Did you install Git correctly?
According to the Bower site, you need to make sure you check the option "Run Git from Windows Command Prompt".
I had this issue where Git was not found when I was trying to install Angular. I re-ran the installer for git and changed my setting and then it worked.
From the bower site: http://bower.io/
It depends on the amount of data you are looking to store. In reality there's no difference between flat files and XML. XML would probably be preferable since it provides a structure to the document. In practice,
The last option, and a lot of applications use now is the Windows Registry. I don't personally recommend it (Registry Bloat, Corruption, other potential issues), but it is an option.
The largest port number is an unsigned short 2^16-1: 65535
A registered port is one assigned by the Internet Corporation for Assigned Names and Numbers (ICANN) to a certain use. Each registered port is in the range 1024–49151.
Since 21 March 2001 the registry agency is ICANN; before that time it was IANA.
Ports with numbers lower than those of the registered ports are called well known ports; port with numbers greater than those of the registered ports are called dynamic and/or private ports.
It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is
lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row
Where ws
is a Worksheet object. In the questions example it was implied that the statement was inside a With
block
With ws
lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
ws.Rows.Count
returns the total count of rows in the worksheet (1048576 in Excel 2010)..Cells(.Rows.Count, "A")
returns the bottom most cell in column "A" in the worksheetThen there is the End
method. The documentation is ambiguous as to what it does.
Returns a Range object that represents the cell at the end of the region that contains the source range
Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:
rng.cells(1,1)
. So Range.End
is not a trivial function.
.row
returns the row index of that cell.I wrote a function for the FFT in Java: http://www.wikijava.org/wiki/The_Fast_Fourier_Transform_in_Java_%28part_1%29
It's in the Public Domain so you can use those functions everywhere (personal or business projects too). Just cite me in the credits and send me just a link of your work, and you're ok.
It is completely reliable. I've checked its output against the Mathematica's FFT and they were always correct until the 15th decimal digit. I think it's a very good FFT implementation for Java. I wrote it on the J2SE 1.6 version, and tested it on the J2SE 1.5-1.6 version.
If you count the number of instruction (it's a lot much simpler than a perfect computational complexity function estimation) you can clearly see that this version is great even if it's not optimized at all. I'm planning to publish the optimized version if there are enough requests.
Let me know if it was useful, and tell me any comment you like.
I share the same code right here:
/**
* @author Orlando Selenu
*
*/
public class FFTbase {
/**
* The Fast Fourier Transform (generic version, with NO optimizations).
*
* @param inputReal
* an array of length n, the real part
* @param inputImag
* an array of length n, the imaginary part
* @param DIRECT
* TRUE = direct transform, FALSE = inverse transform
* @return a new array of length 2n
*/
public static double[] fft(final double[] inputReal, double[] inputImag,
boolean DIRECT) {
// - n is the dimension of the problem
// - nu is its logarithm in base e
int n = inputReal.length;
// If n is a power of 2, then ld is an integer (_without_ decimals)
double ld = Math.log(n) / Math.log(2.0);
// Here I check if n is a power of 2. If exist decimals in ld, I quit
// from the function returning null.
if (((int) ld) - ld != 0) {
System.out.println("The number of elements is not a power of 2.");
return null;
}
// Declaration and initialization of the variables
// ld should be an integer, actually, so I don't lose any information in
// the cast
int nu = (int) ld;
int n2 = n / 2;
int nu1 = nu - 1;
double[] xReal = new double[n];
double[] xImag = new double[n];
double tReal, tImag, p, arg, c, s;
// Here I check if I'm going to do the direct transform or the inverse
// transform.
double constant;
if (DIRECT)
constant = -2 * Math.PI;
else
constant = 2 * Math.PI;
// I don't want to overwrite the input arrays, so here I copy them. This
// choice adds \Theta(2n) to the complexity.
for (int i = 0; i < n; i++) {
xReal[i] = inputReal[i];
xImag[i] = inputImag[i];
}
// First phase - calculation
int k = 0;
for (int l = 1; l <= nu; l++) {
while (k < n) {
for (int i = 1; i <= n2; i++) {
p = bitreverseReference(k >> nu1, nu);
// direct FFT or inverse FFT
arg = constant * p / n;
c = Math.cos(arg);
s = Math.sin(arg);
tReal = xReal[k + n2] * c + xImag[k + n2] * s;
tImag = xImag[k + n2] * c - xReal[k + n2] * s;
xReal[k + n2] = xReal[k] - tReal;
xImag[k + n2] = xImag[k] - tImag;
xReal[k] += tReal;
xImag[k] += tImag;
k++;
}
k += n2;
}
k = 0;
nu1--;
n2 /= 2;
}
// Second phase - recombination
k = 0;
int r;
while (k < n) {
r = bitreverseReference(k, nu);
if (r > k) {
tReal = xReal[k];
tImag = xImag[k];
xReal[k] = xReal[r];
xImag[k] = xImag[r];
xReal[r] = tReal;
xImag[r] = tImag;
}
k++;
}
// Here I have to mix xReal and xImag to have an array (yes, it should
// be possible to do this stuff in the earlier parts of the code, but
// it's here to readibility).
double[] newArray = new double[xReal.length * 2];
double radice = 1 / Math.sqrt(n);
for (int i = 0; i < newArray.length; i += 2) {
int i2 = i / 2;
// I used Stephen Wolfram's Mathematica as a reference so I'm going
// to normalize the output while I'm copying the elements.
newArray[i] = xReal[i2] * radice;
newArray[i + 1] = xImag[i2] * radice;
}
return newArray;
}
/**
* The reference bitreverse function.
*/
private static int bitreverseReference(int j, int nu) {
int j2;
int j1 = j;
int k = 0;
for (int i = 1; i <= nu; i++) {
j2 = j1 / 2;
k = 2 * k + j1 - 2 * j2;
j1 = j2;
}
return k;
}
}
Add the reference again from ./packages/Microsoft.AspNet.Mvc.[version]/lib/net45/System.Web.Mvc.dll
Just another hack can be like this.
I have Array of strings which I need to concatenate. So I added that array into dictionary and then used it inside for loop which worked.
{% set dict1 = {'e':''} %}
{% for i in list1 %}
{% if dict1.update({'e':dict1.e+":"+i+"/"+i}) %} {% endif %}
{% endfor %}
{% set layer_string = dict1['e'] %}
Sure. Here's a completely silly program that demonstrates calling main
recursively.
public class main
{
public static void main(String[] args)
{
for (int i = 0; i < args.length; ++i)
{
if (args[i] != "")
{
args[i] = "";
System.out.println((args.length - i) + " left");
main(args);
}
}
}
}
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
You just need to put "group(1)" instead of "group()" in the following line and the return will be the one you expected:
System.out.println("I found the text: " + matcher.group(**1**).toString());
In Python 3.7.6 for Windows 10. After installation, I use these commands.
1. pip install notebook
2. python -m notebook
OR
C:\Users\Hamza\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts .
For my pc python-scripts are located in the above path. You can add this path in environment variables. Then run command.
1. jupyter notebook
If you don't want to use external libraries and you want to use the java.io instead of java.nio classes, you can use this concise method to copy a folder and all its content:
/**
* Copies a folder and all its content to another folder. Do not include file separator at the end path of the folder destination.
* @param folderToCopy The folder and it's content that will be copied
* @param folderDestination The folder destination
*/
public static void copyFolder(File folderToCopy, File folderDestination) {
if(!folderDestination.isDirectory() || !folderToCopy.isDirectory())
throw new IllegalArgumentException("The folderToCopy and folderDestination must be directories");
folderDestination.mkdirs();
for(File fileToCopy : folderToCopy.listFiles()) {
File copiedFile = new File(folderDestination + File.separator + fileToCopy.getName());
try (FileInputStream fis = new FileInputStream(fileToCopy);
FileOutputStream fos = new FileOutputStream(copiedFile)) {
int read;
byte[] buffer = new byte[512];
while ((read = fis.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step1: copy all the rpm pkg in given locations
Step2: if createrepo is not already installed, as it will not be by default, install it.
[root@pavangildamysql1 8.0.11_rhel7]# yum install createrepo
Step3: create repository metedata and give below permission
[root@pavangildamysql1 8.0.11_rhel7]# chown -R root.root /scratch/PVN/8.0.11_rhel7
[root@pavangildamysql1 8.0.11_rhel7]# createrepo /scratch/PVN/8.0.11_rhel7
Spawning worker 0 with 3 pkgs
Spawning worker 1 with 3 pkgs
Spawning worker 2 with 3 pkgs
Spawning worker 3 with 2 pkgs
Workers Finished
Saving Primary metadata
Saving file lists metadata
Saving other metadata
Generating sqlite DBs
Sqlite DBs complete
[root@pavangildamysql1 8.0.11_rhel7]# chmod -R o-w+r /scratch/PVN/8.0.11_rhel7
Step4: Create repository file with following contents at /etc/yum.repos.d/mysql.repo
[local]
name=My Awesome Repo
baseurl=file:///scratch/PVN/8.0.11_rhel7
enabled=1
gpgcheck=0
Step5 Run this command to install
[root@pavangildamysql1 local]# yum --nogpgcheck localinstall mysql-commercial-server-8.0.11-1.1.el7.x86_64.rpm
The functions* quit()
, exit()
, and sys.exit()
function in the same way: they raise the SystemExit
exception. So there is no real difference, except that sys.exit()
is always available but exit()
and quit()
are only available if the site
module is imported.
The os._exit()
function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork()
call.
Use exit()
or quit()
in the REPL.
Use sys.exit()
in scripts, or raise SystemExit()
if you prefer.
Use os._exit()
for child processes to exit after a call to os.fork()
.
All of these can be called without arguments, or you can specify the exit status, e.g., exit(1)
or raise SystemExit(1)
to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256)
on many systems this will get truncated and your process will actually exit with status 0.
* Actually, quit()
and exit()
are callable instance objects, but I think it's okay to call them functions.
Assembled several of the above answers into an extension method that handles the Endianness of the machine and handles IPv4 addresses that were mapped to IPv6.
public static class IPAddressExtensions
{
/// <summary>
/// Converts IPv4 and IPv4 mapped to IPv6 addresses to an unsigned integer.
/// </summary>
/// <param name="address">The address to conver</param>
/// <returns>An unsigned integer that represents an IPv4 address.</returns>
public static uint ToUint(this IPAddress address)
{
if (address.AddressFamily == AddressFamily.InterNetwork || address.IsIPv4MappedToIPv6)
{
var bytes = address.GetAddressBytes();
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
throw new ArgumentOutOfRangeException("address", "Address must be IPv4 or IPv4 mapped to IPv6");
}
}
Unit tests:
[TestClass]
public class IPAddressExtensionsTests
{
[TestMethod]
public void SimpleIp1()
{
var ip = IPAddress.Parse("0.0.0.15");
uint expected = GetExpected(0, 0, 0, 15);
Assert.AreEqual(expected, ip.ToUint());
}
[TestMethod]
public void SimpleIp2()
{
var ip = IPAddress.Parse("0.0.1.15");
uint expected = GetExpected(0, 0, 1, 15);
Assert.AreEqual(expected, ip.ToUint());
}
[TestMethod]
public void SimpleIpSix1()
{
var ip = IPAddress.Parse("0.0.0.15").MapToIPv6();
uint expected = GetExpected(0, 0, 0, 15);
Assert.AreEqual(expected, ip.ToUint());
}
[TestMethod]
public void SimpleIpSix2()
{
var ip = IPAddress.Parse("0.0.1.15").MapToIPv6();
uint expected = GetExpected(0, 0, 1, 15);
Assert.AreEqual(expected, ip.ToUint());
}
[TestMethod]
public void HighBits()
{
var ip = IPAddress.Parse("200.12.1.15").MapToIPv6();
uint expected = GetExpected(200, 12, 1, 15);
Assert.AreEqual(expected, ip.ToUint());
}
uint GetExpected(uint a, uint b, uint c, uint d)
{
return
(a * 256u * 256u * 256u) +
(b * 256u * 256u) +
(c * 256u) +
(d);
}
}
6 Years later but adding this in case it helps someone.
https://www.codeproject.com/Tips/996401/Authenticate-WebAPIs-with-Basic-and-Windows-Authen
var authenticationBytes = Encoding.ASCII.GetBytes("<username>:<password>");
using (HttpClient confClient = new HttpClient())
{
confClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
confClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.MediaType));
HttpResponseMessage message = confClient.GetAsync("<service URI>").Result;
if (message.IsSuccessStatusCode)
{
var inter = message.Content.ReadAsStringAsync();
List<string> result = JsonConvert.DeserializeObject<List<string>>(inter.Result);
}
}
I give you two answers. npm combined with other tools is powerful but requires some work to setup. If you just want to download some libraries, you might want to use Library Manager instead (released in Visual Studio 15.8).
First add package.json in the root of you project. Add the following content:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"gulp": "3.9.1",
"del": "3.0.0"
},
"dependencies": {
"jquery": "3.3.1",
"jquery-validation": "1.17.0",
"jquery-validation-unobtrusive": "3.2.10",
"bootstrap": "3.3.7"
}
}
This will make NPM download Bootstrap, JQuery and other libraries that is used in a new asp.net core project to a folder named node_modules. Next step is to copy the files to an appropriate place. To do this we will use gulp, which also was downloaded by NPM. Then add a new file in the root of you project named gulpfile.js. Add the following content:
/// <binding AfterBuild='default' Clean='clean' />
/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/
var gulp = require('gulp');
var del = require('del');
var nodeRoot = './node_modules/';
var targetPath = './wwwroot/lib/';
gulp.task('clean', function () {
return del([targetPath + '/**/*']);
});
gulp.task('default', function () {
gulp.src(nodeRoot + "bootstrap/dist/js/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/js"));
gulp.src(nodeRoot + "bootstrap/dist/css/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/css"));
gulp.src(nodeRoot + "bootstrap/dist/fonts/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/fonts"));
gulp.src(nodeRoot + "jquery/dist/jquery.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery/dist/jquery.min.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery/dist/jquery.min.map").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery-validation/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation/dist"));
gulp.src(nodeRoot + "jquery-validation-unobtrusive/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation-unobtrusive"));
});
This file contains a JavaScript code that is executed when the project is build and cleaned. It’s will copy all necessary files to lib2 (not lib – you can easily change this). I have used the same structure as in a new project, but it’s easy to change files to a different location. If you move the files, make sure you also update _Layout.cshtml. Note that all files in the lib2-directory will be removed when the project is cleaned.
If you right click on gulpfile.js, you can select Task Runner Explorer. From here you can run gulp manually to copy or clean files.
Gulp could also be useful for other tasks like minify JavaScript and CSS-files:
https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1
Right click on you project and select Manage client side-libraries. The file libman.json is now open. In this file you specify which library and files to use and where they should be stored locally. Really simple! The following file copies the default libraries that is used when creating a new ASP.NET Core 2.1 project:
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": [
{
"library": "[email protected]",
"files": [ "jquery.js", "jquery.min.map", "jquery.min.js" ],
"destination": "wwwroot/lib/jquery/dist/"
},
{
"library": "[email protected]",
"files": [ "additional-methods.js", "additional-methods.min.js", "jquery.validate.js", "jquery.validate.min.js" ],
"destination": "wwwroot/lib/jquery-validation/dist/"
},
{
"library": "[email protected]",
"files": [ "jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js" ],
"destination": "wwwroot/lib/jquery-validation-unobtrusive/"
},
{
"library": "[email protected]",
"files": [
"css/bootstrap.css",
"css/bootstrap.css.map",
"css/bootstrap.min.css",
"css/bootstrap.min.css.map",
"css/bootstrap-theme.css",
"css/bootstrap-theme.css.map",
"css/bootstrap-theme.min.css",
"css/bootstrap-theme.min.css.map",
"fonts/glyphicons-halflings-regular.eot",
"fonts/glyphicons-halflings-regular.svg",
"fonts/glyphicons-halflings-regular.ttf",
"fonts/glyphicons-halflings-regular.woff",
"fonts/glyphicons-halflings-regular.woff2",
"js/bootstrap.js",
"js/bootstrap.min.js",
"js/npm.js"
],
"destination": "wwwroot/lib/bootstrap/dist"
},
{
"library": "[email protected]",
"files": [ "list.js", "list.min.js" ],
"destination": "wwwroot/lib/listjs"
}
]
}
If you move the files, make sure you also update _Layout.cshtml.
i got the same problem, i used malloc over n over again in a loop for adding new char *string data. i faced the same problem, but after releasing the allocated memory void free()
problem were sorted
Try This:
var info = document.getElementById("area1").value; // Javascript
var info = $("#area1").val(); // jQuery
I just knocked up a quick procedure to do this. It only works for a single row, so I create a temporary view that just selects the row I want, and then replace the pg_temp.temp_view with the actual table that I want to insert into.
CREATE OR REPLACE FUNCTION dv_util.gen_insert_statement(IN p_schema text, IN p_table text)
RETURNS text AS
$BODY$
DECLARE
selquery text;
valquery text;
selvalue text;
colvalue text;
colrec record;
BEGIN
selquery := 'INSERT INTO ' || quote_ident(p_schema) || '.' || quote_ident(p_table);
selquery := selquery || '(';
valquery := ' VALUES (';
FOR colrec IN SELECT table_schema, table_name, column_name, data_type
FROM information_schema.columns
WHERE table_name = p_table and table_schema = p_schema
ORDER BY ordinal_position
LOOP
selquery := selquery || quote_ident(colrec.column_name) || ',';
selvalue :=
'SELECT CASE WHEN ' || quote_ident(colrec.column_name) || ' IS NULL' ||
' THEN ''NULL''' ||
' ELSE '''' || quote_literal('|| quote_ident(colrec.column_name) || ')::text || ''''' ||
' END' ||
' FROM '||quote_ident(p_schema)||'.'||quote_ident(p_table);
EXECUTE selvalue INTO colvalue;
valquery := valquery || colvalue || ',';
END LOOP;
-- Replace the last , with a )
selquery := substring(selquery,1,length(selquery)-1) || ')';
valquery := substring(valquery,1,length(valquery)-1) || ')';
selquery := selquery || valquery;
RETURN selquery;
END
$BODY$
LANGUAGE plpgsql VOLATILE;
Invoked thus:
SELECT distinct dv_util.gen_insert_statement('pg_temp_' || sess_id::text,'my_data')
from pg_stat_activity
where procpid = pg_backend_pid()
I haven't tested this against injection attacks, please let me know if the quote_literal call isn't sufficient for that.
Also it only works for columns that can be simply cast to ::text and back again.
Also this is for Greenplum but I can't think of a reason why it wouldn't work on Postgres, CMIIW.
data = numpy.asarray(im)
Notice:In PIL, img is RGBA. In cv2, img is BGRA.
My robust solution:
def cv_from_pil_img(pil_img):
assert pil_img.mode=="RGBA"
return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGBA2BGRA)
I just want to bring up a valid point to anyone searching for this. If you are going to work with .NET versions before 4.0 (VS2010), please be advised that you have to create constructor chains as shown above.
However, if you're staying in 4.0, I have good news. You can now have a single constructor with optional arguments! I'll simplify the Foo class example:
class Foo {
private int id;
private string name;
public Foo(int id = 0, string name = "") {
this.id = id;
this.name = name;
}
}
class Main() {
// Foo Int:
Foo myFooOne = new Foo(12);
// Foo String:
Foo myFooTwo = new Foo(name:"Timothy");
// Foo Both:
Foo myFooThree = new Foo(13, name:"Monkey");
}
When you implement the constructor, you can use the optional arguments since defaults have been set.
I hope you enjoyed this lesson! I just can't believe that developers have been complaining about construct chaining and not being able to use default optional arguments since 2004/2005! Now it has taken SO long in the development world, that developers are afraid of using it because it won't be backwards compatible.
You could use OHHTTPStubs and stub the network requests to specific URLs to fail.
"\n\r" produces 2 new lines while "\n","\r" & "\r\n" produce single lines if, in the Header, you use content-type: text/plain
.
Beware: If you do the Following php code:
$message='ab<br>cd<br>e<br>f';
print $message.'<br><br>';
$message=str_replace('<br>',"\r\n",$message);
print $message;
you get the following in the Windows browser:
ab
cd
e
f
ab cd e f
and with content-type: text/plain
you get the following in an email output;
ab
cd
e
f
What you want to do is use Page.RegisterStartupScript(key, script) :
See here for more details: http://msdn.microsoft.com/en-us/library/aa478975.aspx
What you basically do is build your javascript string, pass it to that method and give it a unique id( in case you try to register it twice on a page.)
EDIT: This is what you call trigger happy. Feel free to down it. :)
Fastest way (will take extra memory):
var empid=[1,4,5]
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] ;
var empIdObj={};
empid.forEach(function(element) {
empIdObj[element]=true;
});
var filteredArray=[];
records.forEach(function(element) {
if(empIdObj[element.empid])
filteredArray.push(element)
});
I stumbled here trying to look for a way to get the difference between two objects. This is my solution using Lodash:
// Get updated values (including new values)
var updatedValuesIncl = _.omitBy(curr, (value, key) => _.isEqual(last[key], value));
// Get updated values (excluding new values)
var updatedValuesExcl = _.omitBy(curr, (value, key) => (!_.has(last, key) || _.isEqual(last[key], value)));
// Get old values (by using updated values)
var oldValues = Object.keys(updatedValuesIncl).reduce((acc, key) => { acc[key] = last[key]; return acc; }, {});
// Get newly added values
var newCreatedValues = _.omitBy(curr, (value, key) => _.has(last, key));
// Get removed values
var deletedValues = _.omitBy(last, (value, key) => _.has(curr, key));
// Then you can group them however you want with the result
Code snippet below:
_x000D__x000D__x000D__x000D__x000D_var last = {_x000D_ "authed": true,_x000D_ "inForeground": true,_x000D_ "goodConnection": false,_x000D_ "inExecutionMode": false,_x000D_ "online": true,_x000D_ "array": [1, 2, 3],_x000D_ "deep": {_x000D_ "nested": "value",_x000D_ },_x000D_ "removed": "value",_x000D_ };_x000D_ _x000D_ var curr = {_x000D_ "authed": true,_x000D_ "inForeground": true,_x000D_ "deep": {_x000D_ "nested": "changed",_x000D_ },_x000D_ "array": [1, 2, 4],_x000D_ "goodConnection": true,_x000D_ "inExecutionMode": false,_x000D_ "online": false,_x000D_ "new": "value"_x000D_ };_x000D_ _x000D_ // Get updated values (including new values)_x000D_ var updatedValuesIncl = _.omitBy(curr, (value, key) => _.isEqual(last[key], value));_x000D_ // Get updated values (excluding new values)_x000D_ var updatedValuesExcl = _.omitBy(curr, (value, key) => (!_.has(last, key) || _.isEqual(last[key], value)));_x000D_ // Get old values (by using updated values)_x000D_ var oldValues = Object.keys(updatedValuesIncl).reduce((acc, key) => { acc[key] = last[key]; return acc; }, {});_x000D_ // Get newly added values_x000D_ var newCreatedValues = _.omitBy(curr, (value, key) => _.has(last, key));_x000D_ // Get removed values_x000D_ var deletedValues = _.omitBy(last, (value, key) => _.has(curr, key));_x000D_ _x000D_ console.log('oldValues', JSON.stringify(oldValues));_x000D_ console.log('updatedValuesIncl', JSON.stringify(updatedValuesIncl));_x000D_ console.log('updatedValuesExcl', JSON.stringify(updatedValuesExcl));_x000D_ console.log('newCreatedValues', JSON.stringify(newCreatedValues));_x000D_ console.log('deletedValues', JSON.stringify(deletedValues));
_x000D_<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
I had a look into some of the answers above and I'd recommend against using the pattern from @Dan's answer (c. Dec 15 '10), since it incorrectly flags almost 0.4% of valid postcodes as invalid, while the others do not.
Ordnance Survey provide service called Code Point Open which:
contains a list of all the current postcode units in Great Britain
I ran each of the regexs above against the full list of postcodes (Jul 6 '13) from this data using grep
:
cat CSV/*.csv |
# Strip leading quotes
sed -e 's/^"//g' |
# Strip trailing quote and everything after it
sed -e 's/".*//g' |
# Strip any spaces
sed -E -e 's/ +//g' |
# Find any lines that do not match the expression
grep --invert-match --perl-regexp "$pattern"
There are 1,686,202 postcodes total.
The following are the numbers of valid postcodes that do not match each $pattern
:
'^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'
# => 6016 (0.36%)
'^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$'
# => 0
'^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}$'
# => 0
Of course, these results only deal with valid postcodes that are incorrectly flagged as invalid. So:
'^.*$'
# => 0
I'm saying nothing about which pattern is the best regarding filtering out invalid postcodes.
Assuming that you do not want to change orig
, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:
from itertools import chain
dest = dict(chain(orig.items(), extra.items()))
Or without itertools:
dest = dict(list(orig.items()) + list(extra.items()))
Note that you only need to pass the result of items()
into list()
on Python 3, on 2.x dict.items()
already returns a list so you can just do dict(orig.items() + extra.items())
.
As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:
from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))
You're comparing strings. JavaScript compares the ASCII code for each character of the string.
To see why you get false, look at the charCodes:
"1300".charCodeAt(0);
49
"999".charCodeAt(0);
57
The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.
The fix is to treat the strings as numbers. You can use a number of methods:
parseInt(string, radix)
parseInt("1300", 10);
> 1300 - notice the lack of quotes
+"1300"
> 1300
Number("1300")
> 1300
First of all I'd like to say that all users who said about lazy and transactions were right. But in my case there was a slight difference in that I used result of @Transactional method in a test and that was outside real transaction so I got this lazy exception.
My service method:
@Transactional
User get(String uid) {};
My test code:
User user = userService.get("123");
user.getActors(); //org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role
My solution to this was wrapping that code in another transaction like this:
List<Actor> actors = new ArrayList<>();
transactionTemplate.execute((status)
-> actors.addAll(userService.get("123").getActors()));
I had the same problem too. I used this code:
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
Using the ADM
, add the images on the sdcard or anywhere.
And when you are in your vm and the selection screen shows up, browse using the top left dropdown seen in the image below.
The answer to this question lies in how C# Controls work
Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's invoke methods to marshal the call to the proper thread. This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.
Effectively, what Invoke does is ensure that the code you are calling occurs on the thread that the control "lives on" effectively preventing cross threaded exceptions.
From a historical perspective, in .Net 1.1, this was actually allowed. What it meant is that you could try and execute code on the "GUI" thread from any background thread and this would mostly work. Sometimes it would just cause your app to exit because you were effectively interrupting the GUI thread while it was doing something else. This is the Cross Threaded Exception - imagine trying to update a TextBox while the GUI is painting something else.
Effectively, you are interrupting a queue, which can have lots of unforeseen consequences. Invoke is effectively the "polite" way of getting what you want to do into that queue, and this rule was enforced from .Net 2.0 onward via a thrown InvalidOperationException.
To understand what is actually going on behind the scenes, and what is meant by "GUI Thread", it's useful to understand what a Message Pump or Message Loop is.
This is actually already answered in the question "What is a Message Pump" and is recommended reading for understanding the actual mechanism that you are tying into when interacting with controls.
Other reading you may find useful includes:
One of the cardinal rules of Windows GUI programming is that only the thread that created a control can access and/or modify its contents (except for a few documented exceptions). Try doing it from any other thread and you'll get unpredictable behavior ranging from deadlock, to exceptions to a half updated UI. The right way then to update a control from another thread is to post an appropriate message to the application message queue. When the message pump gets around to executing that message, the control will get updated, on the same thread that created it (remember, the message pump runs on the main thread).
and, for a more code heavy overview with a representative sample:
Invalid Cross-thread Operations
// the canonical form (C# consumer)
public delegate void ControlStringConsumer(Control control, string text); // defines a delegate type
public void SetText(Control control, string text) {
if (control.InvokeRequired) {
control.Invoke(new ControlStringConsumer(SetText), new object[]{control, text}); // invoking itself
} else {
control.Text=text; // the "functional part", executing only on the main thread
}
}
Once you have an appreciation for InvokeRequired, you may wish to consider using an extension method for wrapping these calls up. This is ably covered in the Stack Overflow question Cleaning Up Code Littered with Invoke Required.
There is also a further write up of what happened historically that may be of interest.
The problem with the default VS2015 templates is that the compiler isn't actually copied to the {outdir}_PublishedWebsites\tfr\bin\roslyn\
directory, but rather the {outdir}\roslyn\
directory. This is likely different from your local environment since AppHarbor
builds apps using an output directory instead of building the solution "in-place".
To fix it, add the following towards end of .csproj
file right after xml block <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">...</Target>
<PropertyGroup>
<PostBuildEvent>
if not exist "$(WebProjectOutputDir)\bin\Roslyn" md "$(WebProjectOutputDir)\bin\Roslyn"
start /MIN xcopy /s /y /R "$(OutDir)roslyn\*.*" "$(WebProjectOutputDir)\bin\Roslyn"
</PostBuildEvent>
</PropertyGroup>
CREATE TABLE book (
id INT AUTO_INCREMENT primary key NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I am also facing the same problem in Safari Browser
var date = new Date("2011-02-07");
console.log(date) // IE you get ‘NaN’ returned and in Safari you get ‘Invalid Date’
Here the solution:
var d = new Date(2011, 01, 07); // yyyy, mm-1, dd
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss
var d = new Date("02/07/2011"); // "mm/dd/yyyy"
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"
var d = new Date(1297076700000); // milliseconds
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC
My user account did not have the permissions to alter the database and table, as suggested in this solution.
If, like me, you don't care about the character collation (you are using the '=' operator), you can apply the reverse fix. Run this before your SELECT:
SET collation_connection = 'latin1_swedish_ci';
If you want to do it in shell, instead of writing code.
python3 -m zipfile -e myfiles.zip myfiles/
myfiles.zip
is the zip archive and myfiles
is the path to extract the files.
Try adding this to your CSS
html, body {
max-width: 100%;
overflow-x: hidden;
}
How is main called?
When you are using the console application template the code will be compiled requiring a method called Main in the startup object as Main is market as entry point to the application.
By default no startup object is specified in the project propery settings and the Program class will be used by default. You can change this in the project property under the "Build" tab if you wish.
Keep in mind that which ever object you assign to be the startup object must have a method named Main in it.
How are args passed to main method
The accepted format is MyConsoleApp.exe value01 value02 etc...
The application assigns each value after each space into a separate element of the parameter array.
Thus, MyConsoleApp.exe value01 value02 will mean your args paramter has 2 elements:
[0] = "value01"
[1] = "value02"
How you parse the input values and use them is up to you.
Hope this helped.
Additional Reading:
Changing this line:
var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);
To fix the dimensions.
Signed variables use one bit to flag whether they are positive or negative. Unsigned variables don't have this bit, so they can store larger numbers in the same space, but only nonnegative numbers, e.g. 0 and higher.
For more: Unsigned and Signed Integers
There this PHP/Java bridge. This is basically running PHP via FastCGI. I have not used it myself.
If you can not use *ngif, [class.hide] works in angular 7. example:
<mat-select (selectionChange)="changeFilter($event.value)" multiple [(ngModel)]="selected">
<mat-option *ngFor="let filter of gridOptions.columnDefs"
[class.hide]="filter.headerName=='Action'" [value]="filter.field">{{filter.headerName}}</mat-option>
</mat-select>
That's it you are done
As of now, you can only store string values in localStorage. You'll need to serialize the array object and then store it in localStorage.
For example:
localStorage.setItem('session', a.join('|'));
or
localStorage.setItem('session', JSON.stringify(a));
If you are using a framework like Ruby on Rails or Spring MVC you may need to use divs with square braces or other chars, that are not allowed you can use document.getElementById
and this solution still works if you have multiple inputs with the same type.
var div = document.getElementById(divID);
$(div).find('input:text, input:password, input:file, select, textarea')
.each(function() {
$(this).val('');
});
$(div).find('input:radio, input:checkbox').each(function() {
$(this).removeAttr('checked');
$(this).removeAttr('selected');
});
This examples shows how to clear the inputs, for you example you'll need to change it.
addEventListener
can add multiple events, whereas with onclick
this cannot be done.onclick
can be added as an HTML
attribute, whereas an addEventListener
can only be added within <script>
elements.addEventListener
can take a third argument which can stop the event propagation.Both can be used to handle events. However, addEventListener
should be the preferred choice since it can do everything onclick
does and more. Don't use inline onclick
as HTML attributes as this mixes up the javascript and the HTML which is a bad practice. It makes the code less maintainable.
Key should be readable by the logged in user.
Try this:
chmod 400 ~/.ssh/Key file
chmod 400 ~/.ssh/vm_id_rsa.pub
Why not just use .show()/.hide()
instead?
$("#menu").hover(function(){
$('.flyout').show();
},function(){
$('.flyout').hide();
});
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search > Find in Files
(Ctrl+Shift+F for the keyboard addicted) and enter:
(test1|test2)
*.txt
Follow current doc.
to have the path of the current file to be filled.Regular Expression
You could make an array the same size as the ArrayList
and then make an iterated for loop to index the items and insert them into the array.
Run the following command to enable credential caching:
$ git config credential.helper store
$ git push https://github.com/owner/repo.git
Username for 'https://github.com': <USERNAME>
Password for 'https://[email protected]': <PASSWORD>
You should also specify caching expire,
git config --global credential.helper 'cache --timeout 7200'
After enabling credential caching, it will be cached for 7200 seconds (2 hour).
To be able to use std::unordered_map
(or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
A hash function; this must be a class that overrides operator()
and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash
template for your key-type.
A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator()
, or as a specialization of std::equal
, or – easiest of all – by overloading operator==()
for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
With this in place, you can instantiate a std::unordered_map
for the key-type:
int main()
{
std::unordered_map<Key,std::string> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
It will automatically use std::hash<Key>
as defined above for the hash value calculations, and the operator==
defined as member function of Key
for equality checks.
If you don't want to specialize template inside the std
namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
int main()
{
std::unordered_map<Key,std::string,KeyHasher> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value
and hash_combine
function template from the Boost library. The former acts in a similar way as std::hash
for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include <boost/functional/hash.hpp>
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(k.first));
hash_combine(seed,hash_value(k.second));
hash_combine(seed,hash_value(k.third));
// Return the result.
return seed;
}
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
template <>
struct hash<Key>
{
size_t operator()( const Key& k ) const
{
// Compute individual hash values for first, second and third
// http://stackoverflow.com/a/1646913/126995
size_t res = 17;
res = res * 31 + hash<string>()( k.first );
res = res * 31 + hash<string>()( k.second );
res = res * 31 + hash<int>()( k.third );
return res;
}
};
}
Also if you can set JVM timezone this way
System.setProperty("user.timezone", "EST");
or -Duser.timezone=GMT
in the JVM args.
For Dart check "Line length" property in Settings.
++ This worked for me. It's vanilla javascirpt
and good for use cases such as de-cluttering when testing with ngMocks
library:
<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!-- Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>
This is your javascript
file that contains the JSON
data
// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
"Title": "Star Wars",
"Year": "1983",
"Rated": "N/A",
"Released": "01 May 1983",
"Runtime": "N/A",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "N/A",
"Writer": "N/A",
"Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "N/A",
"Metascore": "N/A",
"imdbRating": "7.9",
"imdbVotes": "342",
"imdbID": "tt0251413",
"Type": "game",
"Response": "True"
};
Finally, work with the JSON data anywhere in your code
// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;
Note:- This is great for testing and even karma.conf.js
accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development
environment.
// extract from karma.conf.js
files: [
'json-data/JSONSearchResultHardcodedData.js',
'json-data/JSONFindByIdResults.js'
...
]
Hope this helps.
++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733
UPDATE
An easier way that worked for me is just include a function
at the bottom of the code returning whatever JSON
.
// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
return {
"Title": "Bri Squared",
"Year": "2011",
"Rated": "N/A",
"Released": "N/A",
"Runtime": "N/A",
"Genre": "Comedy",
"Director": "Joy Gohring",
"Writer": "Briana Lane",
"Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
"Metascore": "N/A",
"imdbRating": "8.2",
"imdbVotes": "5",
"imdbID": "tt1937109",
"Type": "movie",
"Response": "True"
}
}
if I remember well... in query analyzer or equivalent:
BACKUP LOG databasename WITH TRUNCATE_ONLY
DBCC SHRINKFILE ( databasename_Log, 1)
I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.
Example:
import networkx as nx
import matplotlib.pyplot as plt
g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)
nx.draw(g,with_labels=True)
plt.draw()
plt.show()
This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.
Note: It's just a simple representation. Weighted Edges could be added like
g.add_edges_from([(1,2),(2,5)], weight=2)
and hence plotted again.
To remove error from eclipse for android there are few steps:-
1.open eclipse check all the error
2.In search tab open SDK manager
3.Remove all the value show as error in eclipse
4.After remove from sdk restart eclipse
You have to select the device in the schemes menu in the top left where you used to select between simulator/device. It won’t let you archive a build for the simulator.
Or you may find that if the iOS device is already selected the archive box isn’t selected when you choose “Edit Schemes” => “Build”.
Rails provides a solution to this: shallow nesting.
I think this is a good because when you deal directly with a known resource, there's no need to use nested routes, as has been discussed in other answers here.
You are reinventing the wheel.
If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).
If you need fast in-memory queues use one of the impementations of java's Queue.
If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.
I had the same error after I installed new packages or updated them:
...
npm ERR! code ELIFECYCLE
npm ERR! errno 1
...
It helped me to run installation command once again or a couple of times. After that, the error disappeared.
Type
git push
from the command line inside the repository directory
Just:
c:\>(for /r %f in (*.java) do @type %f ) | find /c /v ""
Font: https://superuser.com/questions/959036/what-is-the-windows-equivalent-of-wc-l
The best solution for me is:
// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
.onclick
should be set to a function instead of a string. Try
elemm.onclick = function() { alert('blah'); };
instead.
Here are the primary differences:
Syntax: module.service( 'serviceName', function );
Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service
.
Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending ( )
to the injected function reference. Could also be run with injectedArg.call( this )
or similar.
Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory
.
Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.
Here is example using services and factory. Read more about AngularJS Service vs Factory.
You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.
>>> a = "123"
>>> int(a)
123
Here's some freebie code:
def getTwoNumbers():
numberA = raw_input("Enter your first number: ")
numberB = raw_input("Enter your second number: ")
return int(numberA), int(numberB)
The following is an instantiation of the various "just print it" suggestions. I found it instructive.
#include "stdio.h"
int main() {
static int x = 5;
static int *p = &x;
printf("(int) p => %d\n",(int) p);
printf("(int) p++ => %d\n",(int) p++);
x = 5; p = &x;
printf("(int) ++p => %d\n",(int) ++p);
x = 5; p = &x;
printf("++*p => %d\n",++*p);
x = 5; p = &x;
printf("++(*p) => %d\n",++(*p));
x = 5; p = &x;
printf("++*(p) => %d\n",++*(p));
x = 5; p = &x;
printf("*p++ => %d\n",*p++);
x = 5; p = &x;
printf("(*p)++ => %d\n",(*p)++);
x = 5; p = &x;
printf("*(p)++ => %d\n",*(p)++);
x = 5; p = &x;
printf("*++p => %d\n",*++p);
x = 5; p = &x;
printf("*(++p) => %d\n",*(++p));
return 0;
}
It returns
(int) p => 256688152
(int) p++ => 256688152
(int) ++p => 256688156
++*p => 6
++(*p) => 6
++*(p) => 6
*p++ => 5
(*p)++ => 5
*(p)++ => 5
*++p => 0
*(++p) => 0
I cast the pointer addresses to int
s so they could be easily compared.
I compiled it with GCC.
imo there's a better answer for this using Snippets
Create a snippet with a definition like this:
"name_of_your_snippet": {
"scope": "javascript,html",
"prefix": "name_of_your_snippet",
"body": "<${0:b}>$TM_SELECTED_TEXT</${0:b}>"
}
Then bind it to a key in keybindings.json E.g. like this:
{
"key": "alt+w",
"command": "editor.action.insertSnippet",
"args": { "name": "name_of_your_snippet" }
}
I think this should give you exactly the same result as htmltagwrap but without having to install an extension.
It will insert tags around selected text, defaults to <b>
tag & selects the tag so typing lets you change it.
If you want to use a different default tag just change the b
in the body
property of the snippet.
You can configure setup.exe to skip this check using the parameters below -
setup.exe -ignorePrereq -ignorePrereq -J"-Doracle.install.db.validate.supportedOSCheck=false"
Figured it out. The VM's in cloud engine don't come with a root password setup by default so you'll first need to change the password using
sudo passwd
If you do everything correctly, it should do something like this:
user@server[~]# sudo passwd
Changing password for user root.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.
There are all documented in http://docs.python.org/reference/datamodel.html
Change
mAdapter = new RecordingsListAdapter(this, recordings);
to
mAdapter = new RecordingsListAdapter(getActivity(), recordings);
and also make sure that recordings!=null
at mAdapter = new RecordingsListAdapter(this, recordings);
Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.
String tenString = "10"
//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;
//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);
It is possible that the executable is statically linked and that is why ldd gzip
does not see any links - because it isn't. I don't know much about things that far back so I don't know if there would be incompatibilities if libraries are linked in statically. I might expect there to be.
I know it's the most obvious thing going and I'm sure you've done it, but chmod +x ./gzip
, yes? No such file or directory is a classic symptom of that not being done, that's why I mention it.
Check if you mixed tabs and spaces, that is a frequent source of indentation errors.
This is a generalized way in which you do not have to remember the exact location of the variable:
# df = dataframe
# old.var.name = The name you don't like anymore
# new.var.name = The name you want to get
names(df)[names(df) == 'old.var.name'] <- 'new.var.name'
This code pretty much does the following:
names(df)
looks into all the names in the df
[names(df) == old.var.name]
extracts the variable name you want to check<- 'new.var.name'
assigns the new variable name.Add a default constraint with the GETDATE() function as value.
ALTER TABLE myTable
ADD CONSTRAINT CONSTRAINT_NAME
DEFAULT GETDATE() FOR myColumn
# given
df1=pd.DataFrame({'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24'],
'Fruit':['Banana','Orange','Apple','Celery'],
'Num':[22.1,8.6,7.6,10.2],
'Color':['Yellow','Orange','Green','Green']})
df2=pd.DataFrame({'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24','2013-11-25','2013-11-25'],
'Fruit':['Banana','Orange','Apple','Celery','Apple','Orange'],
'Num':[22.1,8.6,7.6,1000,22.1,8.6],
'Color':['Yellow','Orange','Green','Green','Red','Orange']})
# find which rows are in df2 that aren't in df1 by Date and Fruit
df_2notin1 = df2[~(df2['Date'].isin(df1['Date']) & df2['Fruit'].isin(df1['Fruit']) )].dropna().reset_index(drop=True)
# output
print('df_2notin1\n', df_2notin1)
# Color Date Fruit Num
# 0 Red 2013-11-25 Apple 22.1
# 1 Orange 2013-11-25 Orange 8.6
If you see there is a method _numpy(), e.g for an EagerTensor simply call the above method and you will get an ndarray.
Use the web browser control. This requires Adobe reader to be installed but most likely you have it anyway. Set the UrL of the control to the file location.
Use this:
In [105]: a
Out[105]:
array([[15, 30, 88, 31, 33],
[53, 38, 54, 47, 56],
[67, 2, 74, 10, 16],
[86, 33, 15, 51, 32],
[32, 47, 76, 15, 81]], dtype=int32)
In [106]: float32(a)
Out[106]:
array([[ 15., 30., 88., 31., 33.],
[ 53., 38., 54., 47., 56.],
[ 67., 2., 74., 10., 16.],
[ 86., 33., 15., 51., 32.],
[ 32., 47., 76., 15., 81.]], dtype=float32)
Remove Padding: 10%;
or use px instead of percent for .wrap
see the example : http://jsfiddle.net/C93mk/493/
HTML :
<div id="wrapper">
<div id="wrap">
Some relative item placed item
<div id="fixed"></div>
</div>
</div>
CSS:
body{ height:20000px }
#wrapper {padding:10%;}
#wrap{
float: left;
position: relative;
width: 200px;
background:#ccc;
}
#fixed{
position:fixed;
width:inherit;
padding:0px;
height:10px;
background-color:#333;
}
foreach ($arquivos as $key => $item) {
reset($arquivos);
// FIRST AHEAD
if ($key === key($arquivos) || $key !== end(array_keys($arquivos)))
$pdf->cat(null, null, $key);
// LAST
if ($key === end(array_keys($arquivos))) {
$pdf->cat(null, null, $key)
->execute();
}
}
Everytime I use another approach. People seem to store or get position on a view, rather than storing a reference to an object that is displayed by ViewHolder.
I use this approach instead, and just store it in ViewHolder when onBindViewHolder() is called, and set reference to null in onViewRecycled().
Every time ViewHolder becomes invisible, it's recycled. So this doesn't affect in large memory consumption.
@Override
public void onBindViewHolder(final ItemViewHolder holder, int position) {
...
holder.displayedItem = adapterItemsList.get(i);
...
}
@Override
public void onViewRecycled(ItemViewHolder holder) {
...
holder.displayedItem = null;
...
}
class ItemViewHolder extends RecyclerView.ViewHolder {
...
MySuperItemObject displayedItem = null;
...
}
Apples and oranges. Firebase is a Backend-as-a-Service containing identity management, realtime data views and a document database. It runs in the cloud.
MongoDB on the other hand is a full fledged database with a rich query language. In principle it runs on your own machine, but there are cloud providers.
If you are looking for the database component only MongoDB is much more mature and feature-rich.
Here is a clean method I've discovered:
$myArray = [];
array_push($myArray, (object)[
'key1' => 'someValue',
'key2' => 'someValue2',
'key3' => 'someValue3',
]);
return $myArray;
Using CROSS APPLY
:
SELECT ID, Col1, Col2, Col3, MinValue
FROM YourTable
CROSS APPLY (SELECT MIN(d) AS MinValue FROM (VALUES (Col1), (Col2), (Col3)) AS a(d)) A
For those who develop in Android, use TextUtils.
String items = TextUtils.join("", arr);
Assuming arr is of type String[] arr= {"1","2","3"};
The output would be 123
This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.
<LimitExcept OPTIONS>
AuthType Basic
AuthName <AUTH_NAME>
Require valid-user
AuthUserFile <FILE_PATH>
</LimitExcept>
Have you tried this ?
UNIQUE KEY `thekey` (`user`,`email`,`address`)
"pop"ing the first element of an Array is called "shift" ("unshift" being the operation of adding one element in front of the array).
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
Following is the code calculating power of decimal value for RaiseToPower for both -ve and +ve values.
public decimal Power(decimal number, decimal raiseToPower)
{
decimal result = 0;
if (raiseToPower < 0)
{
raiseToPower *= -1;
result = 1 / number;
for (int i = 1; i < raiseToPower; i++)
{
result /= number;
}
}
else
{
result = number;
for (int i = 0; i <= raiseToPower; i++)
{
result *= number;
}
}
return result;
}
Partial dependency implies is a situation where a non-prime attribute(An attribute that does not form part of the determinant(Primary key/Candidate key)) is functionally dependent to a portion/part of a primary key/Candidate key.
To answer your question with a working example:
<script type="text/javascript">
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = new Array();
for (var index in array[i]) {
line.push('"' + array[i][index] + '"');
}
str += line.join(';');
str += '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str));
}
</script>
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
Mouse.GetPosition(mWindow)
gives you the mouse position relative to the parameter of your choice.
mWindow.PointToScreen()
convert the position to a point relative to the screen.
So mWindow.PointToScreen(Mouse.GetPosition(mWindow))
gives you the mouse position relative to the screen, assuming that mWindow
is a window(actually, any class derived from System.Windows.Media.Visual
will have this function), if you are using this inside a WPF window class, this
should work.
Would all these dates be in the database already or do you just want to know the days between the two dates? If it's the first you could use the BETWEEN or <= >= to find the dates between
EXAMPLE:
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
OR
SELECT column_name(s)
FROM table_name
WHERE column_name
value1 >= column_name
AND column_name =< value2
Here are some examples:
> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
weighted mean
> z$y <- rev(z$y)
> z
w x y mean
1 5 1 NA 1
2 6 2 3 2
3 7 3 2 3
4 8 4 1 4
>
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
w x y mean wmean
1 5 1 NA 1 1.000000
2 6 2 3 2 2.666667
3 7 3 2 3 2.333333
4 8 4 1 4 2.000000
setAllowUrlEncodedSlash(true)
didn't work for me. Still internal method isNormalized
return false
when having double slash.
I replaced StrictHttpFirewall
with DefaultHttpFirewall
by having the following code only:
@Bean
public HttpFirewall defaultHttpFirewall() {
return new DefaultHttpFirewall();
}
Working well for me.
Any risk by using DefaultHttpFirewall
?
Whammo blammo (for leading spaces):
SELECT
RIGHT(space(60) + cust_name, 60),
RIGHT(space(60) + cust_address, 60)
OR (for trailing spaces)
SELECT
LEFT(cust_name + space(60), 60),
LEFT(cust_address + space(60), 60),
You can use the pathlib module.
from pathlib import Path
x = Path('./')
print(list(filter(lambda y:y.is_file(), x.iterdir())))
A LEFT JOIN
is absolutely not faster than an INNER JOIN
. In fact, it's slower; by definition, an outer join (LEFT JOIN
or RIGHT JOIN
) has to do all the work of an INNER JOIN
plus the extra work of null-extending the results. It would also be expected to return more rows, further increasing the total execution time simply due to the larger size of the result set.
(And even if a LEFT JOIN
were faster in specific situations due to some difficult-to-imagine confluence of factors, it is not functionally equivalent to an INNER JOIN
, so you cannot simply go replacing all instances of one with the other!)
Most likely your performance problems lie elsewhere, such as not having a candidate key or foreign key indexed properly. 9 tables is quite a lot to be joining so the slowdown could literally be almost anywhere. If you post your schema, we might be able to provide more details.
Edit:
Reflecting further on this, I could think of one circumstance under which a LEFT JOIN
might be faster than an INNER JOIN
, and that is when:
Consider this example:
CREATE TABLE #Test1
(
ID int NOT NULL PRIMARY KEY,
Name varchar(50) NOT NULL
)
INSERT #Test1 (ID, Name) VALUES (1, 'One')
INSERT #Test1 (ID, Name) VALUES (2, 'Two')
INSERT #Test1 (ID, Name) VALUES (3, 'Three')
INSERT #Test1 (ID, Name) VALUES (4, 'Four')
INSERT #Test1 (ID, Name) VALUES (5, 'Five')
CREATE TABLE #Test2
(
ID int NOT NULL PRIMARY KEY,
Name varchar(50) NOT NULL
)
INSERT #Test2 (ID, Name) VALUES (1, 'One')
INSERT #Test2 (ID, Name) VALUES (2, 'Two')
INSERT #Test2 (ID, Name) VALUES (3, 'Three')
INSERT #Test2 (ID, Name) VALUES (4, 'Four')
INSERT #Test2 (ID, Name) VALUES (5, 'Five')
SELECT *
FROM #Test1 t1
INNER JOIN #Test2 t2
ON t2.Name = t1.Name
SELECT *
FROM #Test1 t1
LEFT JOIN #Test2 t2
ON t2.Name = t1.Name
DROP TABLE #Test1
DROP TABLE #Test2
If you run this and view the execution plan, you'll see that the INNER JOIN
query does indeed cost more than the LEFT JOIN
, because it satisfies the two criteria above. It's because SQL Server wants to do a hash match for the INNER JOIN
, but does nested loops for the LEFT JOIN
; the former is normally much faster, but since the number of rows is so tiny and there's no index to use, the hashing operation turns out to be the most expensive part of the query.
You can see the same effect by writing a program in your favourite programming language to perform a large number of lookups on a list with 5 elements, vs. a hash table with 5 elements. Because of the size, the hash table version is actually slower. But increase it to 50 elements, or 5000 elements, and the list version slows to a crawl, because it's O(N) vs. O(1) for the hashtable.
But change this query to be on the ID
column instead of Name
and you'll see a very different story. In that case, it does nested loops for both queries, but the INNER JOIN
version is able to replace one of the clustered index scans with a seek - meaning that this will literally be an order of magnitude faster with a large number of rows.
So the conclusion is more or less what I mentioned several paragraphs above; this is almost certainly an indexing or index coverage problem, possibly combined with one or more very small tables. Those are the only circumstances under which SQL Server might sometimes choose a worse execution plan for an INNER JOIN
than a LEFT JOIN
.
This question seems to be answered, however for completeness, I would add another approach.
You can use a unique ID number generator which is based on Twitter's Snowflake id generator. C# implementation can be found here.
var id64Generator = new Id64Generator();
// ...
public string generateID(string sourceUrl)
{
return string.Format("{0}_{1}", sourceUrl, id64Generator.GenerateId());
}
Note that one of very nice features of that approach is possibility to have multiple generators on independent nodes (probably something useful for a search engine) generating real time, globally unique identifiers.
// node 0
var id64Generator = new Id64Generator(0);
// node 1
var id64Generator = new Id64Generator(1);
// ... node 10
var id64Generator = new Id64Generator(10);
As a response to your question: "i want to reset all the data and keep last 30 days inside the table."
you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html
For example:
CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);
Will run a daily cleanup in your table, keeping the last 30 days data available
The reason for this apparent performance discrepancy between categorical & binary cross entropy is what user xtof54 has already reported in his answer below, i.e.:
the accuracy computed with the Keras method
evaluate
is just plain wrong when using binary_crossentropy with more than 2 labels
I would like to elaborate more on this, demonstrate the actual underlying issue, explain it, and offer a remedy.
This behavior is not a bug; the underlying reason is a rather subtle & undocumented issue at how Keras actually guesses which accuracy to use, depending on the loss function you have selected, when you include simply metrics=['accuracy']
in your model compilation. In other words, while your first compilation option
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
is valid, your second one:
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
will not produce what you expect, but the reason is not the use of binary cross entropy (which, at least in principle, is an absolutely valid loss function).
Why is that? If you check the metrics source code, Keras does not define a single accuracy metric, but several different ones, among them binary_accuracy
and categorical_accuracy
. What happens under the hood is that, since you have selected binary cross entropy as your loss function and have not specified a particular accuracy metric, Keras (wrongly...) infers that you are interested in the binary_accuracy
, and this is what it returns - while in fact you are interested in the categorical_accuracy
.
Let's verify that this is the case, using the MNIST CNN example in Keras, with the following modification:
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # WRONG way
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=2, # only 2 epochs, for demonstration purposes
verbose=1,
validation_data=(x_test, y_test))
# Keras reported accuracy:
score = model.evaluate(x_test, y_test, verbose=0)
score[1]
# 0.9975801164627075
# Actual accuracy calculated manually:
import numpy as np
y_pred = model.predict(x_test)
acc = sum([np.argmax(y_test[i])==np.argmax(y_pred[i]) for i in range(10000)])/10000
acc
# 0.98780000000000001
score[1]==acc
# False
To remedy this, i.e. to use indeed binary cross entropy as your loss function (as I said, nothing wrong with this, at least in principle) while still getting the categorical accuracy required by the problem at hand, you should ask explicitly for categorical_accuracy
in the model compilation as follows:
from keras.metrics import categorical_accuracy
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[categorical_accuracy])
In the MNIST example, after training, scoring, and predicting the test set as I show above, the two metrics now are the same, as they should be:
# Keras reported accuracy:
score = model.evaluate(x_test, y_test, verbose=0)
score[1]
# 0.98580000000000001
# Actual accuracy calculated manually:
y_pred = model.predict(x_test)
acc = sum([np.argmax(y_test[i])==np.argmax(y_pred[i]) for i in range(10000)])/10000
acc
# 0.98580000000000001
score[1]==acc
# True
System setup:
Python version 3.5.3
Tensorflow version 1.2.1
Keras version 2.0.4
UPDATE: After my post, I discovered that this issue had already been identified in this answer.
If you're currently on the branch you want to rename:
git branch -m new_name
Or else:
git branch -m old_name new_name
You can check with:
git branch -a
As you can see, only the local name changed Now, to change the name also in the remote you must do:
git push origin :old_name
This removes the branch, then upload it with the new name:
git push origin new_name
The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.
This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
It seems to me that all approaches (file exchange solutions unconsidered) here are lacking the essential step, or finally leading to it via some blurry workarounds.
The figure size needs to equal the paper size and the white margins are gone.
A = hgload('myFigure.fig');
% set desired output size
set(A, 'Units','centimeters')
height = 15;
width = 19;
% the last two parameters of 'Position' define the figure size
set(A, 'Position',[25 5 width height],...
'PaperSize',[width height],...
'PaperPositionMode','auto',...
'InvertHardcopy', 'off',...
'Renderer','painters'... %recommended if there are no alphamaps
);
saveas(A,'printout','pdf')
Will give you a pdf output as your figure appears, in exactly the size you want. If you want to get it even tighter you can combine this solution with the answer of b3.
Have a look at https://wiki.debian.org/JavaPackage At the bottom of this page an other method is descibed using a command from the java-common package
Not a direct answer to this question but rather to the "issue" of $event.currentTarget
apparently be set to null.
This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.
You can check this for more information: Consecutive calls to console.log produce inconsistent results
You just have to remove the bindings before you use 'applyBindings' again.
ko.cleanNode($element[0]);
should do the trick. HTH.
When you draw to a canvas
element, you are simply drawing a bitmap in immediate mode.
The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.
Therefore, to get a click event on a canvas
element (shape), you need to capture click events on the canvas
HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset.
To add a click
event to your canvas
element, use...
canvas.addEventListener('click', function() { }, false);
To determine which element was clicked...
var elem = document.getElementById('myCanvas'),
elemLeft = elem.offsetLeft + elem.clientLeft,
elemTop = elem.offsetTop + elem.clientTop,
context = elem.getContext('2d'),
elements = [];
// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
// Collision detection between clicked offset and element.
elements.forEach(function(element) {
if (y > element.top && y < element.top + element.height
&& x > element.left && x < element.left + element.width) {
alert('clicked an element');
}
});
}, false);
// Add element.
elements.push({
colour: '#05EFFF',
width: 150,
height: 100,
top: 20,
left: 15
});
// Render elements.
elements.forEach(function(element) {
context.fillStyle = element.colour;
context.fillRect(element.left, element.top, element.width, element.height);
});?
This code attaches a click
event to the canvas
element, and then pushes one shape (called an element
in my code) to an elements
array. You could add as many as you wish here.
The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties.
When the click
event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements
array. If so, it fires an alert()
, which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas
.
For completeness, why your attempts didn't work...
elem.onClick = alert("hello world"); // displays alert without clicking
This is assigning the return value of alert()
to the onClick
property of elem
. It is immediately invoking the alert()
.
elem.onClick = alert('hello world'); // displays alert without clicking
In JavaScript, the '
and "
are semantically identical, the lexer probably uses ['"]
for quotes.
elem.onClick = "alert('hello world!')"; // does nothing, even with clicking
You are assigning a string to the onClick
property of elem
.
elem.onClick = function() { alert('hello world!'); }; // does nothing
JavaScript is case sensitive. The onclick
property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML.
elem.onClick = function() { alert("hello world!"); }; // does nothing
Again, ' === "
.
I used the code below to create a Button and it worked for me.
<input type="button" value="PDF" onclick="location.href='@Url.Action("Export","tblOrder")'"/>
This is possible, but you'll have to build it manually from the location
object:
location.protocol + '//' + location.host + location.pathname
That code is invalid as you can only pass variables into language constructs. empty()
is a language construct.
You have to do this in two lines:
$result = array_intersect($people, $criminals);
$result = !empty($result);
tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log
You can also upload log from admin console : http://yoururl:4848
Give connection URL as jdbc:mysql://localhost:3306/hb_student_tracker?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
You can also do something like this:
SELECT LAST (column_name) AS LAST_CUSTOMER FROM table_name;
Go to File->Project Structure-> Project Settings -> Modules.
Click on the green colored + and add new module. select Application module and set the content root to your project module.
Click next and then finish.
Use this solution
animate(document.documentElement, 'scrollTop', 0, 200);
Thanks
Jefferson is right, you have to do it backwards.
Here's the c# equivalent:
for (var i == list.Items.Count - 1; i >= 0; i--)
{
list.Items.RemoveAt(i);
}
After uncommenting disable_overscan=1 follow my lead. In the link, http://elinux.org/RPiconfig when you search for Video options, you'll also get hdmi_group and hdmi_mode. For, hdmi_group choose 1 if you're using you TV as an video output or choose 2 for monitors. Then in hdmi_mode, you can select the resolution you want from the list. I chose :- hdmi_group=2 hdmi_mode=23 And it worked.
Your question is vague (are you always looking for the first part?), but you can get the exact output you asked for with string.Split
:
string[] substrings = a.Split(',');
b = substrings[0];
Console.WriteLine(b);
Output:
abc
just to help, if any one want to limit post length at home page
.. then can use below code to do that..
the below code is simply a modification of @bfred.it
Sir
add_filter("the_content", "break_text");
function limit_text($text){
if(is_front_page())
{
$length = 250;
if(strlen($text)<$length+10) return $text; //don't cut if too short
$break_pos = strpos($text, ' ', $length); //find next space after desired length
$visible = substr($text, 0, $break_pos);
return balanceTags($visible) . "... <a href='".get_permalink()."'>read more</a>";
}else{
return $text;
}
}
Yeah, there is a very simple utility in Management Studio, if you're just looking to save query results to a CSV.
Right click on the result set, the select "Save Results As". The default file type is CSV.
The problem appears to be that you are reinitializing the list to an empty list in each iteration:
while choice != 0:
...
a = []
a.append(s)
Try moving the initialization above the loop so that it is executed only once.
a = []
while choice != 0:
...
a.append(s)
You can also make a class:
<span class="mychangecolor"> I am in yellow color!!!!!!</span>
then in a css file do:
.mychangecolor{ color:#ff5 /* it changes to yellow */ }
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
I had this problem on jdk1.6.0_37. This is the only JDE/JRE on my system. I don't know why, but the following solved the problem:
Project -> Properties -> Java Build Path - > Libraries
Switch radio button from Execution environment to Alernate JRE. This selects the same jdk1.6.0_37, but after clean/build the compile error disappeared.
Maybe clarification in answer from ram (Mar 16 at 9:00) has to do something with that.
Two things to do:
Project Settings > Project compiler output > Set it as "Project path(You actual project's path)”+”\out”.
Project Settings > Module > Path > Choose "Inherit project compile path"
In my case it was looking after .babelrc
file, and it should contain something like this:
{
"presets": ["es2015-node5", "stage-3"],
"plugins": []
}
You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a
.
To remove go to the subdirectory and rm .git -rf
.
I know this is an old question, but here is my contribution. Instead of all these tricks, you can just simply wrap a function inside another function. Like I have done here:
<div data-bind="click: function(){ f('hello parameter'); }">Click me once</div>
<div data-bind="click: function(){ f('no no parameter'); }">Click me twice</div>
var VM = function(){
this.f = function(param){
console.log(param);
}
}
ko.applyBindings(new VM());
And here is the fiddle
If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.
import java.util.Scanner;
public class ArrayModify {
public static void main(String[] args) {
int[] list;
String st;
String[] stNew;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9
st = scan.nextLine();
stNew = st.split("\\s+");
list = new int[stNew.length]; // Sets array size to 5
for (int i = 0; i < stNew.length; i++){
list[i] = Integer.parseInt(stNew[i]);
System.out.println("You Enterred: " + list[i]);
}
}
}
A useful way to remove a whole set of named-alike objects:
rm(list = ls()[grep("^tmp", ls())])
thereby removing all objects whose name begins with the string "tmp".
Edit: Following Gsee's comment, making use of the pattern
argument:
rm(list = ls(pattern = "^tmp"))
Edit: Answering Rafael comment, one way to retain only a subset of objects is to name the data you want to retain with a specific pattern. For example if you wanted to remove all objects whose name do not start with paper
you would issue the following command:
rm(list = grep("^paper", ls(), value = TRUE, invert = TRUE))
simple just change it to : const uuidv1 = require('uuid'); it will work fine.
Actually you can set custom text to that little blue button. In the xml file just use
android:imeActionLabel="whatever"
on your EditText.
Or in the java file use
etEditText.setImeActionLabel("whatever", EditorInfo.IME_ACTION_DONE);
I arbitrarily choose IME_ACTION_DONE as an example of what should go in the second parameter for this function. A full list of these actions can be found here.
It should be noted that this will not cause text to appear on all keyboards on all devices. Some keyboards do not support text on that button (e.g. swiftkey). And some devices don't support it either. A good rule is, if you see text already on the button, this will change it to whatever you'd want.
If you need only Parameter info then:
On Mac, it's assigned to Command+P
On Windows, it's assigned to Ctrl+P
If you need document info then:
On Mac, it's assigned to Command+Q
On Windows, it's assigned to Ctrl+Q
#include <string>
using std::string;
void myReplace(string& str,
const string& oldStr,
const string& newStr) {
if (oldStr.empty()) {
return;
}
for (size_t pos = 0; (pos = str.find(oldStr, pos)) != string::npos;) {
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
The check for oldStr being empty is important. If for whatever reason that parameter is empty you will get stuck in an infinite loop.
But yeah use the tried and tested C++11 or Boost solution if you can.
The problem is that the DIV that should center your tables has no width defined. By default, DIVs are block elements and take up the entire width of their parent - in this case the entire document (propagating through the #outer DIV), so the automatic margin style has no effect.
For this technique to work, you simply have to set the width of the div that has margin:auto to anything but "auto" or "inherit" (either a fixed pixel value or a percentage).
$var:25%;
$foo:5px;
.selector {
height:unquote("calc( #{$var} - #{$foo} )");
}
You have most of the code…
CURLOPT_HTTPHEADER
for curl_setopt()
takes an array with each header as an element. You have one element with multiple headers.
You also need to add the Authorization header to your $header
array.
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';
I needed to rotate an object but have a call back function. Inspired by John Kern's answer I created this.
function animateRotate (object,fromDeg,toDeg,duration,callback){
var dummy = $('<span style="margin-left:'+fromDeg+'px;">')
$(dummy).animate({
"margin-left":toDeg+"px"
},
{
duration:duration,
step: function(now,fx){
$(object).css('transform','rotate(' + now + 'deg)');
if(now == toDeg){
if(typeof callback == "function"){
callback();
}
}
}
}
)};
Doing this you can simply call the rotate on the object like so... (in my case I'm doing it on a disclosure triangle icon that has already been rotated by default to 270 degress and I'm rotating it another 90 degrees to 360 degrees at 1000 milliseconds. The final argument is the callback after the animation has finished.
animateRotate($(".disclosure_icon"),270,360,1000,function(){
alert('finished rotate');
});
The best solution I've found for this is to contain them in a parent div, and give that div a font-size of 0.
1) When the user logs out (Forms signout in Action) I want to redirect to a login page.
public ActionResult Logout() {
//log out the user
return RedirectToAction("Login");
}
2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)
Why would you want to redirect from a controller init?
the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:
public ActionResult Index() {
return RedirectToAction("whateverAction", "whateverController");
}
Try accessing this:
arguments.callee.caller.name
Using this snippet, you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.
function submitForm(form, successFn){
if (form.getAttribute("id") != '' || form.getAttribute("id") != null){
var id = form.getAttribute("id");
} else {
console.log("Form id attribute was not set; the form cannot be serialized");
}
$.ajax({
type: form.method,
url: form.action,
data: $(id).serializeArray(),
dataType: "json",
success: successFn,
//error: errorFn(data)
});
}
And then just do:
var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
console.log("Form submitted");
});
I had same problem with Spring Boot 2.1.1 and JUnit 4
just added those annotations:
@RunWith( SpringRunner.class )
@SpringBootTest
and all went well.
For Junit 5:
@ExtendWith(SpringExtension.class)
You can use:
SELECT CONVERT(datetime, '24.04.2012', 103) AS Date
Reference: CAST and CONVERT (Transact-SQL)
Link only answers are not considered good practice on StackOverflow, but the advice that is given here should generally NOT be followed up.
I would like to revert to this great answer on a similar question. I quote:
Please stop suggesting to use 777. You're making your file writeable by everyone, which pretty much means you lose all security that the permission system was designed for. If you suggest this, think about the consequences it may have on a poorly configured webserver: it would become incredibly easy to "hack" the website, by overwriting the files. So, don't.
Below is what I do to copy a database from production env to my local env:
MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy
https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
static partial class MoreEnumerable
{
/// <summary>
/// Returns the set of elements in the first sequence which aren't
/// in the second sequence, according to a given key selector.
/// </summary>
/// <remarks>
/// This is a set operation; if multiple elements in <paramref name="first"/> have
/// equal keys, only the first such element is returned.
/// This operator uses deferred execution and streams the results, although
/// a set of keys from <paramref name="second"/> is immediately selected and retained.
/// </remarks>
/// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="first">The sequence of potentially included elements.</param>
/// <param name="second">The sequence of elements whose keys may prevent elements in
/// <paramref name="first"/> from being returned.</param>
/// <param name="keySelector">The mapping from source element to key.</param>
/// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
/// any element in <paramref name="second"/>.</returns>
public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector)
{
return ExceptBy(first, second, keySelector, null);
}
/// <summary>
/// Returns the set of elements in the first sequence which aren't
/// in the second sequence, according to a given key selector.
/// </summary>
/// <remarks>
/// This is a set operation; if multiple elements in <paramref name="first"/> have
/// equal keys, only the first such element is returned.
/// This operator uses deferred execution and streams the results, although
/// a set of keys from <paramref name="second"/> is immediately selected and retained.
/// </remarks>
/// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="first">The sequence of potentially included elements.</param>
/// <param name="second">The sequence of elements whose keys may prevent elements in
/// <paramref name="first"/> from being returned.</param>
/// <param name="keySelector">The mapping from source element to key.</param>
/// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
/// If null, the default equality comparer for <c>TSource</c> is used.</param>
/// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
/// any element in <paramref name="second"/>.</returns>
public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> keyComparer)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (keySelector == null) throw new ArgumentNullException("keySelector");
return ExceptByImpl(first, second, keySelector, keyComparer);
}
private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> keyComparer)
{
var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
foreach (var element in first)
{
var key = keySelector(element);
if (keys.Contains(key))
{
continue;
}
yield return element;
keys.Add(key);
}
}
}
}
delete from t
where id in (1, 4, 6, 7)
the easiest way to avoid slow retrieval of the remote WSDL when you instantiate your SEI is to not retrieve the WSDL from the remote service endpoint at runtime.
this means that you have to update your local WSDL copy any time the service provider makes an impacting change, but it also means that you have to update your local copy any time the service provider makes an impacting change.
When I generate my client stubs, I tell the JAX-WS runtime to annotate the SEI in such a way that it will read the WSDL from a pre-determined location on the classpath. by default the location is relative to the package location of the Service SEI
<wsimport
sourcedestdir="${dao.helter.dir}/build/generated"
destdir="${dao.helter.dir}/build/bin/generated"
wsdl="${dao.helter.dir}/src/resources/schema/helter/helterHttpServices.wsdl"
wsdlLocation="./wsdl/helterHttpServices.wsdl"
package="com.helter.esp.dao.helter.jaxws"
>
<binding dir="${dao.helter.dir}/src/resources/schema/helter" includes="*.xsd"/>
</wsimport>
<copy todir="${dao.helter.dir}/build/bin/generated/com/helter/esp/dao/helter/jaxws/wsdl">
<fileset dir="${dao.helter.dir}/src/resources/schema/helter" includes="*" />
</copy>
the wsldLocation attribute tells the SEI where is can find the WSDL, and the copy makes sure that the wsdl (and supporting xsd.. etc..) is in the correct location.
since the location is relative to the SEI's package location, we create a new sub-package (directory) called wsdl, and copy all the wsdl artifacts there.
all you have to do at this point is make sure you include all *.wsdl, *.xsd in addition to all *.class when you create your client-stub artifact jar file.
(in case your curious, the @webserviceClient annotation is where this wsdl location is actually set in the java code
@WebServiceClient(name = "httpServices", targetNamespace = "http://www.helter.com/schema/helter/httpServices", wsdlLocation = "./wsdl/helterHttpServices.wsdl")
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
pip install django-truncate
settings.py
file:INSTALLED_APPS = [
...
'django_truncate',
]
python manage.py truncate --apps app_name --models table_name