To file under both 'established' and 'key-value store': Berkeley DB.
Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).
Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.
One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.
Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:
p [tab][enter] Hello world!
When you type p [tab] Emmet expands it to:
<p></p>
Pressing [enter] then further expands it to:
<p>
</p>
With the cursor indented and on the line between the tags. Meaning that typing text results in:
<p>
Hello, world!
</p>
View and check the reference paths in your csproj.
I had removed references to System.Web.Mvc (and others) and readded them to a custom path. C:\Project\OurWebReferences
However, after doing this, the reference path in the still csproj did not change. WAS
<Reference Include="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\OurWebProject\bin\Debug\System.Web.Mvc.dll</HintPath>
</Reference>
Changed to manually
<Reference Include="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\OurWebReferences\System.Web.Mvc.dll</HintPath>
</Reference>
Paths are an example only.
Here's how I would solve it:
Just Save your CSV File as a XLS Sheet in excel(By Doing so, you wouldn't have to worry about delimitiers. Excel's spreadsheet format will be read as a table and imported directly into a SQL Table)
Import the File Using SSIS
Write a Custom Script in the import manager to omit/modify the data you're looking for.(Or run a master script to scrutinize the data you're looking to remove)
Good Luck.
I was used to the C# (Sharp) String.Remove method. In Javascript, there is no remove function for string, but there is substr function. You can use the substr function once or twice to remove characters from string. You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):
function Remove(str, startIndex) {
return str.substr(0, startIndex);
}
and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):
function Remove(str, startIndex, count) {
return str.substr(0, startIndex) + str.substr(startIndex + count);
}
and then you can use these two functions or one of them for your needs!
Example:
alert(Remove("data-123", 0, 5));
Output: 123
If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.
For example, if you have a class called MyCustomObject
, that has a property called LongPropertyName
, you can use a custom resolver like this…
public class CustomDataContractResolver : DefaultContractResolver
{
public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(MyCustomObject))
{
if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
{
property.PropertyName = "Short";
}
}
return property;
}
}
Then call for serialization and supply the resolver:
var result = JsonConvert.SerializeObject(myCustomObjectInstance,
new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });
And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}
More info on custom resolvers here
Use Math.floor()
:
var f = 20.536;
var i = Math.floor(f); // 20
I'm useing this way (in laravel)-
<form id="delete-{{$category->id}}" action="{{route('category.destroy',$category->id)}}" style="display: none;" method="POST">
@csrf
@method('DELETE')
</form>
<a href="#" onclick="if (confirm('Are you sure want to delete this item?')) {
event.preventDefault();
document.getElementById('delete-{{$category->id}}').submit();
}else{
event.preventDefault();
}">
<i class="fa fa-trash"></i>
</a>
class(mtcars)
my.mean <- unlist(lapply(mtcars, mean)); my.mean
mpg cyl disp hp drat wt qsec vs
20.090625 6.187500 230.721875 146.687500 3.596563 3.217250 17.848750 0.437500
am gear carb
0.406250 3.687500 2.812500
import sys
print("\n".join(sys.argv))
sys.argv
is a list that contains all the arguments passed to the script on the command line.
Basically,
import sys
print(sys.argv[1:])
One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .
Go to wherever your Eclipse is installed. Right-click -> Show Package Contents -> Contents -> MacOS -> Double-click the executable called eclipse
A terminal window will open and a new instance of eclipse will start.
Note that if you close the terminal window, the new Eclipse instance will be closed also.
To make your life easier, you can drag the executable to your dock for easy access
In order to do a complete refresh, where the grid will be re-rendered alongwith new read request, you can do the following:
Grid.setOptions({
property: true/false
});
Where property can be any property e.g. sortable
that's all you need
childView.frame = parentView.bounds
remove float left.
Edited: removed reference to align center on an image tag.
The valid selector will do the trick.
<input type="text" class="myText" required="required" />
.myText {
//default style of input
}
.myText:valid {
//style when input has text
}
My impression is that your database is pretty enourmous or very badly designed if Linq2Sql does not fit your needs. I have around 10 websites both larger and smaller all using Linq2Sql. I have looked and Entity framework many times but I cannot find a good reason for using it over Linq2Sql. That said I try to use my databases as model so I already have a 1 to 1 mapping between model and database.
At my current job we have a database with 200+ tables. An old database with lots of bad solutions so there I could see the benefit of Entity Framework over Linq2Sql but still I would prefer to redesign the database since the database is the engine of the application and if the database is badly designed and slow then my application will also be slow. Using Entity framework on such a database seems like a quickfix to disguise the bad model but it could never disguise the bad performance you get from such a database.
Migrate your project to androidX.
dependencies are upgraded to androidX. so if you want to use androidX contents migrate your project to androidX.
With Android Studio 3.2 and higher, you can quickly migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
Downgrading dependencies may fix your problem this time - but not recommended
In your scenario, converting a string to a boolean can be done via something like someString === 'true'
(as was already answered).
However, let me try to address your main issue: dealing with the local storage.
The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.
A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.
The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.
function setItemInStorage(key, item) {
localStorage.setItem(key, JSON.stringify(item));
}
function getItemFromStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
Your example could then be rewritten as:
setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);
And:
if (getItemFromStorage('CheckOutPageReload')) {
const pageLoadParams = getItemFromStorage('CheckOutPageReload');
this.btnLoginNumOne = pageLoadParams[0];
this.btnLoginEdit = pageLoadParams[1];
}
Late to the conversation...
But, why not use css? That way you can keep the button as a submit type.
html:
<input type="submit" value="go" />
css:
button, input[type="submit"] {
background:url(/images/submit.png) no-repeat;"
}
Works like a charm.
EDIT: If you want to remove the default button styles, you can use the following css:
button, input[type="submit"]{
color: inherit;
border: none;
padding: 0;
font: inherit;
cursor: pointer;
outline: inherit;
}
from this SO question
That is the right code. What is probably happening is your form is submitting, and you see the new page (where the element will exist again).
"Edit -> EOL Conversion". You can convert to Windows/Linux/Mac EOL there. The current format is displayed in the status bar.
If you don't use conda, just use :
pip install openpyxl
If you use conda, I'd recommend :
conda install -c anaconda openpyxl
instead of simply conda install openpyxl
Because there are issues right now with conda updating (see GitHub Issue #8842) ; this is being fixed and it should work again after the next release (conda 4.7.6)
To start with, from the Oracle Database Data Warehousing Guide:
Restrictions on Fast Refresh on Materialized Views with Joins Only
...
- Rowids of all the tables in the FROM list must appear in the SELECT list of the query.
This means that your statement will need to look something like this:
CREATE MATERIALIZED VIEW MV_Test
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID
FROM TPM_PROJECTVERSION V,
TPM_PROJECT P
WHERE P.PROJECTID = V.PROJECTID
Another key aspect to note is that your materialized view logs must be created as with rowid
.
Below is a functional test scenario:
CREATE TABLE foo(foo NUMBER, CONSTRAINT foo_pk PRIMARY KEY(foo));
CREATE MATERIALIZED VIEW LOG ON foo WITH ROWID;
CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar));
CREATE MATERIALIZED VIEW LOG ON bar WITH ROWID;
CREATE MATERIALIZED VIEW foo_bar
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT AS SELECT foo.foo,
bar.bar,
foo.ROWID AS foo_rowid,
bar.ROWID AS bar_rowid
FROM foo, bar
WHERE foo.foo = bar.foo;
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
With FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
Maximum time between connection request and a timeout error. When the client tries to make a connection, if the timeout wait limit is reached, it will stop trying and raise an error.
SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\"");
cSSH.Disconnect();
cSSH.Dispose();
//using SSH.Net
The following approach was inspired by this answer to a related (more general) question.
The approach is to read the MachineGuid
value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
. This value is generated during OS installation.
There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid
value.
However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.
public string GetMachineGuid()
{
string location = @"SOFTWARE\Microsoft\Cryptography";
string name = "MachineGuid";
using (RegistryKey localMachineX64View =
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
{
if (rk == null)
throw new KeyNotFoundException(
string.Format("Key Not Found: {0}", location));
object machineGuid = rk.GetValue(name);
if (machineGuid == null)
throw new IndexOutOfRangeException(
string.Format("Index Not Found: {0}", name));
return machineGuid.ToString();
}
}
}
Probably not the best solution, but before I came here I just made this on the fly to keep working without having a quick break from study.
def raw_input(x):
input(x)
Then when I run raw_input('Enter your first name: ')
on the script I was working on, it captures it as does input()
would.
There may be a reason not to do this, that I haven't come across yet!
Odd errors like "inappropriate ioctl for device" are usually a result of checking $! at some point other than just after a system call failed. If you'd show your code, I bet someone would rapidly point out your error.
I know this post is old, but what i had to do in the case of the above answers on Linux machine was:
sudo chmod +x directory
Just set the time and date to variables if it will be something that will be in a loop then
:top
set T=%time%
set D=%Date%
echo %T%>>log.txt
echo %d%>>log.txt
echo time:%T%
echo date:%D%
pause
goto top
I suggest making it nice and clean by putting:
@echo off
in front of every thing it get rid of the rubbish C:/users/example/...
and putting
cls
after the :top
to clear the screen before it add the new date and time to the display
This handles not only accents, but also "strokes" (as in ø etc.):
import unicodedata as ud
def rmdiacritics(char):
'''
Return the base character of char, by "removing" any
diacritics like accents or curls and strokes and the like.
'''
desc = ud.name(char)
cutoff = desc.find(' WITH ')
if cutoff != -1:
desc = desc[:cutoff]
try:
char = ud.lookup(desc)
except KeyError:
pass # removing "WITH ..." produced an invalid name
return char
This is the most elegant way I can think of (and it has been mentioned by alexis in a comment on this page), although I don't think it is very elegant indeed. In fact, it's more of a hack, as pointed out in comments, since Unicode names are – really just names, they give no guarantee to be consistent or anything.
There are still special letters that are not handled by this, such as turned and inverted letters, since their unicode name does not contain 'WITH'. It depends on what you want to do anyway. I sometimes needed accent stripping for achieving dictionary sort order.
Incorporated suggestions from the comments (handling lookup errors, Python-3 code).
It should be:
SELECT SalesID, COUNT(*)
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1
Regarding your initial query:
Edit:
And I just thought of this, if you want to see WHICH items are in there more than once (but this depends on which database you are using):
;WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY SalesID ORDER BY SalesID) AS [Num]
FROM AXDelNotesNoTracking
)
SELECT *
FROM cte
WHERE cte.Num > 1
Of course, this just shows the rows that have appeared with the same SalesID but does not show the initial SalesID value that has appeared more than once. Meaning, if a SalesID shows up 3 times, this query will show instances 2 and 3 but not the first instance. Still, it might help depending on why you are looking for multiple SalesID values.
Edit2:
The following query was posted by APC below and is better than the CTE I mention above in that it shows all rows in which a SalesID has appeared more than once. I am including it here for completeness. I merely added an ORDER BY to keep the SalesID values grouped together. The ORDER BY might also help in the CTE above.
SELECT *
FROM AXDelNotesNoTracking
WHERE SalesID IN
( SELECT SalesID
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1
)
ORDER BY SalesID
The answer that was mentioned in this post already several times I have adopted a little bit because I needed to search in only one table too:
(and also made input for the table name a bit more simpler)
ALTER PROC dbo.db_compare_SearchAllTables_sp
(
@SearchStr nvarchar(100),
@TableName nvarchar(256) = ''
)
AS
BEGIN
if PARSENAME(@TableName, 2) is null
set @TableName = 'dbo.' + QUOTENAME(@TableName, '"')
declare @results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @ColumnName nvarchar(128) = '', @SearchStr2 nvarchar(110)
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
IF @TableName <> ''
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' WITH (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
ELSE
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' WITH (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM @results
END
typeof(T).Name;
You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.
for other type of products it will automatically restore it.
Please read following text which will clear your concept about this :
Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.
Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.
If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices
I had exactly the same problem lately, and I installed Wireshark (it is a network monitoring tool). You can see everything with this, except encrypted traffic (HTTPS).
@hop5 and @RnMss suggested to use C++11 lambdas, but if you deal with pointers, you can use them directly:
#include <thread>
#include <iostream>
class CFoo {
public:
int m_i = 0;
void bar() {
++m_i;
}
};
int main() {
CFoo foo;
std::thread t1(&CFoo::bar, &foo);
t1.join();
std::thread t2(&CFoo::bar, &foo);
t2.join();
std::cout << foo.m_i << std::endl;
return 0;
}
outputs
2
Rewritten sample from this answer would be then:
#include <thread>
#include <iostream>
class Wrapper {
public:
void member1() {
std::cout << "i am member1" << std::endl;
}
void member2(const char *arg1, unsigned arg2) {
std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
std::thread member1Thread() {
return std::thread(&Wrapper::member1, this);
}
std::thread member2Thread(const char *arg1, unsigned arg2) {
return std::thread(&Wrapper::member2, this, arg1, arg2);
}
};
int main() {
Wrapper *w = new Wrapper();
std::thread tw1 = w->member1Thread();
tw1.join();
std::thread tw2 = w->member2Thread("hello", 100);
tw2.join();
return 0;
}
Assumption:
list - List<String>
Using Java 8 Streams,
to get first N elements from a list into a list,
List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());
to get first N elements from a list into an Array,
String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);
What should happen if there are more than 1 longest string (think '12', and '01')?
Try that to get the longest element
max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
And then regular foreach
for st in mylist:
if len(st)==max_length:...
First Button submits the form and second does not
<body>
<form ng-app="myApp" ng-controller="myCtrl" ng-submit="Sub()">
<div>
S:<input type="text" ng-model="v"><br>
<br>
<button>Submit</button>
//Dont Submit
<button type='button' ng-click="Dont()">Dont Submit</button>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.Sub=function()
{
alert('Inside Submit');
}
$scope.Dont=function()
{
$scope.v=0;
}
});
</script>
</body>
I've had the same problem, our work environment is based on Eclipse Java projects, and we needed to build automatically an ANT file so that we could use a continuous integration server (Jenkins, in our case).
We rolled out our own Eclipse Java to Ant tool, which is now available on GitHub:
To use it, call:
java -jar ant-build-for-java.jar <folder with repositories> [<.userlibraries file>]
The first argument is the folder with the repositories. It will search the folder recursively for any .project
file. The tool will create a build.xml
in the given folder.
Optionally, the second argument can be an exported .userlibraries file, from Eclipse, needed when any of the projects use Eclipse user libraries. The tool was tested only with user libraries using relative paths, it's how we use them in our repo. This implies that JARs and other archives needed by projects are inside an Eclipse project, and referenced from there.
The tool only supports dependencies from other Eclipse projects and from Eclipse user libraries.
As mysql official documentation:
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
Online Documentation:
YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".
save and open in excel, try refresh data and excel will be monit about parameters.
Document
Document style messages can be validated against predefined schema.
In document style, SOAP message is sent as a single document.
Example of schema:
<types>
<xsd:schema> <xsd:import namespace="http://example.com/"
schemaLocation="http://localhost:8080/ws/hello?xsd=1"/>
</xsd:schema>
</types>
Example of document style soap body message
<message name="getHelloWorldAsString">
<part name="parameters" element="tns:getHelloWorldAsString"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="parameters"> element="tns:getHelloWorldAsStringResponse"/>
</message>
Document style message is loosely coupled.
RPC RPC style messages use method name and parameters to generate XML structure. messages are difficult to be validated against schema. In RPC style, SOAP message is sent as many elements.
<message name="getHelloWorldAsString">
<part name="arg0"> type="xsd:string"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="return"
> type="xsd:string"/>
</message>
Here each parameters are discretely specified, RPC style message is tightly coupled, is typically static, requiring changes to the client when the method signature changes The rpc style is limited to very simple XSD types such as String and Integer, and the resulting WSDL will not even have a types section to define and constrain the parameters
Literal By default style. Data is serialized according to a schema, data type not specified in messages but a reference to schema(namespace) is used to build soap messages.
<soap:body>
<myMethod>
<x>5</x>
<y>5.0</y>
</myMethod>
</soap:body>
Encoded Datatype specified in each parameter
<soap:body>
<myMethod>
<x xsi:type="xsd:int">5</x>
<y xsi:type="xsd:float">5.0</y>
</myMethod>
</soap:body>
Schema free
Try this in your constructor
MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);
The location to set the memory heap size (at least in spark-1.0.0) is in conf/spark-env.
The relevant variables are SPARK_EXECUTOR_MEMORY
& SPARK_DRIVER_MEMORY
.
More docs are in the deployment guide
Also, don't forget to copy the configuration file to all the slave nodes.
You can use the method match()
to extract a substring between two strings. Try the following code:
var str = "My cow always gives milk";
var subStr = str.match("cow(.*)milk");
console.log(subStr[1]);
Output:
always gives
See a complete example here : How to find sub-string between two strings.
To add another answer, the flag -p
(short for --optimize-minimize
) will enable the UglifyJS with default arguments.
You won't get a minified and raw bundle out of a single run or generate differently named bundles so the -p
flag may not meet your use case.
Conversely the -d
option is short for --debug
--devtool sourcemap
--output-pathinfo
My webpack.config.js omits devtool
, debug
, pathinfo
, and the minmize plugin in favor of these two flags.
You're better off looking at argparse for argument parsing.
http://docs.python.org/dev/library/argparse.html
Just makes it easy, no need to do the heavy lifting yourself.
Sounds like ehcache is overkill for what you want, however note that it does not need external configuration files.
It is generally a good idea to move configuration into a declarative configuration files ( so you don't need to recompile when a new installation requires a different expiry time ), but it is not at all required, you can still configure it programmatically. http://www.ehcache.org/documentation/user-guide/configuration
The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.
Task.Factory.StartNew(x=>
throw new Exception("I didn't account for this");
)
However, if we do this, at least the application does not crash.
Task.Factory.StartNew(x=>
try {
throw new Exception("I didn't account for this");
}
catch(Exception ex) {
//Log ex
}
)
Since above code do not cover procedures for extracting list of sheet name for Excel 2007,following code will be applicable for both Excel(97-2003) and Excel 2007 too:
public List<string> ListSheetInExcel(string filePath)
{
OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
String strExtendedProperties = String.Empty;
sbConnection.DataSource = filePath;
if (Path.GetExtension(filePath).Equals(".xls"))//for 97-03 Excel file
{
sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
}
else if (Path.GetExtension(filePath).Equals(".xlsx")) //for 2007 Excel file
{
sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
}
sbConnection.Add("Extended Properties",strExtendedProperties);
List<string> listSheet = new List<string>();
using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
{
conn.Open();
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
{
listSheet.Add(drSheet["TABLE_NAME"].ToString());
}
}
}
return listSheet;
}
Above function returns list of sheet in particular excel file for both excel type(97,2003,2007).
For some reason, I get that error unless I add the "bash" clarifier. Even adding "#!/bin/bash" to the top of my entrypoint file didn't help.
ENTRYPOINT [ "bash", "entrypoint.sh" ]
try this:
var x = function() {
return 1;
};
var t = function(a,b,c) {
return a+b+c;
};
Function.prototype.clone = function() {
var that = this;
var temp = function temporary() { return that.apply(this, arguments); };
for(var key in this) {
if (this.hasOwnProperty(key)) {
temp[key] = this[key];
}
}
return temp;
};
alert(x === x.clone());
alert(x() === x.clone()());
alert(t === t.clone());
alert(t(1,1,1) === t.clone()(1,1,1));
alert(t.clone()(1,1,1));
Beginners needs practical examples. so try the following code.
public class Not_a_Number {
public static void main(String[] args) {
// TODO Auto-generated method stub
String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";
String dottedLine = "------------------------------------------------";
Double numerator = -2.0;
Double denominator = -2.0;
while (denominator <= 1) {
Double x = numerator/denominator;
Double y = new Double (x);
boolean z = y.isNaN();
System.out.println("y = " + y);
System.out.println("z = " + z);
if (z == true){
System.out.println(message);
}
else {
System.out.println("Hi, everyone");
}
numerator = numerator + 1;
denominator = denominator +1;
System.out.println(dottedLine);
} // end of while
} // end of main
} // end of class
Things to ponder:
this
is your code refering togetElementById
usually document.getElementById
?1) In manifest : - call receiver like below code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.safal.checkinternet">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
2) Make one Broad Cast Receiver Class: - In This class add code of Network Check
package com.safal.checkinternet;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if (isOnline(context)){
Toast.makeText(context, "Available", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Not Available", Toast.LENGTH_SHORT).show();
}
}
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
}
3) In your Activity call to Broad Cast Receiver : -
package com.safal.checkinternet;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Call Broad cast Receiver
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(new NetworkChangeReceiver(), filter);
}
}
The particular format for strptime
:
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)
Look at it like this - while you can write a game in C#, it isn't going to open many career doors for you. If you know C++ and Lua, then you're going to be far more employable.
You're also not just talking about PC desktops and Consoles, games nowadays are very much for the mobile devices, so only knowing C# would limit you even further. Sure, C++ isn't going to be the optimal choice for writing iPhone apps, but you're going to be far closer to being an objective-C programmer if you know C++ than if you know C#.
Games devs use C++ not for legacy reasons (though having establish C++ engines and libraries helps) but for performance and experience. Game devs know C++, it works for them very well, so there's no need to change. Its not like line-of-business apps (on Windows) where the developer mindshare moves with the current Microsoft tools.
The code:
public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
The output of java Test abcdef
:
last character: f
Use this, 100% guaranteed:-
vr {
margin-left: 20px;
margin-right: 20px;
height: 50px;
border: 0;
border-left: 1px solid #cccccc;
display: inline-block;
vertical-align: bottom;
}
I had the same issue when I used a DockerFile. My Docker is based on the php:5.5-apache image.
I got that error when executing the command "RUN docker-php-ext-install soap"
I have solved it by adding the following command to my DockerFile
"RUN apt-get update && apt-get install -y libxml2-dev"
Note a similar error such as:
standard_init_linux.go:211: exec user process caused "no such file or directory"
can happen if the architecture an image was built for does not match the one of your system. For instance, trying to run an image built for arm64
on a x86_64
machine can generate this error.
Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.
for (var start = 1; start < 10; start++)
setTimeout(function () { alert('hello'); }, 3000 * start);
The first timeout will be set to 3000 * 1
, the second to 3000 * 2
and so on.
Is the standard procedure not working?
git stash save
git branch xxx HEAD
git checkout xxx
git stash pop
Shorter:
git stash
git checkout -b xxx
git stash pop
you can simply make it transparent
{
width: 20px;
height: 20px;
overflow: hidden;
color:transparent;
}
The easiest way to do this is:
list.sort(key = lambda x:len(x))
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
by now the mounting works on some machines (ubuntu) and some doesn't (centos 7) but installing the plugin solves it
vagrant plugin install vagrant-vbguest
without having to do anything else on top of that, just
vagrant reload
Basically, the module cannot be instantiated. When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.
A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance". OO purists will disagree with that statement, but don't let purity get in the way of getting the job done.
(This answer originally linked to http://www.rubycentral.com/pickaxe/classes.html
, but that link and its domain are no longer active.)
Use org.apache.commons.lang3.StringUtils
String emptyString = new String();
result = StringUtils.defaultIfEmpty(emptyString, "default");
System.out.println(result);
String nullString = null;
result = StringUtils.defaultIfEmpty(nullString, "default");
System.out.println(result);
Both of the above options will print:
default
default
Ruby has no pre/post increment/decrement operator. For instance,
x++
orx--
will fail to parse. More importantly,++x
or--x
will do nothing! In fact, they behave as multiple unary prefix operators:-x == ---x == -----x == ......
To increment a number, simply writex += 1
.
Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)
That explains it better than I ever could.
EDIT: and the reason from the language author himself (source):
- ++ and -- are NOT reserved operator in Ruby.
- C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
- self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
If openssl installation was successfull, search for "OPENSSL" in c drive to locate the config file and set the path.
set OPENSSL_CONF=<location where cnf is available>/openssl.cnf
It worked out for me.
Putting *args
and/or **kwargs
as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:
def my_sum(*args):
return sum(args)
It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.
You don’t actually have to call them args
and kwargs
, that’s just a convention. It’s the *
and **
that do the magic.
The official Python documentation has a more in-depth look.
For anyone else coming across this thread I had this issue and was pulling my hair out. I had the service declaration OUTSIDE of the '< application>' end tag DUH!
RIGHT:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity ...>
...
</activity>
<service android:name=".Service"/>
<receiver android:name=".Receiver">
<intent-filter>
...
</intent-filter>
</receiver>
</application>
<uses-permission android:name="..." />
WRONG but still compiles without errors:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity ...>
...
</activity>
</application>
<service android:name=".Service"/>
<receiver android:name=".Receiver">
<intent-filter>
...
</intent-filter>
</receiver>
<uses-permission android:name="..." />
A variable cannot be both null
and undefined
at the same time. However, the direct answer to your question is:
if (variable != null)
One =
, not two.
There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null
and the other being undefined
, and the result is true
for ==
and false
for !=
. Thus if the value of the variable is undefined
, it's not != null
, and if it's not null, it's obviously not != null
.
Now, the case of an identifier not being defined at all, either as a var
or let
, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:
var isDefined = false;
try {
(variable);
isDefined = true;
}
catch (x) {}
I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window
property (in browser JavaScript):
var isJqueryAvailable = window.jQuery != null;
or
var isJqueryAvailable = "jQuery" in window;
You need to re-add that certificate to your machine or chose another certificate.
To choose another certificate or to recreate one, head over to the Project's properties page, click on Signing tab and either
Once either of these is done, you should be able to build it again.
I did not find Haiku definition here. To be complete, Haiku-os definition is simple __HAIKU__
And if you have more than two lists to concatenate:
import operator
from functools import reduce # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])
# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)
It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args
.
Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read}
and all was fine.
AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/check" //check.xml
android:background="@null"/>
check.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
You could take advantage of ASCII value for each letter and take off 55, easy and fast:
int asciiOffset = 55;
char hex = Character.toUpperCase('A'); // Only A-F uppercase
int val = hex - asciiOffset;
System.out.println("hexadecimal:" + hex);
System.out.println("decimal:" + val);
Output:
hexadecimal:A
decimal:10
I had a similar issue where I needed to select values from a large array, but I wanted the resulting collection to only contain values of a single value.
pluck()
could be used for this purpose (if only 1 key item is required)
you could also use reduce()
. Something like this with reduce:
$result = $items->reduce(function($carry, $item) {
return $carry->push($item->getCode());
}, collect());
private class GetProfileRequestAsyncTasks extends AsyncTask<String, Void, JSONObject> {
@Override
protected void onPreExecute() {
}
@Override
protected JSONObject doInBackground(String... urls) {
if (urls.length > 0) {
String url = urls[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.setHeader("x-li-format", "json");
try {
HttpResponse response = httpClient.execute(httpget);
if (response != null) {
//If status is OK 200
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
//Convert the string result to a JSON Object
return new JSONObject(result);
}
}
} catch (IOException e) {
} catch (JSONException e) {
}
}
return null;
}
@Override
protected void onPostExecute(JSONObject data) {
if (data != null) {
Log.d(TAG, String.valueOf(data));
}
}
}
I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.
import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)
np.split(df, [100,200,300], axis=0]
wants explicit index numbers which may or may not be desirable.
Solutions:
Solution A:
com.oreilly.servlet.MultipartRequest
Solution B:
org.apache.commons.fileupload.MultipartStream
Solution C:
Solution D:
Use Struts. Struts 1.1 handles this automatically.
With the newest API, here's the code I used for it
/*params*/
NSDictionary *params = @{
@"access_token": [[FBSDKAccessToken currentAccessToken] tokenString],
@"fields": @"id"
};
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:@"me"
parameters:params
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSDictionary *res = result;
//res is a dict that has the key
NSLog([res objectForKey:@"id"]);
pyPDF works fine (assuming that you're working with well-formed PDFs). If all you want is the text (with spaces), you can just do:
import pyPdf
pdf = pyPdf.PdfFileReader(open(filename, "rb"))
for page in pdf.pages:
print page.extractText()
You can also easily get access to the metadata, image data, and so forth.
A comment in the extractText code notes:
Locate all text drawing commands, in the order they are provided in the content stream, and extract the text. This works well for some PDF files, but poorly for others, depending on the generator used. This will be refined in the future. Do not rely on the order of text coming out of this function, as it will change if this function is made more sophisticated.
Whether or not this is a problem depends on what you're doing with the text (e.g. if the order doesn't matter, it's fine, or if the generator adds text to the stream in the order it will be displayed, it's fine). I have pyPdf extraction code in daily use, without any problems.
I usually prefer to work with deltas in translate animation, since it avoids a lot of confusion.
Try this out, see if it works for you:
TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);
anim.setAnimationListener(new TranslateAnimation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation)
{
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
params.topMargin += amountToMoveDown;
params.leftMargin += amountToMoveRight;
view.setLayoutParams(params);
}
});
view.startAnimation(anim);
Make sure to make amountToMoveRight
/ amountToMoveDown
final
Hope this helps :)
"As with bootstrap’s own plugins, datepicker provides a data-api that can be used to instantiate datepickers without the need for custom javascript..."
Boostrap DatePicker Documentation
Maybe you want to set format without DatePicker instance, for that, you have to add the property data-date-format="DateFormat"
to main Div tag, for example:
<div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
<input type="text" name="YourName" id="YourId" class="YourClass">
</div>
function isNumberKey(evt,id)_x000D_
{_x000D_
try{_x000D_
var charCode = (evt.which) ? evt.which : event.keyCode;_x000D_
_x000D_
if(charCode==46){_x000D_
var txt=document.getElementById(id).value;_x000D_
if(!(txt.indexOf(".") > -1)){_x000D_
_x000D_
return true;_x000D_
}_x000D_
}_x000D_
if (charCode > 31 && (charCode < 48 || charCode > 57) )_x000D_
return false;_x000D_
_x000D_
return true;_x000D_
}catch(w){_x000D_
alert(w);_x000D_
}_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<INPUT id="txtChar" onkeypress="return isNumberKey(event,this.id)" type="text" name="txtChar">_x000D_
</body>_x000D_
</html>
_x000D_
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.
char *ptr = "Hello";
printf("%40s\n", ptr);
That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).
If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf
statements like the one above, or do it in a loop, changing the value of ptr
each time.
I found that when inserting, the null column values had to be specifically declared as NULL, otherwise I would get a constraint violation error (as opposed to an empty string).
Reformat affects the whole source code and may rebreak your lines, while Correct Indentation only affects the whitespace at the beginning of the lines.
I had the same problem for a while, replacing: smtp.gmail.com
with 173.194.65.108
actually worked for me!
You can just pass the column names as a list with specifying the axis as 0 or 1
By default axis=0
data.drop(["Colname1","Colname2","Colname3","Colname4"],axis=1)
In most use-cases using StringBuilder
or substring
is a good approach (as already answered). However, for performance critical code, this might be a good alternative.
/**
* Delete a single character from index position 'start' from the 'target' String.
*
* ````
* deleteAt("ABC", 0) -> "BC"
* deleteAt("ABC", 1) -> "B"
* deleteAt("ABC", 2) -> "C"
* ````
*/
public static String deleteAt(final String target, final int start) {
return deleteAt(target, start, start + 1);
}
/**
* Delete the characters from index position 'start' to 'end' from the 'target' String.
*
* ````
* deleteAt("ABC", 0, 1) -> "BC"
* deleteAt("ABC", 0, 2) -> "C"
* deleteAt("ABC", 1, 3) -> "A"
* ````
*/
public static String deleteAt(final String target, final int start, int end) {
final int targetLen = target.length();
if (start < 0) {
throw new IllegalArgumentException("start=" + start);
}
if (end > targetLen || end < start) {
throw new IllegalArgumentException("end=" + end);
}
if (start == 0) {
return end == targetLen ? "" : target.substring(end);
} else if (end == targetLen) {
return target.substring(0, start);
}
final char[] buffer = new char[targetLen - end + start];
target.getChars(0, start, buffer, 0);
target.getChars(end, targetLen, buffer, start);
return new String(buffer);
}
To use a simple example, I had a counter that needed to summarise unique IP addresses per visited page on a site. Which is basically grouping by pagename and then by IP. I solved it with a combination of DISTINCT and GROUP BY.
SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;
Try using String.getBytes(). It returns a byte[] representing string data. Example:
String data = "sample data";
byte[] byteData = data.getBytes();
Here is a single-liner of how you can delete ALL browser network cache using Cache.delete()
caches.keys().then((keyList) => Promise.all(keyList.map((key) => caches.delete(key))))
Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.
Many ORM's are great, you need to know why you want to add abstraction on top of JDBC. I can recommend http://www.jooq.org to you (disclaimer: I'm the creator of jOOQ, so this answer is biased). jOOQ embraces the following paradigm:
There are many other good ORM's. Especially Hibernate or iBATIS have a great community. But if you're looking for an intuitive, simple one, I'll say give jOOQ a try. You'll love it! :-)
Check out this example SQL:
// Select authors with books that are sold out
SELECT *
FROM T_AUTHOR a
WHERE EXISTS (SELECT 1
FROM T_BOOK
WHERE T_BOOK.STATUS = 'SOLD OUT'
AND T_BOOK.AUTHOR_ID = a.ID);
And how it can be expressed in jOOQ:
// Alias the author table
TAuthor a = T_AUTHOR.as("a");
// Use the aliased table in the select statement
create.selectFrom(a)
.whereExists(create.selectOne()
.from(T_BOOK)
.where(T_BOOK.STATUS.equal(TBookStatus.SOLD_OUT)
.and(T_BOOK.AUTHOR_ID.equal(a.ID))))));
You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.
It's kind of hard to tell in your exact situation but I'd probably use a v-for
and make an array of finds
to push to as I need more.
Here's how I'd set up my instance:
new Vue({
el: '#app',
data: {
finds: []
},
methods: {
addFind: function () {
this.finds.push({ value: '' });
}
}
});
And here's how I'd set up my template:
<div id="app">
<h1>Finds</h1>
<div v-for="(find, index) in finds">
<input v-model="find.value" :key="index">
</div>
<button @click="addFind">
New Find
</button>
</div>
Although, I'd try to use something besides an index
for the key
.
Here's a demo of the above: https://jsfiddle.net/crswll/24txy506/9/
You want hasOwnProperty()
:
var myObj1 = { _x000D_
prop1: 'no',_x000D_
prop2: function () { return false; }_x000D_
}_x000D_
var myObj2 = { _x000D_
prop1: 'no'_x000D_
}_x000D_
_x000D_
console.log(myObj1.hasOwnProperty('prop2')); // returns true_x000D_
console.log(myObj2.hasOwnProperty('prop2')); // returns false_x000D_
_x000D_
References: Mozilla, Microsoft, phrogz.net.
You can also use the following syntax for the strongly typed version:
<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(),
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ %>
You either need to disable the --strictPropertyInitialization
that
Sajeetharan referred to, or do something like this to satisfy the initialization requirement:
makes: any[] = [];
David Wolever's solution is good, but
If you want to have signed angles you have to determine if a given pair is right or left handed (see wiki for further info).
My solution for this is:
def unit_vector(vector):
""" Returns the unit vector of the vector"""
return vector / np.linalg.norm(vector)
def angle(vector1, vector2):
""" Returns the angle in radians between given vectors"""
v1_u = unit_vector(vector1)
v2_u = unit_vector(vector2)
minor = np.linalg.det(
np.stack((v1_u[-2:], v2_u[-2:]))
)
if minor == 0:
raise NotImplementedError('Too odd vectors =(')
return np.sign(minor) * np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
It's not perfect because of this NotImplementedError
but for my case it works well. This behaviour could be fixed (cause handness is determined for any given pair) but it takes more code that I want and have to write.
__construct
was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor).
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.
An example could go like this:
class Database {
protected $userName;
protected $password;
protected $dbName;
public function __construct ( $UserName, $Password, $DbName ) {
$this->userName = $UserName;
$this->password = $Password;
$this->dbName = $DbName;
}
}
// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );
Everything else is explained in the PHP manual: click here
Here is a version with configurable parameters that you can set programmatically:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />
<xsl:param name="delim" select="','" />
<xsl:param name="quote" select="'"'" />
<xsl:param name="break" select="'
'" />
<xsl:template match="/">
<xsl:apply-templates select="projects/project" />
</xsl:template>
<xsl:template match="project">
<xsl:apply-templates />
<xsl:if test="following-sibling::*">
<xsl:value-of select="$break" />
</xsl:if>
</xsl:template>
<xsl:template match="*">
<!-- remove normalize-space() if you want keep white-space at it is -->
<xsl:value-of select="concat($quote, normalize-space(), $quote)" />
<xsl:if test="following-sibling::*">
<xsl:value-of select="$delim" />
</xsl:if>
</xsl:template>
<xsl:template match="text()" />
</xsl:stylesheet>
instead of using jsonObject try using CsvSchema its way easier and directly converts object to csv
CsvSchema schema = csvMapper.schemaFor(MyClass.class).withHeader();
csvMapper.writer(schema).writeValueAsString(myClassList);
and it mentains the order id your pojo has @JsonPropertyOrder in it
Could someone explain to me, how to call the move method with the variable RIGHT
>>> myMissile = MissileDevice(myBattery) # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)
If you have programmed in any other language with classes, besides python, this sort of thing
class Foo:
bar = "baz"
is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; and variables defined in its scope are attached to the class, not the instances returned by the class. to refer to bar
, above, you can just call it Foo.bar
; you can also access class attributes through instances of the class, like Foo().bar
.
Im utterly baffled about what 'self' refers too,
>>> class Foo:
... def quux(self):
... print self
... print self.bar
... bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>
When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. All this does is arrange for the instance to be passed as the first argument.
This worked for me
Deactivate AdBlock.
Go to inspect -> settings gear -> Uncheck 'enable javascript source maps' and 'enable css source map'.
Refresh.
For those using VPS / virtual hosting.
I was using a VPS, getting errors with MySQL not being able to write to /tmp, and everything looked correct. I had enough free space, enough free inodes, correct permissions. Turned out the problem was outside my VPS, it was the machine hosting the VPS that was full. I only had "virtual space" in my file system, but the machine in the background which hosted the VPS had no "physical space" left. I had to contact the VPS company any they fixed it.
If you think this might be your problem, you could test writing a larger file to /tmp (1GB):
dd if=/dev/zero of=/tmp/file.txt count=1024 bs=1048576
I got a No space left on device
error message, which was a giveaway that it was a disk/volume in the background that was full.
Use FSO to create the file and write to it.
Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test"
oFile.Close
Set fso = Nothing
Set oFile = Nothing
See the documentation here:
By using the column that the index is applied to within your conditions, it will be included automatically. You do not have to use it, but it will speed up queries when it is used.
SELECT * FROM TABLE WHERE attribute = 'value'
Will use the appropriate index.
1.downlad nvm
2.install chocolaty
3.change C:\Program Files\node to C:\Program Files\nodejsx
emphasized textThe first thing that we need to do is install NVM. website : https://docs.microsoft.com/en-us/windows/nodejs/setup-on-windows
I also liked pandas simple grouping. it's powerful, simple and most adequate for large data set
result = pandas.DataFrame(input).groupby(1).groups
You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile
g++ -std=c++0x *.cpp -o output
Try casting the ints to varchar, before adding them to a string:
SET @ActualWeightDIMS = cast(@Actual_Dims_Lenght as varchar(8)) +
'x' + cast(@Actual_Dims_Width as varchar(8)) +
'x' + cast(@Actual_Dims_Height as varhcar(8))
Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function. Also see this answer.
class Foo(object):
# Class variable, shared by all instances of this class
counter = 0
def __call__(self):
Foo.counter += 1
print Foo.counter
# Create an object instance of class "Foo," called "foo"
foo = Foo()
# Make calls to the "__call__" method, via the object's name itself
foo() #prints 1
foo() #prints 2
foo() #prints 3
Note that __call__
makes an instance of a class (object) callable by its own name. That's why calling foo()
above calls the class' __call__
method. From the documentation:
Instances of arbitrary classes can be made callable by defining a
__call__()
method in their class.
Because in development , you will always want to recreate the database,you can define a rake task in your lib/tasks folder like that.
namespace :db do
task :all => [:environment, :drop, :create, :migrate] do
end
end
and in terminal you will run
rake db:all
it will rebuild your database
You may use bellow like in angular 9
<select [(ngModel)]="itemId" formControlName="itemId" class="form-control" >
<option [ngValue]="" disabled>Choose Gender</option>
<option *ngFor="let item of items" [ngValue]="item .id" [selected]="item .id == this.id" >
{{item.name}}
</option>
</select>
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
Yes: TIME_CREATED contains a date and a time. Use TRUNC
to strip the time:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')
UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED
if it exists. An alternative approach without this problem is this:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1
I was experiencing the same problem, and after a bit of experimentation I found a solution. In my click handler, I needed to stop the event from bubbling up, like so:
$("a.close").on("click", function(e){
$("#modal").modal("hide");
e.stopPropagation();
});
You could use the re.sub() method to replace anything not "filelike". But in effect, every character could be valid; so there are no prebuilt functions (I believe), to get it done.
import re
str = "File!name?.txt"
f = open(os.path.join("/tmp", re.sub('[^-a-zA-Z0-9_.() ]+', '', str))
Would result in a filehandle to /tmp/filename.txt.
I think this is bit round-about explanation but still it clarifies using real life example.
Small Example:
Let's say playing an audio involves three steps:
If your audio player does step 1,2,3 sequentially for every song then it is synchronous. You will have to wait for some time to hear the song till the song actually gets fetched and decompressed.
If your audio player does step 1,2,3 independent of each other, then it is asynchronous. ie. While playing audio 1 ( step 3), if it fetches audio 3 from harddisk in parallel (step 1) and it decompresses the audio 2 in parallel. (step 2 ) You will end up in hearing the song without waiting much for fetch and decompress.
If you have multiple numbers per line and you have multiple lines, you can read them in like this:
#!/usr/bin/env python
from os.path import dirname
with open(dirname(__file__) + '/data/path/filename.txt') as input_data:
input_list= [map(int,num.split()) for num in input_data.readlines()]
You should not wrap JavaScript expressions in quotes.
<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>
Take a look at the JavaScript Expressions docs for more info.
Because i'm lazy....
import json
a = [1,2,3]
with open('test.txt', 'w') as f:
f.write(json.dumps(a))
#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
a = json.loads(f.read())
You can put them in the Application:
Application["GlobalVar"] = 1234;
They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.
In addition to what other have said, you may also be interested to know that what in
does is to call the list.__contains__
method, that you can define on any class you write and can get extremely handy to use python at his full extent.
A dumb use may be:
>>> class ContainsEverything:
def __init__(self):
return None
def __contains__(self, *elem, **k):
return True
>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>
When you create a virtual device from Android Studio pay attention to the Play Store Column in the device table. The images with the play store icon have google play pre-installed.
?? In system images that come with google play root is not available.
After you've created the AVD you'll also be able to see from the Android Studio AVD Manager which of your images have google play installed:
you can write a stored procedure like this:
CREATE PROCEDURE sanitize_TABLE()
BEGIN
#replace space with underscore
UPDATE Table SET FieldName = REPLACE(FieldName," ","_") WHERE FieldName is not NULL;
#delete dot
UPDATE Table SET FieldName = REPLACE(FieldName,".","") WHERE FieldName is not NULL;
#delete (
UPDATE Table SET FieldName = REPLACE(FieldName,"(","") WHERE FieldName is not NULL;
#delete )
UPDATE Table SET FieldName = REPLACE(FieldName,")","") WHERE FieldName is not NULL;
#raplace or delete any char you want
#..........................
END
In this way you have modularized control over table.
You can also generalize stored procedure making it, parametric with table to sanitoze input parameter
It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).
Here is a nice CANCEL SIP Call Flow illustration.
If you need a quick, efficient and elegant logout
functionality for JWT-based logins (which is in fact the primary reason to invalidate JWT) here is how: replace the current token with a token that expires say in 1 second.
In details:
As you make the /logout
request from client with the valid JWT attached, delete the JWT you keep in your local storage (if you keep any there for your "remember me" functionality).
Then when the request arrives on server /logout
route handler:
redirect
response and the tocken in the response body. The redirect can be to any public route (say. /home
). Or you can respond with normal non-redirect response to later make desired redirections on client.Now on client
As simple as that. You just got the usual log out on-demand functionality with JWT.
Yes it does not invalidate the original JWT. If anyone (attacker) has hijacked and saved it before he still could use it till it expired. However his window of opportunity is shrinking with the time.
But, here comes the second part of the solution: a very short-lived (10 minutes?) original JWT and longer lived refresh token saved in DB and actually being revoked or deleted from the DB.
Or than blacklisting/whitelisting original JWT or similar approaches mentioned above could be used here.
The quick solution can be applied for loser security requirements. Refresh tockens/blacklist/whitelist part can be added for stricter security requirements cases.
Anyway it is simpler and on-demand extendable aproach.
Simply use this for the so far latest version 4.1.0.
pip install opencv-contrib-python==4.1.0.25
For default version use this:
pip install opencv-contrib-python
My problem was that I didn't accept the connection from the computer after turning on remote debugging. Once I accept the mac address, it went away. Silly mistake, but I didn't see the dialog box the first time. Worth a quick check if the others don't resolve the issue. But likely only a problem the first time you set up a phone.
If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.
Note that if you are using a Portable Class Library, HttpClient will not have PostAsJsonAsync method. To post a content as JSON using a Portable Class Library, you will have to do this:
HttpClient client = new HttpClient();
HttpContent contentPost = new StringContent(argsAsJson, Encoding.UTF8,
"application/json");
await client.PostAsync(new Uri(wsUrl), contentPost).ContinueWith(
(postTask) => postTask.Result.EnsureSuccessStatusCode());
for windows users go to HELP> CHECK FOR UPDATES>UPDATE(click the link updates)
I faced the same issue in my scenario as follow:
I created textbook table first with
create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );
Then chapter table:
create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40),
constraint pk_chapter primary key(txtbk_isbn,chapter_title),
constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));
Then topic table:
create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));
Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn) references textbook(txtbk_isbn),
foreign key (chapter_title) references chapter(chapter_title),
foreign key (topic_id) references topic (topic_id));
The solution was to refer to composite foreign key as below:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title),
foreign key (topic_id) references topic (topic_id));
Thanks to APC post in which he mentioned in his post a statement that:
Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED
Java 8 implementation (List initialized with 60
zeroes):
List<Integer> list = IntStream.of(new int[60])
.boxed()
.collect(Collectors.toList());
new int[N]
- creates an array filled with zeroes & length N boxed()
- each element boxed to an Integercollect(Collectors.toList())
- collects elements of streamSafest option is
Lastrow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
Lastcol = Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column
Don't use UsedRange
or SpecialCells(xlLastCell)
or End(xlUp)
. All these methods may give wrong results if you previously deleted some rows. Excel still counts these invisible cells.
These methods will work again if you delete your cells, save the workbook, close and re-open it.
An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.
angular.http provides an option for it called params
.
$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params
param)
It sounds like what you really want to do is implement an interface.
Your interface will specify the methods that the object can handle and when you pass an object that implements the interface to a method that wants an object that supports the interface, you just type the argument with the name of the interface.
This is older but placing this here for my reference too. boto3.resource is just implementing the default Session, you can pass through boto3.resource session details.
Help on function resource in module boto3:
resource(*args, **kwargs)
Create a resource service client by name using the default session.
See :py:meth:`boto3.session.Session.resource`.
https://github.com/boto/boto3/blob/86392b5ca26da57ce6a776365a52d3cab8487d60/boto3/session.py#L265
you can see that it just takes the same arguments as Boto3.Session
import boto3
S3 = boto3.resource('s3', region_name='us-west-2', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY)
S3.Object( bucket_name, key_name ).delete()
To achieve that one can do it in several ways, namely:
Methods that return the number of occurrence of a single element:
Collections.frequency(animals, "bat");
Java Stream:
Filter
animals.stream().filter("bat"::equals).count();
Just iteration thought the list
public static long manually(Collection<?> c, Object o){
int count = 0;
for(Object e : c)
if(e.equals(o))
count++;
return count;
}
Methods that create a map of frequencies:
Map<String, Long> counts =
animals.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<String, Long> map = new HashMap<>();
c.forEach(e -> map.merge(e, 1L, Long::sum));
Manually
Map<String, Integer> mp = new HashMap<>();
animals.forEach(animal -> mp.compute(animal, (k, v) -> (v == null) ? 1 : v + 1));
A running example with all the methods:
public class Frequency {
public static int frequency(Collection<?> c, Object o){
return Collections.frequency(c, o);
}
public static long filter(Collection<?> c, Object o){
return c.stream().filter(o::equals).count();
}
public static long manually(Collection<?> c, Object o){
int count = 0;
for(Object e : c)
if(e.equals(o))
count++;
return count;
}
public static Map<?, Long> mapGroupBy(Collection<?> c){
return c.stream()
.collect(Collectors.groupingBy(Function.identity() , Collectors.counting()));
}
public static Map<Object, Long> mapMerge(Collection<?> c){
Map<Object, Long> map = new HashMap<>();
c.forEach(e -> map.merge(e, 1L, Long::sum));
return map;
}
public static Map<Object, Long> manualMap(Collection<?> c){
Map<Object, Long> map = new HashMap<>();
c.forEach(e -> map.compute(e, (k, v) -> (v == null) ? 1 : v + 1));
return map;
}
public static void main(String[] args){
List<String> animals = new ArrayList<>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");
System.out.println(frequency(animals, "bat"));
System.out.println(filter(animals,"bat"));
System.out.println(manually(animals,"bat"));
mapGroupBy(animals).forEach((k, v) -> System.out.println(k + " -> "+v));
mapMerge(animals).forEach((k, v) -> System.out.println(k + " -> "+v));
manualMap(animals).forEach((k, v) -> System.out.println(k + " -> "+v));
}
}
The methods name should have reflected what those methods are doing, however, I used the name to reflect the approach being used instead (given that in the current context it is okey).
ALL_CONSTRAINTS
describes constraint definitions on tables accessible to the current user.
DBA_CONSTRAINTS
describes all constraint definitions in the database.
USER_CONSTRAINTS
describes constraint definitions on tables in the current user's schema
Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from
USER_CONSTRAINTS;
To check if the property exists and if it's null too, you can use the function property_exists()
.
Docs: http://php.net/manual/en/function.property-exists.php
As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.
bool property_exists ( mixed $class , string $property )
Example:
if (property_exists($testObject, $property)) {
//do something
}
Same concept as a .jar
file in Java, it is a .zip
file with some metadata files renamed .egg
, for distributing code as bundles.
Specifically: The Internal Structure of Python Eggs
A "Python egg" is a logical structure embodying the release of a specific version of a Python project, comprising its code, resources, and metadata. There are multiple formats that can be used to physically encode a Python egg, and others can be developed. However, a key principle of Python eggs is that they should be discoverable and importable. That is, it should be possible for a Python application to easily and efficiently find out what eggs are present on a system, and to ensure that the desired eggs' contents are importable.
The
.egg
format is well-suited to distribution and the easy uninstallation or upgrades of code, since the project is essentially self-contained within a single directory or file, unmingled with any other projects' code or resources. It also makes it possible to have multiple versions of a project simultaneously installed, such that individual programs can select the versions they wish to use.
This may help somebody in future that's why adding this answer.
In my Case for android studio project. I have to enable Places API as well to get suggestions
This works for me.
My trick is using an attribute selector. Attributes are easier to set up by javascript.
css
.class{ /*normal css... */}
.class[special]:after{ content: 'what you want'}
javascript
function setSpecial(id){ document.getElementById(id).setAttribute('special', '1'); }
html
<element id='x' onclick="setSpecial(this.id)"> ...
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
That loads all the DLLs present in your executable's folder.
In my case I was trying to use Reflection
to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.
EDIT: I timed it, and it only seems to load them the first time.
Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
stopwatch.Restart();
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
Output: 34 0 0 0
So one could potentially run that code before any Reflection searches just in case.
You could use a Bash C Style For Loop to do what you want.
my_array=(one two three)
for ((i=0; i < ${#my_array[@]}; i++ )); do echo "${my_array[$i]}"; done
one
two
three
Try:
if (_checkbox.addEventListener) {
_checkbox.addEventListener("click", setCheckedValues, false);
}
else {
_checkbox.attachEvent("onclick", setCheckedValues);
}
Update:: For Internet Explorer versions prior to IE9, attachEvent method should be used to register the specified listener to the EventTarget it is called on, for others addEventListener should be used.
$smpt = $pdo->prepare("SHOW fields FROM __TABLE__NAME__");
$smpt->execute();
$res = $smpt->fetchAll(PDO::FETCH_ASSOC);
//print_r($res);
Then in $res by cycle look for key of your column Smth like this:
if($field['Field'] == '_my_col_'){
return true;
}
+
**Below code is good for checking column existing in the WordPress tables:**
public static function is_table_col_exists($table, $col)
{
global $wpdb;
$fields = $wpdb->get_results("SHOW fields FROM {$table}", ARRAY_A);
foreach ($fields as $field)
{
if ($field['Field'] == $col)
{
return TRUE;
}
}
return FALSE;
}
When using functional components, you will often get the TypeError: Cannot add property myNewProp, object is not extensible
error when trying to set new properties on props.children
. There is a work around to this by cloning the props and then cloning the child itself with the new props.
const MyParentComponent = (props) => {
return (
<div className='whatever'>
{props.children.map((child) => {
const newProps = { ...child.props }
// set new props here on newProps
newProps.myNewProp = 'something'
const preparedChild = { ...child, props: newProps }
return preparedChild
})}
</div>
)
}
You don't have a validator on the page. Add something like this to show the validation message.
@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
We can Remove or Delete a specified column or sprcified columns by drop() method.
Suppose df is a dataframe.
Column to be removed = column0
Code:
df = df.drop(column0, axis=1)
To remove multiple columns col1, col2, . . . , coln, we have to insert all the columns that needed to be removed in a list. Then remove them by drop() method.
Code:
df = df.drop([col1, col2, . . . , coln], axis=1)
I hope it would be helpful.
One More Thing...
Kyralessa provides great information but I have one other thing to add where I was stumped even after this article.
Under SQL Server Network Configuration > Protocols for Server > TCP/IP Enabled. Right Click TCP/IP and choose properties. Under the IP Addresses you need to set Enabled to Yes for each connection type that you are using.
This happens to me when I'm using Jinja2 for templates. The problem can be solved by running the development server using the runserver_plus
command from django_extensions.
It uses the werkzeug debugger which also happens to be a lot better and has a very nice interactive debugging console. It does some ajax magic to launch a python shell at any frame (in the call stack) so you can debug.
this works well without any special function needed. Much easier to write with php as well. <input onclick="this.form.submit()"/>
Adding to John and Tim's answer.
Unless you are coding for Win98, there are only two of the 6+ string types you should be using in your application
LPWSTR
LPCWSTR
The rest are meant to support ANSI platforms or dual compilations. Those are not as relevant today as they used to be.
Another javascript library worth mentioning is pdfmake.
The browser support does not appear to be as strong as jsPDF, nor does there seem to be an option for shapes, but the options for formatting text are more advanced then the options currently available in jsPDF.
Apparently you also get this error message when you forget the --all
parameter when pushing for the first time. I wrote
git push -u origin
which gave this error, it should have been
git push -u origin --all
Oh how I love these copy-paste errors ...
via Powershell
Remove-Item -Recurse -Force "TestDirectory"
via Command Prompt
We can decode json string into array using json_decode function in php
1) json_decode($json_string) // it returns object
2) json_decode($json_string,true) // it returns array
$json_string = '{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$array = json_decode($json_string,true);
echo $array['type']; //it gives donut
std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.
error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
std::unique_ptr<int>]'
The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.
The following works with the new emplace calls.
std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );
See using unique_ptr with standard library containers for further reading.
Just in case if for example you need to put a min date, the last 3 months and max date next 3 months
$('#id_your_date').datepicker({
maxDate: '+3m',
minDate: '-3m'
});
Posting because when I started LINQ + EntityFramework, I stared at these examples for a day.
If you are using EntityFramework, and you have a navigation property named Meta
on your Post
model object set up, this is dirt easy. If you're using entity and don't have that navigation property, what are you waiting for?
database
.Posts
.Where(post => post.ID == id)
.Select(post => new { post, post.Meta });
If you're doing code first, you'd set up the property thusly:
class Post {
[Key]
public int ID {get; set}
public int MetaID { get; set; }
public virtual Meta Meta {get; set;}
}
let me know, thanks
Another solution that does not involve converting to/from strings:
from math import log10
def decompose(n):
if n == 0:
return [0]
b = int(log10(n)) + 1
return [(n // (10 ** i)) % 10 for i in reversed(range(b))]
property 'map' does not exist on type 'observable response ' angular 6
Solution: Update Angular CLI And Core Version
ng update @angular/cli //Update Angular CLi
ng update @angular/core //Update Angular Core
npm install --save rxjs-compat //For Map Call For Post Method
I see that neither is faster. The compiler generates the same machine code in each condition with a different value.
if(a < 901)
cmpl $900, -4(%rbp)
jg .L2
if(a <=901)
cmpl $901, -4(%rbp)
jg .L3
My example if
is from GCC on x86_64 platform on Linux.
Compiler writers are pretty smart people, and they think of these things and many others most of us take for granted.
I noticed that if it is not a constant, then the same machine code is generated in either case.
int b;
if(a < b)
cmpl -4(%rbp), %eax
jge .L2
if(a <=b)
cmpl -4(%rbp), %eax
jg .L3
There are two cases:
If you are having a single image, irrespective of device version, then you should put your images in drawable folder.
But for the images that you created separately for hdpi, ldpi, mdpi, xhdpi, xxhdpi and xxxhdpi, depending on screen resolution of the mobile that will be using the app, you have to puy them in drawable-hdpi, drawable-ldpi, drawable-mdpi, drawable-xhdpi, drawable-xxhdpi and drawable-xxxhdpi folders respectively.
For the first case, if there is a single image, you can pretty much place it in any drawable folder, but its standard convention to put them in drawable folder.
I had the same issue with a dll yesterday and all it referenced was System, System.Data, and System.Xml. Turns out the build configuration for the Platform type didn't line up. The dll was build for x86 and the program using it was "Any CPU" and since I am running a x64 machine, it ran the program as x64 and had issues with the x86 dll. I don't know if this is your issue or not, just thought that I would mention it as something else to check.
As Obama says "Yes We Can". Here is the link to it. developers.google.com/#jquery
You need to use
ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/jquery-ui.min.js
ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
jQuery CDN
code.jquery.com/ui/[VERSION NO]/jquery-ui.min.js
code.jquery.com/ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
Microsoft
ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/jquery-ui.min.js
ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
Find theme names here http://jqueryui.com/themeroller/ in gallery subtab
.
But i would not recommend you hosting from cdn for the following reasons
http://zoompf.com/blog/2010/01/should-you-use-javascript-library-cdns
Here is an example to convert an NSData object to Base 64. It also shows how to go the other way (decode a base 64 encoded NSData object):
NSData *dataTake2 =
[@"iOS Developer Tips" dataUsingEncoding:NSUTF8StringEncoding];
// Convert to Base64 data
NSData *base64Data = [dataTake2 base64EncodedDataWithOptions:0];
// Do something with the data...
// Now convert back from Base64
NSData *nsdataDecoded = [base64Data initWithBase64EncodedData:base64Data options:0];
Or check this out this will help align all the elements at once.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/showdescriptioncontenttitle"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_gravity="center"
android:gravity="center_horizontal"
>
<TextView
android:id="@+id/showdescriptiontitle"
android:text="Title"
android:textSize="35dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
In short, on MariaDB
1) sudo mysql -u root;
2) use mysql;
3) UPDATE mysql.user SET plugin = 'mysql_native_password',
Password = PASSWORD('pass1234') WHERE User = 'root';
4) FLUSH PRIVILEGES;
5) exit;
Consider
var x = document.getElementById("age");
Here x
is the element with id="age"
.
Now look at the following line
var age = document.getElementById("age").value;
this means you are getting the value of the element which has id="age"
As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:
TSKILL processName
or
TSKILL PID
Have on mind that processName
should not have the .exe
suffix and is limited to 18 characters.
Another option is WMIC
:
wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate
wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get
you can see the available fileds you can filter (and %
can be used as a wildcard).
The same thing was when I've created a new Configuration and Build Scheme.
So the solution for me was to run
pod install
for this newly created Configuration.
Why not just place your button inside of a reference tag e.g
<a href="https://www.google.com/"><button>Next</button></a>
This seems to work perfectly for me and does not add any %20 tags to the link, just how you want it. I have used a link to google to demonstrate.
You could of course wrap this in a form tag but it is not necessary.
When linking another local file just put it in the same folder and add the file name as the reference. Or specify the location of the file if in is not in the same folder.
<a href="myOtherFile"><button>Next</button></a>
This does not add any character onto the end of the URL either, however it does have the files project path as the url before ending with the name of the file. e.g
If my project structure was...
.. denotes a folder - denotes a file while four | denote a sub directory or file in parent folder
..public
|||| ..html
|||| |||| -main.html
|||| |||| -secondary.html
If I open main.html the URL would be,
http://localhost:0000/public/html/main.html?_ijt=i7ms4v9oa7blahblahblah
However, when I clicked the button inside main.html to change to secondary.html, the URL would be,
http://localhost:0000/public/html/secondary.html
No special characters included at the end of the URL. I hope this helps. By the way - (%20 denotes a space in a URL its encoded and inserted in the place of them.)
Note: The localhost:0000 will obviously not be 0000 you'll have your own port number there.
Furthermore the ?_ijt=xxxxxxxxxxxxxx at the end off the main.html URL, x is determined by your own connection so obviously will not be equal to mine.
It might seem like I'm stating some really basic points but I just want to explain as best as I can. Thank you for reading and I hope this help someone at the very least. Happy programming.
git stash show -p | git apply
and then git stash drop
if you want to drop the stashed items.
Maven solution:
I came across all the same issues as above, and for a maven solution I used 2 dependencies. This configuration is only meant for quick testing if you want a simple project to be using a logger, with a standard configuration. I can imagine you want to make a configuration file later on if you need more information and or finetune your own logging levels.
<properties>
<slf4jVersion>1.7.28</slf4jVersion>
</properties>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4jVersion}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>${slf4jVersion}</version>
</dependency>
Be sure that you do not have a session timeout that is very short, and also make sure that if you are using cookie based sessions that you are accepting the session.
The FireFox webDeveloperToolbar is helpful at times like this as you can see the cookies set for your application.
There is a useful undocumented method in the ZipArchive class: addGlob();
$zipFile = "./testZip.zip";
$zipArchive = new ZipArchive();
if ($zipArchive->open($zipFile, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) !== true)
die("Failed to create archive\n");
$zipArchive->addGlob("./*.txt");
if ($zipArchive->status != ZIPARCHIVE::ER_OK)
echo "Failed to write files to zip\n";
$zipArchive->close();
Now documented at: www.php.net/manual/en/ziparchive.addglob.php
You can set the state of the checkbox based on the value:
$('#your-checkbox').prop('checked', value == 1);
--- Shameless plug ---
I have added this function to a library I created
vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------
Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.
If you don't use jQuery
then the script would be something like this:
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
Using jQuery is a lot easier:
function checkVisible( elm, evalType ) {
evalType = evalType || "visible";
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
if (evalType === "above") return ((y < (vpH + st)));
}
This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.
See in action: http://jsfiddle.net/RJX5N/2/
I hope this answers your question.
-- IMPROVED VERSION--
This is a lot shorter and should do it as well:
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/
And a version with threshold
and mode
included:
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}
and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/
I tried this on my VM machine
change the permissions /home/vagrant (did a chmod 700 on it)
now i can ssh directly into my boxes
In my case, I just was mistaking about project credentials: using google-services.json from one project, and server key from another.
I prefer this way so I don't need to remember any rare parameters.
git merge branch_name
It will then say your branch is ahead by "#
" commits, you can now pop these commits off and put them into the working changes with the following:
git reset @~#
For example if after the merge it is 1 commit ahead, use:
git reset @~1
Note: On Windows, quotes are needed. (As Josh noted in comments) eg:
git reset "@~1"
You cannot refer non-static members from a static method.
Non-Static members (like your fxn(int y)) can be called only from an instance of your class.
Example:
You can do this:
public class A
{
public int fxn(int y) {
y = 5;
return y;
}
}
class Two {
public static void main(String[] args) {
int x = 0;
A a = new A();
System.out.println("x = " + x);
x = a.fxn(x);
System.out.println("x = " + x);
}
or you can declare you method as static.
To answer the title-question:
DateTime d1 = ...;
DateTime d2 = ...;
TimeSpan diff = d2 - d1;
int millisceonds = (int) diff.TotalMilliseconds;
You can use this to set a Timer:
timer1.interval = millisceonds;
timer1.Enabled = true;
Don't forget to disable the timer when handling the tick.
But if you want an event at 12:03, just substitute DateTime.Now for d1
.
But it is not clear what the exact function of textBox1 and textBox2 are.