Extending @Def_Os's answer with an actual demo...
As @Def_Os has already said - using Pandas Datareader makes this task a real fun
In [12]: from pandas_datareader import data
pulling all available historical data for AAPL
starting from 1980-01-01
#In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')
# yahoo api is inconsistent for getting historical data, please use google instead.
In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')
first 5 rows
In [14]: aapl.head()
Out[14]:
Open High Low Close Volume Adj Close
Date
1980-12-12 28.750000 28.875000 28.750 28.750 117258400 0.431358
1980-12-15 27.375001 27.375001 27.250 27.250 43971200 0.408852
1980-12-16 25.375000 25.375000 25.250 25.250 26432000 0.378845
1980-12-17 25.875000 25.999999 25.875 25.875 21610400 0.388222
1980-12-18 26.625000 26.750000 26.625 26.625 18362400 0.399475
last 5 rows
In [15]: aapl.tail()
Out[15]:
Open High Low Close Volume Adj Close
Date
2016-06-07 99.250000 99.870003 98.959999 99.029999 22366400 99.029999
2016-06-08 99.019997 99.559998 98.680000 98.940002 20812700 98.940002
2016-06-09 98.500000 99.989998 98.459999 99.650002 26419600 99.650002
2016-06-10 98.529999 99.349998 98.480003 98.830002 31462100 98.830002
2016-06-13 98.690002 99.120003 97.099998 97.339996 37612900 97.339996
save all data as CSV file
In [16]: aapl.to_csv('d:/temp/aapl_data.csv')
d:/temp/aapl_data.csv - 5 first rows
Date,Open,High,Low,Close,Volume,Adj Close
1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
...
Example to recieve it through a request:
a) http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historical
OR
b) http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes
The POJO should be defined as
Response class
public class Response {
private List<Wrapper> wrappers;
// getter and setter
}
Wrapper class
public class Wrapper {
private String id;
private String name;
// getters and setters
}
and mapper to read value
Response response = mapper.readValue(jsonStr , Response.class);
For me it was also the FragmentStatePagerAdapter
, however overriding saveState()
did not work. Here's how I fixed it:
When calling the FragmentStatePagerAdapter
constructor, keep a separate list of fragments within the class, and add a method to remove the fragments:
class PagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> items;
PagerAdapter(ArrayList<Fragment> frags) {
super(getFragmentManager()); //or getChildFragmentManager() or getSupportFragmentManager()
this.items = new ArrayList<>();
this.items.addAll(frags);
}
public void removeFragments() {
Iterator<Fragment> iter = items.iterator();
while (iter.hasNext()) {
Fragment item = iter.next();
getFragmentManager().beginTransaction().remove(item).commit();
iter.remove();
}
notifyDataSetChanged();
}
}
//...getItem() and etc methods...
}
Then in the Activity
, save the ViewPager
position and call adapter.removeFragments()
in the overridden onSaveInstanceState()
method:
private int pagerPosition;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save other view state here
pagerPosition = mViewPager.getCurrentItem();
adapter.removeFragments();
}
Lastly, in the overridden onResume()
method, re-instantiate the adapter if it isn't null
. (If it's null
, then the Activity
is being opened for the first time or after the app has been killed off by Android, in which onCreate
will do the adapter creation.)
@Override
public void onResume() {
super.onResume();
if (adapter != null) {
adapter = new PagerAdapter(frags);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(currentTabPosition);
}
}
I think use this is better:
os.path.realpath(__file__).rsplit('/', X)[0]
In [1]: __file__ = "/aParent/templates/blog1/page.html"
In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'
In [4]: __file__ = "/aParent/templates/blog1/page.html"
In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'
In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'
In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'
StringBuilder is a better option to concat a huge data string because the StringBuilder is a mutable string type and StringBuilder object is an immutable type, that means StringBuilder never create a new instance of object while concat the string.
If we are using string instead of StringBuilder to achieve for concatenation then it will create new instance in memory every time.
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
The sp_xml_preparedocument
stored procedure will parse the XML and the OPENXML
rowset provider will show you a relational view of the XML data.
For details and more examples check the OPENXML documentation.
As for your question,
DECLARE @XML XML
SET @XML = '<rows><row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row></rows>'
DECLARE @handle INT
DECLARE @PrepareXmlStatus INT
EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML
SELECT *
FROM OPENXML(@handle, '/rows/row', 2)
WITH (
IdInvernadero INT,
IdProducto INT,
IdCaracteristica1 INT,
IdCaracteristica2 INT,
Cantidad INT,
Folio INT
)
EXEC sp_xml_removedocument @handle
Best way in my opinion.
$.fn.findByContentText = function (text) {
return $(this).contents().filter(function () {
return $(this).text().trim() == text.trim();
});
};
You can use Arraylist and Treemap, as you said you want repeated values as well then you cant use TreeSet, though it is sorted as well, but you have to define comparator.
You can use the sDom
option for this.
Default with search input in its own div:
sDom: '<"search-box"r>lftip'
If you use jQuery UI (bjQueryUI
set to true
):
sDom: '<"search-box"r><"H"lf>t<"F"ip>'
The above will put the search/filtering input
element into it's own div
with a class named search-box
that is outside of the actual table.
Even though it uses its special shorthand syntax it can actually take any HTML you throw at it.
Feb 2016 version: Admin tab, then select Property in the middle column, click Property Settings, then the Move To Trash Can button at the top right. No need to delete individual views.
URLs are case-preserving, between client and server. But portions of URLs may or may not be case-sensitive, depending on the server, for a couple of reasons.
The following bold parts of URLs may be case-sensitive, depending on the site and/or server configuration.
http:// www. example.com /abc/def.ghi?jkl=mno#pqr
user @ example.com
Case-sensitivity in URLs can have several uses. Mainly:
As a developer, I believe the above can often be handled in better ways, but I also understand there are cases where a situation may not permit this.
For example, imagine an existing product that requires a lot of data placed in the "GET" URL, yet it must be compatible with the maximum URL lengths of all major servers, browsers, and caching/proxy mechanisms. To fit even a moderate-length command string (under 1,024 characters for some older browsers), you'd need to use every unique URL-safe character you could (which is basically what base64url encoding is).
Whether or not URLs should be case-sensitive is debatable. I personally believe they should not be, for simplicity (though it may create longer URLs, we have percent-escapes to easily handle cases where we must ensure preservation of exact characters, and there are ways to transfer data other than right in the URL).
Many seem to agree based on the fact that case-insensitive URLs are explicitly enabled for many popular sites and services, in order to increase usability. The most prominent example is the username portion of email addresses. Most email providers will ignore case and sometimes even dots and other symbols (like "[email protected]" being the same as "[email protected]"). Even though email usernames are case-sensitive by default, according to spec.
However, the fact is that despite what I or others might want, this is the state of how things currently work. And while an eventual worldwide transition to a case-insensitive URL standard is certainly possible, it would likely take quite a long time since case-sensitivity is currently used extensively around the web for various purposes.
As far as best practices go, as a user you can reasonably stick to lowercase for most situations and expect things to work. The main exceptions would be URLs that use case-based encoding or document paths with direct filesystem equivalents. However, such complex URLs are typically copy-pasted (or simply clicked) rather than manually typed.
As a web developer, you should consider keeping URLs as case-insensitive as possible. Though there are clearly some difficult-to-avoid situations, depending on context, as noted above.
How about calling a function from within your callback instead of returning a value in sync_call()?
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {
value = result;
use_value(value);
} );
}
There are many ways to get a page from the command line... but it also depends if you want the code source or the page itself:
If you need the code source:
with curl:
curl $url
with wget:
wget -O - $url
but if you want to get what you can see with a browser, lynx can be useful:
lynx -dump $url
I think you can find so many solutions for this little problem, maybe you should read all man pages for those commands. And don't forget to replace $url
by your URL :)
Good luck :)
A trivial
$num = $num <= 0 ? $num : -$num ;
or, the better solution, IMHO:
$num = -1 * abs($num)
As @VegardLarsen has posted,
the explicit multiplication can be avoided for shortness but I prefer readability over shortness
I suggest to avoid if/else (or equivalent ternary operator) especially if you have to manipulate a number of items (in a loop or using a lambda function), as it will affect performance.
"If the float is a negative, make it a positive."
In order to change the sign of a number you can simply do:
$num = 0 - $num;
or, multiply it by -1, of course :)
You are looking for the insert
function, found in the table
section of the main library.
foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")
Think about it: the database really has to go to every row to do that. In a multi-user environment my COUNT(*)
could be different from your COUNT(*)
. It would be impractical to have a different counter for each and every session so you have literally to count the rows. Most of the time anyway you would have a WHERE clause or a JOIN in your query so your hypothetical counter would be of litte practical value.
There are ways to speed up things however: if you have an INDEX on a NOT NULL column Oracle will count the rows of the index instead of the table. In a proper relational model all tables have a primary key so the COUNT(*)
will use the index of the primary key.
Bitmap index have entries for NULL rows so a COUNT(*) will use a bitmap index if there is one available.
Use the SQLite keyword default
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NAME + " TEXT NOT NULL, "
+ KEY_WORKED + " INTEGER, "
+ KEY_NOTE + " INTEGER DEFAULT 0);");
This link is useful: http://www.sqlite.org/lang_createtable.html
Both or
and ||
evaluate to true if either operand is true. They evaluate their second operand only if the first is false.
As with and
, the only difference between or
and ||
is their precedence.
Just to make life interesting, and
and or
have the same precedence, while &&
has a higher precedence than ||
.
Your for loop doesn't need to just add one. You can loop by three.
for(int i = 0; i < theData.Length; i+=3)
{
string value1 = theData[i];
string value2 = theData[i+1];
string value3 = theData[i+2];
}
Basically, you are just using indexes to grab the values in your array. One point to note here, I am not checking to see if you go past the end of your array. Make sure you are doing bounds checking!
As I (kind of without success) searched for the proper solution for my hack, I want to add my hack here nonetheless: I simply check for support of device orientation, which seems the most significant diffrence between mobiles and desktop:
var is_handheld=0; // just a global if(window.DeviceOrientationEvent) {is_handheld=1;}
That being said, imho a page should also offer manual choice between mobile / desktop layout. I got 1920*1080 and I can zoom in - an oversimplified and feature-reduced wordpressoid chunk is not always a good thing. Especially forcing a layout based on nonworking device detection - it happens all the time.
Running the command prompt or Powershell ISE as an administrator fixed this for me.
With small custom synchronization context, sync function can wait for completion of async function, without creating deadlock. Here is small example for WinForms app.
Imports System.Threading
Imports System.Runtime.CompilerServices
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SyncMethod()
End Sub
' waiting inside Sync method for finishing async method
Public Sub SyncMethod()
Dim sc As New SC
sc.WaitForTask(AsyncMethod())
sc.Release()
End Sub
Public Async Function AsyncMethod() As Task(Of Boolean)
Await Task.Delay(1000)
Return True
End Function
End Class
Public Class SC
Inherits SynchronizationContext
Dim OldContext As SynchronizationContext
Dim ContextThread As Thread
Sub New()
OldContext = SynchronizationContext.Current
ContextThread = Thread.CurrentThread
SynchronizationContext.SetSynchronizationContext(Me)
End Sub
Dim DataAcquired As New Object
Dim WorkWaitingCount As Long = 0
Dim ExtProc As SendOrPostCallback
Dim ExtProcArg As Object
<MethodImpl(MethodImplOptions.Synchronized)>
Public Overrides Sub Post(d As SendOrPostCallback, state As Object)
Interlocked.Increment(WorkWaitingCount)
Monitor.Enter(DataAcquired)
ExtProc = d
ExtProcArg = state
AwakeThread()
Monitor.Wait(DataAcquired)
Monitor.Exit(DataAcquired)
End Sub
Dim ThreadSleep As Long = 0
Private Sub AwakeThread()
If Interlocked.Read(ThreadSleep) > 0 Then ContextThread.Resume()
End Sub
Public Sub WaitForTask(Tsk As Task)
Dim aw = Tsk.GetAwaiter
If aw.IsCompleted Then Exit Sub
While Interlocked.Read(WorkWaitingCount) > 0 Or aw.IsCompleted = False
If Interlocked.Read(WorkWaitingCount) = 0 Then
Interlocked.Increment(ThreadSleep)
ContextThread.Suspend()
Interlocked.Decrement(ThreadSleep)
Else
Interlocked.Decrement(WorkWaitingCount)
Monitor.Enter(DataAcquired)
Dim Proc = ExtProc
Dim ProcArg = ExtProcArg
Monitor.Pulse(DataAcquired)
Monitor.Exit(DataAcquired)
Proc(ProcArg)
End If
End While
End Sub
Public Sub Release()
SynchronizationContext.SetSynchronizationContext(OldContext)
End Sub
End Class
This post is intended to rescue the people who are suffering from *not being able to properly setup Apache2 for Perl on Ubuntu. (The system configurations specific to your Linux machine will be mentioned within square brackets, like [this]).
Possible outcome of an improperly setup Apache 2:
If one follows the steps described below with a reasonable intelligence, he/she can get through the errors mentioned above.
Before starting the steps. Go to /etc/hosts
file and add IP address / domain-name` for example:
127.0.0.1 www.BECK.com
Step 1: Install apache2
Step 2: Install mod_perl
Step 3: Configure apache2
open sites-available/default
and add the following,
<Files ~ "\.(pl|cgi)$">
SetHandler perl-script
PerlResponseHandler ModPerl::PerlRun
Options +ExecCGI
PerlSendHeader On
</Files>
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory [path-to-store-your-website-files-like-.html-(perl-scripts-should-be-stored-in-cgi-bin] >
####(The Perl/CGI scripts can be stored out of the cgi-bin directory, but that's a story for another day. Let's concentrate on washing out the issue at hand)
####
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ScriptAlias /cgi-bin/ [path-where-you-want-your-.pl-and-.cgi-files]
<Directory [path-where-you-want-your-.pl-and-.cgi-files]>
AllowOverride None
Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
AddHandler cgi-script .pl
Order allow,deny
allow from all
</Directory>
<Files ~ "\.(pl|cgi)$">
SetHandler perl-script
PerlResponseHandler ModPerl::PerlRun
Options +ExecCGI
PerlSendHeader On
</Files>
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory [path-to-store-your-website-files-like-.html-(perl-scripts-should-be-stored-in-cgi-bin] >
####(The Perl/CGI scripts can be stored out of the cgi-bin directory, but that's a story for another day. Let's concentrate on washing out the issue at hand)
####
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ScriptAlias /cgi-bin/ [path-where-you-want-your-.pl-and-.cgi-files]
<Directory [path-where-you-want-your-.pl-and-.cgi-files]>
AllowOverride None
Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
AddHandler cgi-script .pl
Order allow,deny
allow from all
</Directory>
Add the following lines to your /etc/apache2/apache2.conf
file.
AddHandler cgi-script .cgi .pl
<Files ~ "\.pl$">
Options +ExecCGI
</Files>
<Files ~ "\.cgi$">
Options +ExecCGI
</Files>
<IfModule mod_perl.c>
<IfModule mod_alias.c>
Alias /perl/ /home/sly/host/perl/
</IfModule>
<Location /perl>
SetHandler perl-script
PerlHandler Apache::Registry
Options +ExecCGI
</Location>
</IfModule>
<Files ~ "\.pl$">
Options +ExecCGI
</Files>
Very important, or at least I guess so, only after doing this step, I got it to work.
AddHandler cgi-script .cgi .pl
<Files ~ "\.pl$">
Options +ExecCGI
</Files>
<Files ~ "\.cgi$">
Options +ExecCGI
</Files>
<IfModule mod_perl.c>
<IfModule mod_alias.c>
Alias /perl/ /home/sly/host/perl/
</IfModule>
<Location /perl>
SetHandler perl-script
PerlHandler Apache::Registry
Options +ExecCGI
</Location>
</IfModule>
<Files ~ "\.pl$">
Options +ExecCGI
</Files>
Very important, or at least I guess so, only after doing this step, I got it to work.
Add the following to you /etc/apache2/sites-enabled/000-default
file
<Files ~ "\.(pl|cgi)$">
SetHandler perl-script
PerlResponseHandler ModPerl::PerlRun
Options +ExecCGI
PerlSendHeader On
</Files>
Now add, your Perl script as test.pl in the place where you mentioned before in step 3 as [path-where-you-want-your-.pl-and-.cgi-files].
Give permissions to the .pl
file using chmod
and then, type the webaddress/cgi-bin/test.pl
in the address bar of the browser, there you go, you got it.
(Now, many of the things would have been redundant in this post. Kindly ignore it.)
Swift 5*
I, always use view extension to make view corners round, set border color and width and it has been the most convenient way for me. just copy and paste this code and controlle these properties in attribute inspector.
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.borderColor = color.cgColor
} else {
layer.borderColor = nil
}
}
}
}
There is a standard function in R for that
tabulate(numbers)
Files "LICENSE.txt" and "NOTICE.txt" are case sensitive. So for SPring android library I had to add
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/notice.txt'
}
}
Just use the array of options, to see, which option is currently selected.
$options = array( 'one', 'two', 'three' );
$output = '';
for( $i=0; $i<count($options); $i++ ) {
$output .= '<option '
. ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>'
. $options[$i]
. '</option>';
}
Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.
JpaRepository
The Spring Data JpaRepository
defines the following two methods:
getOne
, which returns an entity proxy that is suitable for setting a @ManyToOne
or @OneToOne
parent association when persisting a child entity.findById
, which returns the entity POJO after running the SELECT statement that loads the entity from the associated tableHowever, in your case, you didn't call either getOne
or findById
:
Person person = personRepository.findOne(1L);
So, I assume the findOne
method is a method you defined in the PersonRepository
. However, the findOne
method is not very useful in your case. Since you need to fetch the Person
along with is roles
collection, it's better to use a findOneWithRoles
method instead.
You can define a PersonRepositoryCustom
interface, as follows:
public interface PersonRepository
extends JpaRepository<Person, Long>, PersonRepositoryCustom {
}
public interface PersonRepositoryCustom {
Person findOneWithRoles(Long id);
}
And define its implementation like this:
public class PersonRepositoryImpl implements PersonRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public Person findOneWithRoles(Long id)() {
return entityManager.createQuery("""
select p
from Person p
left join fetch p.roles
where p.id = :id
""", Person.class)
.setParameter("id", id)
.getSingleResult();
}
}
That's it!
HTML Table row heights will typically change proportionally to the table height, if the table height is larger than the height of your rows. Since the table is forcing the height of your rows, you can remove the table height to resolve the issue. If this is not acceptable, you can also give the rows explicit height, and add a third row that will auto size to the remaining table height.
Another option in CSS2 is the Max-Height Property, although it may lead to strange behavior in a table.http://www.w3schools.com/cssref/pr_dim_max-height.asp
.
Megabyte means 2^20 bytes. I know that technically that doesn't mesh with the SI units, and that some folks have come up with a new terminology to mean 2^20. None of that matters. Efforts to change the language to "clarify" things are doomed to failure.
Hard-drive manufacturers use it to mean 1,000,000 bytes, because that's what it means in SI so they figure technically they aren't lying (while actually they are). That falls under lies, damn lies, and marketing.
This is a solution that means that as you add new stored procedures to the schema, users can execute them without having to call grant execute on the new stored procedure:
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'asp_net')
DROP USER asp_net
GO
IF EXISTS (SELECT * FROM sys.database_principals
WHERE name = N'db_execproc' AND type = 'R')
DROP ROLE [db_execproc]
GO
--Create a database role....
CREATE ROLE [db_execproc] AUTHORIZATION [dbo]
GO
--...with EXECUTE permission at the schema level...
GRANT EXECUTE ON SCHEMA::dbo TO db_execproc;
GO
--http://www.patrickkeisler.com/2012/10/grant-execute-permission-on-all-stored.html
--Any stored procedures that are created in the dbo schema can be
--executed by users who are members of the db_execproc database role
--...add a user e.g. for the NETWORK SERVICE login that asp.net uses
CREATE USER asp_net
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE]
WITH DEFAULT_SCHEMA=[dbo]
GO
--...and add them to the roles you need
EXEC sp_addrolemember N'db_execproc', 'asp_net';
EXEC sp_addrolemember N'db_datareader', 'asp_net';
EXEC sp_addrolemember N'db_datawriter', 'asp_net';
GO
Reference: Grant Execute Permission on All Stored Procedures
In my case I was testing a Tomcat app in eclipse and got this error. I solved it by checking the .classpath
file and corrected this entry:
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
The attribute org.eclipse.jst.component.dependency
had been missing.
My favourite solution was the one by @EugenKonkov because it didn't imply the presence of other utilities (the coreutils package).
But it failed for the relative paths "." and "..", so here is a slightly improved version handling these special cases.
It still fails if the user doesn't have the permission to cd
into the parent directory of the relative path, though.
#! /bin/sh
# Takes a path argument and returns it as an absolute path.
# No-op if the path is already absolute.
function to-abs-path {
local target="$1"
if [ "$target" == "." ]; then
echo "$(pwd)"
elif [ "$target" == ".." ]; then
echo "$(dirname "$(pwd)")"
else
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
fi
}
If you can run the "sdkmanager" from the command line, then running sdkmanager --verbose --list
will reveal the paths it checks.
For example, I have installed the SDK in c:\spool\Android
and for me running the sdkmanager --verbose --list
looks like:
>sdkmanager --list --verbose
Info: Parsing c:\spool\Android\build-tools\27.0.3\package.xml
Info: Parsing c:\spool\Android\emulator\package.xml
Info: Parsing c:\spool\Android\extras\android\m2repository\package.xml
Info: Parsing c:\spool\Android\extras\intel\Hardware_Accelerated_Execution_Manager\package.xml
Info: Parsing c:\spool\Android\patcher\v4\package.xml
Info: Parsing c:\spool\Android\platform-tools\package.xml
Info: Parsing c:\spool\Android\platforms\android-27\package.xml
Info: Parsing c:\spool\Android\tools\package.xml
Installed packages:=====================] 100% Computing updates...
--------------------------------------
build-tools;27.0.3
Description: Android SDK Build-Tools 27.0.3
Version: 27.0.3
Installed Location: c:\spool\Android\build-tools\27.0.3
P.S. On another PC I let the Android Studio install the Android SDK for me, and the SDK ended up in C:\Users\MyUsername\AppData\Local\Android\Sdk
.
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
datetime
is a builtin module, so there is no (Python) source file.
For modules coming from .py
(or .pyc
) files, you can use mymodule.__file__
, e.g.
> import random
> random.__file__
'C:\\Python25\\lib\\random.pyc'
Compared to some previous answers, the main difference is that this piece of code takes into consideration when the input string is:
Here it is:
public static class StringExtensions
{
public static string Right(this string str, int length)
{
return str.Substring(str.Length - length, length);
}
public static string MyLast(this string str, int length)
{
if (str == null)
return null;
else if (str.Length >= length)
return str.Substring(str.Length - length, length);
else
return str;
}
}
The above answer only adds the sqljdbc4.jar to the local repository. As a result, when creating the final project jar for distribution, sqljdbc4 will again be missing as was indicated in the comment by @Tony regarding runtime error.
Microsoft (and Oracle and other third party providers) restrict the distribution of their software as per the ENU/EULA. Therefore those software modules do not get added in Maven produced jars for distribution. There are hacks to get around it (such as providing the location of the 3rd party jar file at runtime), but as a developer you must be careful about violating the licensing.
A better approach for jdbc connectors/drivers is to use jTDS, which is compatible to most DBMS's, more reliable, faster (as per benchmarks), and distributed under GNU license. It will make your life much easier to use this than trying to pound the square peg into the round hole following any of the other techniques above.
While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).
I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.
I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.
If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.
Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.
Update 2: Same solution seems to be needed on iOS 13 beta builds as well.
Essentially, coupling is how much a given object or set of object relies on another object or another set of objects in order to accomplish its task.
Think of a car. In order for the engine to start, a key must be inserted into the ignition, turned, gasoline must be present, a spark must occur, pistons must fire, and the engine must come alive. You could say that a car engine is highly coupled to several other objects. This is high coupling, but it's not really a bad thing.
Think of a user control for a web page that is responsible for allowing users to post, edit, and view some type of information. The single control could be used to let a user post a new piece of information or edit a new piece of information. The control should be able to be shared between two different paths - new and edit. If the control is written in such a way that it needs some type of data from the pages that will contain it, then you could say it's too highly coupled. The control should not need anything from its container page.
Try using cygwin instead of bash. that worked for me
I had similar issue. try this $('#myAnchor').get(0).click();
this works for me
Just encountered with this issue in my rails application in production. A lot of answers here gave me hints and helped me to finally come to an answer that worked fine for me.
I am running Nginx and it was simple enough to just modify the my_app.conf file (where my_app is your app name). You can find this file in /etc/nginx/conf.d
If you do not have location / {}
already you can just add it under server {}
, then add add_header 'Access-Control-Allow-Origin' '*';
under location / {}
.
The final format should look something like this:
server {
server_name ...;
listen ...;
root ...;
location / {
add_header 'Access-Control-Allow-Origin' '*';
}
}
Try this it's simple and fast
SELECT T.name AS [TABLE NAME], I.rows AS [ROWCOUNT]
FROM sys.tables AS T
INNER JOIN sys.sysindexes AS I ON T.object_id = I.id
AND I.indid < 2 ORDER BY I.rows DESC
You Can use simply
git checkout commithash
in this sequence
git clone `URLTORepository`
cd `into your cloned folder`
git checkout commithash
commit hash looks like this "45ef55ac20ce2389c9180658fdba35f4a663d204"
This question needs a newer answer :)
const convertTime12to24 = (time12h) => {_x000D_
const [time, modifier] = time12h.split(' ');_x000D_
_x000D_
let [hours, minutes] = time.split(':');_x000D_
_x000D_
if (hours === '12') {_x000D_
hours = '00';_x000D_
}_x000D_
_x000D_
if (modifier === 'PM') {_x000D_
hours = parseInt(hours, 10) + 12;_x000D_
}_x000D_
_x000D_
return `${hours}:${minutes}`;_x000D_
}_x000D_
_x000D_
console.log(convertTime12to24('01:02 PM'));_x000D_
console.log(convertTime12to24('05:06 PM'));_x000D_
console.log(convertTime12to24('12:00 PM'));_x000D_
console.log(convertTime12to24('12:00 AM'));
_x000D_
While both of the above answers work well if key,value are strings, I had a situation to append a string and integer (jq errors using the above expressions)
Requirement: To construct a url out below json
pradeep@seleniumframework>curl http://192.168.99.103:8500/v1/catalog/service/apache-443 | jq .[0]
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 251 100 251 0 0 155k 0 --:--:-- --:--:-- --:--:-- 245k
{
"Node": "myconsul",
"Address": "192.168.99.103",
"ServiceID": "4ce41e90ede4:compassionate_wozniak:443",
"ServiceName": "apache-443",
"ServiceTags": [],
"ServiceAddress": "",
"ServicePort": 1443,
"ServiceEnableTagOverride": false,
"CreateIndex": 45,
"ModifyIndex": 45
}
Solution:
curl http://192.168.99.103:8500/v1/catalog/service/apache-443 |
jq '.[0] | "http://" + .Address + ":" + "\(.ServicePort)"'
write the code that you want to be executed inside this. When your document is ready, this will be executed.
$(document).ready(function() {
});
In PowerShell v5.1 this is slightly different compared to v5. According to MS documentation, it has to have a -Path
parameter to specify the archive file path.
Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference
Or else, this can be an actual path:
Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference
value.replaceAll("[^A-Za-z0-9]", "")
[^abc]
When a caret^
appears as the first character inside square brackets, it negates the pattern. This pattern matches any character except a or b or c.
Looking at the keyword as two function:
[(Pattern)] = match(Pattern)
[^(Pattern)] = notMatch(Pattern)
Moreover regarding a pattern:
A-Z = all characters included from A to Z
a-z = all characters included from a to z
0=9 = all characters included from 0 to 9
Therefore it will substitute all the char NOT included in the pattern
On Windows also check whether the file is not encrypted using EFS. I had the same problem untill I decrypted the file manualy.
With tr
:
# Converts upper to lower case
$ tr '[:upper:]' '[:lower:]' < input.txt > output.txt
# Converts lower to upper case
$ tr '[:lower:]' '[:upper:]' < input.txt > output.txt
Or, sed
on GNU (but not BSD or Mac as they don't support \L
or \U
):
# Converts upper to lower case
$ sed -e 's/\(.*\)/\L\1/' input.txt > output.txt
# Converts lower to upper case
$ sed -e 's/\(.*\)/\U\1/' input.txt > output.txt
for the react-router 2.5.2,the solution is so easy:
//someConponent
...
render:function(){
return (
<h1>This is the parent component who pass the prop to this.props.children</h1>
{this.props.children && React.cloneElement(this.props.children,{myProp:'value'})}
)
}
...
Use the -File
parameter in front of the filename. The quotes make PowerShell think it is a string of commands.
my app structure:
NodeAPP (folder)
|-- app (folder)
|-- all other file is here
|-- node_modules (folder)
|-- package.json
|-- server.js (my server file)
first install reload with this command:
npm install [-g] [--save-dev] reload
then change package.json:
"scripts": {
"start": "nodemon -e css,ejs,js,json --watch app"
}
now you must use reload in your server file:
var express = require('express');
var reload = require('reload');
var app = express();
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log( 'server is running on port ' + app.get('port'));
});
reload(server, app);
and for last change, end of your response send this script:
<script src="/reload/reload.js"></script>
now start your app with this code:
npm start
<?php
pclose(popen("start /B test.bat", "r")); die();
?>
This may be helpful
byte[] bytes = System.Convert.FromBase64String(stringInBase64);
How about writing some color-based class in a global sass file, thus we don't need to care where variables are. Just like the following:
// base.scss
@import "./_variables.scss";
.background-color{
background: $bg-color;
}
and then, we can use the background-color
class in any file.
My point is that I don't need to import variable.scss
in any file, just use it.
Test if SSH over the HTTPS port is possible, run this SSH command:
$ ssh -T -p 443 [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.
If that worked, great! If not, you may need to follow our troubleshooting guide.
If you are able to SSH into [email protected]
over port 443, you can override your SSH settings to force any connection to GitHub to run though that server and port.
To set this in your ssh config, edit the file at ~/.ssh/config
, and add this section:
Host github.com
Hostname ssh.github.com
Port 443
You can test that this works by connecting once more to GitHub:
$ ssh -T [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.
From Authenticating to GitHub / Using SSH over the HTTPS port
The solution provided by ebeneditos works perfectly.
But if you have cv2.imwrite()
in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite()
individually.
As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)
Now if you want to modify the path, you just have to change the path
variable.
Edited based on solution provided by Kallz
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.
According to this site add
CONFIG += c++11
to your .pro file (see at the bottom of that web page). It requires Qt 5.
The other answers, suggesting
QMAKE_CXXFLAGS += -std=c++11
(or QMAKE_CXXFLAGS += -std=c++0x
)
also work with Qt 4.8 and gcc / clang.
In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/
You can use from root directory:
RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html
Or:
RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');
There are answers over the net that try to solve this, however none of them functioned correctly for me. Goal: put a background image on the body
and have background-size: cover;
work mobile, without media queries, overflows
, or hacky z-index: -1;
position: absolute;
overlays.
Here is what I did to solve this. It works on Chrome on Android even when keyboard drawer is active. If someone wants to test iPhone that would be cool:
body {
background: #FFFFFF url('../image/something.jpg') no-repeat fixed top center;
background-size: cover;
-webkit-background-size: cover; /* safari may need this */
}
Here is the magic. Treat html
like a wrapper with a ratio enforced height relative to the actual viewport. You know the classic responsive tag <meta name="viewport" content="width=device-width, initial-scale=1">
? This is why the vh
is used. Also, on the surface it would seem like body
should get these rules, and it may look ok...until a change of height like when the keyboard opens up.
html {
height: 100vh; /* set viewport constraint */
min-height: 100%; /* enforce height */
}
Normally, I'd suggest trying the ANSI-92 standard meta tables for something like this but I see now that Oracle doesn't support it.
-- this works against most any other database
SELECT
*
FROM
INFORMATION_SCHEMA.COLUMNS C
INNER JOIN
INFORMATION_SCHEMA.TABLES T
ON T.TABLE_NAME = C.TABLE_NAME
WHERE
C.COLUMN_NAME = 'columnname'
AND T.TABLE_NAME = 'tablename'
Instead, it looks like you need to do something like
-- Oracle specific table/column query
SELECT
*
FROM
ALL_TAB_COLUMNS
WHERE
TABLE_NAME = 'tablename'
AND COLUMN_NAME = 'columnname'
I do apologize in that I don't have an Oracle instance to verify the above. If it does not work, please let me know and I will delete this post.
You could put it as a startup item... Startup items don't show off a prompt to run as an administrator at all.
Check this article Elevated Program Shortcut Without UAC rompt
Use command line :
mysql.exe -u USERNAME -p PASSWORD DATABASENAME < MYDATABASE.sql
where MYDATABASE.sql is your sql file.
Or perhaps you are on a readonly mounted fs
The
break
statement terminates the execution of the nearest enclosingdo
,for
,switch
, orwhile
statement in which it appears. Control passes to the statement that follows the terminated statement.
from msdn.
This was introduced in v3.1.0: http://getbootstrap.com/css/#grid-example-fluid
Commit #62736046 added ".container-fluid variation for full-width containers and layouts".
Firstly, it's not clear what your date format is.
There already is an answer involving strftime("%s")
.
I like to expand on that answer.
SQLite has only the following storage classes: NULL, INTEGER, REAL, TEXT or BLOB. To simplify things, I'm going to assume dates are REAL containing the seconds since 1970-01-01. Here's a sample schema for which I will put in the sample data of "1st December 2018":
CREATE TABLE Payment (DateCreated REAL);
INSERT INTO Payment VALUES (strftime("%s", "2018-12-01"));
Now let's work out the date difference between "1st December 2018" and now (as I write this, it is midday 12th December 2018):
Date difference in days:
SELECT (strftime("%s", "now") - DateCreated) / 86400.0 FROM Payment;
-- Output: 11.066875
Date difference in hours:
SELECT (strftime("%s", "now") - DateCreated) / 3600.0 FROM Payment;
-- Output: 265.606388888889
Date difference in minutes:
SELECT (strftime("%s", "now") - DateCreated) / 60.0 FROM Payment;
-- Output: 15936.4833333333
Date difference in seconds:
SELECT (strftime("%s", "now") - DateCreated) FROM Payment;
-- Output: 956195.0
Stick with the present tense imperative because
From a quick google search it seems that the problem is a file or url couldn't be found be the HTTPservice.
Here are the links where I found this information:
http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/
Swift 3,4:
2 useful conversions:
string(from: Date) // to convert from Date to a String
date(from: String) // to convert from String to Date
Usage: 1.
let date = Date() //gives today's date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let todaysDateInUKFormat = dateFormatter.string(from: date)
2.
let someDateInString = "23.06.2017"
var getDateFromString = dateFormatter.date(from: someDateInString)
Add to your JS:
jQuery(document).ready(function($) {
$("body").css({
'padding-top': $(".navbar").outerHeight() + 'px'
})
});
Use the Date
object provided by javascript. It's not unique or special to Google's scripting environment.
Using the -X
flag with whatever HTTP verb you want:
curl -X PUT -d arg=val -d arg2=val2 localhost:8080
This example also uses the -d
flag to provide arguments with your PUT request.
Use matplotlib
's calls that won't block:
Using draw()
:
from matplotlib.pyplot import plot, draw, show
plot([1,2,3])
draw()
print('continue computation')
# at the end call show to ensure window won't close.
show()
Using interactive mode:
from matplotlib.pyplot import plot, ion, show
ion() # enables interactive mode
plot([1,2,3]) # result shows immediatelly (implicit draw())
print('continue computation')
# at the end call show to ensure window won't close.
show()
I had a package-lock.json
file from an old version of my package.json, I deleted that and then everything installed correctly.
I originally came in here to find how to make PyTest
print in VSCode's console while running/debugging the unit test from there. This can be done with the following launch.json
configuration. Given .venv
the virtual environment folder.
"version": "0.2.0",
"configurations": [
{
"name": "PyTest",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config:python.pythonPath}",
"module": "pytest",
"args": [
"-sv"
],
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.venv",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
}
]
}
None of the answers work for me. Remove data-toggle="tab"
from the a
prevents the tab from activating, but it also adds the #tabId
hash to the URL. That is unacceptable to me. What is also unacceptable is using javascript.
What does work is added the disabled
class to the li
and removing the href
attribute of its containing a
.
In addition to the above answers, I would say for columns having no single word name, you may use:-
df[df['Product ID'].str.contains("foo") == True]
Hope this helps.
If you have a multi-config (matrix) job, you do not have a JDK dropdown but need to configure the jdk as build axis.
another solution is catching onClick event and for aggregate data to js function you can
.hmtl.erb
<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>
.js
// handle my-class click
$('a.my-class').on('click', function () {
var link = $(this);
var array = link.data('array');
});
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:
$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session
or
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
I believe you need something similar to the following:
<script type="text/javascript">
var count;
function increment(){
count++;
}
</script>
...
and
<input type="button" onClick="increment()" value="Increment"/>
or
<input type="button" onClick="count++" value="Increment"/>
Use stored procedures.
And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".
Best way is to change launcher icons separately for both iOS and Android.
Change the icons in iOS and Android module separately. The plugin produces different size icons from the same icon which are distorted.
Follow this link: https://flutter.dev/docs/deployment/android
Try to use union all
as below
SELECT [Type], [Total Sales] From Before
union all
SELECT 'Total', Sum([Total Sales]) From Before
if you have problem with ordering, as i-one suggested try this:
select [Type], [Total Sales]
from (SELECT [Type], [Total Sales], 0 [Key]
From Before
union all
SELECT 'Total', Sum([Total Sales]), 1 From Before) sq
order by [Key], Type
I've used it to send intraday trades between different fund management systems. If you want to learn more about what a great technology messaging is, I can thoroughly recommend the book "Enterprise Integration Patterns". There are some JMS examples for things like request/reply and publish/subscribe.
Messaging is an excellent tool for integration.
To change the size of (almost) all text elements, in one place, and synchronously, rel()
is quite efficient:
g+theme(text = element_text(size=rel(3.5))
You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)),
strip.text.x = element_text(size=rel(3.5)),
strip.text.y = element_text(size=rel(3.5)))
# perl -de 0
$match="hi(.*)"
$sub='$1'
$res="hi1234"
$res =~ s/$match/$sub/gee
p $res
1234
Be careful, though. This causes two layers of eval
to occur, one for each e
at the end of the regex:
This solution accepts at least 1 number and at least 1 character:
[^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))
So my question is this - if throwing from a destructor results in undefined behavior, how do you handle errors that occur during a destructor?
The main problem is this: you can't fail to fail. What does it mean to fail to fail, after all? If committing a transaction to a database fails, and it fails to fail (fails to rollback), what happens to the integrity of our data?
Since destructors are invoked for both normal and exceptional (fail) paths, they themselves cannot fail or else we're "failing to fail".
This is a conceptually difficult problem but often the solution is to just find a way to make sure that failing cannot fail. For example, a database might write changes prior to committing to an external data structure or file. If the transaction fails, then the file/data structure can be tossed away. All it has to then ensure is that committing the changes from that external structure/file an atomic transaction that can't fail.
The pragmatic solution is perhaps just make sure that the chances of failing on failure are astronomically improbable, since making things impossible to fail to fail can be almost impossible in some cases.
The most proper solution to me is to write your non-cleanup logic in a way such that the cleanup logic can't fail. For example, if you're tempted to create a new data structure in order to clean up an existing data structure, then perhaps you might seek to create that auxiliary structure in advance so that we no longer have to create it inside a destructor.
This is all much easier said than done, admittedly, but it's the only really proper way I see to go about it. Sometimes I think there should be an ability to write separate destructor logic for normal execution paths away from exceptional ones, since sometimes destructors feel a little bit like they have double the responsibilities by trying to handle both (an example is scope guards which require explicit dismissal; they wouldn't require this if they could differentiate exceptional destruction paths from non-exceptional ones).
Still the ultimate problem is that we can't fail to fail, and it's a hard conceptual design problem to solve perfectly in all cases. It does get easier if you don't get too wrapped up in complex control structures with tons of teeny objects interacting with each other, and instead model your designs in a slightly bulkier fashion (example: particle system with a destructor to destroy the entire particle system, not a separate non-trivial destructor per particle). When you model your designs at this kind of coarser level, you have less non-trivial destructors to deal with, and can also often afford whatever memory/processing overhead is required to make sure your destructors cannot fail.
And that's one of the easiest solutions naturally is to use destructors less often. In the particle example above, perhaps upon destroying/removing a particle, some things should be done that could fail for whatever reason. In that case, instead of invoking such logic through the particle's dtor which could be executed in an exceptional path, you could instead have it all done by the particle system when it removes a particle. Removing a particle might always be done during a non-exceptional path. If the system is destroyed, maybe it can just purge all particles and not bother with that individual particle removal logic which can fail, while the logic that can fail is only executed during the particle system's normal execution when it's removing one or more particles.
There are often solutions like that which crop up if you avoid dealing with lots of teeny objects with non-trivial destructors. Where you can get tangled up in a mess where it seems almost impossible to be exception-safety is when you do get tangled up in lots of teeny objects that all have non-trivial dtors.
It would help a lot if nothrow/noexcept actually translated into a compiler error if anything which specifies it (including virtual functions which should inherit the noexcept specification of its base class) attempted to invoke anything that could throw. This way we'd be able to catch all this stuff at compile-time if we actually write a destructor inadvertently which could throw.
Uhm, what's wrong with this:
#include <iostream>
using namespace std;
int main(int, char **)
{
char c = 'A';
int x = c; // Look ma! No cast!
cout << "The character '" << c << "' has an ASCII code of " << x << endl;
return 0;
}
Changing the registry worked for me.
If its helpful to anyone, I initially prefixed "z_" to the entries in "ShellIconOverlayIdentifiers" that I wanted to move down. However that didn't seem to bring up the TortoiseSVN entries. It might be due to case sensitivity wherein lowercase "z" still precedes uppercase "T". Finally, prefixing with "Z_" instead did the trick.
For people using .NET can use IPAddress class to parse IPv4/IPv6 string and store it as a VARBINARY(16)
. Can use the same class to convert byte[]
to string. If want to convert the VARBINARY
in SQL:
--SELECT
-- dbo.varbinaryToIpString(CAST(0x7F000001 AS VARBINARY(4))) IPv4,
-- dbo.varbinaryToIpString(CAST(0x20010DB885A3000000008A2E03707334 AS VARBINARY(16))) IPv6
--ALTER
CREATE
FUNCTION dbo.varbinaryToIpString
(
@varbinaryValue VARBINARY(16)
)
RETURNS VARCHAR(39)
AS
BEGIN
IF @varbinaryValue IS NULL
RETURN NULL
IF DATALENGTH(@varbinaryValue) = 4
BEGIN
RETURN
CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 1, 1))) + '.' +
CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 2, 1))) + '.' +
CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 3, 1))) + '.' +
CONVERT(VARCHAR(3), CONVERT(INT, SUBSTRING(@varbinaryValue, 4, 1)))
END
IF DATALENGTH(@varbinaryValue) = 16
BEGIN
RETURN
sys.fn_varbintohexsubstring(0, @varbinaryValue, 1, 2) + ':' +
sys.fn_varbintohexsubstring(0, @varbinaryValue, 3, 2) + ':' +
sys.fn_varbintohexsubstring(0, @varbinaryValue, 5, 2) + ':' +
sys.fn_varbintohexsubstring(0, @varbinaryValue, 7, 2) + ':' +
sys.fn_varbintohexsubstring(0, @varbinaryValue, 9, 2) + ':' +
sys.fn_varbintohexsubstring(0, @varbinaryValue, 11, 2) + ':' +
sys.fn_varbintohexsubstring(0, @varbinaryValue, 13, 2) + ':' +
sys.fn_varbintohexsubstring(0, @varbinaryValue, 15, 2)
END
RETURN 'Invalid'
END
I found a flow which is fastest for me, by first associating a keyboard shortcut Alt+k
to "Compare Active File With..." (#a). (Similar to wisbucky's answer but further improved and more step-wise.)
Then, to compare two files:
Alt+k
, a quick open menu will be shown with file B focused.Enter
.Result: file A on left and file B on right. (Tested on VS Code 1.27.1)
#a - to do so, press Ctrl-k Ctrl-s
to show Keyboard Shortcuts, type compare
on the top search box, and double click the "Keybinding" column for "Compare Active File With...", press Alt+k
then Enter
to assign it.
As long as your script is executable and doesn't have any extension you can drag it as-is to the right side (Document side) of the Dock and it will run in a terminal window when clicked instead of opening an editor.
If you want to have an extension (like foo.sh), you can go to the file info window in Finder and change the default application for that particular script from whatever it is (TextEdit, TextMate, whatever default is set on your computer for .sh files) to Terminal. It will then just execute instead of opening in a text editor. Again, you will have to drag it to the right side of the Dock.
From WebService returns XML even when ResponseFormat set to JSON:
Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.
Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services
I like using this method:
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
Usage:
if ( isFunction(me.onChange) ) {
me.onChange(str); // call the function with params
}
I tried this: Create a file header.html like
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Your application</title>
Now include header.html in your HTML pages like:
<head>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script>
$(function(){ $("head").load("header.html") });
</script>
</head>
Works perfectly fine.
I vote for:
await Promise.all([someCall(), anotherCall()]);
Be aware of the moment you call functions, it may cause unexpected result:
// Supposing anotherCall() will trigger a request to create a new User
if (callFirst) {
await someCall();
} else {
await Promise.all([someCall(), anotherCall()]); // --> create new User here
}
But following always triggers request to create new User
// Supposing anotherCall() will trigger a request to create a new User
const someResult = someCall();
const anotherResult = anotherCall(); // ->> This always creates new User
if (callFirst) {
await someCall();
} else {
const finalResult = [await someResult, await anotherResult]
}
Simple jQuery solution - find the <a>
element where href="x"
and click it:
$('a[href="#tabs-2"]').click();
You can't do it the way you've written it because C++ class member functions have a hidden this
parameter passed in. pthread_create()
has no idea what value of this
to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has no this
parameter), or a plain ordinary function to bootstrap the class:
class C
{
public:
void *hello(void)
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
Don't use quotes with <<EOF
:
var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF
Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
Just write what you really wanted to know:
fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")
It's much simpler than anything with substring.
You can use the attribute df.empty
to check whether it's empty or not:
if df.empty:
print('DataFrame is empty!')
Source: Pandas Documentation
This is full source code to draw direction path from source latitude and longitude to destination latitude and longitude. I have changed the above code to fit for latitude and longitude rather than source and destination. So anyone who is accessing his latitude and longitude through his gps can get the direction from his gps device to the destination coordinates.
Thanks to above answers we could make such a change and get path direction.
public class DrawMapActivity extends MapActivity {
MapView myMapView = null;
MapController myMC = null;
GeoPoint geoPoint = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMapView = (MapView) findViewById(R.id.mapview);
geoPoint = null;
myMapView.setSatellite(false);
double fromLat = 12.303534;
double fromLong = 76.64611;
double toLat = 12.9715987;
double toLong = 77.5945627;
String sourceLat = Double.toString(fromLat);
String sourceLong = Double.toString(fromLong);
String destinationLat = Double.toString(toLat);
String destinationLong = Double.toString(toLong);
String pairs[] = getDirectionData(sourceLat,sourceLong, destinationLat, destinationLong );
String[] lngLat = pairs[0].split(",");
// STARTING POINT
GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
myMC = myMapView.getController();
geoPoint = startGP;
myMC.setCenter(geoPoint);
myMC.setZoom(10);
myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));
// NAVIGATE THE PATH
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),(int) (Double.parseDouble(lngLat[0]) * 1E6));
myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
Log.d("xxx", "pair:" + pairs[i]);
}
// END POINT
myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));
myMapView.getController().animateTo(startGP);
myMapView.setBuiltInZoomControls(true);
myMapView.displayZoomControls(true);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private String[] getDirectionData(String sourceLat, String sourceLong, String destinationLat, String destinationLong) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&" +"saddr="+sourceLat+","+sourceLong+"&daddr="+destinationLat+","+destinationLong + "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
}
//*****************************************************************************
class DirectionPathOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
public DirectionPathOverlay(GeoPoint gp1, GeoPoint gp2) {
this.gp1 = gp1;
this.gp2 = gp2;
}
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
paint.setColor(Color.BLUE);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(2);
canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,(float) point2.y, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
}
}
Hope it helps for other Stack Overflow users
In Eclipse,
When you use JDBC in your servlet, the driver jar must be placed in the WEB-INF/lib directory of your project.
You can't, you'll have to do something like
<script type="text/javascript">
var php_var = "<?php echo $php_var; ?>";
</script>
You can also load it with AJAX
rhino is right, the snippet lacks of a type for the sake of brevity.
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
If you are checking against a lot of intervals, I suggest using an interval tree.
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
Here are a couple dplyr
options that keep non-duplicate rows based on columns id and id2:
library(dplyr)
df %>% distinct(id, id2, .keep_all = TRUE)
df %>% group_by(id, id2) %>% filter(row_number() == 1)
df %>% group_by(id, id2) %>% slice(1)
It's easy,this is my solution using objects!
My POJO
public class Person implements Serializable{
private String name;
private int age;
//get & set
}
Method Notification
Person person = new Person();
person.setName("david hackro");
person.setAge(10);
Intent notificationIntent = new Intent(this, Person.class);
notificationIntent.putExtra("person",person);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.notification_icon)
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.ColorTipografiaAdeudos))
.setPriority(2)
.setLargeIcon(bm)
.setTicker(fotomulta.getTitle())
.setContentText(fotomulta.getMessage())
.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT))
.setWhen(System.currentTimeMillis())
.setContentTitle(fotomulta.getTicketText())
.setDefaults(Notification.DEFAULT_ALL);
New Activity
private Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_push);
person = (Person) getIntent().getSerializableExtra("person");
}
Good Luck!!
In bash, contrary to [
, [[
prevents word splitting of variable values.
There are many cases where it gives a much more elegant solution over the iterative method, the common example being traversal of a binary tree, so it isn't necessarily more difficult to maintain. In general, iterative versions are usually a bit faster (and during optimization may well replace a recursive version), but recursive versions are simpler to comprehend and implement correctly.
I don't think it is possible using just HTML. However using javascript this should be doable. Bassicly we loop over each image, test if it is complete and if it's naturalWidth is zero then that means that it not found. Here is the code:
fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=img.length;
for(;i<l;i++){
var t = img[i];
if(t.naturalWidth === 0){
//this image is broken
t.src = url;
}
}
}
Use it like this:
window.onload = function() {
fixBrokenImages('example.com/image.png');
}
Tested in Chrome and Firefox
A segmentation fault is caused by a request for a page that the process does not have listed in its descriptor table, or an invalid request for a page that it does have listed (e.g. a write request on a read-only page).
A dangling pointer is a pointer that may or may not point to a valid page, but does point to an "unexpected" segment of memory.
Just stick the img tag inside the h1 tag as part of the content.
Try to delete the folder c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u
manually and then retry the pip command.
This is what I recently did for my Data Visualization Application which has a 2008 SQL Database. In this example I am recieving a list returned from a stored procedure:
public List<CumulativeInstrumentsDataRow> GetCumulativeInstrumentLogs(RunLogFilter filter)
{
EFDbContext db = new EFDbContext();
if (filter.SystemFullName == string.Empty)
{
filter.SystemFullName = null;
}
if (filter.Reconciled == null)
{
filter.Reconciled = 1;
}
string sql = GetRunLogFilterSQLString("[dbo].[rm_sp_GetCumulativeInstrumentLogs]", filter);
return db.Database.SqlQuery<CumulativeInstrumentsDataRow>(sql).ToList();
}
And then this extension method for some formatting in my case:
public string GetRunLogFilterSQLString(string procedureName, RunLogFilter filter)
{
return string.Format("EXEC {0} {1},{2}, {3}, {4}", procedureName, filter.SystemFullName == null ? "null" : "\'" + filter.SystemFullName + "\'", filter.MinimumDate == null ? "null" : "\'" + filter.MinimumDate.Value + "\'", filter.MaximumDate == null ? "null" : "\'" + filter.MaximumDate.Value + "\'", +filter.Reconciled == null ? "null" : "\'" + filter.Reconciled + "\'");
}
this will work as you asked without CHAR(38):
update t set country = 'Trinidad and Tobago' where country = 'trinidad & '|| 'tobago';
create table table99(col1 varchar(40));
insert into table99 values('Trinidad &' || ' Tobago');
insert into table99 values('Trinidad &' || ' Tobago');
insert into table99 values('Trinidad &' || ' Tobago');
insert into table99 values('Trinidad &' || ' Tobago');
SELECT * FROM table99;
update table99 set col1 = 'Trinidad and Tobago' where col1 = 'Trinidad &'||' Tobago';
If you just want to give users using a MS browser a warning or something, this code should be good.
HTML:
<p id="IE">You are not using a microsoft browser</p>
Javascript:
using_ms_browser = navigator.appName == 'Microsoft Internet Explorer' || (navigator.appName == "Netscape" && navigator.appVersion.indexOf('Edge') > -1) || (navigator.appName == "Netscape" && navigator.appVersion.indexOf('Trident') > -1);
if (using_ms_browser == true){
document.getElementById('IE').innerHTML = "You are using a MS browser"
}
Thanks to @GavinoGrifoni
In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.
When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).
Remember to call wait() on the child process to prevent any lingering zombies.
Note that %in%
returns a logical vector of TRUE
and FALSE
. To negate it, you can use !
in front of the logical statement:
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
!where_case_travelled_1 %in%
c('Outside Canada','Outside province/territory of residence but within Canada'))
Regarding your original approach with -c(...)
, -
is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")
). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -
.
In C (not C++), you have to declare struct variables like:
struct myStruct myVariable;
In order to be able to use myStruct myVariable;
instead, you can typedef
the struct:
typedef struct myStruct someStruct;
someStruct myVariable;
You can combine struct
definition and typedef
s it in a single statement which declares an anonymous struct
and typedef
s it.
typedef struct { ... } myStruct;
awk '{ sub("[^a-zA-Z0-9\"!@#$%^&*|_\[](){}", ""); print }' MYinputfile.txt > pipe_out_to_CONVERTED_FILE.txt
Variable interpolation does not happen in single quotes. You need to use double quotes as:
$i = 1
echo "<p class=\"paragraph$i\"></p>";
++i;
I got the same problem just doing an npm install. Run with antivirus disabled (if you use Windows Defender, turn off Real-Time protection and Cloud-based protection). That worked for me!
Using boost is the best option as it helps you to provide a neat and concise code, but if you want to stick to STL
void listbox_add(const char* item, ListBox &lb)
{
lb.add(item);
}
int foo()
{
const char* starr[] = {"ram", "mohan", "sita"};
ListBox listBox;
std::for_each(starr,
starr + sizeof(starr)/sizeof(char*),
std::bind2nd(std::ptr_fun(&listbox_add), listBox));
}
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.
Try disabling iptables: service iptables stop
If this works, enable TCP port 80 to your firewall rules: run system-config-selinux from root, and enable TCP port 80 (HTTP) on your firewall.
If the array contains both positive and negative data, I'd go with:
import numpy as np
a = np.random.rand(3,2)
# Normalised [0,1]
b = (a - np.min(a))/np.ptp(a)
# Normalised [0,255] as integer: don't forget the parenthesis before astype(int)
c = (255*(a - np.min(a))/np.ptp(a)).astype(int)
# Normalised [-1,1]
d = 2.*(a - np.min(a))/np.ptp(a)-1
If the array contains nan
, one solution could be to just remove them as:
def nan_ptp(a):
return np.ptp(a[np.isfinite(a)])
b = (a - np.nanmin(a))/nan_ptp(a)
However, depending on the context you might want to treat nan
differently. E.g. interpolate the value, replacing in with e.g. 0, or raise an error.
Finally, worth mentioning even if it's not OP's question, standardization:
e = (a - np.mean(a)) / np.std(a)
you can use below methods
public static String parseUrl(String surl) throws Exception
{
URL u = new URL(surl);
return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}
or
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
the second one is better than first.
For me $numberAsString -as [int]
of @Shay Levy is the best practice, I also use [type]::Parse(...)
or [type]::TryParse(...)
But, depending on what you need you can just put a string containing a number on the right of an arithmetic operator with a int on the left the result will be an Int32:
PS > $b = "10"
PS > $a = 0 + $b
PS > $a.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
You can use Exception (try/parse) to behave in case of Problem
Simply add this code:
if (string.Contains("search_text")) { MessageBox.Show("Message."); }
well after a few modification of the code provided by mace,i ended up building a stopwatch. https://codepen.io/truestbyheart/pen/EGELmv
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Stopwatch</title>
<style>
#center {
margin: 30% 30%;
font-family: tahoma;
}
.stopwatch {
border:1px solid #000;
background-color: #eee;
text-align: center;
width:656px;
height: 230px;
overflow: hidden;
}
.stopwatch span{
display: block;
font-size: 100px;
}
.stopwatch p{
display: inline-block;
font-size: 40px;
}
.stopwatch a{
font-size:45px;
}
a:link,
a:visited{
color :#000;
text-decoration: none;
padding: 12px 14px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="center">
<div class="timer stopwatch"></div>
</div>
<script>
const Stopwatch = function(elem, options) {
let timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval,
hrs = 0,
min = 0;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
if (action !== "reset") {
let a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
} else if (action === "reset") {
let a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
clean();
event.preventDefault();
});
return a;
}
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render(0);
}
function clean() {
min = 0;
hrs = 0;
clock = 0;
render(0);
}
function update() {
clock += delta();
render();
}
function render() {
if (Math.floor(clock / 1000) === 60) {
min++;
reset();
if (min === 60) {
min = 0;
hrs++;
}
}
timer.innerHTML =
hrs + "<p>hrs</p>" + min + "<p>min</p>" + Math.floor(clock / 1000)+ "<p>sec</p>";
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
};
// Initiating the Stopwatch
var elems = document.getElementsByClassName("timer");
for (var i = 0, len = elems.length; i < len; i++) {
new Stopwatch(elems[i]);
}
</script>
</body>
</html>
I have make some changes in my case in: xampp\phpMyAdmin\libraries\config.default.php
i have searched for : $cfg['ExecTimeLimit']
and change the value at right side...
You can change Right hand Value to any higher value, like '5000'. and it works.
I had a similar situation, and the following process worked for me:
In the terminal, type
vi ~/.profile
Then add this line in the file, and save
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home
where version is the one on your computer, such as 1.7.0_25
Exit the editor, then type the following command make it become effective
source ~/.profile
Then type java -version to check the result
java -version
What is .profile? From:http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515
.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.
If you're writing code that you envisage is going to be compiled on a wide variety of platforms, with a number of different compilers, then using these flags yourself will help to ensure you don't produce code that only compiles under GCC.
It takes a few steps to get the perfect preview for WhatsApp, Twitter, Facebook and bookmark icons for pc's and mobile devices. If you like reading go to ogp.me - but make sure to read steps 1 - 6 in this answer to get the best WhatsApp preview.
Please note: some apps or websites use cache or even store the website preview to their database. This means when you're testing your link in WhatsApp or Facebook for example, you'll most likely not see any difference right away. Using another link (another page) will do the trick. But as soon as you use that link once, this "please note" section starts all over again.
Step 1: title
Maximum of 65 characters
<title>your keyword rich title of the website and/or webpage</title>
Step 2: description
Maximum of 155 characters
<meta name="description" content="description of your website/webpage, make sure you use keywords!">
Step 3: og:title
Maximum 35 characters
<meta property="og:title" content="short title of your website/webpage" />
Step 4: og:url
Full link to the current webpage address
<meta property="og:url" content="https://www.example.com/webpage/" />
Step 5: og:description
Maximum 65 characters
<meta property="og:description" content="description of your website/webpage">
Step 6: og:image
Image(JPG or PNG) with a size less than 300KB and minimum dimensions of 300 x 200 *. This image should be served via a HTTPS connection with a valid non-self-signed certificate.
<meta property="og:image" content="//cdn.example.com/uploads/images/webpage_300x200.png">
* @RichDeBourke mentioned this to me, but apparently WhatsApp has increased its maximum image size (dimensions as well as file size). I did some tests: it does not work consistently every time on every device. I tested 2.x Mb images and even that seemed to work 9/10 times. <300KB is the safest approach, but you should be fine using larger images as of 18-02-2020. I would recommend keeping the file size below 2MB, though. And definitely throw your image through TinyPNG or any other image compression algorithm if you haven't already.
If you completed the steps above, you can now see your preview in WhatsApp! However, be aware of the "please note" section above.
Step 7: og:type
In order for your object to be represented within the graph, you need to specify its type. Here's a list of the global types available: http://ogp.me/#types. You can also specify your own types.
<meta property="og:type" content="article" />
Step 8: og:locale
The locale of the resource. You can also use og:locale:alternate if you have other language translations available.
If you don't specify og:locale, it defaults to en_US.
<meta property="og:locale" content="en_GB" />
<meta property="og:locale:alternate" content="fr_FR" />
<meta property="og:locale:alternate" content="es_ES" />
Step 9: Twitter
For the best Twitter support read this.
Step 10: Facebook
For the best Facebook support read this.
Step 11: favicon
For the best favicon support for all browsers and devices read this.
Bonus step 12: video/audio
It's also possible to share audio/video. Facebook and twitter for example share videos very well. Read ogp.me.
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
Other solutions are good enough to answer your query. However, if you are looking for just one command to do that for you -
Create a file name "run", in directory where your Java files are. And save this in your file -
javac "$1.java"
if [ $? -eq 0 ]; then
echo "--------Run output-------"
java "$1"
fi
give this file run permission by running -
chmod 777
Now you can run any of your files by merely running -
./run <yourfilename> (don't add .java in filename)
Just a speculation, I have not enough experience to try it... )-:
Since GoogleMap is a fragment, it should be possible to catch marker onClick event and show custom fragment view. A map fragment will be still visible on the background. Does anybody tried it? Any reason why it could not work?
The disadvantage is that map fragment would be freezed on backgroud, until a custom info fragment return control to it.
while(choice!=99)
{
cin>>choice;
if (choice==99)
exit(0);
cin>>gNum;
}
Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...
transition-property:width;
This should work. you have to have browser dependent code
Simplest example using the Standard Library.
#include <iostream>
using namespace std;
int main()
{
char c = 'n';
cout << "HEX " << hex << (int)c << endl; // output in hexadecimal
cout << "ASC" << c << endl; // output in ascii
return 0;
}
To check the output, codepad returns: 6e
and an online ascii-to-hexadecimal conversion tool yields 6e as well. So it works.
You can also do this:
template<class T> std::string toHexString(const T& value, int width) {
std::ostringstream oss;
oss << hex;
if (width > 0) {
oss << setw(width) << setfill('0');
}
oss << value;
return oss.str();
}
Can you not just send the bytes as bytes, or convert each byte to a character and send as a string? Doing it like you are will take up a minimum of 85 characters in the string, when you only have 11 bytes to send. You could create a string representation of the bytes, so it'd be "[B@405217f8", which can easily be converted to a bytes
or bytearray
object in Python. Failing that, you could represent them as a series of hexadecimal digits ("5b42403430353231376638") taking up 22 characters, which could be easily decoded on the Python side using binascii.unhexlify()
.
All the validation from model are skipped when we use validate: false
user = User.new(....)
user.save(validate: false)
Also a good script, although my laptop ran out of memory, but this was on a very large table
https://basitaalishan.com/2014/02/23/rebuild-all-indexes-on-all-tables-in-the-sql-server-database/
USE [<mydatabasename>]
Go
--/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--Arguments Data Type Description
-------------- ------------ ------------
--@FillFactor [int] Specifies a percentage that indicates how full the Database Engine should make the leaf level
-- of each index page during index creation or alteration. The valid inputs for this parameter
-- must be an integer value from 1 to 100 The default is 0.
-- For more information, see http://technet.microsoft.com/en-us/library/ms177459.aspx.
--@PadIndex [varchar](3) Specifies index padding. The PAD_INDEX option is useful only when FILLFACTOR is specified,
-- because PAD_INDEX uses the percentage specified by FILLFACTOR. If the percentage specified
-- for FILLFACTOR is not large enough to allow for one row, the Database Engine internally
-- overrides the percentage to allow for the minimum. The number of rows on an intermediate
-- index page is never less than two, regardless of how low the value of fillfactor. The valid
-- inputs for this parameter are ON or OFF. The default is OFF.
-- For more information, see http://technet.microsoft.com/en-us/library/ms188783.aspx.
--@SortInTempDB [varchar](3) Specifies whether to store temporary sort results in tempdb. The valid inputs for this
-- parameter are ON or OFF. The default is OFF.
-- For more information, see http://technet.microsoft.com/en-us/library/ms188281.aspx.
--@OnlineRebuild [varchar](3) Specifies whether underlying tables and associated indexes are available for queries and data
-- modification during the index operation. The valid inputs for this parameter are ON or OFF.
-- The default is OFF.
-- Note: Online index operations are only available in Enterprise edition of Microsoft
-- SQL Server 2005 and above.
-- For more information, see http://technet.microsoft.com/en-us/library/ms191261.aspx.
--@DataCompression [varchar](4) Specifies the data compression option for the specified index, partition number, or range of
-- partitions. The options for this parameter are as follows:
-- > NONE - Index or specified partitions are not compressed.
-- > ROW - Index or specified partitions are compressed by using row compression.
-- > PAGE - Index or specified partitions are compressed by using page compression.
-- The default is NONE.
-- Note: Data compression feature is only available in Enterprise edition of Microsoft
-- SQL Server 2005 and above.
-- For more information about compression, see http://technet.microsoft.com/en-us/library/cc280449.aspx.
--@MaxDOP [int] Overrides the max degree of parallelism configuration option for the duration of the index
-- operation. The valid input for this parameter can be between 0 and 64, but should not exceed
-- number of processors available to SQL Server.
-- For more information, see http://technet.microsoft.com/en-us/library/ms189094.aspx.
--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
-- Ensure a USE <databasename> statement has been executed first.
SET NOCOUNT ON;
DECLARE @Version [numeric] (18, 10)
,@SQLStatementID [int]
,@CurrentTSQLToExecute [nvarchar](max)
,@FillFactor [int] = 100 -- Change if needed
,@PadIndex [varchar](3) = N'OFF' -- Change if needed
,@SortInTempDB [varchar](3) = N'OFF' -- Change if needed
,@OnlineRebuild [varchar](3) = N'OFF' -- Change if needed
,@LOBCompaction [varchar](3) = N'ON' -- Change if needed
,@DataCompression [varchar](4) = N'NONE' -- Change if needed
,@MaxDOP [int] = NULL -- Change if needed
,@IncludeDataCompressionArgument [char](1);
IF OBJECT_ID(N'TempDb.dbo.#Work_To_Do') IS NOT NULL
DROP TABLE #Work_To_Do
CREATE TABLE #Work_To_Do
(
[sql_id] [int] IDENTITY(1, 1)
PRIMARY KEY ,
[tsql_text] [varchar](1024) ,
[completed] [bit]
)
SET @Version = CAST(LEFT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - 1) + N'.' + REPLACE(RIGHT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), LEN(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)))), N'.', N'') AS [numeric](18, 10))
IF @DataCompression IN (N'PAGE', N'ROW', N'NONE')
AND (
@Version >= 10.0
AND SERVERPROPERTY(N'EngineEdition') = 3
)
BEGIN
SET @IncludeDataCompressionArgument = N'Y'
END
IF @IncludeDataCompressionArgument IS NULL
BEGIN
SET @IncludeDataCompressionArgument = N'N'
END
INSERT INTO #Work_To_Do ([tsql_text], [completed])
SELECT 'ALTER INDEX [' + i.[name] + '] ON' + SPACE(1) + QUOTENAME(t2.[TABLE_CATALOG]) + '.' + QUOTENAME(t2.[TABLE_SCHEMA]) + '.' + QUOTENAME(t2.[TABLE_NAME]) + SPACE(1) + 'REBUILD WITH (' + SPACE(1) + + CASE
WHEN @PadIndex IS NULL
THEN 'PAD_INDEX =' + SPACE(1) + CASE i.[is_padded]
WHEN 1
THEN 'ON'
WHEN 0
THEN 'OFF'
END
ELSE 'PAD_INDEX =' + SPACE(1) + @PadIndex
END + CASE
WHEN @FillFactor IS NULL
THEN ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), REPLACE(i.[fill_factor], 0, 100))
ELSE ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), @FillFactor)
END + CASE
WHEN @SortInTempDB IS NULL
THEN ''
ELSE ', SORT_IN_TEMPDB =' + SPACE(1) + @SortInTempDB
END + CASE
WHEN @OnlineRebuild IS NULL
THEN ''
ELSE ', ONLINE =' + SPACE(1) + @OnlineRebuild
END + ', STATISTICS_NORECOMPUTE =' + SPACE(1) + CASE st.[no_recompute]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + ', ALLOW_ROW_LOCKS =' + SPACE(1) + CASE i.[allow_row_locks]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + ', ALLOW_PAGE_LOCKS =' + SPACE(1) + CASE i.[allow_page_locks]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + CASE
WHEN @IncludeDataCompressionArgument = N'Y'
THEN CASE
WHEN @DataCompression IS NULL
THEN ''
ELSE ', DATA_COMPRESSION =' + SPACE(1) + @DataCompression
END
ELSE ''
END + CASE
WHEN @MaxDop IS NULL
THEN ''
ELSE ', MAXDOP =' + SPACE(1) + CONVERT([varchar](2), @MaxDOP)
END + SPACE(1) + ')'
,0
FROM [sys].[tables] t1
INNER JOIN [sys].[indexes] i ON t1.[object_id] = i.[object_id]
AND i.[index_id] > 0
AND i.[type] IN (1, 2)
INNER JOIN [INFORMATION_SCHEMA].[TABLES] t2 ON t1.[name] = t2.[TABLE_NAME]
AND t2.[TABLE_TYPE] = 'BASE TABLE'
INNER JOIN [sys].[stats] AS st WITH (NOLOCK) ON st.[object_id] = t1.[object_id]
AND st.[name] = i.[name]
SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0
WHILE @SQLStatementID IS NOT NULL
BEGIN
SELECT @CurrentTSQLToExecute = [tsql_text]
FROM #Work_To_Do
WHERE [sql_id] = @SQLStatementID
PRINT @CurrentTSQLToExecute
EXEC [sys].[sp_executesql] @CurrentTSQLToExecute
UPDATE #Work_To_Do
SET [completed] = 1
WHERE [sql_id] = @SQLStatementID
SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0
END
Here are still one problem: Escaped string does not look readable when assigned to input value
var string = _.escape("<img src=fake onerror=alert('boo!')>");
$('input').val(string);
Exapmle: https://jsfiddle.net/kjpdwmqa/3/
Usually a simple hash function works by taking the "component parts" of the input (characters in the case of a string), and multiplying them by the powers of some constant, and adding them together in some integer type. So for example a typical (although not especially good) hash of a string might be:
(first char) + k * (second char) + k^2 * (third char) + ...
Then if a bunch of strings all having the same first char are fed in, then the results will all be the same modulo k, at least until the integer type overflows.
[As an example, Java's string hashCode is eerily similar to this - it does the characters reverse order, with k=31. So you get striking relationships modulo 31 between strings that end the same way, and striking relationships modulo 2^32 between strings that are the same except near the end. This doesn't seriously mess up hashtable behaviour.]
A hashtable works by taking the modulus of the hash over the number of buckets.
It's important in a hashtable not to produce collisions for likely cases, since collisions reduce the efficiency of the hashtable.
Now, suppose someone puts a whole bunch of values into a hashtable that have some relationship between the items, like all having the same first character. This is a fairly predictable usage pattern, I'd say, so we don't want it to produce too many collisions.
It turns out that "because of the nature of maths", if the constant used in the hash, and the number of buckets, are coprime, then collisions are minimised in some common cases. If they are not coprime, then there are some fairly simple relationships between inputs for which collisions are not minimised. All the hashes come out equal modulo the common factor, which means they'll all fall into the 1/n th of the buckets which have that value modulo the common factor. You get n times as many collisions, where n is the common factor. Since n is at least 2, I'd say it's unacceptable for a fairly simple use case to generate at least twice as many collisions as normal. If some user is going to break our distribution into buckets, we want it to be a freak accident, not some simple predictable usage.
Now, hashtable implementations obviously have no control over the items put into them. They can't prevent them being related. So the thing to do is to ensure that the constant and the bucket counts are coprime. That way you aren't relying on the "last" component alone to determine the modulus of the bucket with respect to some small common factor. As far as I know they don't have to be prime to achieve this, just coprime.
But if the hash function and the hashtable are written independently, then the hashtable doesn't know how the hash function works. It might be using a constant with small factors. If you're lucky it might work completely differently and be nonlinear. If the hash is good enough, then any bucket count is just fine. But a paranoid hashtable can't assume a good hash function, so should use a prime number of buckets. Similarly a paranoid hash function should use a largeish prime constant, to reduce the chance that someone uses a number of buckets which happens to have a common factor with the constant.
In practice, I think it's fairly normal to use a power of 2 as the number of buckets. This is convenient and saves having to search around or pre-select a prime number of the right magnitude. So you rely on the hash function not to use even multipliers, which is generally a safe assumption. But you can still get occasional bad hashing behaviours based on hash functions like the one above, and prime bucket count could help further.
Putting about the principle that "everything has to be prime" is as far as I know a sufficient but not a necessary condition for good distribution over hashtables. It allows everybody to interoperate without needing to assume that the others have followed the same rule.
[Edit: there's another, more specialized reason to use a prime number of buckets, which is if you handle collisions with linear probing. Then you calculate a stride from the hashcode, and if that stride comes out to be a factor of the bucket count then you can only do (bucket_count / stride) probes before you're back where you started. The case you most want to avoid is stride = 0, of course, which must be special-cased, but to avoid also special-casing bucket_count / stride equal to a small integer, you can just make the bucket_count prime and not care what the stride is provided it isn't 0.]
In express if we import express from "express" and use app = express(); then app having all functionality of express
if we use app.use()
with any module/middleware function to use in whole express project
I was facing with this problem some time ago and I found java.util.LinkedList
is best for my case. It has several methods, with different namings, but they're doing what is needed:
push() -> LinkedList.addLast(); // Or just LinkedList.add();
pop() -> LinkedList.pollLast();
shift() -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();
Try calling setWillNotDraw(false)
from surfaceCreated
:
public void surfaceCreated(SurfaceHolder holder) {
try {
setWillNotDraw(false);
mycam.setPreviewDisplay(holder);
mycam.startPreview();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG,"Surface not created");
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(area, rectanglePaint);
Log.w(this.getClass().getName(), "On Draw Called");
}
and calling invalidate
from onTouchEvent
:
public boolean onTouch(View v, MotionEvent event) {
invalidate();
return true;
}
Anybody facing the same issues, follow the simple steps:
Import the project android
from downloaded zxing-master
zip file using option Import project (Eclipse ADT, Gradle, etc.)
and add the dollowing 2 lines of codes in your app level build.gradle
file and and you are ready to run.
So simple, yahh...
dependencies {
// https://mvnrepository.com/artifact/com.google.zxing/core
compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
// https://mvnrepository.com/artifact/com.google.zxing/android-core
compile group: 'com.google.zxing', name: 'android-core', version: '3.2.0'
}
You can always find latest version core
and android core
from below links:
https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 https://mvnrepository.com/artifact/com.google.zxing/android-core/3.2.0
UPDATE (29.05.2019)
Add these dependencies instead:
dependencies {
implementation 'com.google.zxing:core:3.4.0'
implementation 'com.google.zxing:android-core:3.3.0'
}
Here's the simple check, and creates the dir if doesn't exists:
## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)
if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
print("Dir already exists!")
}
In Windows it worked for me only after trying the following: 1. Open cmd inside the folder where "requests" is unpacked. (CTRL+SHIFT+right mouse click, choose the appropriate popup menu item) 2. (Here is the path to your pip3.exe)\pip3.exe install requests Done
You need to specify both source and destination, and if you want to copy directories you should look at the -r option.
So to recursively copy /home/user/whatever from remote server to your current directory:
scp -pr user@remoteserver:whatever .
You can also use the shorter format
From the man page:
%F full date; same as %Y-%m-%d
Example:
#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)
htmlFor
to replace for
!you can find more info by following the below links.
https://facebook.github.io/react/docs/dom-elements.html#htmlfor
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
I really like explanation by Jeremy west.... another approach which is really easy for understanding is given here http://courses.washington.edu/css343/zander/NotesProbs/heapcomplexity
since, buildheap depends using depends on heapify and shiftdown approach is used which depends upon sum of the heights of all nodes. So, to find the sum of height of nodes which is given by S = summation from i = 0 to i = h of (2^i*(h-i)), where h = logn is height of the tree solving s, we get s = 2^(h+1) - 1 - (h+1) since, n = 2^(h+1) - 1 s = n - h - 1 = n- logn - 1 s = O(n), and so complexity of buildheap is O(n).
You need to create an object since printInformation()
is non-static. Try:
int main() {
MyClass o;
o.printInformation();
fgetc( stdin );
return(0);
}
Microsoft Common Object Runtime Library.
See http://www.danielmoth.com/Blog/mscorlibdll.aspx and What does 'Cor' stand for?
Another option for plotting inline from an array of images could be:
import IPython
def showimg(a):
IPython.display.display(PIL.Image.fromarray(a))
where a is an array
a.shape
(720, 1280, 3)
Add into the global properties section in the pom file:
<project>
...
<properties>
<additionalparam>-Xdoclint:none</additionalparam>
</properties>
The common solution provided here in the other answers (adding that property in the plugins section) did not work for some reason. Only by setting it globally I could build the javadoc jar successfully.
Using the .loc[] accessor:
In [25]: a.loc[a['c1'] == 8].index[0]
Out[25]: 4
Can also use the get_loc() by setting 'c1' as the index. This will not change the original dataframe.
In [17]: a.set_index('c1').index.get_loc(8)
Out[17]: 4
As for me here the most easily way to add text(Tab -> \t) in textarea by cursor position and save the focus on cursor:
$('#text').keyup(function () {
var cursor = $('#text').prop('selectionStart');
//if cursot is first in textarea
if (cursor == 0) {
//i will add tab in line
$('#text').val('\t' + $('#text').val());
//here we set the cursor position
$('#text').prop('selectionEnd', 1);
} else {
var value = $('#text').val();
//save the value before cursor current position
var valToCur = value.substring(0, cursor);
//save the value after cursor current position
var valAfter = value.substring(cursor, value.length);
//save the new value with added tab in text
$('#text').val(valToCur + '\t' + valAfter);
//set focus of cursot after insert text (1 = because I add only one symbol)
$('#text').prop('selectionEnd', cursor + 1);
}
});
This works for me:
try(InputStream pdfin = new FileInputStream("input.pdf");OutputStream pdfout = new FileOutputStream("output.pdf")){
byte[] buffer = new byte[1024];
int bytesRead;
while((bytesRead = pdfin.read(buffer))!=-1){
pdfout.write(buffer,0,bytesRead);
}
}
But Jon's answer doesn't work for me if used in the following way:
try(InputStream pdfin = new FileInputStream("input.pdf");OutputStream pdfout = new FileOutputStream("output.pdf")){
int k = readFully(pdfin).length;
System.out.println(k);
}
Outputs zero as length. Why is that ?
Expanding on @Ryan G mentioned usage of the pandas.DataFrame.astype(<type>)
method, one can use the errors=ignore
argument to only convert those columns that do not produce an error, which notably simplifies the syntax. Obviously, caution should be applied when ignoring errors, but for this task it comes very handy.
>>> df = pd.DataFrame(np.random.rand(3, 4), columns=list('ABCD'))
>>> df *= 10
>>> print(df)
... A B C D
... 0 2.16861 8.34139 1.83434 6.91706
... 1 5.85938 9.71712 5.53371 4.26542
... 2 0.50112 4.06725 1.99795 4.75698
>>> df['E'] = list('XYZ')
>>> df.astype(int, errors='ignore')
>>> print(df)
... A B C D E
... 0 2 8 1 6 X
... 1 5 9 5 4 Y
... 2 0 4 1 4 Z
From pandas.DataFrame.astype docs:
errors : {‘raise’, ‘ignore’}, default ‘raise’
Control raising of exceptions on invalid data for provided dtype.
- raise : allow exceptions to be raised
- ignore : suppress exceptions. On error return original object
New in version 0.20.0.
You can do
var color = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
Or this (you will need the System.Windows.Media
namespace)
var color = (Color)ColorConverter.ConvertFromString("#FFFFFF");
GO to App -> then Targets -> Build Phases -> Compile Source
Now, Select the file in which you want to disable ARC
paste this snippet "-fno-objc-arc" After pasting press ENTER
in each file where you want to disable ARC.
You have a few options:
You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!
Use Linq's Union:
using System.Linq;
var l1 = new List<int>() { 1,2,3,4,5 };
var l2 = new List<int>() { 3,5,6,7,8 };
var l3 = l1.Union(l2).ToList();
Use RGBA like this: background-color: rgba(255, 0, 0, .5)
To create a simple time delay, you can import Darwin and then use sleep(seconds) to do the delay. That only takes whole seconds, though, so for more precise measurements you can import Darwin and use usleep(millionths of a second) for very precise measurement. To test this, I wrote:
import Darwin
print("This is one.")
sleep(1)
print("This is two.")
usleep(400000)
print("This is three.")
Which prints, then waits for 1 sec and prints, then waits for 0.4 sec then prints. All worked as expected.
It seems to me the last line of your example code should simply be:
Task<Item> itsMe = o as Task<Item>;
Or am I missing something?
Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
Because I recently needed this, I looked at the source of the answer in:
c# extend class by adding properties
and created a more dynamic version:
public static class ObjectExtenders
{
static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();
public static string GetFlags(this object objectItem, string key)
{
return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
}
public static void SetFlags(this object objectItem, string key, string value)
{
if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
{
Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
}
else
{
Flags.GetOrCreateValue(objectItem).Add(new stringObject()
{
Key = key,
Value = value
});
}
}
class stringObject
{
public string Key;
public string Value;
}
}
It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)
Make a new folder inside htdocs and access it in browser.Like this or this. Always start Apache when you start working or check whether it has started (in Control panel of xampp).
The size of storage required and how big the numbers can be.
On SQL Server:
tinyint
1 byte, 0 to 255smallint
2 bytes, -215 (-32,768) to 215-1 (32,767)int
4 bytes, -231 (-2,147,483,648) to 231-1 (2,147,483,647)bigint
8 bytes, -263 (-9,223,372,036,854,775,808) to 263-1 (9,223,372,036,854,775,807)You can store the number 1 in all 4, but a bigint
will use 8 bytes, while a tinyint
will use 1 byte.
You can use styled components.
Install it with npm i styled-components
import React from 'react';
import styled from 'styled-components';
const YourEffect = styled.div`
height: 50px;
position: relative;
&:after {
// whatever you want with normal CSS syntax. Here, a custom orange line as example
content: '';
width: 60px;
height: 4px;
background: orange
position: absolute;
bottom: 0;
left: 0;
},
const YourComponent = props => {
return (
<YourEffect>...</YourEffect>
)
}
export default YourComponent
Could always do:
db.foo.find().forEach(function(f){print(tojson(f, '', true));});
To get that compact view.
Also, I find it very useful to limit the fields returned by the find so:
db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});
which would return only the _id and name field from foo.
Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().
This is all you have to do:
In front.inc
global $name;
$name = 'james';
string.IsNullOrEmpty(str) - if you'd like to check string value has been provided
string.IsNullOrWhiteSpace(str) - basically this is already a sort of business logic implementation (i.e. why " " is bad, but something like "~~" is good).
My advice - do not mix business logic with technical checks. So, for example, string.IsNullOrEmpty is the best to use at the beginning of methods to check their input parameters.
A simple and flexible offline recognition on Android is implemented by CMUSphinx, an open source speech recognition toolkit. It works purely offline, fast and configurable It can listen continuously for keyword, for example.
You can find latest code and tutorial here.
Update in 2019: Time goes fast, CMUSphinx is not that accurate anymore. I recommend to try Kaldi toolkit instead. The demo is here.
Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.
col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):
<div class="row">
<div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
<div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.
Open Arduino IDE and go to files and click on the preference in the Arduino IDE.
Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.
Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.
You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.
A work-around is to use @tvanfosson's answer (the selected answer) and use JQuery (or Javascript) to set the option's value to 0:
$(document).ready(function () {
$('#DropDownListId option:first').val('0');
});
Hope this helps.
I have just solved such a problem by myself after I referred a mass of solutions found via Google and Stack Overflow.
First, please assure that you have set up an IBOutlet of your UIScrollView, Then please take a close look at Apple Doc: Keyboard Management. Finally, if you can scroll the background, but the keyboard still covers the Text Fields, please have a look at this piece of code:
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (aRect.size.height < activeField.frame.origin.y+activeField.frame.size.height) {
CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y+activeField.frame.size.height-aRect.size.height);
[scrollView setContentOffset:scrollPoint animated:YES];
The main difference between this piece and Apple's lies in the if condition. I believe apple's calculation of scroll distance and condition of whether text field covered by keyboard are not accurate, so I made my modification as above.
Let me know if it works