Go to obj folder in you app folder, then Debug. In there delete the manifest file and build again. It worked for me.
You can also look at filever.exe, which can be downloaded as part of the Windows XP SP2 Support Tools package - only 4.7MB of download.
if you do not want to create a custom class loader. You can read the jar file stream. And transfer it to a File object. Then you can get the url of the File. Send it to the URLClassLoader, you can load the jar file as you want. sample:
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("example"+ ".jar");
final File tempFile = File.createTempFile("temp", ".jar");
tempFile.deleteOnExit(); // you can delete the temp file or not
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(resourceAsStream, out);
}
IOUtils.closeQuietly(resourceAsStream);
URL url = tempFile.toURI().toURL();
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});
urlClassLoader.loadClass()
...
TLDR : check if packaging
element inside the pom.xml file is set to jar
.
Like this - <packaging>jar</packaging>
. If it set to pom
your target folder will not be created even after you Clean and Build your project and Maven executable won't be able to find .class
files (because they don't exist), after which you get Error: Could not find or load main class your.package.name.MainClass
After creating a Maven POM project in Netbeans 8.2, the content of the default pom.xml
file are as follows -
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myproject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Here packaging
element is set to pom
. Hence the target
directory is not created as we are not enabling maven to package our application as a jar
file. Change it to jar
then Clean and Build your project, you should see target directory created at root location. Now you should be able to run that java file with main method.
When no packaging is declared, Maven assumes the packaging as jar
. Other core packaging values are pom
, war
, maven-plugin
, ejb
, ear
, rar
. These define the goals that execute on each corresponsding build life-cycle phase of that package. See more here
I've run into a similar issue and, although I know it isn't the cause the OP had, I'll post it here so that if someone else runs across this problem in the future an answer will be available.
If you add a class before the designer class you will get a MissingManifestResourceException
exception at runtime (no compile time error or warning) because
Visual Studio requires that designers use the first class in the file.
For (slightly) more information see this post.
Create the folder META-INF
and the file MANIFEST.MF
in that folder with this content:
Manifest-Version: 1.0
Class-Path: .
Main-Class: [YOUR_MAIN_CLASS]
Then compile including that manifest file.
Before you call setContentView()
, call setTheme(android.R.style...)
and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).
Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)
This is a problem still as of 7.2.1 . Create a library cause you do not know what it will do if you make it an application & you are screwed.
Did find how to fix this though. Edit nbproject/project.properties
, change the following line to false as shown:
mkdist.disabled=false
After this you can change the main class in properties and it will be reflected in manifest.
If your class path is fully specified in manifest, maybe you need the last version of java runtime environment. My problem fixed when i reinstalled the jre 8.
You have to convert the type of your return value of the method to the Generic type which you pass to the method during calling.
public static T values<T>()
{
Random random = new Random();
int number = random.Next(1, 4);
return (T)Convert.ChangeType(number, typeof(T));
}
You need pass a type that is type casteable for the value you return through that method.
If you would want to return a value which is not type casteable to the generic type you pass, you might have to alter the code or make sure you pass a type that is casteable for the return value of method. So, this approach is not reccomended.
if you want to encode or decode an array from or to JSON you can use these functions
$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);
json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string
with json_decode you can take the results from the API and only output what you want, for example:
echo $myArray['payload']['ign'];
Converting anything to a string should either 1) allocate the resultant string or 2) pass in a char *
destination and size. Sample code below:
Both work for all int
including INT_MIN
. They provide a consistent output unlike snprintf()
which depends on the current locale.
Method 1: Returns NULL
on out-of-memory.
#define INT_DECIMAL_STRING_SIZE(int_type) ((CHAR_BIT*sizeof(int_type)-1)*10/33+3)
char *int_to_string_alloc(int x) {
int i = x;
char buf[INT_DECIMAL_STRING_SIZE(int)];
char *p = &buf[sizeof buf - 1];
*p = '\0';
if (i >= 0) {
i = -i;
}
do {
p--;
*p = (char) ('0' - i % 10);
i /= 10;
} while (i);
if (x < 0) {
p--;
*p = '-';
}
size_t len = (size_t) (&buf[sizeof buf] - p);
char *s = malloc(len);
if (s) {
memcpy(s, p, len);
}
return s;
}
Method 2: It returns NULL
if the buffer was too small.
static char *int_to_string_helper(char *dest, size_t n, int x) {
if (n == 0) {
return NULL;
}
if (x <= -10) {
dest = int_to_string_helper(dest, n - 1, x / 10);
if (dest == NULL) return NULL;
}
*dest = (char) ('0' - x % 10);
return dest + 1;
}
char *int_to_string(char *dest, size_t n, int x) {
char *p = dest;
if (n == 0) {
return NULL;
}
n--;
if (x < 0) {
if (n == 0) return NULL;
n--;
*p++ = '-';
} else {
x = -x;
}
p = int_to_string_helper(p, n, x);
if (p == NULL) return NULL;
*p = 0;
return dest;
}
[Edit] as request by @Alter Mann
(CHAR_BIT*sizeof(int_type)-1)*10/33+3
is at least the maximum number of char
needed to encode the some signed integer type as a string consisting of an optional negative sign, digits, and a null character..
The number of non-sign bits in a signed integer is no more than CHAR_BIT*sizeof(int_type)-1
. A base-10 representation of a n
-bit binary number takes up to n*log10(2) + 1
digits. 10/33
is slightly more than log10(2)
. +1 for the sign char
and +1 for the null character. Other fractions could be used like 28/93.
Method 3: If one wants to live on the edge and buffer overflow is not a concern, a simple C99 or later solution follows which handles all int
.
#include <limits.h>
#include <stdio.h>
static char *itoa_simple_helper(char *dest, int i) {
if (i <= -10) {
dest = itoa_simple_helper(dest, i/10);
}
*dest++ = '0' - i%10;
return dest;
}
char *itoa_simple(char *dest, int i) {
char *s = dest;
if (i < 0) {
*s++ = '-';
} else {
i = -i;
}
*itoa_simple_helper(s, i) = '\0';
return dest;
}
int main() {
char s[100];
puts(itoa_simple(s, 0));
puts(itoa_simple(s, 1));
puts(itoa_simple(s, -1));
puts(itoa_simple(s, 12345));
puts(itoa_simple(s, INT_MAX-1));
puts(itoa_simple(s, INT_MAX));
puts(itoa_simple(s, INT_MIN+1));
puts(itoa_simple(s, INT_MIN));
}
Sample output
0
1
-1
12345
2147483646
2147483647
-2147483647
-2147483648
Use either float or inline elements:
Example JSBIN
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div>float example</div>
<div><div style="float:left">Floating left content</div><div>Some content</div></div>
<div>inline block example</div>
<div><div style="display:inline-block">Some content</div><div style="display:inline-block">Next content</div></div>
</body>
</html>
Here is the modified script which i took from http://www.foliotek.com/devblog/sql-server-optimization-with-index-rebuilding which i found useful to post here. Although it uses a cursor and i know what is the main problem with cursors it can be easily converted to a cursor-less version.
It is well-documented and you can easily read through it and modify to your needs.
IF OBJECT_ID('tempdb..#work_to_do') IS NOT NULL
DROP TABLE tempdb..#work_to_do
BEGIN TRY
--BEGIN TRAN
use yourdbname
-- Ensure a USE statement has been executed first.
SET NOCOUNT ON;
DECLARE @objectid INT;
DECLARE @indexid INT;
DECLARE @partitioncount BIGINT;
DECLARE @schemaname NVARCHAR(130);
DECLARE @objectname NVARCHAR(130);
DECLARE @indexname NVARCHAR(130);
DECLARE @partitionnum BIGINT;
DECLARE @partitions BIGINT;
DECLARE @frag FLOAT;
DECLARE @pagecount INT;
DECLARE @command NVARCHAR(4000);
DECLARE @page_count_minimum SMALLINT
SET @page_count_minimum = 50
DECLARE @fragmentation_minimum FLOAT
SET @fragmentation_minimum = 30.0
-- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function
-- and convert object and index IDs to names.
SELECT object_id AS objectid ,
index_id AS indexid ,
partition_number AS partitionnum ,
avg_fragmentation_in_percent AS frag ,
page_count AS page_count
INTO #work_to_do
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL,
'LIMITED')
WHERE avg_fragmentation_in_percent > @fragmentation_minimum
AND index_id > 0
AND page_count > @page_count_minimum;
IF CURSOR_STATUS('global', 'partitions') >= -1
BEGIN
PRINT 'partitions CURSOR DELETED' ;
CLOSE partitions
DEALLOCATE partitions
END
-- Declare the cursor for the list of partitions to be processed.
DECLARE partitions CURSOR LOCAL
FOR
SELECT *
FROM #work_to_do;
-- Open the cursor.
OPEN partitions;
-- Loop through the partitions.
WHILE ( 1 = 1 )
BEGIN;
FETCH NEXT
FROM partitions
INTO @objectid, @indexid, @partitionnum, @frag, @pagecount;
IF @@FETCH_STATUS < 0
BREAK;
SELECT @objectname = QUOTENAME(o.name) ,
@schemaname = QUOTENAME(s.name)
FROM sys.objects AS o
JOIN sys.schemas AS s ON s.schema_id = o.schema_id
WHERE o.object_id = @objectid;
SELECT @indexname = QUOTENAME(name)
FROM sys.indexes
WHERE object_id = @objectid
AND index_id = @indexid;
SELECT @partitioncount = COUNT(*)
FROM sys.partitions
WHERE object_id = @objectid
AND index_id = @indexid;
SET @command = N'ALTER INDEX ' + @indexname + N' ON '
+ @schemaname + N'.' + @objectname + N' REBUILD';
IF @partitioncount > 1
SET @command = @command + N' PARTITION='
+ CAST(@partitionnum AS NVARCHAR(10));
EXEC (@command);
--print (@command); //uncomment for testing
PRINT N'Rebuilding index ' + @indexname + ' on table '
+ @objectname;
PRINT N' Fragmentation: ' + CAST(@frag AS VARCHAR(15));
PRINT N' Page Count: ' + CAST(@pagecount AS VARCHAR(15));
PRINT N' ';
END;
-- Close and deallocate the cursor.
CLOSE partitions;
DEALLOCATE partitions;
-- Drop the temporary table.
DROP TABLE #work_to_do;
--COMMIT TRAN
END TRY
BEGIN CATCH
--ROLLBACK TRAN
PRINT 'ERROR ENCOUNTERED:' + ERROR_MESSAGE()
END CATCH
My team just ran into this problem within our build environment. The issue was due to a difference in the <HintPath> element of the .csproj file.
Our common assembly had a correct relative path to the directory containing our reference assemblies. The dependent assembly had a path from a former directory structure. The solution successfully compiled on dev machines as the GAC resolved the dependent's reference to the correct version installed in C:\Program Files. The build environment had a legacy install of the assembly (even though it should have had none) that it fell back to and thus the error. Updating the <HintPath> in a text editor corrected the problem.
Thread.isAlive()
What your looking for is Reverse Geo Coding. Have a look at this example here. https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
git push origin +7f6d03:master
This will revert your repo to mentioned commit number
It turns out that OpenSSL is compiled and enabled in php 5.3 of XAMPP 1.7.2 and so no longer requires a separate extension dll.
However, you STILL need to enable it in your PHP.ini file the line extension=php_openssl.dll
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
Star in version (like "2.10.3.*") - it is simple, but the numbers are too large
AutoBuildVersion - looks great but its dont work on my VS2010.
@DrewChapin's script works, but I can not in my studio set different modes for Debug pre-build event and Release pre-build event.
so I changed the script a bit... commamd:
"%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\10.0\TextTransform.exe" -a !!$(ConfigurationName)!1 "$(ProjectDir)Properties\AssemblyInfo.tt"
and script (this works to the "Debug" and "Release" configurations):
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
int incRevision = 1;
int incBuild = 1;
try { incRevision = Convert.ToInt32(this.Host.ResolveParameterValue("","","Debug"));} catch( Exception ) { incBuild=0; }
try { incBuild = Convert.ToInt32(this.Host.ResolveParameterValue("","","Release")); } catch( Exception ) { incRevision=0; }
try {
string currentDirectory = Path.GetDirectoryName(Host.TemplateFile);
string assemblyInfo = File.ReadAllText(Path.Combine(currentDirectory,"AssemblyInfo.cs"));
Regex pattern = new Regex("AssemblyVersion\\(\"\\d+\\.\\d+\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
MatchCollection matches = pattern.Matches(assemblyInfo);
revision = Convert.ToInt32(matches[0].Groups["revision"].Value) + incRevision;
build = Convert.ToInt32(matches[0].Groups["build"].Value) + incBuild;
}
catch( Exception ) { }
#>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Game engine. Keys: F2 (Debug trace), F4 (Fullscreen), Shift+Arrows (Move view). ")]
[assembly: AssemblyProduct("Game engine")]
[assembly: AssemblyDescription("My engine for game")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © Name 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]
// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("00000000-0000-0000-0000-000000000000")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.1.<#= this.revision #>.<#= this.build #>")]
[assembly: AssemblyFileVersion("0.1.<#= this.revision #>.<#= this.build #>")]
<#+
int revision = 0;
int build = 0;
#>
i found a way that's works:
axios
.delete(URL, {
params: { id: 'IDDataBase'},
headers: {
token: 'TOKEN',
},
})
.then(function (response) {
})
.catch(function (error) {
console.log(error);
});
I hope this work for you too.
Create docker image with openssh-server
preinstalled:
FROM ubuntu:16.04
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:screencast' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
Build the image using:
$ docker build -t eg_sshd .
Run a test_sshd
container:
$ docker run -d -P --name test_sshd eg_sshd
$ docker port test_sshd 22
0.0.0.0:49154
Ssh to your container:
$ ssh [email protected] -p 49154
# The password is ``screencast``.
root@f38c87f2a42d:/#
Source: https://docs.docker.com/engine/examples/running_ssh_service/#build-an-eg_sshd-image
Use the flex-grow
property to make a flex item consume free space on the main axis.
This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.
A common example is flex-grow: 1
or, using the shorthand property, flex: 1
.
Hence, instead of width: 96%
on your div, use flex: 1
.
You wrote:
So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.
The squashing of the fixed-width div is related to another flex property: flex-shrink
By default, flex items are set to flex-shrink: 1
which enables them to shrink in order to prevent overflow of the container.
To disable this feature use flex-shrink: 0
.
For more details see The flex-shrink
factor section in the answer here:
Learn more about flex alignment along the main axis here:
Learn more about flex alignment along the cross axis here:
As posted by 'Dan' in a similar thread, there is a possible fix if you're not using a sprite:
How do I make background-size work in IE?
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";
However, this scales the entire image to fit in the allocated area. So if your using a sprite, this may cause issues.
Caution
The filter has a flaw, any links inside the allocated area are no longer clickable.
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
Simple one, add before Main
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
Code inside Main/Method:
string className = "IEFrame";
string windowName = "New Tab - Windows Internet Explorer";
IntPtr IE = FindWindow(className, windowName);
if (IE == IntPtr.Zero)
{
return;
}
SetForegroundWindow(IE);
InputSimulator.SimulateKeyPress(VirtualKeyCode.F5);
Note:
Add InputSimulator as reference. To download Click here
To find Class & Window name, use WinSpy++. To download Click here
Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern desktop OS's.
Edit: Even so, I would strongly caution against making this assumption in your code. If you're going to write something that absolutely has to have a pointers of a certain size, you'd better check it!
Function pointers are a different story -- see Jens' answer for more info.
Pyflakes does what you ask, it just checks the syntax. From the docs:
Pyflakes makes a simple promise: it will never complain about style, and it will try very, very hard to never emit false positives.
Pyflakes is also faster than Pylint or Pychecker. This is largely because Pyflakes only examines the syntax tree of each file individually.
To install and use:
$ pip install pyflakes
$ pyflakes yourPyFile.py
You can get them using the Query String:
$idArray = explode('&',$_SERVER["QUERY_STRING"]);
This will give you:
$idArray[0] = "id=1";
$idArray[1] = "id=2";
$idArray[2] = "id=3";
Then
foreach ($idArray as $index => $avPair)
{
list($ignore, $value) = explode("=", $avPair);
$id[$index] = $value;
}
This will give you
$id[0] = "1";
$id[1] = "2";
$id[2] = "3";
Here is the simple and single line of code
For this use the SQL Inbuild RAND() function.
Here is the formula to generate random number between two number (RETURN INT Range)
Here a is your First Number (Min) and b is the Second Number (Max) in Range
SELECT FLOOR(RAND()*(b-a)+a)
Note: You can use CAST or CONVERT function as well to get INT range number.
( CAST(RAND()*(25-10)+10 AS INT) )
Example:
SELECT FLOOR(RAND()*(25-10)+10);
Here is the formula to generate random number between two number (RETURN DECIMAL Range)
SELECT RAND()*(b-a)+a;
Example:
SELECT RAND()*(25-10)+10;
More details check this: https://www.techonthenet.com/sql_server/functions/rand.php
I would have thought this would be the most bootstrap-esque way of doing things:
<button type='button' class='btn btn-success col-xs-12'> First buttton baby </button>
All I'm doing is adding the class col-xs-12
to the button.
And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.
moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
You are correct in that your list contains a reference to the original dictionary.
a.append(b.copy())
should do the trick.
Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b)
, which makes a deep copy.
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
.
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).
Example usage:
require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
I think it's very fun to come up with ways to solve this. Below are some.
(All functions below assume argument is a single character. Change to n[0]
to enforce it)
function isCharDigit(n){
return !!n.trim() && n > -1;
}
function isCharDigit(n){
return !!n.trim() && n*0==0;
}
function isCharDigit(n){
return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
}
var isCharDigit = (function(){
var a = [1,1,1,1,1,1,1,1,1,1];
return function(n){
return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
}
})();
function isCharDigit(n){
return !!n.trim() && !isNaN(+n);
}
var str = ' 90ABcd#?:.+', char;
for( char of str )
console.log( char, isCharDigit(char) );
It seems to me that the answer to this question is (at least now) clearly documented on the Safari HTML5 docs:
User Control of Downloads Over Cellular Networks
In Safari on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and autoplay are disabled. No data is loaded until the user initiates it. This means the JavaScript play() and load() methods are also inactive until the user initiates playback, unless the play() or load() method is triggered by user action. In other words, a user-initiated Play button works, but an onLoad="play()" event does not.
This plays the movie: <input type="button" value="Play" onClick="document.myMovie.play()">
This does nothing on iOS: <body onLoad="document.myMovie.play()">
Add this alias to your .gitconfig:
[alias]
lg = log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\n--abbrev-commit --date=relative
And use the command like this:
> git lg
> git lg -- filename
The output will look almost exactly the same as the gitk output. Enjoy.
SELECT
u . *
FROM
room u
JOIN
facilities_r fu ON fu.id_uc = u.id_uc
AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc
You must use OR here, not AND.
Since id_fu cannot be equal to 4 and 3, both at once.
If you have the .dSYM and the .crash file in the same sub-folder, these are the steps you can take:
$ atos -arch arm64 -o TheElements.app.dSYM/Contents/Resources/DWARF/TheElements -l 0x1000e4000 0x00000001000effdc
-[AtomicElementViewController myTransitionDidStop:finished:context:]
Authoritative source: https://developer.apple.com/library/content/technotes/tn2151/_index.html#//apple_ref/doc/uid/DTS40008184-CH1-SYMBOLICATE_WITH_ATOS
Like andynormancx' post, use this (if you're working in an Unix environment):
scriptname > /dev/null
Or you can use this (if you're working in a Windows environment):
scriptname > nul
Code you have is right way to do it if you want to do using JDK without any external libraries. There is no simple "one-liner" that you could use in JDK.
If you can use external libs, I recommend that you look into org.apache.commons.lang.StringUtils class in Apache Commons library.
An example of usage:
List<String> list = Arrays.asList("Bill", "Bob", "Steve");
String joinedResult = StringUtils.join(list, " and ");
I figured out that this behaves like a mousedown event:
button:active:hover {}
Using OVER()
and LIMIT 1
:
SELECT COUNT(1) OVER()
FROM posts
INNER JOIN votes ON votes.post_id = posts.id
GROUP BY posts.id
LIMIT 1;
It looks like there is an extra curly bracket in the code.
function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}
extending accepted answer with jquery
what if you want to add more canvas?, this jquery.each answer it
responsiveCanvas(); //first init
$(window).resize(function(){
responsiveCanvas(); //every resizing
stage.update(); //update the canvas, stage is object of easeljs
});
function responsiveCanvas(target){
$(canvas).each(function(e){
var parentWidth = $(this).parent().outerWidth();
var parentHeight = $(this).parent().outerHeight();
$(this).attr('width', parentWidth);
$(this).attr('height', parentHeight);
console.log(parentWidth);
})
}
it will do all the job for you
why we dont set the width
or the height
via css or style? because it will stretch your canvas instead of make it into expecting size
A pure CSS
solution (#content { min-height: 100%; }
) will work in a lot of cases, but not in all of them - especially IE6 and IE7.
Unfortunately, you will need to resort to a JavaScript solution in order to get the desired behavior.
This can be done by calculating the desired height for your content <div>
and setting it as a CSS property in a function:
function resizeContent() {
var contentDiv = document.getElementById('content');
var headerDiv = document.getElementById('header');
// This may need to be done differently on IE than FF, but you get the idea.
var viewPortHeight = window.innerHeight - headerDiv.clientHeight;
contentDiv.style.height =
Math.max(viewportHeight, contentDiv.clientHeight) + 'px';
}
You can then set this function as a handler for onLoad
and onResize
events:
<body onload="resizeContent()" onresize="resizeContent()">
. . .
</body>
Use:
int myInt = 2934;
string myHex = myInt.ToString("X"); // Gives you hexadecimal
int myNewInt = Convert.ToInt32(myHex, 16); // Back to int again.
See How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide) for more information and examples.
You can just call it.
function test(){
print_r(func_get_args());
}
test("blah");
test("blah","blah");
Output:
Array ( [0] => blah ) Array ( [0] => blah [1] => blah )
Here is a code fragment
soup = BeautifulSoup(:"index.html")
titleList = soup.findAll('title')
divList = soup.findAll('div', attrs={ "class" : "article story"})
As you can see I find all tags and then I find all tags with class="article" inside
This property:
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false);
...can be used to have no:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
However, I wouldn't consider this best practice.
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("th:href", "@{/filepath}")
fileref.setAttribute("href", "/filepath")
I'm using thymeleaf and this is work fine. Thanks
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
In Magento 1.9.4.0 and maybe all versions in 1.x use:
Mage::getStoreConfig('general/store_information/address');
and the following params, it depends what you want to get:
You have to create a password file: see http://www.postgresql.org/docs/9.0/interactive/libpq-pgpass.html for more info.
See here, this can help you:
public static boolean setObject(Context context, Object o) {
Field[] fields = o.getClass().getFields();
SharedPreferences sp = context.getSharedPreferences(o.getClass()
.getName(), Context.MODE_PRIVATE);
Editor editor = sp.edit();
for (int i = 0; i < fields.length; i++) {
Class<?> type = fields[i].getType();
if (isSingle(type)) {
try {
final String name = fields[i].getName();
if (type == Character.TYPE || type.equals(String.class)) {
Object value = fields[i].get(o);
if (null != value)
editor.putString(name, value.toString());
} else if (type.equals(int.class)
|| type.equals(Short.class))
editor.putInt(name, fields[i].getInt(o));
else if (type.equals(double.class))
editor.putFloat(name, (float) fields[i].getDouble(o));
else if (type.equals(float.class))
editor.putFloat(name, fields[i].getFloat(o));
else if (type.equals(long.class))
editor.putLong(name, fields[i].getLong(o));
else if (type.equals(Boolean.class))
editor.putBoolean(name, fields[i].getBoolean(o));
} catch (IllegalAccessException e) {
LogUtils.e(TAG, e);
} catch (IllegalArgumentException e) {
LogUtils.e(TAG, e);
}
} else {
// FIXME ???????
}
}
return editor.commit();
}
<div id='myInputF2'> YES ITS DIV TEXT TO COPY </div>
<script>
function myFunctionF2() {
str = document.getElementById('myInputF2').innerHTML;
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
alert('Copied the text:' + el.value);
};
</script>
more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f
I suggest
l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)
Check this demo.
Do everything in the inline of UL tag
<ul class="dropdown-menu scrollable-menu" role="menu" style="height: auto;max-height: 200px; overflow-x: hidden;">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li><a href="#">Action</a></li>
..
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
</ul>
In adition to the other answers mentioning the Tasks view:
It is also possible to filter the Tasks that are listed to only show the TODOs that contain the text // TODO Auto-generated method stub
.
To achieve this you can click on the Filters... button in the top right of the Tasks View and define custom filters like this:
This way it's a bit easier and faster to find only some of the TODOs in the project in the Tasks View, and you don't have to search for the text in all files using the eclipse search tool (which can take quite some time).
Try to add type of configuration in dependency line. For example:
implementation project(path: ':some_module', **configuration: 'default'**)`
To dump large tables, you should combine the --single-transaction option with --quick.
http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction
I think there are two different things here. The first one is that normal SSH authentication requires the user to put the account's password (where the account password will be authenticated against different methods, depending on the sshd configuration).
You can avoid putting that password using certificates. With certificates you still have to put a password, but this time is the password of your private key (that's independent of the account's password).
To do this you can follow the instructions pointed out by steveth45:
If you want to avoid putting the certificate's password every time then you can use ssh-agent, as pointed out by DigitalRoss
The exact way you do this depends on Unix vs Windows, but essentially you need to run ssh-agent in the background when you log in, and then the first time you log in, run ssh-add to give the agent your passphrase. All ssh-family commands will then consult the agent and automatically pick up your passphrase.
Start here: man ssh-agent.
The only problem of ssh-agent is that, on *nix at least, you have to put the certificates password on every new shell. And then the certificate is "loaded" and you can use it to authenticate against an ssh server without putting any kind of password. But this is on that particular shell.
With keychain you can do the same thing as ssh-agent but "system-wide". Once you turn on your computer, you open a shell and put the password of the certificate. And then, every other shell will use that "loaded" certificate and your password will never be asked again until you restart your PC.
Gnome has a similar application, called Gnome Keyring that asks for your certificate's password the first time you use it and then it stores it securely so you won't be asked again.
Here's a simpler solution that worked for me:
In XCode5, double-click on your app's target. This brings up the Info pane for the target. In the "Build Settings" section, check the "code signing" section for any old profiles and replace with the correct one. update the value of "code signing identity" and "provisioning profile"
I had the same problem and I found out that it was the nodemon problem. First I was using this script to start my process:
{"dev": "nodemon -r dotenv/config app.js"}
the app boots correctly, but as soon as any file changes, nodemon can't restart it. In the meantime, the app still continues to run in the background. If I do Ctrl+C, it quits, but there's no more process on port 3000, so killing it by port fuser -k 3000/tcp doesn't do anything.
And, I was using .env port in app.js file.
const port = process.env.PORT || 3000;
So, I changed the port value to 3000 only and it worked.
const port = 3000;
I had to find another way to load .env file, but this solved the issue for me. Hope that helps.
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
The changelog is sloppily worded. from __future__ import absolute_import
does not care about whether something is part of the standard library, and import string
will not always give you the standard-library module with absolute imports on.
from __future__ import absolute_import
means that if you import string
, Python will always look for a top-level string
module, rather than current_package.string
. However, it does not affect the logic Python uses to decide what file is the string
module. When you do
python pkg/script.py
pkg/script.py
doesn't look like part of a package to Python. Following the normal procedures, the pkg
directory is added to the path, and all .py
files in the pkg
directory look like top-level modules. import string
finds pkg/string.py
not because it's doing a relative import, but because pkg/string.py
appears to be the top-level module string
. The fact that this isn't the standard-library string
module doesn't come up.
To run the file as part of the pkg
package, you could do
python -m pkg.script
In this case, the pkg
directory will not be added to the path. However, the current directory will be added to the path.
You can also add some boilerplate to pkg/script.py
to make Python treat it as part of the pkg
package even when run as a file:
if __name__ == '__main__' and __package__ is None:
__package__ = 'pkg'
However, this won't affect sys.path
. You'll need some additional handling to remove the pkg
directory from the path, and if pkg
's parent directory isn't on the path, you'll need to stick that on the path too.
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
You have to properly understand what is a "stdafx.h", aka precompiled header. Other questions or Wikipedia will answer that. In many cases a precompiled header can be avoided, especially if your project is small and with few dependencies. In your case, as you probably started from a template project, it was used to include Windows.h
only for the _TCHAR
macro.
Then, precompiled header is usually a per-project file in Visual Studio world, so:
#include <stdafx.h>
to #include "stdafx.h"
. It is supposed to be a project local file, not to be resolved in include directories.Secondly: it's inadvisable to include the precompiled header in your own headers, to not clutter namespace of other source that can use your code as a library, so completely remove its inclusion in vector.h
.
You could do a preg_replace
like:
$new_url = preg_replace('/&?return=[^&]*/', '', $old_url);
public static bool isnull(object T)
{
return T == null ? true : false;
}
use:
isnull(object.check.it)
Conditional use:
isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;
Update (another way) updated 08/31/2017 and 01/25/2021. Thanks for the comment.
public static bool IsNull(object T)
{
return (bool)T ? true : false;
}
And for the records, you have my code on Github, go check it out: https://github.com/j0rt3g4/ValidateNull PS: This one is especially for you Chayim Friedman, don't use beta software assuming that is all true. Wait for final versions or use your own environment to test, before assuming true beta software without any sort of documentation or demonstration from your end.
@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs
sizes so you won't notice, but if you used anything else (e.g. col-sm
, col-md
, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/
.left-side {
background-color: blue;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.something {
height: 100%;
background-color: red;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.row {
background-color: green;
overflow: hidden;
}
I get the error in another situation, and here are the problem and the solution:
I have 2 classes derived from a same base class named LevledItem:
public partial class Team : LeveledItem
{
//Everything is ok here!
}
public partial class Story : LeveledItem
{
//Everything is ok here!
}
But in their DbContext, I copied some code but forget to change one of the class name:
public class MFCTeamDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Other codes here
modelBuilder.Entity<LeveledItem>()
.Map<Team>(m => m.Requires("Type").HasValue(ItemType.Team));
}
public class ProductBacklogDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Other codes here
modelBuilder.Entity<LeveledItem>()
.Map<Team>(m => m.Requires("Type").HasValue(ItemType.Story));
}
Yes, the second Map< Team> should be Map< Story>. And it cost me half a day to figure it out!
Run this command in project root directory.
1>. List of iPhone devices for found the connected Real Devices and Simulator. same as like adb devices command for android.
xcrun instruments -s devices
2>. Select device using this command which you want to run your app
Using Device Name
react-native run-ios --device "Kool's iPhone"
Using UDID
react-native run-ios --device --udid 0412e2c2******51699
wait and watch to run your app in specific devices - K00L ;)
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});
There are other solutions you can look into http://ngmodules.org/modules/ngUpload as discussed here file uploader integration for angularjs
Building up on @wasinger's reply above, in Bootstrap 4.5 I had to override not only the color variables but also the box-shadow
itself.
$input-focus-width: .2rem !default;
$input-focus-color: rgba($YOUR_COLOR, .25) !default;
$input-focus-border-color: rgba($YOUR_COLOR, .5) !default;
$input-focus-box-shadow: 0 0 0 $input-focus-width $input-focus-color !default;
If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.
I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.
Try:
Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff"
Then do another round of copy/paste of all the extensions (joined together with ;
as above) for "All graphics types":
Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff"
If you want to cut a string for a specifited length and add dots use
// Length to cut
var lengthToCut = 20;
// Sample text
var text = "The quick brown fox jumps over the lazy dog";
// We are getting 50 letters (0-50) from sample text
var cutted = text.substr(0, lengthToCut );
document.write(cutted+"...");
Or if you want to cut not by length but with words count use:
// Number of words to cut
var wordsToCut = 3;
// Sample text
var text = "The quick brown fox jumps over the lazy dog";
// We are splitting sample text in array of words
var wordsArray = text.split(" ");
// This will keep our generated text
var cutted = "";
for(i = 0; i < wordsToCut; i++)
cutted += wordsArray[i] + " "; // Add to cutted word with space
document.write(cutted+"...");
Good luck...
I tried to use dplyr::rename and I get an error:
occ_5d <- dplyr::rename(occ_5d, rowname='code_5d')
Error: Unknown column `code_5d`
Call `rlang::last_error()` to see a backtrace
I instead used the base R function which turns out to be quite simple and effective:
names(occ_5d)[1] = "code_5d"
you need to register it in index.android.js / index.ios.js
like this:
'use strict';
import {
AppRegistry
} from 'react-native';
import app from "./app";
AppRegistry.registerComponent('test', () => app);
It is an annotation to suppress compile warnings about unchecked generic operations (not exceptions), such as casts. It essentially implies that the programmer did not wish to be notified about these which he is already aware of when compiling a particular bit of code.
You can read more on this specific annotation here:
Additionally, Oracle provides some tutorial documentation on the usage of annotations here:
As they put it,
"The 'unchecked' warning can occur when interfacing with legacy code written before the advent of generics (discussed in the lesson titled Generics)."
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.logger.org.hibernate.hql.ast.AST=info
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.cache=info
log4j.logger.org.hibernate.jdbc=debug
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
log4j.appender.hb.layout.ConversionPattern=HibernateLog --> %d{HH:mm:ss} %-5p %c - %m%n
log4j.appender.hb.Threshold=TRACE
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
Some frameworks use persistence.xml
:
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
DataFrame.append
does not modify the DataFrame in place. You need to do df = df.append(...)
if you want to reassign it back to the original variable.
For a more aesthetic appearance :) can be:
left:-9999em;
top:-9999em;
position for .sNv2 .nav UL
can be replaced by z-index:-1
and z-index:1
for .sNv2 .nav LI:Hover UL
You just need to supply a password. You can do it within the same command line with the following syntax:
openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password]
You will then be prompted for a password to encrypt the private key in your output file. Include the "nodes" option in the line above if you want to export the private key unencrypted (plaintext):
openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password] -nodes
More info: http://www.openssl.org/docs/apps/pkcs12.html
Use position: relative on the parent element.
Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.
Also: Psyco vs. C++.
It's still a bad comparison, since noone would do the numbercrunchy stuff benchmarks tend to focus on in pure Python anyway. A better one would be comparing the performance of realistic applications, or C++ versus NumPy, to get an idea whether your program will be noticeably slower.
<div class="wrapper">test test test</div>
.wrapper{
width:100px;
height:100px;
margin:0 auto;
}
Your variable energies
probably has the wrong shape:
>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'
And that's what happens if you read columnar data using your approach:
>>> data
array([[ 1., 2., 3.],
[ 3., 4., 5.],
[ 5., 6., 7.],
[ 8., 9., 10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
[ 3.],
[ 5.],
[ 8.]])
Probably you can simply use
>>> data[:,0]
array([ 1., 3., 5., 8.])
instead.
(P.S. Your code looks like it's undecided about whether it's data
or elementdata
. I've assumed it's simply a typo.)
Ezward has already provided a good answer, but I noticed that one of the comments asks how it is used. For people like me who stumble across this question, I thought it would be useful to have a link to the official documentation on getters and setters on the Typescript website as that explains it well, will hopefully always stay up-to-date as changes are made, and shows example usage:
http://www.typescriptlang.org/docs/handbook/classes.html
In particular, for those not familiar with it, note that you don't incorporate the word 'get' into a call to a getter (and similarly for setters):
var myBar = myFoo.getBar(); // wrong
var myBar = myFoo.get('bar'); // wrong
You should simply do this:
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set) (false is correct too obviously!)
given a class like:
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
then the 'bar' getter for the private '_bar' property will be called.
Simplest example would consist of:
Composing XML SOAP message similar to this
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetInfoByZIP xmlns="http://www.webserviceX.NET">
<USZip>string</USZip>
</GetInfoByZIP>
</soap:Body>
</soap:Envelope>
POSTing message to webservice url using XHR
Parsing webservice's XML SOAP response similar to this
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
<GetInfoByZIPResult>
<NewDataSet xmlns="">
<Table>
<CITY>...</CITY>
<STATE>...</STATE>
<ZIP>...</ZIP>
<AREA_CODE>...</AREA_CODE>
<TIME_ZONE>...</TIME_ZONE>
</Table>
</NewDataSet>
</GetInfoByZIPResult>
</GetInfoByZIPResponse>
</soap:Body>
</soap:Envelope>
Presenting results to user.
But it's a lot of hassle without external JavaScript libraries.
For anyone looking for a solution on a modern stack:
import jsonp from 'jsonp';
import queryString from 'query-string';
// formData being an object with your form data like:
// { EMAIL: '[email protected]' }
jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
console.log(err);
console.log(data);
});
During the installation you got a message
Composer successfully installed to: ...
this indicates where Composer was installed. But you might also search for the file composer.phar
on your system.
Then simply:
composer.phar
./home/<user>/.composer
C:\Users\<username>\AppData\Roaming\Composer
That's it.
Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.
It worked for me so here's hoping it helps someone else, too.
You have indented part of your code in settings.py:
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
#'django.contrib.admindocs',
'tinymce',
'sorl.thumbnail',
'south',
'django_facebook',
'djcelery',
'devserver',
'main',
Therefore, it is giving you an error.
I took another approach inspired by @john-rees above - especially when his approach started to fail for me at some point. Basically recurse the subtree and sort files by their path-length - delete from longest to the shortest
Get-ChildItem $tfsLocalPath -Recurse | #Find all children
Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} | #Calculate the length of their path
Sort-Object PathLength -Descending | #sort by path length descending
%{ Get-Item -LiteralPath $_.FullName } |
Remove-Item -Force
Regarding the -LiteralPath magic, here's another gotchya that may be hitting you: https://superuser.com/q/212808
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:
ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************ TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif
If you use the library "JQuery", you can call this:
Tab:
$.tabNext();
Shift+Tab:
$.tabPrev();
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script>
(function($){
'use strict';
/**
* Focusses the next :focusable element. Elements with tabindex=-1 are focusable, but not tabable.
* Does not take into account that the taborder might be different as the :tabbable elements order
* (which happens when using tabindexes which are greater than 0).
*/
$.focusNext = function(){
selectNextTabbableOrFocusable(':focusable');
};
/**
* Focusses the previous :focusable element. Elements with tabindex=-1 are focusable, but not tabable.
* Does not take into account that the taborder might be different as the :tabbable elements order
* (which happens when using tabindexes which are greater than 0).
*/
$.focusPrev = function(){
selectPrevTabbableOrFocusable(':focusable');
};
/**
* Focusses the next :tabable element.
* Does not take into account that the taborder might be different as the :tabbable elements order
* (which happens when using tabindexes which are greater than 0).
*/
$.tabNext = function(){
selectNextTabbableOrFocusable(':tabbable');
};
/**
* Focusses the previous :tabbable element
* Does not take into account that the taborder might be different as the :tabbable elements order
* (which happens when using tabindexes which are greater than 0).
*/
$.tabPrev = function(){
selectPrevTabbableOrFocusable(':tabbable');
};
function tabIndexToInt(tabIndex){
var tabIndexInded = parseInt(tabIndex);
if(isNaN(tabIndexInded)){
return 0;
}else{
return tabIndexInded;
}
}
function getTabIndexList(elements){
var list = [];
for(var i=0; i<elements.length; i++){
list.push(tabIndexToInt(elements.eq(i).attr("tabIndex")));
}
return list;
}
function selectNextTabbableOrFocusable(selector){
var selectables = $(selector);
var current = $(':focus');
// Find same TabIndex of remainder element
var currentIndex = selectables.index(current);
var currentTabIndex = tabIndexToInt(current.attr("tabIndex"));
for(var i=currentIndex+1; i<selectables.length; i++){
if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === currentTabIndex){
selectables.eq(i).focus();
return;
}
}
// Check is last TabIndex
var tabIndexList = getTabIndexList(selectables).sort(function(a, b){return a-b});
if(currentTabIndex === tabIndexList[tabIndexList.length-1]){
currentTabIndex = -1;// Starting from 0
}
// Find next TabIndex of all element
var nextTabIndex = tabIndexList.find(function(element){return currentTabIndex<element;});
for(var i=0; i<selectables.length; i++){
if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === nextTabIndex){
selectables.eq(i).focus();
return;
}
}
}
function selectPrevTabbableOrFocusable(selector){
var selectables = $(selector);
var current = $(':focus');
// Find same TabIndex of remainder element
var currentIndex = selectables.index(current);
var currentTabIndex = tabIndexToInt(current.attr("tabIndex"));
for(var i=currentIndex-1; 0<=i; i--){
if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === currentTabIndex){
selectables.eq(i).focus();
return;
}
}
// Check is last TabIndex
var tabIndexList = getTabIndexList(selectables).sort(function(a, b){return b-a});
if(currentTabIndex <= tabIndexList[tabIndexList.length-1]){
currentTabIndex = tabIndexList[0]+1;// Starting from max
}
// Find prev TabIndex of all element
var prevTabIndex = tabIndexList.find(function(element){return element<currentTabIndex;});
for(var i=selectables.length-1; 0<=i; i--){
if(tabIndexToInt(selectables.eq(i).attr("tabIndex")) === prevTabIndex){
selectables.eq(i).focus();
return;
}
}
}
/**
* :focusable and :tabbable, both taken from jQuery UI Core
*/
$.extend($.expr[ ':' ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function(dataName){
return function(elem){
return !!$.data(elem, dataName);
};
}) :
// support: jQuery <1.8
function(elem, i, match){
return !!$.data(elem, match[ 3 ]);
},
focusable: function(element){
return focusable(element, !isNaN($.attr(element, 'tabindex')));
},
tabbable: function(element){
var tabIndex = $.attr(element, 'tabindex'),
isTabIndexNaN = isNaN(tabIndex);
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable(element, !isTabIndexNaN);
}
});
/**
* focussable function, taken from jQuery UI Core
* @param element
* @returns {*}
*/
function focusable(element){
var map, mapName, img,
nodeName = element.nodeName.toLowerCase(),
isTabIndexNotNaN = !isNaN($.attr(element, 'tabindex'));
if('area' === nodeName){
map = element.parentNode;
mapName = map.name;
if(!element.href || !mapName || map.nodeName.toLowerCase() !== 'map'){
return false;
}
img = $('img[usemap=#' + mapName + ']')[0];
return !!img && visible(img);
}
return ( /^(input|select|textarea|button|object)$/.test(nodeName) ?
!element.disabled :
'a' === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible(element);
function visible(element){
return $.expr.filters.visible(element) && !$(element).parents().addBack().filter(function(){
return $.css(this, 'visibility') === 'hidden';
}).length;
}
}
})(jQuery);
</script>
<a tabindex="5">5</a><br>
<a tabindex="20">20</a><br>
<a tabindex="3">3</a><br>
<a tabindex="7">7</a><br>
<a tabindex="20">20</a><br>
<a tabindex="0">0</a><br>
<script>
var timer;
function tab(){
window.clearTimeout(timer)
timer = window.setInterval(function(){$.tabNext();}, 1000);
}
function shiftTab(){
window.clearTimeout(timer)
timer = window.setInterval(function(){$.tabPrev();}, 1000);
}
</script>
<button tabindex="-1" onclick="tab()">Tab</button>
<button tabindex="-1" onclick="shiftTab()">Shift+Tab</button>
</body>
</html>
_x000D_
I modify jquery.tabbable PlugIn to complete.
This worked for me... just clear the textbox completely as non-numeric keys are pressed.
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
If IsNumeric(TextBox2.Text) Then
'nada
Else
TextBox2.Clear()
End If
End Sub
Just wanted to share a curiosity:
when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!
For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !
Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!
Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK
and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.
I prefer to use ToString()
and IFormatProvider
.
double value = 100000.3
Console.WriteLine(value.ToString("0,0.00", new CultureInfo("en-US", false)));
Output: 10,000.30
See the official documentation (http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements001.htm#i54330)
Variable-length character string having maximum length size bytes or characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2. BYTE indicates that the column will have byte length semantics; CHAR indicates that the column will have character semantics.
But in Oracle Databast 12c maybe 32767 (http://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF30020)
Variable-length character string having maximum length size bytes or characters. You must specify size for VARCHAR2. Minimum size is 1 byte or 1 character. Maximum size is: 32767 bytes or characters if MAX_STRING_SIZE = EXTENDED 4000 bytes or characters if MAX_STRING_SIZE = STANDARD
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
Maybe this helps:
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
def in_dictlist((key, value), my_dictlist):
for this in my_dictlist:
if this[key] == value:
return this
return {}
print in_dictlist(('main_color','red'), a)
print in_dictlist(('main_color','pink'), a)
The first example is more "easy to read".
Actually, in my opinion you should only use the second one whenever you have to add some "else logic", but for a simple Conditional, use the first flavor. If you are worried about the long of the condition you always can use the next syntax:
if(ConditionOneThatIsTooLongAndProbablyWillUseAlmostOneLine
&& ConditionTwoThatIsLongAsWell
&& ConditionThreeThatAlsoIsLong) {
//Code to execute
}
Good Luck!
I do not believe Android supports full justification.
UPDATE 2018-01-01: Android 8.0+ supports justification modes with TextView
.
I think you can use display: inline-block
on the element you want to center and set text-align: center;
on its parent. This definitely center the div on all screen sizes.
Here you can see a fiddle: http://jsfiddle.net/PwC4T/2/ I add the code here for completeness.
HTML
<div id="container">
<div id="main">
<div id="somebackground">
Hi
</div>
</div>
</div>
CSS
#container
{
text-align: center;
}
#main
{
display: inline-block;
}
#somebackground
{
text-align: left;
background-color: red;
}
For vertical centering, I "dropped" support for some older browsers in favour of display: table;
, which absolutely reduce code, see this fiddle: http://jsfiddle.net/jFAjY/1/
Here is the code (again) for completeness:
HTML
<body>
<div id="table-container">
<div id="container">
<div id="main">
<div id="somebackground">
Hi
</div>
</div>
</div>
</div>
</body>
CSS
body, html
{
height: 100%;
}
#table-container
{
display: table;
text-align: center;
width: 100%;
height: 100%;
}
#container
{
display: table-cell;
vertical-align: middle;
}
#main
{
display: inline-block;
}
#somebackground
{
text-align: left;
background-color: red;
}
The advantage of this approach? You don't have to deal with any percantage, it also handles correctly the <video>
tag (html5), which has two different sizes (one during load, one after load, you can't fetch the tag size 'till video is loaded).
The downside is that it drops support for some older browser (I think IE8 won't handle this correctly)
Though the reason mentioned by Kevin is correct, but I would definitely check below before moving to something else:
cglibs
in my classpath. hibernate
versions in my classpath.Chances are good that having multiple or conflicting version of any of the above could cause unexpected issues like the one in question.
Sorry for my bad English. Checking Mails using Python with MAPI is easier,
outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetFirst()
Here we can get the most first mail into the Mail box, or into any sub folder. Actually, we need to check the Mailbox number & orientation. With the help of this analysis we can check each mailbox & its sub mailbox folders.
Similarly please find the below code, where we can see, the last/ earlier mails. How we need to check.
`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetLast()`
With this we can get most recent email into the mailbox. According to the above mentioned code, we can check our all mail boxes, & its sub folders.
these links may be helpful
_CrtIsValidPointer Verifies that a specified memory range is valid for reading and writing (debug version only). http://msdn.microsoft.com/en-us/library/0w1ekd5e.aspx
_CrtCheckMemory Confirms the integrity of the memory blocks allocated in the debug heap (debug version only). http://msdn.microsoft.com/en-us/library/e73x0s4b.aspx
I've made a function which allows you to move multiple selected options up or down
$('#your_select_box').move_selected_options('down');
$('#your_select_boxt').move_selected_options('up');
Dependencies:
$.fn.reverse = [].reverse;
function swapWith() (Paolo Bergantino)
First it checks whether the first/last selected option is able to move up/down. Then it loops through all the elements and calls
swapWith(element.next() or element.prev())
jQuery.fn.move_selected_options = function(up_or_down) {
if(up_or_down == 'up'){
var first_can_move_up = $("#" + this.attr('id') + ' option:selected:first').prev().size();
if(first_can_move_up){
$.each($("#" + this.attr('id') + ' option:selected'), function(index, option){
$(option).swapWith($(option).prev());
});
}
} else {
var last_can_move_down = $("#" + this.attr('id') + ' option:selected:last').next().size();
if(last_can_move_down){
$.each($("#" + this.attr('id') + ' option:selected').reverse(), function(index, option){
$(option).swapWith($(option).next());
});
}
}
return $(this);
}
As someone else pointed out, the Web Audio API has a better timer.
But in general, if these events happen consistently, how about you put them all on the same timer? I'm thinking about how a step sequencer works.
Practically, could it looks something like this?
var timer = 0;
var limit = 8000; // 8000 will be the point at which the loop repeats
var drumInterval = 8000;
var chordInterval = 1000;
var bassInterval = 500;
setInterval(function {
timer += 500;
if (timer == drumInterval) {
// Do drum stuff
}
if (timer == chordInterval) {
// Do chord stuff
}
if (timer == bassInterval) {
// Do bass stuff
}
// Reset timer once it reaches limit
if (timer == limit) {
timer = 0;
}
}, 500); // Set the timer to the smallest common denominator
Will something like this work for you?
>>> def namestr(**kwargs):
... for k,v in kwargs.items():
... print "%s = %s" % (k, repr(v))
...
>>> namestr(a=1, b=2)
a = 1
b = 2
And in your example:
>>> choice = {'key': 24; 'data': None}
>>> namestr(choice=choice)
choice = {'data': None, 'key': 24}
>>> printvars(**globals())
__builtins__ = <module '__builtin__' (built-in)>
__name__ = '__main__'
__doc__ = None
namestr = <function namestr at 0xb7d8ec34>
choice = {'data': None, 'key': 24}
If need to find nested in some dirs:
find / -type f -wholename "*dirname/filename"
Or connected dirs:
find / -type d -wholename "*foo/bar"
OCV goes out of its way to make sure you can't do this without knowing the element type, but if you want an easily codable but not-very-efficient way to read it type-agnostically, you can use something like
double val=mean(someMat(Rect(x,y,1,1)))[channel];
To do it well, you do have to know the type though. The at<> method is the safe way, but direct access to the data pointer is generally faster if you do it correctly.
To drop duplicate indices, use
df = df.loc[df.index.drop_duplicates()]
. C.f. pandas.pydata.org/pandas-docs/stable/generated/… – BallpointBen Apr 18 at 15:25
This is wrong but I can't reply directly to BallpointBen's comment due to low reputation. The reason its wrong is that df.index.drop_duplicates()
returns a list of unique indices, but when you index back into the dataframe using those the unique indices it still returns all records. I think this is likely because indexing using one of the duplicated indices will return all instances of the index.
Instead, use df.index.duplicated()
, which returns a boolean list (add the ~
to get the not-duplicated records):
df = df.loc[~df.index.duplicated()]
You need to control the opening of sub forms from a main form.
In my case I'm opening a Login window first before I launch my form1. I control everything from Program.cs. Set up a validation flag in Program.cs. Open Login window from Program.cs. Control then goes to login window. Then if the validation is good, set the validation flag to true from the login window. Now you can safely close the login window. Control returns to Program.cs. If the validation flag is true, open form1. If the validation flag is false, your application will close.
In Program.cs:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
//Validation flag
public static bool ValidLogin = false;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
if (ValidLogin)
{
Application.Run(new Form1());
}
}
}
In Login.cs:
private void btnOK_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "x" && txtPassword.Text == "x")
{
Program.ValidLogin = true;
this.Close();
}
else
{
MessageBox.Show("Username or Password are incorrect.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
The code below solved it for me:
@Override
public void onDestroyView() {
if (getView() != null) {
ViewGroup parent = (ViewGroup) getView().getParent();
parent.removeAllViews();
}
super.onDestroyView();
}
Note: The error was from my fragment class and by overriding the onDestroy method like this, I could solve it.
Use Json
class instead of Content
as shown following:
// When I want to return an error:
if (!isFileSupported)
{
Response.StatusCode = (int) HttpStatusCode.BadRequest;
return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
}
else
{
// When I want to return sucess:
Response.StatusCode = (int)HttpStatusCode.OK;
return Json("Message sent!", MediaTypeNames.Text.Plain);
}
Also set contentType:
contentType: 'application/json; charset=utf-8',
Well you are right public static variables are used without making an instance of the class but private static variables are not. The main difference between them and where I use the private static variables is when you need to use a variable in a static function. For the static functions you can only use static variables, so you make them private to not access them from other classes. That is the only case I use private static for.
Here is an example:
Class test {
public static String name = "AA";
private static String age;
public static void setAge(String yourAge) {
//here if the age variable is not static you will get an error that you cannot access non static variables from static procedures so you have to make it static and private to not be accessed from other classes
age = yourAge;
}
}
For a simple use of slice
, use my extension to Array Class:
Array.prototype.subarray = function(start, end) {
if (!end) { end = -1; }
return this.slice(start, this.length + 1 - (end * -1));
};
Then:
var bigArr = ["a", "b", "c", "fd", "ze"];
Test1:
bigArr.subarray(1, -1);
< ["b", "c", "fd", "ze"]
Test2:
bigArr.subarray(2, -2);
< ["c", "fd"]
Test3:
bigArr.subarray(2);
< ["c", "fd","ze"]
Might be easier for developers coming from another language (i.e. Groovy).
for Earth plugin APIs, create the balloon outside your loop and pass your counter to the function to get unique contents for each placemark!
function createBalloon(placemark, i, event) {
var p = placemark;
var j = i;
google.earth.addEventListener(p, 'click', function (event) {
// prevent the default balloon from popping up
event.preventDefault();
var balloon = ge.createHtmlStringBalloon('');
balloon.setFeature(event.getTarget());
balloon.setContentString('iframePath#' + j);
ge.setBalloon(balloon);
});
}
Here we have 1000.000 words list. 1000.000 words
namespace WindowsFormsApplication2
{
public class WordDef
{
public string Word { get; set; }
public int WordSum { get; set; }
public int Length { get; set; }
public string AnagramWord { get; set; }
public string Ordered { get; set; }
public int GetAsciiSum(string word)
{
int sum = 0;
foreach (char c in word)
{
sum += (int)c;
}
return sum;
}
}
}
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class AngramTestForm : Form
{
private ConcurrentBag<string> m_Words;
private ConcurrentBag<string> m_CacheWords;
private ConcurrentBag<WordDef> m_Anagramlist;
public AngramTestForm()
{
InitializeComponent();
m_CacheWords = new ConcurrentBag<string>();
}
private void button1_Click(object sender, EventArgs e)
{
m_Words = null;
m_Anagramlist = null;
m_Words = new ConcurrentBag<string>();
m_Anagramlist = new ConcurrentBag<WordDef>();
if (m_CacheWords.Count == 0)
{
foreach (var s in GetWords())
{
m_CacheWords.Add(s);
}
}
m_Words = m_CacheWords;
Stopwatch sw = new Stopwatch();
sw.Start();
//DirectCalculation();
AsciiCalculation();
sw.Stop();
Console.WriteLine("The End! {0}", sw.ElapsedMilliseconds);
this.Invoke((MethodInvoker)delegate
{
lbResult.Text = string.Concat(sw.ElapsedMilliseconds.ToString(), " Miliseconds");
});
StringBuilder sb = new StringBuilder();
foreach (var w in m_Anagramlist)
{
if (w != null)
{
sb.Append(string.Concat(w.Word, " - ", w.AnagramWord, Environment.NewLine));
}
}
txResult.Text = sb.ToString();
}
private void DirectCalculation()
{
List<WordDef> wordDef = new List<WordDef>();
foreach (var w in m_Words)
{
WordDef wd = new WordDef();
wd.Word = w;
wd.WordSum = wd.GetAsciiSum(w);
wd.Length = w.Length;
wd.Ordered = String.Concat(w.OrderBy(c => c));
wordDef.Add(wd);
}
foreach (var w in wordDef)
{
foreach (var t in wordDef)
{
if (w.Word != t.Word)
{
if (w.Ordered == t.Ordered)
{
t.AnagramWord = w.Word;
m_Anagramlist.Add(new WordDef() { Word = w.Word, AnagramWord = t.Word });
}
}
}
}
}
private void AsciiCalculation()
{
ConcurrentBag<WordDef> wordDef = new ConcurrentBag<WordDef>();
Parallel.ForEach(m_Words, w =>
{
WordDef wd = new WordDef();
wd.Word = w;
wd.WordSum = wd.GetAsciiSum(w);
wd.Length = w.Length;
wd.Ordered = String.Concat(w.OrderBy(c => c));
wordDef.Add(wd);
});
var tempWordByLength = from w in wordDef
group w by w.Length into newGroup
orderby newGroup.Key
select newGroup;
foreach (var wList in tempWordByLength)
{
List<WordDef> wd = wList.ToList<WordDef>();
var tempWordsBySum = from w in wd
group w by w.WordSum into newGroup
orderby newGroup.Key
select newGroup;
Parallel.ForEach(tempWordsBySum, ws =>
{
List<WordDef> we = ws.ToList<WordDef>();
if (we.Count > 1)
{
CheckCandidates(we);
}
});
}
}
private void CheckCandidates(List<WordDef> we)
{
for (int i = 0; i < we.Count; i++)
{
for (int j = i + 1; j < we.Count; j++)
{
if (we[i].Word != we[j].Word)
{
if (we[i].Ordered == we[j].Ordered)
{
we[j].AnagramWord = we[i].Word;
m_Anagramlist.Add(new WordDef() { Word = we[i].Word, AnagramWord = we[j].Word });
}
}
}
}
}
private static string[] GetWords()
{
string htmlCode = string.Empty;
using (WebClient client = new WebClient())
{
htmlCode = client.DownloadString("https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/10_million_password_list_top_1000000.txt");
}
string[] words = htmlCode.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
return words;
}
}
}
Try using ReadAsStringAsync() instead.
var foo = resp.Content.ReadAsStringAsync().Result;
The reason why it ReadAsAsync<string>()
doesn't work is because ReadAsAsync<>
will try to use one of the default MediaTypeFormatter
(i.e. JsonMediaTypeFormatter
, XmlMediaTypeFormatter
, ...) to read the content with content-type
of text/plain
. However, none of the default formatter can read the text/plain
(they can only read application/json
, application/xml
, etc).
By using ReadAsStringAsync()
, the content will be read as string regardless of the content-type.
You can use StrCSS as well, it creates isolated classnames and much more! Example code would look like. You can (optional) install the VSCode extension from the Visual Studio Marketplace for syntax highlighting support!
source: strcss
import { Sheet } from "strcss";
import React, { Component } from "react";
const sheet = new Sheet(`
map button
color green
color red !ios
fontSize 16
on hover
opacity .5
at mobile
fontSize 10
`);
export class User extends Component {
render() {
return <div className={sheet.map.button}>
{"Look mom, I'm green!
Unless you're on iOS..."}
</div>;
}
}
I was trying to compare A-B columns and highlight equal text, but usinng the obove fomrulas some text did not match at all. So I used form (VBA macro to compare two columns and color highlight cell differences) codes and I modified few things to adapt it to my application and find any desired column (just by clicking it). In my case, I use large and different numbers of rows on each column. Hope this helps:
Sub ABTextCompare()
Dim Report As Worksheet
Dim i, j, colNum, vMatch As Integer
Dim lastRowA, lastRowB, lastRow, lastColumn As Integer
Dim ColumnUsage As String
Dim colA, colB, colC As String
Dim A, B, C As Variant
Set Report = Excel.ActiveSheet
vMatch = 1
'Select A and B Columns to compare
On Error Resume Next
Set A = Application.InputBox(Prompt:="Select column to compare", Title:="Column A", Type:=8)
If A Is Nothing Then Exit Sub
colA = Split(A(1).Address(1, 0), "$")(0)
Set B = Application.InputBox(Prompt:="Select column being searched", Title:="Column B", Type:=8)
If A Is Nothing Then Exit Sub
colB = Split(B(1).Address(1, 0), "$")(0)
'Select Column to show results
Set C = Application.InputBox("Select column to show results", "Results", Type:=8)
If C Is Nothing Then Exit Sub
colC = Split(C(1).Address(1, 0), "$")(0)
'Get Last Row
lastRowA = Report.Cells.Find("", Range(colA & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column A
lastRowB = Report.Cells.Find("", Range(colB & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column B
Application.ScreenUpdating = False
'***************************************************
For i = 2 To lastRowA
For j = 2 To lastRowB
If Report.Cells(i, A.Column).Value <> "" Then
If InStr(1, Report.Cells(j, B.Column).Value, Report.Cells(i, A.Column).Value, vbTextCompare) > 0 Then
vMatch = vMatch + 1
Report.Cells(i, A.Column).Interior.ColorIndex = 35 'Light green background
Range(colC & 1).Value = "Items Found"
Report.Cells(i, A.Column).Copy Destination:=Range(colC & vMatch)
Exit For
Else
'Do Nothing
End If
End If
Next j
Next i
If vMatch = 1 Then
MsgBox Prompt:="No Itmes Found", Buttons:=vbInformation
End If
'***************************************************
Application.ScreenUpdating = True
End Sub
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
You need to use a hashbang. Add it to the first line of your python script.
#! <full path of python interpreter>
Then change the file permissions, and add the executing permission.
chmod +x <filename>
And finally execute it using
./<filename>
If its in the current directory,
You may want to read this page of the MySQL manual. How a table gets locked is dependent on what type of table it is.
MyISAM uses table locks to achieve a very high read speed, but if you have an UPDATE statement waiting, then future SELECTS will queue up behind the UPDATE.
InnoDB tables use row-level locking, and you won't have the whole table lock up behind an UPDATE. There are other kind of locking issues associated with InnoDB, but you might find it fits your needs.
Windows User need to download S3EXPLORER from this link which also has installation instructions :- http://s3browser.com/download.aspx
Then provide you AWS credentials like secretkey, accesskey and region to the s3explorer, this link contains configuration instruction for s3explorer:Copy Paste Link in brower: s3browser.com/s3browser-first-run.aspx
Now your all s3 buckets would be visible on left panel of s3explorer.
Simply select the bucket, and click on Buckets menu on top left corner, then select Download all files to option from the menu. Below is the screenshot for the same:
Then browse a folder to download the bucket at a particular place
Click on OK and your download would begin.
I'm very happy with kdesvn - integrates very well with konqueror, much like trortousesvn with windows explorer, and supports most of the functionality of tortoisesvn.
Of course, you'll benefit from this integration, if you use kubunto, and not ubuntu.
For any specific Runnable
instance, call Handler.removeCallbacks()
. Note that it uses the Runnable
instance itself to determine which callbacks to unregister, so if you are creating a new instance each time a post is made, you need to make sure you have references to the exact Runnable
to cancel. Example:
Handler myHandler = new Handler();
Runnable myRunnable = new Runnable() {
public void run() {
//Some interesting task
}
};
You can call myHandler.postDelayed(myRunnable, x)
to post another callback to the message queue at other places in your code, and remove all pending callbacks with myHandler.removeCallbacks(myRunnable)
Unfortunately, you cannot simply "clear" the entire MessageQueue
for a Handler
, even if you make a request for the MessageQueue
object associated with it because the methods for adding and removing items are package protected (only classes within the android.os package can call them). You may have to create a thin Handler
subclass to manage a list of Runnable
s as they are posted/executed...or look at another paradigm for passing your messages between each Activity
Hope that Helps!
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
i got solution what you are getting as per imp help=y
it is mentioned that imp is only valid for TRANSPORT_TABLESPACE
as below:
Keyword Description (Default) Keyword Description (Default)
--------------------------------------------------------------------------
USERID username/password FULL import entire file (N)
BUFFER size of data buffer FROMUSER list of owner usernames
FILE input files (EXPDAT.DMP) TOUSER list of usernames
SHOW just list file contents (N) TABLES list of table names
IGNORE ignore create errors (N) RECORDLENGTH length of IO record
GRANTS import grants (Y) INCTYPE incremental import type
INDEXES import indexes (Y) COMMIT commit array insert (N)
ROWS import data rows (Y) PARFILE parameter filename
LOG log file of screen output CONSTRAINTS import constraints (Y)
DESTROY overwrite tablespace data file (N)
INDEXFILE write table/index info to specified file
SKIP_UNUSABLE_INDEXES skip maintenance of unusable indexes (N)
FEEDBACK display progress every x rows(0)
TOID_NOVALIDATE skip validation of specified type ids
FILESIZE maximum size of each dump file
STATISTICS import precomputed statistics (always)
RESUMABLE suspend when a space related error is encountered(N)
RESUMABLE_NAME text string used to identify resumable statement
RESUMABLE_TIMEOUT wait time for RESUMABLE
COMPILE compile procedures, packages, and functions (Y)
STREAMS_CONFIGURATION import streams general metadata (Y)
STREAMS_INSTANTIATION import streams instantiation metadata (N)
DATA_ONLY import only data (N)
The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE import transportable tablespace metadata (N)
TABLESPACES tablespaces to be transported into database
DATAFILES datafiles to be transported into database
TTS_OWNERS users that own data in the transportable tablespace set
So, Please create table space for your user:
CREATE TABLESPACE <tablespace name> DATAFILE <path to save, example: 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\ABC.dbf'> SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE 10G EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
DAlert jQuery UI Plugin Check this out, This may help you
Set the class .fill
to height: 100%
.fill {
min-height: 100%;
height: 100%;
}
(I put a red background for #map
so you can see it takes up 100% height)
Can also encode like below.... gathered from https://davidwalsh.name/domdocument-utf8-problem
$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8'));
echo $dom->saveHTML();
No, it's doesn't give you a single executable in the sense that you only have one file afterwards - but you have a directory which contains everything you need for running your program, including an exe file.
I just wrote this setup.py today. You only need to invoke python setup.py py2exe
.
Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.
Use the title
attribute, for example:
<div title="them's hoverin' words">hover me</div>
_x000D_
or:
<span title="them's hoverin' words">hover me</span>
_x000D_
I'd do it like this:
<select onchange="jsFunction()">
<option value="" disabled selected style="display:none;">Label</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
If you want you could have the same label as the first option, which in this case is 1. Even better: put a label in there for the choices in the box.
One cool solution might be separating all environment-specific values into some separate angular module, that all other modules depend on:
angular.module('configuration', [])
.constant('API_END_POINT','123456')
.constant('HOST','localhost');
Then your modules that need those entries can declare a dependency on it:
angular.module('services',['configuration'])
.factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
return $resource(API_END_POINT + 'user');
});
Now you could think about further cool stuff:
The module, that contains the configuration can be separated into configuration.js, that will be included at your page.
This script can be easily edited by each of you, as long as you don’t check this separate file into git. But it's easier to not check in the configuration if it is in a separate file. Also, you could branch it locally.
Now, if you have a build-system, like ANT or Maven, your further steps could be implementing some placeholders for the values API_END_POINT, that will be replaced during build-time, with your specific values.
Or you have your configuration_a.js
and configuration_b.js
and decide at the backend which to include.
You need to push i
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i < yearEnd+1; i++) {
arr.push(i);
}
Then, your resulting array will be:
arr = [2000, 2001, 2003, ... 2039, 2040]
Hope this helps
I think that the the align="center"
aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.
text-align
is doing a similar sort of thing.
left:50%
is ignored unless you set the div's position to be something like relative or absolute.
The generally accepted methods is to use the following properties
width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;
the margins being auto means they grow/shrink to match the browser window (or parent div)
UPDATE
Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.
margin:0 auto;
this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.
Here's how you can do that (quick and dirty solution. If you really need this kind of behavior, you should either reconsider your design or override all IList<T>
members and aggregate the source list):
using System;
using System.Collections.Generic;
namespace ConsoleApplication3
{
public class ModifiableList<T> : List<T>
{
private readonly IList<T> pendingAdditions = new List<T>();
private int activeEnumerators = 0;
public ModifiableList(IEnumerable<T> collection) : base(collection)
{
}
public ModifiableList()
{
}
public new void Add(T t)
{
if(activeEnumerators == 0)
base.Add(t);
else
pendingAdditions.Add(t);
}
public new IEnumerator<T> GetEnumerator()
{
++activeEnumerators;
foreach(T t in ((IList<T>)this))
yield return t;
--activeEnumerators;
AddRange(pendingAdditions);
pendingAdditions.Clear();
}
}
class Program
{
static void Main(string[] args)
{
ModifiableList<int> ints = new ModifiableList<int>(new int[] { 2, 4, 6, 8 });
foreach(int i in ints)
ints.Add(i * 2);
foreach(int i in ints)
Console.WriteLine(i * 2);
}
}
}
Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:
var re = new RegExp(yyy, 'g');
xxx.match(re);
Any flags you need (such as /g) can go into the second parameter.
Not sure if this will benefit anybody, but if you are using Azure CloudShell PowerShell you can just type:
code file.txt
And Visual Studio code will popup with the file to be edit, pretty great.
Lea's converter is no longer available. I just used this converter
Steps:
Dec code points
Unicode U+hex notation
(eg U+2022)content: '\2022'
ps. I have no connection with the web site.
Material UI have implemented their own Flexbox layout via the Grid component.
It appears they initially wanted to keep themselves as purely a 'components' library. But one of the core developers decided it was too important not to have their own. It has now been merged into the core code and was released with v1.0.0.
You can install it via:
npm install @material-ui/core
It is now in the official documentation with code examples.
I'm not quite sure what you mean by "sorting the items after index 0", but if you just want to sort the array of strings returned by SerialPort.GetPortNames()
, you can use Array.Sort.
It is a xml error for some reason may be because of deleting a view or string in another view or may be for missing " or /> ..... etc
But here I am using a good technique to figure out where is the problem exactly :-
I know it is not the solution of the main problem but it will make you find where is the error quickly and save you time.
Update
There is another way you can find out easily, as Bennik2000 write in comment, you can look at the right scrollbar for red lines, they also indicate errors.
Update
I found a very simple way to get where is the error exactly if it is in resource file or even java file.
1- Go to Project Window.
2- Open the file that has the error.
3- Click F2 to go to the nearest error appears (it will go to the correct line)
The $'\t' notation given in other answers is shell-specific -- it seems to work in bash and zsh but is not universal.
NOTE: The following is for the fish
shell and does not work in bash:
In the fish
shell, one can use an unquoted \t
, for example:
grep \t foo.txt
Or one can use the hex or unicode notations e.g.:
grep \X09 foo.txt
grep \U0009 foo.txt
(these notations are useful for more esoteric characters)
Since these values must be unquoted, one can combine quoted and unquoted values by concatenation:
grep "foo"\t"bar"
WARNING: Security researches have found several poisoned packages on PyPI, including a package named
urllib
, which will 'phone home' when installed. If you usedpip install urllib
some time after June 2017, remove that package as soon as possible.
You can't, and you don't need to.
urllib2
is the name of the library included in Python 2. You can use the urllib.request
library included with Python 3, instead. The urllib.request
library works the same way urllib2
works in Python 2. Because it is already included you don't need to install it.
If you are following a tutorial that tells you to use urllib2
then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2
comes with that version.
Alternatively, install the requests
library for a higher-level and easier to use API. It'll work on both Python 2 and 3.
Use a collection that is a static property of your Car
class.
Every time you create a new instance of a Car
, store the reference in this collection.
To destroy all Car
s, just set all items to null
.
$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);
$my_url outputs:
http://localhost/test.php?id=http%3A%2F%2Fgoogle.com%2F%3Fvar%3D234%26key%3D234
So now you can get this value using $_GET['id']
or $_REQUEST['id']
(decoded).
echo urldecode($_GET["id"]);
Output
http://google.com/?var=234&key=234
To get every GET parameter:
foreach ($_GET as $key=>$value) {
echo "$key = " . urldecode($value) . "<br />\n";
}
$key
is GET key and $value
is GET value for $key
.
Or you can use alternative solution to get array of GET params
$get_parameters = array();
if (isset($_SERVER['QUERY_STRING'])) {
$pairs = explode('&', $_SERVER['QUERY_STRING']);
foreach($pairs as $pair) {
$part = explode('=', $pair);
$get_parameters[$part[0]] = sizeof($part)>1 ? urldecode($part[1]) : "";
}
}
$get_parameters
is same as url decoded $_GET
.
What directory is file.txt in? cron runs jobs in your home directory, so unless your script cd
s somewhere else, that's where it's going to look for/create file.txt.
EDIT: When you refer to a file without specifying its full path (e.g. file.txt
, as opposed to the full path /home/myUser/scripts/file.txt
) in shell, it's taken that you're referring to a file in your current working directory. When you run a script (whether interactively or via crontab), the script's working directory has nothing at all to do with the location of the script itself; instead, it's inherited from whatever ran the script.
Thus, if you cd
(change working directory) to the directory the script's in and then run it, file.txt
will refer to a file in the same directory as the script. But if you don't cd
there first, file.txt
will refer to a file in whatever directory you happen to be in when you ran the script. For instance, if your home directory is /home/myUser, and you open a new shell and immediately run the script (as scripts/test.sh
or /home/myUser/scripts/test.sh
; ./test.sh
won't work), it'll touch the file /home/myUser/file.txt because /home/myUser is your current working directory (and therefore the script's).
When you run a script from cron
, it does essentially the same thing: it runs it with the working directory set to your home directory. Thus all file references in the script are taken relative to your home directory, unless the script cd
s somewhere else or specifies an absolute path to the file.
I don't think you can get it directly, but there are a few ways to find it indirectly.
One way is to use the GC.GetTotalMemory
method to measure the amount of memory used before and after creating your object. This won't be perfect, but as long as you control the rest of the application you may get the information you are interested in.
Apart from that you can use a profiler to get the information or you could use the profiling api to get the information in code. But that won't be easy to use I think.
See Find out how much memory is being used by an object in C#? for a similar question.
You could use XML.
E.g.
declare @xmlstring as varchar(100)
set @xmlstring = '<args><arg value="42" /><arg2>-1</arg2></args>'
declare @docid int
exec sp_xml_preparedocument @docid output, @xmlstring
select [id],parentid,nodetype,localname,[text]
from openxml(@docid, '/args', 1)
The command sp_xml_preparedocument is built in.
This would produce the output:
id parentid nodetype localname text
0 NULL 1 args NULL
2 0 1 arg NULL
3 2 2 value NULL
5 3 3 #text 42
4 0 1 arg2 NULL
6 4 3 #text -1
which has all (more?) of what you you need.
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
The use of the package \usepackage{fancyvrb}
allows the definition of the fontsize argument inside Verbatim:
\begin{Verbatim}[fontsize=\small]
print "Hello, World"
\end{Verbatim}
The fontsize that you can specify are the common
\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge
If you're only doing a few of them (and/or the array size is large), then you were on the right track with array_search:
$list = array('string1', 'string2', 'string3');
$k = array_search('string2', $list); //$k = 1;
If you want all (or a lot of them), a loop will prob do you better:
foreach ($list as $key => $value) {
echo $value . " in " . $key . ", ";
}
// Prints "string1 in 0, string2 in 1, string3 in 2, "
The following attribute on the ACTIVITY in AndroidManifest.xml is all you need:
android:configChanges="orientation"
So, the full activity node would be:
<activity android:name="Activity1"
android:icon="@drawable/icon"
android:label="App Name"
android:excludeFromRecents="true"
android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
If you are trying to do redirect in beforeAction() you should use send() method
return $this->redirect('/some/url',302)->send();
I got this error on importing models in tests, i.e. given this Django project structure:
|-- myproject
|-- manage.py
|-- myproject
|-- myapp
|-- models.py # defines model: MyModel
|-- tests
|-- test_models.py
in file test_models.py
I imported MyModel
in this way:
from models import MyModel
The problem was fixed if it is imported in this way:
from myapp.models import MyModel
Hope this helps!
PS: Maybe this is a bit late, but I not found in others answers how to solve this problem in my code and I want to share my solution.
This is a great resource and has worked very well, the few times I've used it. Creates the following code....
<style>
.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; }
.embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
</style>
<div class='embed-container'>
<iframe src='http://player.vimeo.com/video/66140585' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</div>
Another way is to pass a list of lists to a one-argument routine:
import os
from multiprocessing import Pool
def task(args):
print "PID =", os.getpid(), ", arg1 =", args[0], ", arg2 =", args[1]
pool = Pool()
pool.map(task, [
[1,2],
[3,4],
[5,6],
[7,8]
])
One can than construct a list lists of arguments with one's favorite method.
I got the answer:(It's simple )
Take a ArrayList then cast it and find the size of the arraylist. Here it is :
ArrayList count = new ArrayList();
count=(ArrayList) maptabcolname.get("k1"); //here "k1" is Key
System.out.println("number of elements="+count.size());
It will show the size. (Give suggestion). It's working.
@UniqueConstraint this annotation is used for annotating single or multiple unique keys at the table level separated by comma, which is why you get an error. it will only work if you let JPA create your tables
Example
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder(builderClassName = "Builder", toBuilder = true)
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = {"person_id", "company_id"}))
public class AppUser extends BaseEntity {
@Column(name = "person_id")
private Long personId;
@ManyToOne
@JoinColumn(name = "company_id")
private Company company;
}
https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/UniqueConstraint.html
On the other hand To ensure a field value is unique you can write
@Column(unique=true)
String username;
You can use PreferredSize:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Example',
home: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50.0), // here the desired height
child: AppBar(
// ...
)
),
body: // ...
)
);
}
}
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
Since API Level 21 (Lollipop) Android provides a PdfRenderer class:
// create a new renderer
PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());
// let us just render all pages
final int pageCount = renderer.getPageCount();
for (int i = 0; i < pageCount; i++) {
Page page = renderer.openPage(i);
// say we render for showing on the screen
page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);
// do stuff with the bitmap
// close the page
page.close();
}
// close the renderer
renderer.close();
For more information see the sample app.
For older APIs I recommend Android PdfViewer library, it is very fast and easy to use, licensed under Apache License 2.0:
pdfView.fromAsset(String)
.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
.enableSwipe(true)
.swipeHorizontal(false)
.enableDoubletap(true)
.defaultPage(0)
.onDraw(onDrawListener)
.onLoad(onLoadCompleteListener)
.onPageChange(onPageChangeListener)
.onPageScroll(onPageScrollListener)
.onError(onErrorListener)
.enableAnnotationRendering(false)
.password(null)
.scrollHandle(null)
.load();
Most simple, without caring about delegates
if(textBox1.InvokeRequired == true)
textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});
else
textBox1.Text = "Invoke was NOT needed";
Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team
, of type int
, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:
@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;
Then, the following query will work flawlessly:
select e from Employee e inner join e.team
Which will load all the employees, except those that aren't associated to any team.
The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss
, id_profession
).
It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.
A further possibility is to make a direct javascript link to your function:
<form action="javascript:your_function();" method="post">
...
You would usually use map for that kind of thing.
buttonsListArr = initialArr.map(buttonInfo => (
<Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);
(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)
As a side, I would use an object instead of an array. I find it looks nicer:
initialArr = [
{
id: 1,
color: "blue",
text: "text1"
},
{
id: 2,
color: "red",
text: "text2"
},
];
buttonsListArr = initialArr.map(buttonInfo => (
<Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);
I would like to add my little contribution to this post:
def to_camelcase(str):
return ' '.join([t.title() for t in str.split()])
Some encoding strategies, please uncomment to taste :
#!/bin/bash
#
tmpfile=$1
echo '-- info about file file ........'
file -i $tmpfile
enca -g $tmpfile
echo 'recoding ........'
#iconv -f iso-8859-2 -t utf-8 back_test.xml > $tmpfile
#enca -x utf-8 $tmpfile
#enca -g $tmpfile
recode CP1250..UTF-8 $tmpfile
You might like to check the encoding by opening and reading the file in a form of a loop... but you might need to check the filesize first :
#PYTHON
encodings = ['utf-8', 'windows-1250', 'windows-1252'] # add more
for e in encodings:
try:
fh = codecs.open('file.txt', 'r', encoding=e)
fh.readlines()
fh.seek(0)
except UnicodeDecodeError:
print('got unicode error with %s , trying different encoding' % e)
else:
print('opening the file with encoding: %s ' % e)
break
It's security all about. Make sure you have double check your firewall (windows and anti virus) in some cases when you disabled av firewall and restart your computer, automatically windows firewall is active and it's still block your application. Hope this is helpful ..
You didn't use FROM expression for a table
SELECT DISTINCT Description, Date as treatmentDate
**FROM <A TABLE>**
WHERE doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I
AND P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');
This disables the script errors and also disables other windows.. such as the NTLM login window or the client certificate accept window. The below will suppress only javascript errors.
// Hides script errors without hiding other dialog boxes.
private void SuppressScriptErrorsOnly(WebBrowser browser)
{
// Ensure that ScriptErrorsSuppressed is set to false.
browser.ScriptErrorsSuppressed = false;
// Handle DocumentCompleted to gain access to the Document object.
browser.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(
browser_DocumentCompleted);
}
private void browser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).Document.Window.Error +=
new HtmlElementErrorEventHandler(Window_Error);
}
private void Window_Error(object sender,
HtmlElementErrorEventArgs e)
{
// Ignore the error and suppress the error dialog box.
e.Handled = true;
}
If you want to use jquery in a web application (e.g. React) and jquery is already loaded with <script src="jquery-3.3.1.js"...
On the webpage you can do:
npm install --save-dev @types/query
and the use it with:
let $: JQueryStatic = (window as any)["jQuery"];
so, you don't need to load jquery a second time (with npm install --save jquery
)
but have all the advantages of Typescript
Other users commenting that the Content-Type
is plain/text
when encoding. You have to set the Content-Type
first w.Header().Set
, then the HTTP response code w.WriteHeader
.
If you call w.WriteHeader
first then call w.Header().Set
after you will get plain/text
.
An example handler might look like this;
func SomeHandler(w http.ResponseWriter, r *http.Request) {
data := SomeStruct{}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(data)
}
As sometimes I prefer to switch routes by Application then by buttons, this is a minimal working example what works for me:
import { Component } from 'react'
import { BrowserRouter as Router, Link } from 'react-router-dom'
class App extends Component {
constructor(props) {
super(props)
/** @type BrowserRouter */
this.router = undefined
}
async handleSignFormSubmit() {
await magic()
this.router.history.push('/')
}
render() {
return (
<Router ref={ el => this.router = el }>
<Link to="/signin">Sign in</Link>
<Route path="/signin" exact={true} render={() => (
<SignPage onFormSubmit={ this.handleSignFormSubmit } />
)} />
</Router>
)
}
}
I'm not sure about the parameters(mpaction, format), if they are specified for the amazonaws page or ##.##.
Try to urlencode() the url.
With version 3 of PowerShell you can chain the replace calls together:
(Get-Content $sourceFile) | ForEach-Object {
$_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
} | Set-Content $destinationFile
Regarding Johnathan Sampson's Linux example, watch out when you are doing an intval on the outcome of the "du" function, if the size is >2GB, it will keep showing 2GB.
Replace:
$totalSize = intval(fgets($io, 80));
by:
strtok(fgets($io, 80), " ");
supposed your "du" function returns the size separated with space followed by the directory/file name.
Apologies for my previously mixed up answer.
Here is how to do:
myTreeView.SelectedNode = myTreeNode;
I have tested the code below and it works:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
treeView1.Nodes.Add("1", "1");
treeView1.Nodes.Add("2", "2");
treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
treeView1.SelectedNode = treeNode;
MessageBox.Show(treeNode.IsSelected.ToString());
}
}
I got this confusion in one of my project as well and found this post, very helpful. Tried the same in my playground and here is the summary. Hope this helps someone with stored properties and functions of type static
, final
,class
, overriding class vars etc.
class Simple {
init() {print("init method called in base")}
class func one() {print("class - one()")}
class func two() {print("class - two()")}
static func staticOne() {print("staticOne()")}
static func staticTwo() {print("staticTwo()")}
final func yesFinal() {print("yesFinal()")}
static var myStaticVar = "static var in base"
//Class stored properties not yet supported in classes; did you mean 'static'?
class var myClassVar1 = "class var1"
//This works fine
class var myClassVar: String {
return "class var in base"
}
}
class SubSimple: Simple {
//Successful override
override class func one() {
print("subClass - one()")
}
//Successful override
override class func two () {
print("subClass - two()")
}
//Error: Class method overrides a 'final' class method
override static func staticOne() {
}
//error: Instance method overrides a 'final' instance method
override final func yesFinal() {
}
//Works fine
override class var myClassVar: String {
return "class var in subclass"
}
}
And here is the testing samples:
print(Simple.one())
print(Simple.two())
print(Simple.staticOne())
print(Simple.staticTwo())
print(Simple.yesFinal(Simple()))
print(SubSimple.one())
print(Simple.myStaticVar)
print(Simple.myClassVar)
print(SubSimple.myClassVar)
//Output
class - one()
class - two()
staticOne()
staticTwo()
init method called in base
(Function)
subClass - one()
static var in base
class var in base
class var in subclass
I suggest using Postman to generate the request code. Simply make the request using Postman then hit the code tab:
Then you'll get the following window to choose in which language you want your request code to be:
Python's if
can be used as a ternary operator:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts
the >>
appends the output of echo
to the file.
Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.
First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.
Second, it requires you to add an entry for every host name on a domain; just adding websitename.com
will not block www.websitename.com
, for example.
On Android 4.4 KitKat, I found mine in:
/sdcard/Android/data/<app.package.name>
try
{
for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
{
for (int col = 0; col < dataGridView1.Rows[rows].Cells.Count; col++)
{
s1 = dataGridView1.Rows[0].Cells[0].Value.ToString();
label20.Text = s1;
}
}
}
catch (Exception ex)
{
MessageBox.Show("try again"+ex);
}
For Windows it seems possible to control the amount of memory MongoDB uses, see this tutorial at Captain Codeman:
Yes, it will be encrypted.
You'll understand it if you simply check what happens behind the scenes.
You can insert into a table from a SELECT.
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
(SELECT id FROM state WHERE name = 'New York'),
(SELECT id FROM positions WHERE name = 'Sales Executive'),
(SELECT id FROM manager WHERE name = 'Barry Green')
FROM
dual
Or, similarly...
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
state.id,
positions.id,
manager.id
FROM
state
CROSS JOIN
positions
CROSS JOIN
manager
WHERE
state.name = 'New York'
AND positions.name = 'Sales Executive'
AND manager.name = 'Barry Green'
Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.
Just unset the node:
$str = <<<STR
<a>
<b>
<c>
</c>
</b>
</a>
STR;
$xml = simplexml_load_string($str);
unset($xml –> a –> b –> c); // this would remove node c
echo $xml –> asXML(); // xml document string without node c
This code was taken from How to delete / remove nodes in SimpleXML.
Your example seems to indicate that you would like to display the a string followed by an integer, in which case:
string text = "Player: ";
int i = 4;
cout << text << i << endl;
would work fine.
But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:
#include <sstream>
#include <iostream>
using namespace std;
std::string operator+(std::string const &a, int b) {
std::ostringstream oss;
oss << a << b;
return oss.str();
}
int main() {
int i = 4;
string text = "Player: ";
cout << (text + i) << endl;
}
In fact, you can use templates to make this approach more powerful:
template <class T>
std::string operator+(std::string const &a, const T &b){
std::ostringstream oss;
oss << a << b;
return oss.str();
}
Now, as long as object b
has a defined stream output, you can append it to your string (or, at least, a copy thereof).
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>