This is a recursive version that works with letter drives as well as UNC. I used the error catching to implement it but if anyone can do one without, I would be interested to see it. This approach works from the branches to the root so it will be somewhat usable when you don't have permissions in the root and lower parts of the directory tree.
' Reverse create directory path. This will create the directory tree from the top down to the root.
' Useful when working on network drives where you may not have access to the directories close to the root
Sub RevCreateDir(strCheckPath As String)
On Error GoTo goUpOneDir:
If Len(Dir(strCheckPath, vbDirectory)) = 0 And Len(strCheckPath) > 2 Then
MkDir strCheckPath
End If
Exit Sub
' Only go up the tree if error code Path not found (76).
goUpOneDir:
If Err.Number = 76 Then
Call RevCreateDir(Left(strCheckPath, InStrRev(strCheckPath, "\") - 1))
Call RevCreateDir(strCheckPath)
End If
End Sub
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.
Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.
/**
* Date to timestamp
* @param string template
* @param string date
* @return string
* @example datetotime("d-m-Y", "26-02-2012") return 1330207200000
*/
function datetotime(template, date){
date = date.split( template[1] );
template = template.split( template[1] );
date = date[ template.indexOf('m') ]
+ "/" + date[ template.indexOf('d') ]
+ "/" + date[ template.indexOf('Y') ];
return (new Date(date).getTime());
}
For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.
Module ArrayExtension
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
If arr IsNot Nothing Then
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
Else
ReDim arr(0)
arr(0) = item
End If
End Sub
End Module
I solved it with ExecuteSqlCommand
Put your own method like mine in DbContext as your own instances:
public void addmessage(<yourEntity> _msg)
{
var date = new SqlParameter("@date", _msg.MDate);
var subject = new SqlParameter("@subject", _msg.MSubject);
var body = new SqlParameter("@body", _msg.MBody);
var fid = new SqlParameter("@fid", _msg.FID);
this.Database.ExecuteSqlCommand("exec messageinsert @Date , @Subject , @Body , @Fid", date,subject,body,fid);
}
so you can have a method in your code-behind like this :
[WebMethod] //this method is static and i use web method because i call this method from client side
public static void AddMessage(string Date, string Subject, string Body, string Follower, string Department)
{
try
{
using (DBContext reposit = new DBContext())
{
msge <yourEntity> Newmsg = new msge();
Newmsg.MDate = Date;
Newmsg.MSubject = Subject.Trim();
Newmsg.MBody = Body.Trim();
Newmsg.FID= 5;
reposit.addmessage(Newmsg);
}
}
catch (Exception)
{
throw;
}
}
this is my SP :
Create PROCEDURE dbo.MessageInsert
@Date nchar["size"],
@Subject nchar["size"],
@Body nchar["size"],
@Fid int
AS
insert into Msg (MDate,MSubject,MBody,FID) values (@Date,@Subject,@Body,@Fid)
RETURN
hope helped you
If you're developing an application that transfers data using AMF (fairly common in a particular set of GIS web APIs I use regularly), Fiddler does not currently provide an AMF decoder that will allow you to easily view the binary data in an easily-readable format. Charles provides this functionality.
Add this dependency to work with Apache POI
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16-beta1</version>
</dependency>
Angular.js creates a watcher for every model we create in view. Whenever a model is changed, an "ng-dirty" class is appeneded to the model, so the watcher will observe all models which have the class "ng-dirty" & update their values in the controller & vice versa.
You're passing link=$a
and link=$b
in the hrefs for A and B, respectively. They are treated as strings, not variables. The following should fix that for you:
echo '<a href="pass.php?link=' . $a . '">Link 1</a>';
// and
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
The value of $a
also isn't included on pass.php
. I would suggest making a common variable file and include it on all necessary pages.
There are already many good answers to the part "what is uintptr_t data type". I will try to address the "what it can be used for?" part in this post.
Primarily for bitwise operations on pointers. Remember that in C++ one cannot perform bitwise operations on pointers. For reasons see Why can't you do bitwise operations on pointer in C, and is there a way around this?
Thus in order to do bitwise operations on pointers one would need to cast pointers to type unitpr_t and then perform bitwise operations.
Here is an example of a function that I just wrote to do bitwise exclusive or of 2 pointers to store in a XOR linked list so that we can traverse in both directions like a doubly linked list but without the penalty of storing 2 pointers in each node.
template <typename T>
T* xor_ptrs(T* t1, T* t2)
{
return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(t1)^reinterpret_cast<uintptr_t>(t2));
}
The EOF flag is only set after a read operation attempts to read past the end of the file. get()
is returning the symbolic constant traits::eof()
(which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof()
be true. If you want to check for this condition, you can do something like the following:
int ch;
while ((ch = inf.get()) != EOF) {
std::cout << static_cast<char>(ch) << "\n";
}
Basically, you need to include the Wordpress loop in your search.php template to loop through the search results and show them as part of the template.
Below is a very basic example from The WordPress Theme Search Template and Page Template over at ThemeShaper.
<?php
/**
* The template for displaying Search Results pages.
*
* @package Shape
* @since Shape 1.0
*/
get_header(); ?>
<section id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header><!-- .page-header -->
<?php shape_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'search' ); ?>
<?php endwhile; ?>
<?php shape_content_nav( 'nav-below' ); ?>
<?php else : ?>
<?php get_template_part( 'no-results', 'search' ); ?>
<?php endif; ?>
</div><!-- #content .site-content -->
</section><!-- #primary .content-area -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
I don't know about others, but I was used to define a "global constant" (DEBUG
) and then a global function (debug(msg)
) that would print msg
only if DEBUG == True
.
Then I write my debug statements like:
debug('My value: %d' % value)
...then I pick up unit testing and never did this again! :)
Draw a rectangle like sdleihssirhc said!
ctx.fillRect (10, 10, 1, 1);
^-- should draw a 1x1 rectangle at x:10, y:10
Using this HTML:
<div id="myElement" style="position: absolute">This stays at the top</div>
This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.
$(window).scroll(function() {
$('#myElement').css('top', $(this).scrollTop() + "px");
});
As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.
First of all, if you want to use HTML inside the content you need to set the HTML option to true:
$('.danger').popover({ html : true});
Then you have two options to set the content for a Popover
Using data-content: You need to escape the HTML content, something like this:
<a class='danger' data-placement='above'
data-content="<div>This is your div content</div>"
title="Title" href='#'>Click</a>
You can either escape the HTML manually or use a function. I don't know about PHP but in Rails we use *html_safe*.
Using a JS function: If you do this, you have several options. The easiest I think is to put your div content hidden wherever you want and then write a function to pass its content to popover. Something like this:
$(document).ready(function(){
$('.danger').popover({
html : true,
content: function() {
return $('#popover_content_wrapper').html();
}
});
});
And then your HTML looks like this:
<a class='danger' data-placement='above' title="Popover Title" href='#'>Click</a>
<div id="popover_content_wrapper" style="display: none">
<div>This is your div content</div>
</div>
Hope it helps!
PS: I've had some troubles when using popover and not setting the title attribute... so, remember to always set the title.
You can do it with:
NSNumber *myNumber = @15;
NSString *myNumberInString = [myNumber stringValue];
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
_x000D_
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
_x000D_
To disable a single rule for the rest of the file below:
/* eslint no-undef: "off"*/
const uploadData = new FormData();
Here is a solution I use in one of my project.
network_utils.telnet
import socket
from timeit import default_timer as timer
def telnet(hostname, port=23, timeout=1):
start = timer()
connection = socket.socket()
connection.settimeout(timeout)
try:
connection.connect((hostname, port))
end = timer()
delta = end - start
except (socket.timeout, socket.gaierror) as error:
logger.debug('telnet error: ', error)
delta = None
finally:
connection.close()
return {
hostname: delta
}
def test_telnet_is_null_when_host_unreachable(self):
hostname = 'unreachable'
response = network_utils.telnet(hostname)
self.assertDictEqual(response, {'unreachable': None})
def test_telnet_give_time_when_reachable(self):
hostname = '127.0.0.1'
response = network_utils.telnet(hostname, port=22)
self.assertGreater(response[hostname], 0)
you can use
git pull --rebase <your_reponame> <your_branch>
this will help incase you have some changes not yet registered on your local repo. especially README.md
A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.
Ah, the following works and does what I want:
configurations {
runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"
}
It seems that an Exclude Rule only has two attributes - group
and module
. However, the above syntax doesn't prevent you from specifying any arbitrary property as a predicate. When trying to exclude from an individual dependency you cannot specify arbitrary properties. For example, this fails:
dependencies {
compile ('org.springframework.data:spring-data-hadoop-core:2.0.0.M4-hadoop22') {
exclude group: "org.slf4j", name: "slf4j-log4j12"
}
}
with
No such property: name for class: org.gradle.api.internal.artifacts.DefaultExcludeRule
So even though you can specify a dependency with a group:
and name:
you can't specify an exclusion with a name:
!?!
Perhaps a separate question, but what exactly is a module then? I can understand the Maven notion of groupId:artifactId:version, which I understand translates to group:name:version in Gradle. But then, how do I know what module (in gradle-speak) a particular Maven artifact belongs to?
FOR SQLALCHEMY AND PYTHON
The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:
e = create_engine(
"mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.
Imperative programming is telling the computer explicitly what to do, and how to do it, like specifying order and such
C#:
for (int i = 0; i < 10; i++)
{
System.Console.WriteLine("Hello World!");
}
Declarative is when you tell the computer what to do, but not really how to do it. Datalog / Prolog is the first language that comes to mind in this regard. Basically everything is declarative. You can't really guarantee order.
C# is a much more imperative programming language, but certain C# features are more declarative, like Linq
dynamic foo = from c in someCollection
let x = someValue * 2
where c.SomeProperty < x
select new {c.SomeProperty, c.OtherProperty};
The same thing could be written imperatively:
dynamic foo = SomeCollection.Where
(
c => c.SomeProperty < (SomeValue * 2)
)
.Select
(
c => new {c.SomeProperty, c.OtherProperty}
)
(example from wikipedia Linq)
if you are still interested, this function removes spaces from the beginning of the string, and I just had it working in my code:
void removeSpaces(char *str1)
{
char *str2;
str2=str1;
while (*str2==' ') str2++;
if (str2!=str1) memmove(str1,str2,strlen(str2)+1);
}
There are many ways to scroll up and down in Selenium Webdriver I always use Java Script to do the same.
Below is the code which always works for me if I want to scroll up or down
// This will scroll page 400 pixel vertical
((JavascriptExecutor)driver).executeScript("scroll(0,400)");
You can get full code from here Scroll Page in Selenium
If you want to scroll for a element then below piece of code will work for you.
je.executeScript("arguments[0].scrollIntoView(true);",element);
You will get the full doc here Scroll for specific Element
The --author
option doesn't work:
*** Please tell me who you are.
Run
git config --global user.email "[email protected]"
git config --global user.name "Your Name"
This does:
git -c user.name='A U Thor' -c [email protected] commit
From here:
Windows
For Example, C:\Program Files\MySQL\MySQL Server 5.1\my.ini
#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"
Find the “datadir”
, this is the where does MySQL stored the data in Windows.
Linux
yongmo@myserver:~$ find / -name my.cnf
find: /home/lost+found: Permission denied
find: /lost+found: Permission denied
/etc/mysql/my.cnf
my.cnf
file like this: cat /etc/mysql/my.cnf
yongmo@myserver:~$ cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/english
skip-external-locking
“datadir”
, this is where does MySQL stored the data in Linux system.Here's a quick, admittedly butchered response, but in a sentence:
1NF : Your table is organized as an unordered set of data, and there are no repeating columns.
2NF: You don't repeat data in one column of your table because of another column.
3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.
For more detail, see wikipedia...
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
It starts working because on the base.py you have all information needed in a basic settings file. You need the line:
SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&022shmi1jcgihb*'
So it works and when you do from base import *
, it imports SECRET_KEY into your development.py
.
You should always import basic settings before doing any custom settings.
EDIT:
Also, when django imports development from your package, it initializes all variables inside base since you defined from base import *
inside __init__.py
Just to update this answer unless anyone comes across this later, since JDK 6 you can use
File file = new File('/directory/to/file');
file.setWritable(boolean);
file.setReadable(boolean);
file.setExecutable(boolean);
you can find the documentation on Oracle File(Java Platform SE 7). Bear in mind that these commands only work if the current working user has ownership or write access to that file. I am aware that OP wanted chmod type access for more intricate user configuration. these will set the option across the board for all users.
Add a log4j.properties(log4j.xml) file with at least one appender in root of your classpath.
The contents of the file(log4j.properties) can be as simple as
log4j.rootLogger=WARN,A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %c %x - %m%n
This will enable log4j logging with default log level as WARN
and use the java console to log the messages.
EDIT:
Task has Wait method, Task.Wait(), which waits for the "promise" to resolve and then continues, thus rendering it synchronous. example:
async Task<String> MyAsyncMethod() { ... }
String mySyncMethod() {
return MyAsyncMethod().Wait();
}
When compiling your program, you need to include dict.c as well, eg:
gcc -o test1 test1.c dict.c
Plus you have a typo in dict.c definition of CreateDictionary
, it says CreateDectionary
(e
instead of i
)
Syntax looks like:
$ split [OPTION] [INPUT [PREFIX]]
where prefix is PREFIXaa, PREFIXab, ...
Just use proper one and youre done or just use mv for renameing.
I think
$ mv * *.txt
should work but test it first on smaller scale.
:)
I had exactly the same issue when downloading from S3 very large files.
The example solution from AWS docs just does not work:
var file = fs.createWriteStream(options.filePath);
file.on('close', function(){
if(self.logger) self.logger.info("S3Dataset file download saved to %s", options.filePath );
return callback(null,done);
});
s3.getObject({ Key: documentKey }).createReadStream().on('error', function(err) {
if(self.logger) self.logger.error("S3Dataset download error key:%s error:%@", options.fileName, error);
return callback(error);
}).pipe(file);
While this solution will work:
var file = fs.createWriteStream(options.filePath);
s3.getObject({ Bucket: this._options.s3.Bucket, Key: documentKey })
.on('error', function(err) {
if(self.logger) self.logger.error("S3Dataset download error key:%s error:%@", options.fileName, error);
return callback(error);
})
.on('httpData', function(chunk) { file.write(chunk); })
.on('httpDone', function() {
file.end();
if(self.logger) self.logger.info("S3Dataset file download saved to %s", options.filePath );
return callback(null,done);
})
.send();
The createReadStream
attempt just does not fire the end
, close
or error
callback for some reason. See here about this.
I'm using that solution also for writing down archives to gzip, since the first one (AWS example) does not work in this case either:
var gunzip = zlib.createGunzip();
var file = fs.createWriteStream( options.filePath );
s3.getObject({ Bucket: this._options.s3.Bucket, Key: documentKey })
.on('error', function (error) {
if(self.logger) self.logger.error("%@",error);
return callback(error);
})
.on('httpData', function (chunk) {
file.write(chunk);
})
.on('httpDone', function () {
file.end();
if(self.logger) self.logger.info("downloadArchive downloaded %s", options.filePath);
fs.createReadStream( options.filePath )
.on('error', (error) => {
return callback(error);
})
.on('end', () => {
if(self.logger) self.logger.info("downloadArchive unarchived %s", options.fileDest);
return callback(null, options.fileDest);
})
.pipe(gunzip)
.pipe(fs.createWriteStream(options.fileDest))
})
.send();
You can look up the constraint name in the sys.key_constraints table:
SELECT name
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = Object_id('dbo.Student');
If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:
DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);
SELECT @table = N'dbo.Student';
SELECT @sql = 'ALTER TABLE ' + @table
+ ' DROP CONSTRAINT ' + name + ';'
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(@table);
EXEC sp_executeSQL @sql;
This code is from Aaron Bertrand (source).
Take 2. My answer below didn't get me all the way to the desired result, but it may still be useful to somebody. The auto-select feature of the ComboBox was causing me major pain. This one uses a TextBox sitting over the top of a ComboBox, allowing me to ignore whatever appears in the ComboBox itself and just respond to the selection changed event.
Code behind
public partial class TestForm : Form
{
// Custom class for managing calls to an external address finder service
private readonly AddressFinder _addressFinder;
// Events for handling async calls to address finder service
private readonly AddressSuggestionsUpdatedEventHandler _addressSuggestionsUpdated;
private delegate void AddressSuggestionsUpdatedEventHandler(object sender, AddressSuggestionsUpdatedEventArgs e);
public TestForm()
{
InitializeComponent();
_addressFinder = new AddressFinder(new AddressFinderConfigurationProvider());
_addressSuggestionsUpdated += AddressSuggestions_Updated;
}
private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
comboBox1_SelectionChangeCommitted(sender, e);
comboBox1.DroppedDown = false;
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
if (comboBox1.Items.Count > 0)
{
if (comboBox1.SelectedIndex > 0)
{
comboBox1.SelectedIndex--;
}
}
e.Handled = true;
}
else if (e.KeyCode == Keys.Down)
{
if (comboBox1.Items.Count > 0)
{
if (comboBox1.SelectedIndex < comboBox1.Items.Count - 1)
{
comboBox1.SelectedIndex++;
}
}
e.Handled = true;
}
else if (e.KeyCode == Keys.Enter)
{
comboBox1_SelectionChangeCommitted(sender, e);
comboBox1.DroppedDown = false;
textBox1.SelectionStart = textBox1.TextLength;
e.Handled = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r') // Enter key
{
e.Handled = true;
return;
}
if (char.IsControl(e.KeyChar) && e.KeyChar != '\b') // Backspace key
{
return;
}
if (textBox1.Text.Length > 1)
{
Task.Run(() => GetAddressSuggestions(textBox1.Text));
}
}
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
if (comboBox1.Items.Count > 0 &&
comboBox1.SelectedItem.IsNotNull() &&
comboBox1.SelectedItem is KeyValuePair<string, string>)
{
var selectedItem = (KeyValuePair<string, string>)comboBox1.SelectedItem;
textBox1.Text = selectedItem.Value;
// Do Work with selectedItem
}
}
private async Task GetAddressSuggestions(string searchString)
{
var addressSuggestions = await _addressFinder.CompleteAsync(searchString).ConfigureAwait(false);
if (_addressSuggestionsUpdated.IsNotNull())
{
_addressSuggestionsUpdated.Invoke(this, new AddressSuggestionsUpdatedEventArgs(addressSuggestions));
}
}
private void AddressSuggestions_Updated(object sender, AddressSuggestionsUpdatedEventArgs eventArgs)
{
try
{
ThreadingHelper.BeginUpdate(comboBox1);
ThreadingHelper.ClearItems(comboBox1);
if (eventArgs.AddressSuggestions.Count > 0)
{
foreach (var addressSuggestion in eventArgs.AddressSuggestions)
{
var item = new KeyValuePair<string, string>(addressSuggestion.Key, addressSuggestion.Value.ToUpper());
ThreadingHelper.AddItem(comboBox1, item);
}
ThreadingHelper.SetDroppedDown(comboBox1, true);
ThreadingHelper.SetVisible(comboBox1, true);
}
else
{
ThreadingHelper.SetDroppedDown(comboBox1, false);
}
}
finally
{
ThreadingHelper.EndUpdate(comboBox1);
}
}
private class AddressSuggestionsUpdatedEventArgs : EventArgs
{
public IList<KeyValuePair<string, string>> AddressSuggestions { get; }
public AddressSuggestionsUpdatedEventArgs(IList<KeyValuePair<string, string>> addressSuggestions)
{
AddressSuggestions = addressSuggestions;
}
}
}
You may or may not have issues with setting the DroppedDown property of the ComboBox. I eventually just wrapped it up in a try block with an empty catch block. Not a great solution, but it works.
Please see my other answer below for info on ThreadingHelpers.
Enjoy.
First you have to make sure the access level of the variable is protected or public. If the variable or property is private the page won't have access to it.
Code Behind
protected String Clients { get; set; }
Aspx
<span><%=Clients %> </span>
There is a built-in middleware that makes it easier than writing a custom one.
Asp.Net Core 5
version:
app.UseExceptionHandler(a => a.Run(async context =>
{
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandlerPathFeature.Error;
await context.Response.WriteAsJsonAsync(new { error = exception.Message });
}));
Older versions (they did not have WriteAsJsonAsync
extension):
app.UseExceptionHandler(a => a.Run(async context =>
{
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandlerPathFeature.Error;
var result = JsonConvert.SerializeObject(new { error = exception.Message });
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(result);
}));
It should do pretty much the same, just a bit less code to write.
Important: Remember to add it before UseMvc
(or UseRouting
in .Net Core 3) as order is important.
Consider using matplotlib.cbook pieces
for example:
import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
print s
If you are accessing Oracle with JDBC (Java) you can use DatabaseMetadata class. If you are accessing Oracle with ADO.NET you can use a similar approach.
If you are accessing Oracle with ODBC, you can use SQLTables function.
Otherwise, if you just need the information in SQLPlus or similar Oracle client, one of the queries already mentioned will do. For instance:
select TABLE_NAME from user_tables
You can do this 2 ways, via js or html (easist)
$('.carousel').carousel({
interval: false,
});
That will make the auto sliding stop because there no Milliseconds added and will never slider next.
data-interval="false"
and removing data-ride="carousel"
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
becomes:
<div id="carouselExampleCaptions" class="carousel slide" data-interval="false">
updated based on @webMan's comment
There are many ways to do it, but this is pretty simple and avoids issues with disrupting inline content positioning. You might need to adjust for margins/padding, too.
#backdrop, #curtain {
height: 100px;
width: 200px;
}
#curtain {
position: relative;
top: -100px;
}
You can also use as many classes as needed on a tag, but an id must be unique to the document. Also be careful of using too many divs, when another more semantic tag can do the job.
<p id="unique" class="x y z">Styled paragraph</p>
When you click on the image you'll get the alert:
<img src="logo1.jpg" onClick='alert("Hello World!")'/>
if this is what you want.
You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.
You can however have cells span multiple columns, such as:
<table>
<tr>
<td>25</td>
<td>50</td>
<td>25</td>
</tr>
<tr>
<td colspan="2">75</td>
<td>20</td>
</tr>
</table>
As an aside, you should avoid using style attributes like border
and bgcolor
and prefer CSS for those.
For Spreedsheet + PHP 7, you must write instead of PHPExcel_Cell::columnIndexFromString
, \PhpOffice\PhpSpreadsheet\Cell::columnIndexFromString
. And at the loop is a mistake, there you must <
not work with <=
. Otherwise, he takes a column too much into the loop.
you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference
When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.
DatabaseMetaData.supportsBatchUpdates()
method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.executeBatch()
is used to start the execution of all the statements grouped together.addBatch()
method. However, you cannot selectively choose which statement to remove.EXAMPLE:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertEmp1 = "insert into emp values
(10,'jay','trainee')";
String insertEmp2 = "insert into emp values
(11,'jayes','trainee')";
String insertEmp3 = "insert into emp values
(12,'shail','trainee')";
con.setAutoCommit(false);
stmt.addBatch(insertEmp1);//inserting Query in stmt
stmt.addBatch(insertEmp2);
stmt.addBatch(insertEmp3);
ResultSet rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows before batch execution= "
+ rs.getRow());
stmt.executeBatch();
con.commit();
System.out.println("Batch executed");
rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows after batch execution= "
+ rs.getRow());
}
}
refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm
You can give it a property display block; so it will behave like a div and have its own line
CSS:
.feature_desc {
display: block;
....
}
If you want to just uncommit the last commit use this:
git reset HEAD~
work like charm for me.
It is a simple way to do rows-count.
ResultSet rs = job.getSearchedResult(stmt);
int rsCount = 0;
//but notice that you'll only get correct ResultSet size after end of the while loop
while(rs.next())
{
//do your other per row stuff
rsCount = rsCount + 1;
}//end while
How about making everything easier with Json.NET?
public void LoadJson()
{
using (StreamReader r = new StreamReader("file.json"))
{
string json = r.ReadToEnd();
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
}
}
public class Item
{
public int millis;
public string stamp;
public DateTime datetime;
public string light;
public float temp;
public float vcc;
}
You can even get the values dynamically
without declaring Item
class.
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}
Please disable js bundling and increase memory. That should fix it. I fixed mine by disabling js bundling.
Thanks
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
Use the TRUNCATE TABLE
command.
Escape the hyphen.
[a-zA-Z0-9!$* \t\r\n\-]
UPDATE:
Never mind this answer - you can add the hyphen to the group but you don't have to escape it. See Konrad Rudolph's answer instead which does a much better job of answering and explains why.
Uri is serializable, so you can save strings and convert it back when loading
when saving
String str = myUri.toString();
and when loading
Uri myUri = Uri.parse(str);
Try using SCP on Windows to transfer files, you can download SCP from Putty's website. Then try running:
pscp.exe filename.extension [email protected]:directory/subdirectory
There is a full length guide here.
It's the null conditional operator. It basically means:
"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
In your example, the point is that if a
is null
, then a?.PropertyOfA
will evaluate to null
rather than throwing an exception - it will then compare that null
reference with foo
(using string's ==
overload), find they're not equal and execution will go into the body of the if
statement.
In other words, it's like this:
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}
... except that a
is only evaluated once.
Note that this can change the type of the expression, too. For example, consider FileInfo.Length
. That's a property of type long
, but if you use it with the null conditional operator, you end up with an expression of type long?
:
FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null
A better method is using strrpos + substr (faster than explode for that) :
$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);
But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php
I have the same problem. This error occurs because conection pooling. When exists two or more users acess the system the connetion pooling reuse a connetion and the transation too. If the first user execute commit ou rollback the transaction is no longe usable.
For escape characters also this will work using pattern matching:
myString.replace(/((<)|(<)(?:.|\n)*?(>)|(>))/gm, '');
oldDate
is not in the format of the SimpleDateFormat
you are using to parse it.
Try this format: dd-MMM-yyyy
- It matches what you're trying to parse.
is a small amount of data saved in the browser (client-side)
can be set from PHP with setcookie
and then will be sent to the client's browser (HTTP response header Set-cookie
)
can be set directly client-side in Javascript: document.cookie = 'foo=bar';
if no expiration date is set, by default, it will expire when the browser is closed.
Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';
. Close the tab, reopen the same website, open the Console, do document.cookie
: you will see foo=bar
is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie
is empty.
you can also set a precise expiration date other than "deleted when browser is closed".
the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie
). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:
can be read client-side with document.cookie
can be read server-side with $_COOKIE['foo']
Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):
from bottle import get, run, request, response
@get('/')
def index():
if request.get_cookie("visited"):
return "Welcome back! Nice to see you again"
else:
response.set_cookie("visited", "yes")
return "Hello there! Nice to meet you"
run(host='localhost', port=8080, debug=True, reloader=True)
is some data relative to a browser session saved server-side
each server-side language may implement it in a different way
in PHP, when session_start();
is called:
jo96fme9ko0f85cdglb3hl6ah6
/var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/
:
(it can also be be sent via the URL instead of cookie but not the default behaviour)
you can see the session ID on client-side with document.cookie
:
the PHPSESSID
cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.
can be set/read in PHP with $_SESSION
the client-side does not see the session data but only the ID: do this in index.php
:
<?php
session_start();
$_SESSION["abc"]="def";
?>
The only thing that is seen on client-side is (as mentioned above) the session ID:
because of this, session is useful to store data that you don't want to be seen or modified by the client
you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie
document.body
is not yet available when your code runs.
What you can do instead:
var docBody=document.getElementsByTagName("body")[0];
docBody.appendChild(mySpan);
A missing intermediate certificate might be the problem.
You may want to check your https://hostname with curl, openssl or a website like https://www.digicert.com/help/.
No idea why Chrome (possibly) sometimes has problems validating these certs.
PLEASE do not use object as a class name:
public class MyObject //better to choose an appropriate name
{
string id;
DateTime date;
public string ID
{
get { return id; }
set { id = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
}
You should implement INotifyPropertyChanged
for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.
Your Viewmodel class/ dialogbox class should have a Property
of your MyObject
list. ObservableCollection<MyObject>
is the way to go:
public ObservableCollection<MyObject> MyList
{
get...
set...
}
In your xaml
you should set the Itemssource
to your collection of MyObject
. (the Datacontext
have to be your dialogbox class!)
<DataGrid ItemsSource="{Binding Source=MyList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
$cfg['Servers'][$i]['AllowNoPassword'] = false;
for multiple scripts, use this
var loadScript = function(src) {
var tag = document.createElement('script');
tag.async = false;
tag.src = src;
document.getElementsByTagName('body').appendChild(tag);
}
loadScript('//cdnjs.com/some/library.js')
loadScript('//cdnjs.com/some/other/library.js')
Use x86 images and download "Intel Hardware Accelerated Execution Manager" from the sdk manager.
See here how to enable it: http://developer.android.com/tools/devices/emulator.html#accel-vm
Your emulator will be super fast!
Just add these lines of code to your activity/fragment java file:
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
Make sure you follow the language definition for JSON. In your second example, the section:
"labs":[{
""
}]
Is invalid since an object must be composed of zero or more key-value pairs "a" : "b"
, where "b"
may be any valid value. Some parsers may automatically interpret { "" }
to be { "" : null }
, but this is not a clearly defined case.
Also, you are using a nested array of objects [{}]
quite a bit. I would only do this if:
SARose's answer worked for me until I updated from Ubuntu 20.04 LTS. The slight change I made to his code makes it work on the latest Ubuntu release.
import subprocess
def find_files(file_name):
command = ['locate'+ ' ' + file_name]
output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
output = output.decode()
search_results = output.split('\n')
return search_results
What you've got (according to the debug image) is an object array containing a string array. So you need something like:
Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];
You haven't shown the type of values
- if this is already Object[]
then you could just use (String[])values[0]
.
Of course even with the cast to Object[]
you could still do it in one statement, but it's ugly:
String[] strings = (String[]) ((Object[])values)[0];
The benefit of doing server side validation over client side validation is that client side validation can be bypassed/manipulated:
In short - always, always validate server-side and then consider client-side validation as an added "extra" to enhance the end user experience.
I had the same issue in Win7 regarding running a script (.bat) at startup (When the computer boots vs when someone logs in) that would modify the network parameters using netsh. What ended up working for me was the following:
Click on “Create New Task” on the right hand side of the screen and set the parameters as follows:
a. Set the user account to SYSTEM
b. Choose "Run with highest privileges"
c. Choose the OS for Windows7
Here's a solution that keeps things within a dplyr pipe chain. You sort the data in advance, and then using mutate_at to convert to a factor. I've modified the data slightly to show how this solution can be applied generally, given data that can be sensibly sorted:
# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
amount=c(48.4, 48.1, 46.8,
25.9, 26.0, 24.9,
20.8, 21.5, 16.5,
21.1, 21.4, 20.1))
temp %>%
arrange(size_num) %>% # sort
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
You can apply this solution to arrange the bars within facets, too, though you can only choose a single, preferred order:
temp %>%
arrange(size_num) %>%
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
arrange(desc(amount)) %>%
mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
you can use 'Android iOS Emulator' plugin and Add the Android Studio emulator script to your settings in Visual Studio Code:
Mac:
emulator.emulatorPath": "~/Library/Android/sdk/tools/emulator
Windows:
emulator.emulatorPath": "<your android home>\\Sdk\\emulator\\emulator.exe
Linux:
emulator.emulatorPath": "~/Documents/SDK/tools
Your visual studio code settings are found here: File -> Preferences -> Setting -> User Setting -> Extensions -> Emulator Configuration. Open command pallete Cmd-Shift-P -> Type Emulator
I have faced the same issue. The following steps in VS 2013 solved the problem for me:
set()
is exactly what you want. O(1) lookups, and smaller than a dict.
The best way to implement a RESTful search is to consider the search itself to be a resource. Then you can use the POST verb because you are creating a search. You do not have to literally create something in a database in order to use a POST.
For example:
Accept: application/json
Content-Type: application/json
POST http://example.com/people/searches
{
"terms": {
"ssn": "123456789"
},
"order": { ... },
...
}
You are creating a search from the user's standpoint. The implementation details of this are irrelevant. Some RESTful APIs may not even need persistence. That is an implementation detail.
You should set body
and html
to position:fixed;
, and then set right:
, left:
, top:
, and bottom:
to 0;
. That way, even if content overflows it will not extend past the limits of the viewport.
For example:
<html>
<body>
<div id="wrapper"></div>
</body>
</html>
CSS:
html, body, {
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
}
Caveat: Using this method, if the user makes their window smaller, content will be cut off.
There is a Win32 (C++) function in shlwapi.dll that does exactly what you want: PathRelativePathTo()
I'm not aware of any way to access this from .NET other than to P/Invoke it, though.
You can append array of Data at the end of custom state:
const [vehicleData, setVehicleData] = React.useState<any[]>([]);
setVehicleData(old => [...old, ...newArrayData]);
For example, In below, you appear an example of axios:
useEffect(() => {
const fetchData = async () => {
const result = await axios(
{
url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
method: 'get',
}
);
setVehicleData(old => [...old, ...result.data.data]);
};
fetchData();
}, [page]);
Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.
That's why you can't use something 'not hashable' as a dict key, like a list:
>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.
Actually, I believe you want to use the __getattr__
special method instead.
Quote from the Python docs:
__getattr__( self, name)
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism,__getattr__()
is not called. (This is an intentional asymmetry between__getattr__()
and__setattr__()
.) This is done both for efficiency reasons and because otherwise__setattr__()
would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the__getattribute__()
method below for a way to actually get total control in new-style classes.
Note: for this to work, the instance should not have a test
attribute, so the line self.test=20
should be removed.
A 302 redirect means that the page was temporarily moved, while a 301 means that it was permanently moved.
301s are good for SEO value, while 302s aren't because 301s instruct clients to forget the value of the original URL, while the 302 keeps the value of the original and can thus potentially reduce the value by creating two, logically-distinct URLs that each produce the same content (search engines view them as distinct duplicates rather than a single resource with two names).
One of the approaches may be like this:
1) Create a CSS file with name "style.css" and define an id selector in it:
#pane{ -fx-background-image: url("background_image.jpg"); -fx-background-repeat: stretch; -fx-background-size: 900 506; -fx-background-position: center center; -fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0); }
2) Set the id of the most top control (or any control) in the scene with value defined in CSS and load this CSS file into the scene:
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.setId("pane");
Scene scene = new Scene(root, 300, 250);
scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
}
You can also give an id to the control in a FXML file:
<StackPane id="pane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="demo.Sample">
<children>
</children>
</StackPane>
For more info about JavaFX CSS Styling refer to this guide.
Very convenient tool for logging is http://logging.apache.org/log4net/
You can also make something of themselves less (more) powerful. You can use http://msdn.microsoft.com/ru-ru/library/system.io.filestream (v = vs.110). Aspx
The issue is with your project which is not able to complete maven build. Steps to follow :
This will update your maven build and will surely remove your errors with pom.xml
more generic answer in kotlin
fun setClickableText(view: TextView, firstSpan: String, secondSpan: String) {
val context = view.context
val builder = SpannableStringBuilder()
val unClickableSpan = SpannableString(firstSpan)
val span = SpannableString(" "+secondSpan)
builder.append(unClickableSpan);
val clickableSpan: ClickableSpan = object : ClickableSpan() {
override fun onClick(textView: View) {
val intent = Intent(context, HomeActivity::class.java)
context.startActivity(intent)
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = true
ds.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.ITALIC));
}
}
builder.append(span);
builder.setSpan(clickableSpan, firstSpan.length, firstSpan.length+secondSpan.length+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
view.setText(builder,TextView.BufferType.SPANNABLE)
view.setMovementMethod(LinkMovementMethod.getInstance());
}
The default port 1433 is used when there is only one SQL Server named instance running on the computer.
When multiple SQL Server named instances are running, they run by default under a dynamic port (49152–65535). In this scenario, an application will connect to the SQL Server Browser service port (UDP 1434) to get the dynamic port and then connect to the dynamic port directly.
in case the above does not work for you. for me this did not for some reasons;
the UNIX numbers i am working on are from the Mozilla place.sqlite dates.
to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)
Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked
You should write :
if (self.a != 0) and (self.b != 0) :
"&
" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&
" is "and" in Python.
A shorter way to check what you want is to use the "in" operator :
if 0 not in (self.a, self.b) :
You can check if anything is part of a an iterable with "in", it works for :
"foo" in ("foo", 1, c, etc)
will return true"foo" in ["foo", 1, c, etc]
will return true"a" in "ago"
will return true"foo" in {"foo" : "bar"}
will return trueAs an answer to the comments :
Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.
For the triangle check, it's easier to read :
0 not in (self.a, self.b, self.c)
Than
(self.a != 0) and (self.b != 0) and (self.c != 0)
It's easier to refactor too.
Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.
You should use white-space with display table
Example:
legend {
display:table; /* Enable line-wrapping in IE8+ */
white-space:normal; /* Enable line-wrapping in old versions of some other browsers */
}
Offical plugins
You can use the output callback plugins. For example, starting in Ansible 2.4, you can use the debug output callback plugin:
# In ansible.cfg:
[defaults]
stdout_callback = debug
(Altervatively, run export ANSIBLE_STDOUT_CALLBACK=debug
before running your playbook)
Important: you must run ansible-playbook
with the -v
(--verbose
) option to see the effect. With stdout_callback = debug
set, the output should now look something like this:
TASK [Say Hello] ********************************
changed: [192.168.1.2] => {
"changed": true,
"rc": 0
}
STDOUT:
Hello!
STDERR:
Shared connection to 192.168.1.2 closed.
There are other modules besides the debug
module if you want the output to be formatted differently. There's json
, yaml
, unixy
, dense
, minimal
, etc. (full list).
For example, with stdout_callback = yaml
, the output will look something like this:
TASK [Say Hello] **********************************
changed: [192.168.1.2] => changed=true
rc: 0
stderr: |-
Shared connection to 192.168.1.2 closed.
stderr_lines:
- Shared connection to 192.168.1.2 closed.
stdout: |2-
Hello!
stdout_lines: <omitted>
Third-party plugins
If none of the official plugins are satisfactory, you can try the human_log
plugin. There are a few versions:
The answer to this is very needed today because not everyone wants to use cURL to consume web services. Also PHP does allow for this using the following code
function get_info()
{
$post_data = array(
'test' => 'foobar',
'okay' => 'yes',
'number' => 2
);
// Send a request to example.com
$result = $this->post_request('http://www.example.com/', $post_data);
if ($result['status'] == 'ok'){
// Print headers
echo $result['header'];
echo '<hr />';
// print the result of the whole request:
echo $result['content'];
}
else {
echo 'A error occured: ' . $result['error'];
}
}
function post_request($url, $data, $referer='') {
// Convert the data array into URL Parameters like a=b&foo=bar etc.
$data = http_build_query($data);
// parse the given URL
$url = parse_url($url);
if ($url['scheme'] != 'http') {
die('Error: Only HTTP request are supported !');
}
// extract host and path:
$host = $url['host'];
$path = $url['path'];
// open a socket connection on port 80 - timeout: 30 sec
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp){
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
if ($referer != '')
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
}
else {
return array(
'status' => 'err',
'error' => "$errstr ($errno)"
);
}
// close the socket connection:
fclose($fp);
// split the result header from the content
$result = explode("\r\n\r\n", $result, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
// return as structured array:
return array(
'status' => 'ok',
'header' => $header,
'content' => $content);
}
I had the same issue, ended up using the much more convenient Guava Resources:
Resources.getResource("my.file")
Here's two more ways, both very concise.
$arr1 = @(0) * 20
$arr2 = ,0 * 20
<script>
$(document).ready(function() {
$('#nametable').DataTable({
"bPaginate": false,
"bFilter": false,
"bInfo": false
});
});
</script>
in your datatable constructor
https://datatables.net/forums/discussion/20006/how-to-remove-cross-icon-in-search-box
For the ones having this same problem, but with a responsive design, you can also use:
width: 75%;
position: fixed;
left: 50%;
margin-left: -37.5%;
Doing this will always keep your fixed div
centered on the screen, even with a responsive design.
I needed a similar function (but different) to generate a unique-ish ID based on the username and current time. So:
window.newId = ->
# create a number based on the username
unless window.userNumber?
window.userNumber = 0
for c,i in window.MyNamespace.userName
char = window.MyNamespace.userName.charCodeAt(i)
window.MyNamespace.userNumber+=char
((window.MyNamespace.userNumber + Math.floor(Math.random() * 1e15) + new Date().getMilliseconds()).toString(36)).toUpperCase()
Produces:
2DVFXJGEKL
6IZPAKFQFL
ORGOENVMG
... etc
edit Jun 2015: For new code I use shortid: https://www.npmjs.com/package/shortid
Inspired by Nathanael Smith's answer and Eric Freese's comment, it could be as simple as:
var exec = require('child_process').exec;
exec('coffee -cw my_file.coffee').stdout.pipe(process.stdout);
Hi use this class this will compare both lists and shows exactly the mismatch b/w both lists.
import java.util.ArrayList;
import java.util.List;
public class ListCompare {
/**
* @param args
*/
public static void main(String[] args) {
List<String> dbVinList;
dbVinList = new ArrayList<String>();
List<String> ediVinList;
ediVinList = new ArrayList<String>();
dbVinList.add("A");
dbVinList.add("B");
dbVinList.add("C");
dbVinList.add("D");
ediVinList.add("A");
ediVinList.add("C");
ediVinList.add("E");
ediVinList.add("F");
/*ediVinList.add("G");
ediVinList.add("H");
ediVinList.add("I");
ediVinList.add("J");*/
List<String> dbVinListClone = dbVinList;
List<String> ediVinListClone = ediVinList;
boolean flag;
String mismatchVins = null;
if(dbVinListClone.containsAll(ediVinListClone)){
flag = dbVinListClone.removeAll(ediVinListClone);
if(flag){
mismatchVins = getMismatchVins(dbVinListClone);
}
}else{
flag = ediVinListClone.removeAll(dbVinListClone);
if(flag){
mismatchVins = getMismatchVins(ediVinListClone);
}
}
if(mismatchVins != null){
System.out.println("mismatch vins : "+mismatchVins);
}
}
private static String getMismatchVins(List<String> mismatchList){
StringBuilder mismatchVins = new StringBuilder();
int i = 0;
for(String mismatch : mismatchList){
i++;
if(i < mismatchList.size() && i!=5){
mismatchVins.append(mismatch).append(",");
}else{
mismatchVins.append(mismatch);
}
if(i==5){
break;
}
}
String mismatch1;
if(mismatchVins.length() > 100){
mismatch1 = mismatchVins.substring(0, 99);
}else{
mismatch1 = mismatchVins.toString();
}
return mismatch1;
}
}
For my mac Big Sur, with gist from answers above, following steps work for me.
$ ssh-keygen -q -t rsa -N 'password' -f ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa
And added ssh public key to git hub by following instruction;
If all gone well, you should be able to get the following result;
$ ssh -T [email protected]
Hi user_name! You've successfully authenticated,...
It turns out you can do this, with the help of the built-in Zip File System provider. However, passing a resource URI directly to Paths.get
won't work; instead, one must first create a zip filesystem for the jar URI without the entry name, then refer to the entry in that filesystem:
static Path resourceToPath(URL resource)
throws IOException,
URISyntaxException {
Objects.requireNonNull(resource, "Resource URL cannot be null");
URI uri = resource.toURI();
String scheme = uri.getScheme();
if (scheme.equals("file")) {
return Paths.get(uri);
}
if (!scheme.equals("jar")) {
throw new IllegalArgumentException("Cannot convert to Path: " + uri);
}
String s = uri.toString();
int separator = s.indexOf("!/");
String entryName = s.substring(separator + 2);
URI fileURI = URI.create(s.substring(0, separator));
FileSystem fs = FileSystems.newFileSystem(fileURI,
Collections.<String, Object>emptyMap());
return fs.getPath(entryName);
}
Update:
It’s been rightly pointed out that the above code contains a resource leak, since the code opens a new FileSystem object but never closes it. The best approach is to pass a Consumer-like worker object, much like how Holger’s answer does it. Open the ZipFS FileSystem just long enough for the worker to do whatever it needs to do with the Path (as long as the worker doesn’t try to store the Path object for later use), then close the FileSystem.
I fixed it just by changing target compile version to 1.8. Its in:
File >> Settings >> Build, Execution, Deployment >> Compiler >> Java Compiler
"2020 Update? Url::forceScheme was acting funky for me, but this worked liked a dime."
https
code snippet.
resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');
app/providers/RouteServiceProvider.php
. /**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
resolve(\Illuminate\Routing\UrlGenerator::class)->forceScheme('https');
parent::boot();
}
php artisan route:clear && composer dumpautoload
to clear Laravel's cached routes and cached Service Providers.Install it using NuGet:
Install-Package Newtonsoft.Json
Posting this as an answer.
I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".
To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P
So maybe:
def super_cool_logic():
# execute common code here
@app.route("/foo")
def do_foo():
# do some logic here
super_cool_logic()
return render_template("foo.html")
@app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
super_cool_logic()
return render_template("foo.html", messages={"main":"Condition failed on page baz"})
I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)
Use IS NULL
or IS NOT NULL
in WHERE-clause instead of ISNULL() method:
SELECT myField1
FROM myTable1
WHERE myField1 IS NOT NULL
Obviously you can't parse N/A
to int
value. you can do something like following to handle that NumberFormatException
.
String str="N/A";
try {
int val=Integer.parseInt(str);
}catch (NumberFormatException e){
System.out.println("not a number");
}
You can use the following method
private function generateStringCondition($value = '',$field = '', $operator = '', $regex = '', $wildcardStart = '', $wildcardEnd = ''){
if($value != ''){
$where = " $field $regex '$wildcardStart".strtolower($value)."$wildcardEnd' ";
$searchArray = explode(' ', $value);
if(sizeof($searchArray) > 1){
foreach ($searchArray as $key=>$value){
$where .="$operator $field $regex '$wildcardStart".strtolower($value)."$wildcardEnd'";
}
}
}else{
$where = '';
}
return $where;
}
use this method like below
$where = $this->generateStringCondition($yourSearchString, 'LOWER(columnName)','or', 'like', '%', '%');
$sql = "select * from table $where";
You should follow 2 steps:
This step can be followed by running the cmd in the specific folder location where there will be .war
file. This step helpful as Jenkins needs some disk space to perform builds and keep archives.
set JENKINS_HOME=c:\folder\Jenkins
This step will be helpful to change the port number, and works can be performed accordingly.
java -jar jenkins.war --httpPort=8585
Douglas Crockford has some very good explanations of inheritance in JavaScript:
echo time_diff_string('2013-05-01 00:22:35', 'now');
echo time_diff_string('2013-05-01 00:22:35', 'now', true);
4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
function time_diff_string($from, $to, $full = false) {
$from = new DateTime($from);
$to = new DateTime($to);
$diff = $to->diff($from);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
You say it's not working. What are you expecting to happen?
There's no way of getting the data out of a FormData
object; it's just intended for you to use to send data along with an XMLHttpRequest
object (for the send
method).
Update almost five years later: In some newer browsers, this is no longer true and you can now see the data provided to FormData
in addition to just stuffing data into it. See the accepted answer for more info.
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
Wikipedia says:
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
In detail, when you have an object foo that has a void hello() function:
class foo {
virtual void hello(); // Code : printf("Hello!");
}
A child of foo, will also have a hello() function:
class bar : foo {
// no functions in here but yet, you can call
// bar.hello()
}
However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override
class bar : foo {
virtual void hello() override; // Code : printf("Hello Bar!");
}
From the Intel Instructions
"The SDK Manager will download the installer to the "extras" directory, under the main SDK directory. Even though the SDK manager says "Installed" it actually means that the Intel HAXM executable was downloaded. You will still need to run the installer from the "extras" directory to finish installation.
Extract the installer inside the "extras" directory and follow the installation instructions for your platform."
switch(KEYEVENT.getKeyCode()){
case KeyEvent.VK_ENTER:
// I was trying to use case 13 from the ascii table.
//Krewn Generated method stub...
break;
}
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
The following worked for me:
USE [master]
SET DEADLOCK_PRIORITY HIGH
exec sp_dboption '[StuckDB]', 'single user', 'FALSE';
ALTER DATABASE [StuckDB] SET MULTI_USER WITH NO_WAIT
ALTER DATABASE [StuckDB] SET MULTI_USER WITH ROLLBACK IMMEDIATE
Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.
The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.
Here's a start.. Open to suggestions/improvements.
Server
public class ChatHub : Hub
{
public void SendChatMessage(string who, string message)
{
string name = Context.User.Identity.Name;
Clients.Group(name).addChatMessage(name, message);
Clients.Group("[email protected]").addChatMessage(name, message);
}
public override Task OnConnected()
{
string name = Context.User.Identity.Name;
Groups.Add(Context.ConnectionId, name);
return base.OnConnected();
}
}
JavaScript
(Notice how addChatMessage
and sendChatMessage
are also methods in the server code above)
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.addChatMessage = function (who, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(who).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#chat').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
Testing
<TouchableHighlight>
element can have only one child inside Try this. Download the file 'numberbatch-en-17.06.txt' from https://conceptnet.s3.amazonaws.com/downloads/2017/numberbatch/numberbatch-en-17.06.txt.gz and extract it. The function 'get_sentence_vector' uses a simple sum of word vectors. However it can be improved by using weighted sum where weights are proportional to Tf-Idf of each word.
import math
import numpy as np
std_embeddings_index = {}
with open('path/to/numberbatch-en-17.06.txt') as f:
for line in f:
values = line.split(' ')
word = values[0]
embedding = np.asarray(values[1:], dtype='float32')
std_embeddings_index[word] = embedding
def cosineValue(v1,v2):
"compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
sumxx, sumxy, sumyy = 0, 0, 0
for i in range(len(v1)):
x = v1[i]; y = v2[i]
sumxx += x*x
sumyy += y*y
sumxy += x*y
return sumxy/math.sqrt(sumxx*sumyy)
def get_sentence_vector(sentence, std_embeddings_index = std_embeddings_index ):
sent_vector = 0
for word in sentence.lower().split():
if word not in std_embeddings_index :
word_vector = np.array(np.random.uniform(-1.0, 1.0, 300))
std_embeddings_index[word] = word_vector
else:
word_vector = std_embeddings_index[word]
sent_vector = sent_vector + word_vector
return sent_vector
def cosine_sim(sent1, sent2):
return cosineValue(get_sentence_vector(sent1), get_sentence_vector(sent2))
I did run for the given sentences and found the following results
s1 = "This is a foo bar sentence ."
s2 = "This sentence is similar to a foo bar sentence ."
s3 = "What is this string ? Totally not related to the other two lines ."
print cosine_sim(s1, s2) # Should give high cosine similarity
print cosine_sim(s1, s3) # Shouldn't give high cosine similarity value
print cosine_sim(s2, s3) # Shouldn't give high cosine similarity value
0.9851735249068168
0.6570885718962608
0.6589335425458225
getContentResolver()
is method of class android.content.Context
, so to call it you definitely need an instance
of Context ( Activity or Service for example).
In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.
def change change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13 change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13 end
I had this problem when missing a closing tag in the html.
So instead of:
<table></table>
..my HTML was
<table>...<table>
Tried to load jQuery after angular as mentioned above. This prevented the error message, but didn't really fix the problem. And jQuery '.find' didn't really work afterwards..
Solution was to fix the missing closing tag.
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
I found a way of resizing font size according to div size, without any JavaScript. I don't know how much efficient it's, but it nicely gets the job done.
Embed a SVG element inside the required div, and then use a foreignObject tag inside which you can use HTML elements. A sample code snippet that got my job done is given below.
<!-- The SVG element given below should be place inside required div tag -->
<svg viewBox='0 2 108.5 29' xmlns='http://www.w3.org/2000/svg'>
<!-- The below tag allows adding HTML elements inside SVG tag -->
<foreignObject x='5' y='0' width='93.5%' height='100%'>
<!-- The below tag can be styled using CSS classes or style attributes -->
<div xmlns='http://www.w3.org/1999/xhtml' style='text-overflow: ellipsis; overflow: hidden; white-space: nowrap;'>
Required text goes here
</div>
</foreignObject>
</svg>
All the viewBox, x, y, width and height values can be changed according to requirement.
Text can be defined inside the SVG element itself, but when the text overflows, ellipsis can't be added to SVG text. So, HTML element(s) are defined inside a foreignObject
element, and text-overflow styles are added to that/those element(s).
Use par(las=1)
.
See ?par
:
las
numeric in {0,1,2,3}; the style of axis labels.
0: always parallel to the axis [default],
1: always horizontal,
2: always perpendicular to the axis,
3: always vertical.
None of the solutions described above worked for me. However reinstalling the package
Microsoft.CodeDom.Providers.DotNetCompilerPlatform
using nuget gui is a (not too nice) walkaround
Gulp 4.0 has changed the way that tasks should be defined if the task depends on another task to execute. The list parameter has been deprecated.
An example from your gulpfile.js would be:
// Starts a BrowerSync instance
gulp.task('server', ['build'], function(){
browser.init({server: './_site', port: port});
});
Instead of the list parameter they have introduced gulp.series()
and gulp.parallel()
.
This task should be changed to something like this:
// Starts a BrowerSync instance
gulp.task('server', gulp.series('build', function(){
browser.init({server: './_site', port: port});
}));
I'm not an expert in this. You can see a more robust example in the gulp documentation for running tasks in series or these following excellent blog posts by Jhey Thompkins and Stefan Baumgartner
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
Bit heavy because of using pandas but works:
import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()
try this:
.button input, .button a {
//css here
}
That will apply the style to all a tags nested inside of <p class="button"></p>
Set the colspan
attribute to 2.
ClusterIP: Services are reachable by pods/services in the Cluster
If I make a service called myservice in the default namespace of type: ClusterIP then the following predictable static DNS address for the service will be created:
myservice.default.svc.cluster.local (or just myservice.default, or by pods in the default namespace just "myservice" will work)
And that DNS name can only be resolved by pods and services inside the cluster.
NodePort: Services are reachable by clients on the same LAN/clients who can ping the K8s Host Nodes (and pods/services in the cluster) (Note for security your k8s host nodes should be on a private subnet, thus clients on the internet won't be able to reach this service)
If I make a service called mynodeportservice in the mynamespace namespace of type: NodePort on a 3 Node Kubernetes Cluster. Then a Service of type: ClusterIP will be created and it'll be reachable by clients inside the cluster at the following predictable static DNS address:
mynodeportservice.mynamespace.svc.cluster.local (or just mynodeportservice.mynamespace)
For each port that mynodeportservice listens on a nodeport in the range of 30000 - 32767 will be randomly chosen. So that External clients that are outside the cluster can hit that ClusterIP service that exists inside the cluster.
Lets say that our 3 K8s host nodes have IPs 10.10.10.1, 10.10.10.2, 10.10.10.3, the Kubernetes service is listening on port 80, and the Nodeport picked at random was 31852.
A client that exists outside of the cluster could visit 10.10.10.1:31852, 10.10.10.2:31852, or 10.10.10.3:31852 (as NodePort is listened for by every Kubernetes Host Node) Kubeproxy will forward the request to mynodeportservice's port 80.
LoadBalancer: Services are reachable by everyone connected to the internet* (Common architecture is L4 LB is publicly accessible on the internet by putting it in a DMZ or giving it both a private and public IP and k8s host nodes are on a private subnet)
(Note: This is the only service type that doesn't work in 100% of Kubernetes implementations, like bare metal Kubernetes, it works when Kubernetes has cloud provider integrations.)
If you make mylbservice, then a L4 LB VM will be spawned (a cluster IP service, and a NodePort Service will be implicitly spawned as well). This time our NodePort is 30222. the idea is that the L4 LB will have a public IP of 1.2.3.4 and it will load balance and forward traffic to the 3 K8s host nodes that have private IP addresses. (10.10.10.1:30222, 10.10.10.2:30222, 10.10.10.3:30222) and then Kube Proxy will forward it to the service of type ClusterIP that exists inside the cluster.
You also asked:
Does the NodePort service type still use the ClusterIP? Yes*
Or is the NodeIP actually the IP found when you run kubectl get nodes? Also Yes*
Lets draw a parrallel between Fundamentals:
A container is inside a pod. a pod is inside a replicaset. a replicaset is inside a deployment.
Well similarly:
A ClusterIP Service is part of a NodePort Service. A NodePort Service is Part of a Load Balancer Service.
In that diagram you showed, the Client would be a pod inside the cluster.
To go up a directory in a link, use ..
. This means "go up one directory", so your link will look something like this:
<a href="../index.html">Home</a>
Try this
format: 'DD/MM/YYYY hh:mm A'
As we all know JS is case-sensitive. So this will display
10/05/2016 12:00 AM
In your case is
format: 'DD/MM/YYYY'
Display : 10/05/2016
My bootstrap datetimepicker is based on eonasdan bootstrap-datetimepicker
process.cwd()
returns the current working directory,
i.e. the directory from which you invoked the node
command.
__dirname
returns the directory name of the directory containing the JavaScript source code file
WebDriverWait wait = new WebDriverWait(driver,5)
wait.until(ExpectedConditions.visibilityOf(element));
you can use this as some time before loading whole page code gets executed and throws and error. time is in second
Here's some status code, which you should know for your kind of knowledge.
- 100 Continue
- 101 Switching Protocols
- 102 Processing
- 103 Early Hints
- 200 OK
- 201 Created
- 202 Accepted
- 203 Non-Authoritative Information
- 204 No Content
- 205 Reset Content
- 206 Partial Content
- 207 Multi-Status
- 208 Already Reported
- 226 IM Used
- 300 Multiple Choices
- 301 Moved Permanently
- 302 Found
- 303 See Other
- 304 Not Modified
- 305 Use Proxy
- 306 Switch Proxy
- 307 Temporary Redirect
- 308 Permanent Redirect
- 400 Bad Request
- 401 Unauthorized
- 402 Payment Required
- 403 Forbidden
- 404 Not Found
- 405 Method Not Allowed
- 406 Not Acceptable
- 407 Proxy Authentication Required
- 408 Request Timeout
- 409 Conflict
- 410 Gone
- 411 Length Required
- 412 Precondition Failed
- 413 Payload Too Large
- 414 URI Too Long
- 415 Unsupported Media Type
- 416 Range Not Satisfiable
- 417 Expectation Failed
- 418 I'm a teapot
- 420 Method Failure
- 421 Misdirected Request
- 422 Unprocessable Entity
- 423 Locked
- 424 Failed Dependency
- 426 Upgrade Required
- 428 Precondition Required
- 429 Too Many Requests
- 431 Request Header Fields Too Large
- 451 Unavailable For Legal Reasons
- 500 Internal Server error
- 501 Not Implemented
- 502 Bad Gateway
- 503 Service Unavailable
- 504 gateway Timeout
- 505 Http version not supported
- 506 Varient Also negotiate
- 507 Insufficient Storage
- 508 Loop Detected
- 510 Not Extended
- 511 Network Authentication Required
This is due to spring-config.xml is not in classpath.
Add complete path of spring-config.xml to your classpath.
Also write command you execute to run your project. You can check classpath in command.
For everyone with the problem
Error: Command '['/Users/me/Sites/site/venv3/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1.
You have to install python3.6-venv
sudo apt-get install python3.6-venv
This method is easy and powerful.
Value is a date and "DD-MM-YYYY" is the mask of the date.
moment().diff(moment(value, "DD-MM-YYYY"), 'years');
I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.
#include "cv.h"
#include "highgui.h"
#include <iostream>
int main(int, char**) {
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp";
/* it may be an address of an mjpeg stream,
e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
//Create output window for displaying frames.
//It's important to create this window outside of the `for` loop
//Otherwise this window will be created automatically each time you call
//`imshow(...)`, which is very inefficient.
cv::namedWindow("Output Window");
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:
// H.264 stream RTSP address, where 10.10.10.10 is an IP address
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp
// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp
You could use an OrderedDictionary, but I would question why you would want to do that.
I made a CSS approach to this that is sized by the viewport width, but maxes out at 100% of the viewport height. It doesn't require box-sizing:border-box
. If a pseudo element cannot be used, the pseudo-code's CSS can be applied to a child. Demo
.container {
position: relative;
max-width:100vh;
max-height:100%;
margin:0 auto;
overflow: hidden;
}
.container:before {
content: "";
display: block;
margin-top: 100%;
}
.child {
position: absolute;
top: 0;
left: 0;
}
Support table for viewport units
I wrote about this approach and others in a CSS-Tricks article on scaling responsive animations that you should check out.
If you want to remove all instances of 4 without needing to know the index:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();
Non-LINQ: (.NET Framework 2.0)
static bool isNotFour(int n)
{
return n != 4;
}
int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour).ToArray();
If you want to remove just the first instance:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
Non-LINQ: (.NET Framework 2.0)
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();
Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.
A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code
Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.
The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.
The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.
One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.
1. In my opinion, the most convenient way is to search for one
occurrence first, and then invoke the following :substitute
command:
:%s///gc
Since the pattern is empty, this :substitute
command will look for
the occurrences of the last-used search pattern, and will then replace
them with the empty string, each time asking for user confirmation,
realizing exactly the desired behavior.
2. If it is a common pattern in one’s editing habits, one can further define a couple of text-object selection mappings to operate specifically on the match of the last search pattern under the cursor. The following two mappings can be used in both Visual and Operator-pending modes to select the text of the preceding match of the last search pattern.
vnoremap <silent> i/ :<c-u>call SelectMatch()<cr>
onoremap <silent> i/ :call SelectMatch()<cr>
function! SelectMatch()
if search(@/, 'bcW')
norm! v
call search(@/, 'ceW')
else
norm! gv
endif
endfunction
Using these mappings one can delete the match under the cursor with
di/
, or apply any other operator or visually select it with vi/
.
I'm adding another answer to this as I had the same problem and solved it the same way:
I had installed SSL on apache2 using a2enmod ssl
, which seems to have added an extra configuration in /etc/apache2/ports.conf
:
NameVirtualHost *:80
Listen 80
NameVirtualHost *:443
Listen 443
<IfModule mod_ssl.c>
Listen 443
</IfModule>
<IfModule mod_gnutls.c>
Listen 443
</IfModule>
I had to comment out the first Listen 443
after the NameVirtualHost *:443
directive:
NameVirtualHost *:443
#Listen 443
But I'm thinking I can as well let it and comment the others. Anyway, thank you for the solution :)
This behavior is documented in the java.util.Date -class documentation:
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
It is also marked as deprecated. Use java.util.Calendar instead.
Put this line in your Activity
in the Manifest
:
<activity android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
...
</activity>
and make sure you didn't put Toolbar
in your layout
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
/>
This seems to work well for me. Tested on Touchwiz 5.1, LineageOS 7.1, and CyanogenMod 11.
ip route list match 0 table all scope global
Gives output similar to this:
default via 192.168.1.1 dev wlan0 table wlan0 proto static
You have to add extra parameter -g, which generates source level debug information. It will look like:
gcc -g prog.c
After that you can use gdb in common way.
I know I'm late to the party, but now there's a quick answer to this:
git fetch --prune --prune-tags # or just git fetch -p -P
Yes, it's now an option to fetch.
If you don't want to fetch, and just prune:
git remote prune origin
You can use find
with the -prune
option.
An example from man find
:
cd /source-dir find . -name .snapshot -prune -o \( \! -name *~ -print0 \)| cpio -pmd0 /dest-dir This command copies the contents of /source-dir to /dest-dir, but omits files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in ~, but not their con- tents. The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on.
Using pgadmin4 :
Now there you can enable or disable login, roles and other options
Here's a video and explaination how to use Instruments and NSZombie to find and fix memory crashes on iOS: http://www.markj.net/iphone-memory-debug-nszombie/
I had the same problem, this is the solution i came up with, which is much easier!
Make a little 1px x 1px transparent image and save it as a .png file.
In the CSS for your DIV, use this code:
background:transparent url('/images/trans-bg.png') repeat center top;
Remember to change the file path to your transparent image.
I think this solution works in all browsers, maybe except for IE 6, but I haven't tested.
Correction to top query above, to allow to run from any database
SELECT COUNT(COLUMN_NAME) FROM [*database*].INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'
I have mysql data folder replaced by a windows directory junction. I suspect ib_logfile0/1 and/or ibdata1 is corrupted.
Just try to delete those files and computername.err. Then restart mysql service. That's what I did, with success.
Copying ibdata1 files, after a full reinstallation of mysql, to the junction dir and replacing dir by the junction, restarting mysql, was not enough.
You have to let mysql rebuild those files.
Try this using list comprehension:
import pandas as pd
df = pd.DataFrame(
[p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)
I know, its old a post to answer but like I came across searching for the same post, someone else might turn here as well
By adding : colour in ggplot function , I could achieve the lines with different colors related to the group present in the plot.
ggplot(data=Set6, aes(x=Semana, y=Net_Sales_in_pesos, group = Agencia_ID, colour = as.factor(Agencia_ID)))
and
geom_line()
For broken consoles like cmd.exe
and HTML output you can always use:
my_unicode_string.encode('ascii','xmlcharrefreplace')
This will preserve all the non-ascii chars while making them printable in pure ASCII and in HTML.
WARNING: If you use this in production code to avoid errors then most likely there is something wrong in your code. The only valid use case for this is printing to a non-unicode console or easy conversion to HTML entities in an HTML context.
And finally, if you are on windows and use cmd.exe then you can type chcp 65001
to enable utf-8 output (works with Lucida Console font). You might need to add myUnicodeString.encode('utf8')
.
I have found this parameter -u with read.
"-u 1" means "read from stdin"
while read -r newline; do
((i++))
read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)
You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:
http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA
You need to configure the war plugin:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warName>bird.war</warName>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
More info here
This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.
Func<DateTime> RandomDayFunc()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
return () => start.AddDays(gen.Next(range));
}
The short answer is "you can't". What you'll need to do is either use a subquery or you could convert your existing stored procedure in to a table function. Creating it as function would depend on how "reusable" you would need it to be.
You can make a link perform an Ajax post request when it's clicked.
In jQuery:
$('a').click(function(e) {
var $this = $(this);
e.preventDefault();
$.post('url', {'user': 'something', 'foo': 'bar'}, function() {
window.location = $this.attr('href');
});
});
You could also make the link submit a POST form with JavaScript:
<form action="url" method="post">
<input type="hidden" name="user" value="something" />
<a href="#">CLick</a>
</form>
<script>
$('a').click(function(e) {
e.preventDefault();
$(this).parents('form').submit();
});
</script>
I threw CMS's excellent answer into a quick jQuery extension:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
};
})(jQuery, window);
It expects an array of objects which contain "text" and "value" keys. So usage is as follows:
var options = [
{text: "one", value: 1},
{text: "two", value: 2}
];
$("#foo").replaceOptions(options);
It looks like this question has been answered all ready, but I'll post my input anyway.
I know when I like to use self-executing functions.
var myObject = {
childObject: new function(){
// bunch of code
},
objVar1: <value>,
objVar2: <value>
}
The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...
object: {
childObject: {
childObject: {<value>, <value>, <value>}
},
objVar1: <value>,
objVar2: <value>
}
Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.
Have you tried?
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Example Link: Webview File Download - Thanks @c49
http://msdn.microsoft.com/en-us/library/wkze6zky.aspx
menu: Project-->Add Reference
click: assemblies, framework
Put a checkmark on Microsoft.VisualBasic.
Hit OK.
That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.
In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".
At the top of your c# file you neeed:
using Microsoft.VisualBasic;
Then you can look at writing the code.
The code would be something like:
private void btnOK_Click(object sender, EventArgs e)
{
if ( Information.IsNumeric(startingbudget) )
{
MessageBox.Show("This is a number.");
}
}
Bash 4 has a coproc
command which establishes a named pipe to a command and allows you to communicate through it.
If you want each task to run regardless of any failures, you can do something like:
task :build_all do
[:debug, :release].each do |t|
ts = 0
begin
Rake::Task["build"].invoke(t)
rescue
ts = 1
next
ensure
Rake::Task["build"].reenable # If you need to reenable
end
return ts # Return exit code 1 if any failed, 0 if all success
end
end
diff -r
will do this, telling you both if any files have been added or deleted, and what's changed in the files that have been modified.
There is nice like() method in JPA criteria API. Try to use that, hope it will help.
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery criteriaQuery = cb.createQuery(Employees.class);
Root<Employees> rootOfQuery = criteriaQuery.from(Employees.class);
criteriaQuery.select(rootOfQuery).where(cb.like(rootOfQuery.get("firstName"), "H%"));
Based on the solution of the Jordan, I created a function that automatically creates a hidden input with the same name and same value of the select you want to become invalid. The first parameter can be an id or a jquery element; the second is a Boolean optional parameter where "true" disables and "false" enables the input. If omitted, the second parameter switches the select between "enabled" and "disabled".
function changeSelectUserManipulation(obj, disable){
var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
disable = disable? !!disable : !$obj.is(':disabled');
if(disable){
$obj.prop('disabled', true)
.after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
}else{
$obj.prop('disabled', false)
.next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
}
}
changeSelectUserManipulation("select_id");
Assuming you also can't use s.union(t)
, which is equivalent to s | t
, you could try
>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])
Or, if you want a comprehension,
>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])
MongoDB needs a folder to store the database. Create a C:\data\db\
directory:
mkdir C:\data\db
and then start MongoDB:
C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe
Sometimes C:\data\db
folder already exists due to previous installation. So if for this reason mongod.exe
does not work, you may delete all the contents from C:\data\db
folder and execute mongod.exe
again.
Note: This answer isn't valid for iOS 11 and later.
I prefer
[mainTableView setContentOffset:CGPointZero animated:YES];
If you have a top inset on your table view, you have to subtract it:
[mainTableView setContentOffset:CGPointMake(0.0f, -mainTableView.contentInset.top) animated:YES];
Here is a small snippet to demonstrate the date modifications:
$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";
There is no standard library function to do this, but it's not too hard to roll your own. There is an existing question on SO about doing this that was answered with source code.
Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.
After importing PDFKit, you should initialize a PDFView
with a local or a remote URL and display it in your view.
if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
let pdfView = PDFView(frame: view.frame)
pdfView.document = PDFDocument(url: url)
view.addSubview(pdfView)
}
Read more about PDFKit in the Apple Developer documentation.
If you want to install/upgrade all packages to the latest version and you are running windows you can use this in powershell.exe
:
foreach($package in @("animations","common","compiler","core","forms","http","platform-browser","platform-browser-dynamic","router")) {
npm install @angular/$package@latest -E
}
If you also use the cli
, you can do this:
foreach($package in @('animations','common','compiler','core','forms','http','platform-browser','platform-browser-dynamic','router', 'cli','compiler-cli')){
iex "npm install @angular/$package@latest -E $(If($('cli','compiler-cli').Contains($package)){'-D'})";
}
This will save the packages exact (-E), and the cli packages in devDependencies
(-D)
Any definition is valid. As long as you are consistent in your implementation (always put equal nodes to the right, always put them to the left, or never allow them) then you're fine. I think it is most common to not allow them, but it is still a BST if they are allowed and place either left or right.
Sorry for the late response, I recently had the same problem with PHP and found out that when working with arrays that do not use $key => $value
structure, when using the foreach
loop you actual copy the value of the position on the loop variable, in this case $image
. Try using this code and it will fix your problem.
for ($i=0; $i < count($images[1]); $i++)
{
if($images[1][$i] == 'http://i27.tinypic.com/29yk345.gif' ||
$images[1][$i] == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
$images[1][$i] == 'http://i42.tinypic.com/9pp2456x.gif')
{
unset($images[1][$i]);
}
}
var_dump($images);die();
The answer for Ashwini is great, in pointing out that scipy.math.factorial
, numpy.math.factorial
, math.factorial
are the same functions. However, I'd recommend use the one that Janne mentioned, that scipy.special.factorial
is different. The one from scipy can take np.ndarray
as an input, while the others can't.
In [12]: import scipy.special
In [13]: temp = np.arange(10) # temp is an np.ndarray
In [14]: math.factorial(temp) # This won't work
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-039ec0734458> in <module>()
----> 1 math.factorial(temp)
TypeError: only length-1 arrays can be converted to Python scalars
In [15]: scipy.special.factorial(temp) # This works!
Out[15]:
array([ 1.00000000e+00, 1.00000000e+00, 2.00000000e+00,
6.00000000e+00, 2.40000000e+01, 1.20000000e+02,
7.20000000e+02, 5.04000000e+03, 4.03200000e+04,
3.62880000e+05])
So, if you are doing factorial to a np.ndarray, the one from scipy will be easier to code and faster than doing the for-loops.
You can create bitmap with captured image as below:
Bitmap bitmap = Bitmap.createScaledBitmap(capturedImage, width, height, true);
Here you can specify width and height of the bitmap that you want to set to your ImageView. The height and width you can set according to the screen dpi of the device also, by reading the screen dpi of different devices programmatically.