(I tried previous answers but they lacks in some points. For example if you don't do a return;
after finishing activity, remaining activity code runs. Also you need to edit onCreate with return. If you doesn't run super.onCreate() you will get a runtime error)
Say you have MainActivity
and ChildActivity
.
Inside ChildActivity add this:
Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
return true;
Inside MainActivity's onCreate add this:
@Override
public void onCreate(Bundle savedInstanceState) {
mContext = getApplicationContext();
super.onCreate(savedInstanceState);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
// your current codes
// your current codes
}
That worked for me in Swift 5 like a charm, just add it to your viewDidLoad()
self.navigationItem.setHidesBackButton(true, animated: true)
I would suggest something like this, where str
is your input string:
StringBuffer hex = new StringBuffer();
char[] raw = tokens[0].toCharArray();
for (int i=0;i<raw.length;i++) {
if (raw[i]<=0x000F) { hex.append("000"); }
else if(raw[i]<=0x00FF) { hex.append("00" ); }
else if(raw[i]<=0x0FFF) { hex.append("0" ); }
hex.append(Integer.toHexString(raw[i]).toUpperCase());
}
As specified in oracle official tutorial , it states that:
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
If I have an Application interacting with database using JDBC
, And I have a method that takes the argument as the int item
and double price
. The price
for corresponding item is read from database table. I simply multiply the total number of item
purchased with the price
value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG
in your database. So , and IllegalArguementException()
should be thrown in this case which would state that the price can't be negative
.
I hope that I have expressed my point clearly..
Put it in double quotes:
echo "\t";
Single quotes do not expand escaped characters.
Use the documentation when in doubt.
get the latest version information from:
https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin
click on the latest version (or the one you'd like to use) and you'll see the the dependency info (as of 2019-05 it's 3.8.1):
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
you might want to use the version tag and the comment for your plugin tag.
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source />
<target />
</configuration>
</plugin>
if you like you can modify your pom to have the version information in the properties tag as outlined in another answer.
Below code will fix root = tk.Tk()
to its size before it was called:
root.resizable(False, False)
Extended Kon's code to help debug a stored procedure:
private void ExtractSqlCommandForDebugging(SqlCommand cmd)
{
string sql = "exec " + cmd.CommandText;
bool first = true;
foreach (SqlParameter p in cmd.Parameters)
{
string value = ((p.Value == DBNull.Value) ? "null"
: (p.Value is string) ? "'" + p.Value + "'"
: p.Value.ToString());
if (first)
{
sql += string.Format(" {0}={1}", p.ParameterName, value);
first = false;
}
else
{
sql += string.Format("\n , {0}={1}", p.ParameterName, value);
}
}
sql += "\nGO";
Debug.WriteLine(sql);
}
In my first test case, it generated:
exec dbo.MyStoredProcName @SnailMail=False
, @Email=True
, @AcceptSnailMail=False
, @AcceptEmail=False
, @DistanceMiles=-1
, @DistanceLocationList=''
, @ExcludeDissatisfied=True
, @ExcludeCodeRed=True
, @MinAge=null
, @MaxAge=18
, @GenderTypeID=-1
, @NewThisYear=-1
, @RegisteredThisYear=-1
, @FormersTermGroupList=''
, @RegistrationStartDate=null
, @RegistrationEndDate=null
, @DivisionList='25'
, @LocationList='29,30'
, @OneOnOneOPL=-1
, @JumpStart=-1
, @SmallGroup=-1
, @PurchasedEAP=-1
, @RedeemedEAP=-1
, @ReturnPlanYes=False
, @MinNetPromoter=-1
, @MinSurveyScore=-1
, @VIPExclusionTypes='-2'
, @FieldSelectionMask=65011584
, @DisplayType=0
GO
You will probably need to add some more conditional "..is..." type assignments, e.g. for dates and times.
from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import re
import ssl
def tag_visible(element):
if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, Comment):
return False
if re.match(r"[\n]+",str(element)): return False
return True
def text_from_html(url):
body = urllib.request.urlopen(url,context=ssl._create_unverified_context()).read()
soup = BeautifulSoup(body ,"lxml")
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
text = u",".join(t.strip() for t in visible_texts)
text = text.lstrip().rstrip()
text = text.split(',')
clean_text = ''
for sen in text:
if sen:
sen = sen.rstrip().lstrip()
clean_text += sen+','
return clean_text
url = 'http://www.nytimes.com/2009/12/21/us/21storm.html'
print(text_from_html(url))
Instead of SELECT max(len(CR)) AS Max_Length_String FROM table1
Use
SELECT (CR) FROM table1
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)
You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.
The Basic Auth / Session ID can be stolen via:
By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.
The new (more secure) flow would be:
Updated 30.07.15:
JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).
I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).
Updated 17.07.16:
JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.
In my case, during a lazy-loading conversion of my application I had incorrectly imported the RoutingModule
instead of my ComponentModule
inside app-routing.module.ts
How about a solution where you put the actual "data" of the table inside its own div, with overflow: scroll;
? Then the browser will automatically create scrollbars for the portion of the "table" you do not want to lock, and you can put the "table header"/first row just above that <div>
.
Not sure how that would work with scrolling horizontally though.
Check out Project Silk. Not only does it demonstrate DDD but other cutting edge patterns. This is an excellent resource for any Web Developer. A full overview of the project can be found on MSDN.
Traditionally PHP has been tolerant to bad practice and failures in code,
which makes debugging quite hard.
The problem in this specific case is that both mysqli and PDO
by default don't tell you, when a query failed and just return FALSE
.
(I will not talk about the depricated mysql extention.
The support for prepared statements is reason anough to switch either to PDO or mysqli.)
But you can change the default behavior of PHP to always throw exceptions when a query fails.
For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->query('select emal from users');
$data = $result->fetchAll();
This will show you the following:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8
As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.
Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
you will get
Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9
For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');
$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();
You will get
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
you only get
Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10
Of course, you could manually check the MySQL errors. But I would go crazy if I had to do that every time I made a typo - or worse - every time I want to query the database.
Refactoring of @srini-beerge's answer which gets the output and the return code
import subprocess
def run_win_cmd(cmd):
result = []
process = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for line in process.stdout:
result.append(line)
errcode = process.returncode
for line in result:
print(line)
if errcode is not None:
raise Exception('cmd %s failed, see above for details', cmd)
tableB.col1 = tableA.col1
OR tableB.col2 = tableA.col1
OR tableB.col1 = tableA.col2
OR tableB.col1 = tableA.col2
This can be caused by multiple scenarios like
imports: [
BrowserModule
,routing <= Missing Comma
,FeatureComponentsModule
],
imports: [
BrowserModule,
,routing <=Double Comma
,FeatureComponentsModule
],
I suggest to use
for string only state values
export default class Home extends React.Component<{}, { [key: string]: string }> { }
for string key and any type of state values
export default class Home extends React.Component<{}, { [key: string]: any}> { }
for any key / any values
export default class Home extends React.Component<{}, { [key: any]: any}> {}
Had similar problem. Added in build.gradle and it worked for me.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}"
on the html input.
The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.
You need to add the URL to your app:
That's all and you are done. Make sure that the app's URL is the same from where you're logging in.
To catch all the event surrounding model changes, can consider using
<input (ngModelChange)="inputFilter($event)"/>
It will detect copy / paste, keyup, any condition that changes the value of the model.
And then:
inputFilter(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}
UPDATE 2020 JULY
Preview version of chromium based WebView 2 is released by the Microsoft. Now you can embed new Chromium Edge browser into a .NET application.
UPDATE 2018 MAY
If you're targeting application to run on Windows 10, then now you can embed Edge browser into your .NET application by using Windows Community Toolkit.
WPF Example:
Install Windows Community Toolkit Nuget Package
Install-Package Microsoft.Toolkit.Win32.UI.Controls
XAML Code
<Window
x:Class="WebViewTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WPF="clr-namespace:Microsoft.Toolkit.Win32.UI.Controls.WPF;assembly=Microsoft.Toolkit.Win32.UI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WebViewTest"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<WPF:WebView x:Name="wvc" />
</Grid>
</Window>
CS Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// You can also use the Source property here or in the WPF designer
wvc.Navigate(new Uri("https://www.microsoft.com"));
}
}
WinForms Example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// You can also use the Source property here or in the designer
webView1.Navigate(new Uri("https://www.microsoft.com"));
}
}
Please refer to this link for more information.
IMHO there is not a better explanation than the fact about How was the first compiler written?
These days the Operating System loading is the most common process referred as Bootstrapping
You maybe wanted to do the following:
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
I found some detailed instructions here: http://digitallibraryworld.com/?p=6
The key piece of advice seems to be, don't use the 64-bit ASP.DLL (found in system32) if you've configured the app pool to run 32-bit applications (instead, use the 32-bit ASP.DLL).
Add a script map using the following setting:
Request Path: *.asp
Executable: C:\Windows\system32\inetsrv\asp.dll
Name: whatever you want. I named my Classic ASPThe executable above is 64 BIT ASP handler for your asp script. If you want your ASP script to be handled in 32 bit environment, you need to use executable from this location:
C:\Windows\SysWOW64\inetsrv\asp.dll
.
Of course, if you don't need to load any 32-bit libraries (or data providers, etc.), just make your life easier by running the 64-bit ASP.DLL!
Check here:
NEW Version of MYSQL does it this way.
In the new my-sql if the password is left empty while installing then it is based on the auth_socket
plugin.
The correct way is to login to my-sql with sudo
privilege.
$ sudo mysql -u root -p
And then updating the password using:
$ ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new-password';
Once this is done stop and start
the mysql server.
$ sudo service mysql stop
$ sudo service mysql start
For complete details you can refer to this link.
Do comment for any doubt.
I could not access the context object directly.
My solution is as following:
Context appContext = Android.App.Application.Context;
var wifiManager = (WifiManager)appContext.GetSystemService(WifiService);
wifiManager.SetWifiEnabled(state);
Also I had to change some writings eg. WIFI_SERVICE vs. WifiService.
From 1700 to 1917, official calendar was the Julian calendar. Since then they we use the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that 32nd day in 1918, was the February 14th.
In both calendar systems, February is the only month with a variable amount of days, it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 while in the Gregorian calendar, leap years are either of the following:
Divisible by 400.
Divisible by 4 and not divisible by 100.
So the program for leap year will be:
def leap_notleap(year):
yr = ''
if year <= 1917:
if year % 4 == 0:
yr = 'leap'
else:
yr = 'not leap'
elif year >= 1919:
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
yr = 'leap'
else:
yr = 'not leap'
else:
yr = 'none actually, since feb had only 14 days'
return yr
The previous posts information is correct, but it does not have details on how to link containers, which should be connected as "external_links".
Hope this example make more clear to you:
Suppose you have app1/docker-compose.yml, with two services (svc11 and svc12), and app2/docker-compose.yml with two more services (svc21 and svc22) and suppose you need to connect in a crossed fashion:
svc11 needs to connect to svc22's container
So the configuration should be like this:
this is app1/docker-compose.yml:
version: '2'
services:
svc11:
container_name: container11
[..]
networks:
- default # this network
- app2_default # external network
external_links:
- container22:container22
[..]
svc12:
container_name: container12
[..]
networks:
default: # this network (app1)
driver: bridge
app2_default: # external network (app2)
external: true
this is app2/docker-compose.yml:
version: '2'
services:
svc21:
container_name: container21
[..]
networks:
- default # this network (app2)
- app1_default # external network (app1)
external_links:
- container11:container11
[..]
svc22:
container_name: container22
[..]
networks:
default: # this network (app2)
driver: bridge
app1_default: # external network (app1)
external: true
Use this:
DateTime dateTime = DateTime.Now;
DateTime? newDateTime = null;
TimeSpan numberOfDays = new TimeSpan(2, 0, 0, 0, 0);
newDateTime = dateTime.Add(numberOfDays);
Guys let's understand the syntax of it.
If class file is present in the Current Dir.
java -cp . fileName
If class file is present within the Dir. Go to the Parent Dir and enter below cmd.
java -cp . dir1.dir2.dir3.fileName
If there is a dependency on external jars then,
java -cp .:./jarName1:./jarName2 fileName
Hope this helps.
You can add a Dictionary
extension like this:
extension Dictionary {
func mergedWith(otherDictionary: [Key: Value]) -> [Key: Value] {
var mergedDict: [Key: Value] = [:]
[self, otherDictionary].forEach { dict in
for (key, value) in dict {
mergedDict[key] = value
}
}
return mergedDict
}
}
Then usage is as simple as the following:
var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]
var combinedDict = dict1.mergedWith(dict2)
// => ["a": "foo", "b": "bar"]
If you prefer a framework that also includes some more handy features then checkout HandySwift. Just import it to your project and you can use the above code without adding any extensions to the project yourself.
I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-
export k=$(date "+%k");
if [ $k -ge 16 ]
then exit 0;
else
echo "good job for nothing";
fi;
that way I resolved my problem. Hope that will help for you too.
From http://api.jquery.com/jQuery/
Selector Context By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:
$( "div.foo" ).click(function() {
$( "span", this ).addClass( "bar" );
});
When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.
So for your example I would suggest something like:
$("div", ".container").each(function(){
//do whatever
});
svn log --verbose -r 42
I figure it ought to be as simple as this:
url.split("/")[2]
Another possibility is:
create or replace FUNCTION getNth (
input varchar2,
nth number
) RETURN varchar2 AS
nthVal varchar2(80);
BEGIN
with candidates (s,e,n) as (
select 1, instr(input,',',1), 1 from dual
union all
select e+1, instr(input,',',e+1), n+1
from candidates where e > 0)
select substr(input,s,case when e > 0 then e-s else length(input) end)
into nthVal
from candidates where n=nth;
return nthVal;
END getNth;
It's a little too expensive to run, as it computes the complete split every time the caller asks for one of the items in there...
Here is how you get the execution path of the application:
var path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
MSDN has a full reference on how to determine the Executing Application's Path.
Note that the value in path
will be in the form of file:\c:\path\to\bin\folder
, so before using the path you may need to strip the file:\
off the front. E.g.:
path = path.Substring(6);
In order to navigate to a different drive just use
cd /E/Study/Codes
It will solve your problem.
Put the IPtables configuration in the traditional file and it will be loaded after boot:
/etc/sysconfig/iptables
Use sprintf library
Here you have a link where you can find the features of this library.
Mobile number Validation using Java Script, This link will provide demo and more information.
function isNumber(evt) {_x000D_
evt = (evt) ? evt : window.event;_x000D_
var charCode = (evt.which) ? evt.which : evt.keyCode;_x000D_
if (charCode > 31 && (charCode < 48 || charCode > 57)) {_x000D_
alert("Please enter only Numbers.");_x000D_
return false;_x000D_
}_x000D_
_x000D_
return true;_x000D_
}_x000D_
_x000D_
function ValidateNo() {_x000D_
var phoneNo = document.getElementById('txtPhoneNo');_x000D_
_x000D_
if (phoneNo.value == "" || phoneNo.value == null) {_x000D_
alert("Please enter your Mobile No.");_x000D_
return false;_x000D_
}_x000D_
if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {_x000D_
alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");_x000D_
return false;_x000D_
}_x000D_
_x000D_
alert("Success ");_x000D_
return true;_x000D_
}
_x000D_
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />_x000D_
<input type="button" value="Submit" onclick="ValidateNo();">
_x000D_
--user
installs in site.USER_SITE
.
For my case, it was /Users/.../Library/Python/2.7/bin
. So I have added that to my PATH (in ~/.bash_profile
file):
export PATH=$PATH:/Users/.../Library/Python/2.7/bin
webpack
is not only in your node-modules/webpack/bin/
directory, it's also linked in node_modules/.bin
.
You have the npm bin
command to get the folder where npm will install executables.
You can use the scripts
property of your package.json
to use webpack from this directory which will be exported.
"scripts": {
"scriptName": "webpack --config etc..."
}
For example:
"scripts": {
"build": "webpack --config webpack.config.js"
}
You can then run it with:
npm run build
Or even with arguments:
npm run build -- <args>
This allow you to have you webpack.config.js
in the root folder of your project without having webpack globally installed or having your webpack configuration in the node_modules
folder.
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
That has an obvious solution. I had the same problem later. Not related to Assembly References or ... .It'll occur In hierarchy calling of MVC Partial views, when you have complicated page structures. So calling/rendering each part separately on each page (maybe a master page or partial) will cause to not see required parts of page like the bellow code :
@RenderSection("Scripts", required: false)
That simply forces page to find and render related section and in case of failure shows you an error message like you.
So I suggest you to trace your pages (like program trace) from master to all of its partials to Detect Dependencies. Maybe it be a terrible work, but no other choices available here.
Not that according to my experience, some conditional situations in programming causes not to show you the right error causes the problem.
try adding android:scaleType="fitXY"
to your ImageView
.
select * from xyz where (1=(CASE WHEN @AnnualFeeType = 'All' THEN 1 ELSE 0 END) OR AnnualFeeType = @AnnualFeeType)
I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5
This makes me happy.
Try this: Live Demo
display: table
is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>
.
CSS:
#container {
background: #ccc;
display: table
}
#left, #right {
display: table-cell
}
#left {
width: 150px;
background: #f0f;
border: 5px dotted blue;
}
#right {
background: #aaa;
border: 3px solid #000
}
Trying to explain this doubt with simple diagrams.
Read Committed: Here in this isolation level, Transaction T1 will be reading the updated value of the X committed by Transaction T2.
Repeatable Read: In this isolation level, Transaction T1 will not consider the changes committed by the Transaction T2.
Here is a good starting point.
HTML:
<div class="containing-table">
<div class="centre-align">
<div class="content"></div>
</div>
</div>
CSS:
.containing-table {
display: table;
width: 100%;
height: 400px; /* for demo only */
border: 1px dotted blue;
}
.centre-align {
padding: 10px;
border: 1px dashed gray;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.content {
width: 50px;
height: 50px;
background-color: red;
display: inline-block;
vertical-align: top; /* Removes the extra white space below the baseline */
}
See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/
.containing-table
establishes the width and height context for .centre-align
(the table-cell).
You can apply text-align
and vertical-align
to alter .centre-align
as needed.
Note that .content
needs to use display: inline-block
if it is to be centered horizontally using the text-align property.
host or hostname would be the i.p address of the remote server, or if you can access it over the network by computer name, that should work to.
Sample form using PHP for direct payments.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">
<input type="hidden" name="amount_' . $x . '" value="' . $price . '">
<input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '">
<input type="hidden" name="custom" value="' . $product_id_array . '">
<input type="hidden" name="notify_url" value="https://www.yoursite.com/my_ipn.php">
<input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="cbt" value="Return to The Store">
<input type="hidden" name="cancel_return" value="https://www.yoursite.com/paypal_cancel.php">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!">
</form>
kindly go through the fields notify_url, return, cancel_return
sample code for handling ipn (my_ipn.php) which is requested by paypal after payment has been made.
For more information on creating a IPN, please refer to this link.
<?php
// Check to see there are posted variables coming into the script
if ($_SERVER['REQUEST_METHOD'] != "POST")
die("No Post Variables");
// Initialize the $req variable and add CMD key value pair
$req = 'cmd=_notify-validate';
// Read the post from PayPal
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// Now Post all of that back to PayPal's server using curl, and validate everything with PayPal
// We will use CURL instead of PHP for this for a more universally operable script (fsockopen has issues on some environments)
//$url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
$url = "https://www.paypal.com/cgi-bin/webscr";
$curl_result = $curl_err = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$curl_result = @curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);
$req = str_replace("&", "\n", $req); // Make it a nice list in case we want to email it to ourselves for reporting
// Check that the result verifies
if (strpos($curl_result, "VERIFIED") !== false) {
$req .= "\n\nPaypal Verified OK";
} else {
$req .= "\n\nData NOT verified from Paypal!";
mail("[email protected]", "IPN interaction not verified", "$req", "From: [email protected]");
exit();
}
/* CHECK THESE 4 THINGS BEFORE PROCESSING THE TRANSACTION, HANDLE THEM AS YOU WISH
1. Make sure that business email returned is your business email
2. Make sure that the transaction?s payment status is ?completed?
3. Make sure there are no duplicate txn_id
4. Make sure the payment amount matches what you charge for items. (Defeat Price-Jacking) */
// Check Number 1 ------------------------------------------------------------------------------------------------------------
$receiver_email = $_POST['receiver_email'];
if ($receiver_email != "[email protected]") {
//handle the wrong business url
exit(); // exit script
}
// Check number 2 ------------------------------------------------------------------------------------------------------------
if ($_POST['payment_status'] != "Completed") {
// Handle how you think you should if a payment is not complete yet, a few scenarios can cause a transaction to be incomplete
}
// Check number 3 ------------------------------------------------------------------------------------------------------------
$this_txn = $_POST['txn_id'];
//check for duplicate txn_ids in the database
// Check number 4 ------------------------------------------------------------------------------------------------------------
$product_id_string = $_POST['custom'];
$product_id_string = rtrim($product_id_string, ","); // remove last comma
// Explode the string, make it an array, then query all the prices out, add them up, and make sure they match the payment_gross amount
// END ALL SECURITY CHECKS NOW IN THE DATABASE IT GOES ------------------------------------
////////////////////////////////////////////////////
// Homework - Examples of assigning local variables from the POST variables
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
$custom = $_POST['custom'];
// Place the transaction into the database
// Mail yourself the details
mail("[email protected]", "NORMAL IPN RESULT YAY MONEY!", $req, "From: [email protected]");
?>
The below image will help you in understanding the paypal process.
For further reading refer to the following links;
hope this helps you..:)
Latest Stable release of sklearn 0.20.0 has train_test_split is under model_selection not under cross_validation
In order to check your sklearn version :
import sklearn print (sklearn.version) 0.20.2
git reset --hard origin/{branchName}
is the correct solution to reset all your local changes done by rebase.
found it under /Users/username/apache-maven-3.3.9/conf
Restarting Your Server Can Resolve this problem.
I was getting the same error while Using Dynamic Jasper Reporting , When i deploy my Application for first use to Create Reports, the Report creation works fine, But Once I Do Hot Deployment of some code changes To the Server, I was getting This Error.
Is there a reason you didn't just use this?
<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Cow">Cow</option>
</select>
if($_POST['submit'] && $_POST['submit'] != 0)
{
$animal=$_POST['animal'];
}
You must to wrap your following code into a block (Either method or static).
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
Without a block you can only declare variables and more than that assign them a value in single statement.
For method main() will be best choice for now:
public class details {
public static void main(String[] args){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
or If you want to use static block then...
public class details {
static {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
or if you want to build another method then..
public class details {
public static void main(String[] args){
myMethod();
}
private static void myMethod(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
Also worry about exception due to BufferedReader .
The following is how I do it using Visual Studio 2017 for an RDL targetted for SSRS 2017:
Right-click on the field in the textbox on the design surface and choose Placeholder Properties. Choose the Number panel and click on Date in the Category listbox, then select the formatting you are looking for in the Type listbox.
i solved it using jquery
<script type="text/javascript">_x000D_
$(document).ready(function(e) {_x000D_
var h = $('nav').height() + 20;_x000D_
$('body').animate({ paddingTop: h });_x000D_
});_x000D_
</script>
_x000D_
Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.
To get the file path from the user use this function:
Private Function get_user_specified_filepath() As String
'or use the other code example here.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Please select the file."
get_user_specified_filepath = fd.SelectedItems(1)
End Function
Then just open the file read only and assign it to a variable:
dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().
EDIT: lbrandy's answer is correct in all cases.
Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:
<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
<div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
<div class="uil-default-css">
<img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
</div>
<div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;"> </div>
</div>
<div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>
Finally, replace .loader-text element's
content on the fly on every navigation event and turn on the #resultloading
div, note that it is initially hidden.
var showLoader = function (text) {
$('#resultLoading').show();
$('#resultLoading').find('.loader-text').html(text);
};
jQuery(document).ready(function () {
jQuery(window).on("beforeunload ", function () {
showLoader('Loading, please wait...');
});
});
This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.
The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.
Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.
If you need to see the output of an existing program that extensively used printf w/o changing the code (or with minimal changes) you can redefine printf as follows and add it to the common header (stdafx.h).
int print_log(const char* format, ...)
{
static char s_printf_buf[1024];
va_list args;
va_start(args, format);
_vsnprintf(s_printf_buf, sizeof(s_printf_buf), format, args);
va_end(args);
OutputDebugStringA(s_printf_buf);
return 0;
}
#define printf(format, ...) \
print_log(format, __VA_ARGS__)
I have found that a button works, but that you'll want to add style="height: 100%;"
to the button so that it will show more than the first line on Safari for iPhone iOS 5.1.1
Change setTimeout("changeImage()", 30000);
to setInterval("changeImage()", 30000);
and remove var timerid = setInterval(changeImage, 30000);
.
If you use AIX try this This will attach a text file and include a HTML body If this does not work catch the output in the /var/spool/mqueue
#!/usr/bin/kWh
if (( $# < 1 ))
then
echo "\n\tSyntax: $(basename) MAILTO SUBJECT BODY.html ATTACH.txt "
echo "\tmailzatt"
exit
fi
export MAILTO=${[email protected]}
MAILFROM=$(whoami)
SUBJECT=${2-"mailzatt"}
export BODY=${3-/apps/bin/attch.txt}
export ATTACH=${4-/apps/bin/attch.txt}
export HST=$(hostname)
#export BODY="/wrk/stocksum/report.html"
#export ATTACH="/wrk/stocksum/Report.txt"
#export MAILPART=`uuidgen` ## Generates Unique ID
#export MAILPART_BODY=`uuidgen` ## Generates Unique ID
export MAILPART="==".$(date +%d%S)."===" ## Generates Unique ID
export MAILPART_BODY="==".$(date +%d%Sbody)."===" ## Generates Unique ID
(
echo "To: $MAILTO"
echo "From: mailmate@$HST "
echo "Subject: $SUBJECT"
echo "MIME-Version: 1.0"
echo "Content-Type: multipart/mixed; boundary=\"$MAILPART\""
echo ""
echo "--$MAILPART"
echo "Content-Type: multipart/alternative; boundary=\"$MAILPART_BODY\""
echo ""
echo ""
echo "--$MAILPART_BODY"
echo "Content-Type: text/html"
echo "Content-Disposition: inline"
cat $BODY
echo ""
echo "--$MAILPART_BODY--"
echo ""
echo "--$MAILPART"
echo "Content-Type: text/plain"
echo "Content-Disposition: attachment; filename=\"$(basename $ATTACH)\""
echo ""
cat $ATTACH
echo ""
echo "--${MAILPART}--"
) | /usr/sbin/sendmail -t
This simple solution forces the IEnumerable
's generic type to implement IComparable
. Because of
OrderBy
's definition.
If you don't want to make such an assumption but still want use this solution, you can use the following piece of code :
bool equal = collection1.OrderBy(i => i?.GetHashCode())
.SequenceEqual(collection2.OrderBy(i => i?.GetHashCode()));
Usually all users will have write access to /tmp. Place the file to /tmp and then login to putty , then you can sudo and copy the file.
UPDATE im
SET mf_item_number = gm.SKU --etc
FROM item_master im
JOIN group_master gm
ON im.sku = gm.sku
JOIN Manufacturer_Master mm
ON gm.ManufacturerID = mm.ManufacturerID
WHERE im.mf_item_number like 'STA%' AND
gm.manufacturerID = 34
To make it clear... The UPDATE
clause can refer to an table alias specified in the FROM
clause. So im
in this case is valid
UPDATE A
SET foo = B.bar
FROM TableA A
JOIN TableB B
ON A.col1 = B.colx
WHERE ...
If you are on Mac or Linux, just go to the terminal and type in:
whereis jarsigner
It will give you the location of the jarsigner
If you are stuck using Spring 2.5 you could define a bean for each of your properties and inject them using qualifiers. Like this:
<bean id="someFile" class="java.io.File">
<constructor-arg value="${someFile}"/>
</bean>
and
@Service
public class Thing
public Thing(@Qualifier("someFile") File someFile) {
...
Its not super readable but it gets the job done.
Maybe specifying a width would work. When you position:absolute
an element, it's width will shrink to the contents I believe.
The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'.
By default, the router checks URL elements from the left to see if the URL matches a given path, and stops when there is a match. For example, '/team/11/user' matches 'team/:id'.
The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.
This answers the 'best random' request:
Adi's answer1 from Security.StackExchange has a solution for this:
Make sure you have OpenSSL support, and you'll never go wrong with this one-liner
$token = bin2hex(openssl_random_pseudo_bytes(16));
1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/
If you have a bunch of chars and want to concat them into a string, why not do
System.out.println("" + char1 + char2 + char3);
?
In Python for assertion I use:
assert len(driver.find_elements_by_css_selector("your_css_selector")) == 0
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
The with
function will let you use shorthand column references and sum
will count TRUE
results from the expression(s).
sum(with(aaa, sex==1 & group1==2))
## [1] 3
sum(with(aaa, sex==1 & group2=="A"))
## [1] 2
As @mnel pointed out, you can also do:
nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3
nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2
The benefit of that is that you can do:
nrow(aaa)
## [1] 6
And, the behaviour matches Stata's count
almost exactly (syntax notwithstanding).
Using JSTL:
<c:set var="message" value='${requestScope["Error_Message"]}' />
Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.
<c:out value="${message}"/>
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
Try the following:
color.gradient <- function(x, colors=c("red","yellow","green"), colsteps=100) {
return( colorRampPalette(colors) (colsteps) [ findInterval(x, seq(min(x),max(x), length.out=colsteps)) ] )
}
x <- c((1:100)^2, (100:1)^2)
plot(x,col=color.gradient(x), pch=19,cex=2)
Pasting my code here, this should help. It shows the package which can be used.
import org.json.JSONException;
import org.json.JSONObject;
public class extractingJSON {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"}}";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
System.out.println(name);
String first = jsonObj.getJSONObject("arr").getString("a");
System.out.println(first);
}
}
u can use placeholder and when u write a text on the search box placeholder will hidden. Thanks
<input placeholder="Search" type="text" />
No, the URL will always be updated when params are passed to transitionTo
.
This happens on state.js:698 in ui-router.
What would be ideal what be to use a .ASPX page as a template somehow, then just tell my code to serve that page, and use the HTML returned for the email.
You could easily just construct a WebRequest to hit an ASPX page and get the resultant HTML. With a little more work, you can probably get it done without the WebRequest. A PageParser and a Response.Filter would allow you to run the page and capture the output...though there may be some more elegant ways.
var persons = new List<Person>
{
new Person {ID = 1, Name = "jhon", Salary = 2500},
new Person {ID = 2, Name = "Sena", Salary = 1500},
new Person {ID = 3, Name = "Max", Salary = 5500},
new Person {ID = 4, Name = "Gen", Salary = 3500}
};
var acertainperson = persons.Where(p => p.Name == "jhon").First();
Console.WriteLine("{0}: {1} points",
acertainperson.Name, acertainperson.Salary);
jhon: 2500 points
var doingprettywell = persons.Where(p => p.Salary > 2000);
foreach (var person in doingprettywell)
{
Console.WriteLine("{0}: {1} points",
person.Name, person.Salary);
}
jhon: 2500 points
Max: 5500 points
Gen: 3500 points
var astupidcalc = from p in persons
where p.ID > 2
select new
{
Name = p.Name,
Bobos = p.Salary*p.ID,
Bobotype = "bobos"
};
foreach (var person in astupidcalc)
{
Console.WriteLine("{0}: {1} {2}",
person.Name, person.Bobos, person.Bobotype);
}
Max: 16500 bobos
Gen: 14000 bobos
You can also use YourJS.fullNumber. For instance YourJS.fullNumber(Number.MAX_VALUE)
results in the following:
179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
It also works for really small numbers. YourJS.fullNumber(Number.MIN_VALUE)
returns this:
0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005
It is important to note that this function will always return finite numbers as strings but will return non-finite numbers (eg. NaN
or Infinity
) as undefined
.
You can test it out in the YourJS Console here.
I've stumble across this question, trying to build an Ionic + Cordova app using Gradle from Android Studio installation, rather that installing Gradle separately.
On Centos, the Gradle binary was here: /home/YOURUSERNAME/.gradle/wrapper/dists/gradle-VERSION-all/CUSTOM_HASH/gradle-VERSION/bin
So, I've added export PATH=/home/maxim/.gradle/wrapper/dists/gradle-4.1-all/bzyivzo6n839fup2jbap0tjew/gradle-4.1/bin:$PATH
to my ~/.bashrc
and ionic cordova run android
command worked just fine.
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
Just for the sake of academic interest, I did it this way...
(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day
Firebase is a suite of features .
I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .
When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .
A more explicit example, built on Damien's code (calls a test resource at http://httpbin.org/). For python3. Note that if the server redirects to another URL, uri
in add_password
has to contain the new root URL (it's possible to pass a list of URLs, also).
import ssl
import urllib.parse
import urllib.request
def get_resource(uri, user, passwd=False):
"""
Get the content of the SSL page.
"""
uri = 'https://httpbin.org/basic-auth/user/passwd'
user = 'user'
passwd = 'passwd'
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, uri, user, passwd)
auth_handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(auth_handler, urllib.request.HTTPSHandler(context=context))
urllib.request.install_opener(opener)
return urllib.request.urlopen(uri).read()
See doco for setText() in TextView http://developer.android.com/reference/android/widget/TextView.html
To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.
Instead of giving the path following way:
C:\Users\User_name\AppData\Local\Continuum\anaconda3\python.exe
Do this:
C:\Users\User_name\AppData\Local\Continuum\anaconda3\
I had the exact same problem with my instance. My problem was that I forgot to allow port 80 access to the server. Maybe that's your issue as well?
Check with your WHM and make sure that port is open for the IP address of your site,
To those who use centos and have stumbled upon this post :
$ yum install curl-devel
and when compiling your program example.cpp
, link to the curl library:
$ g++ example.cpp -lcurl -o example
"-o example
" creates the executable example
instead of the default a.out
.
The next line runs example
:
$ ./example
You are using a pathname separator which is platform dependent. Windows uses "\" and Unix uses "/".
// in foo.h
class Foo {
static const unsigned char* Msg;
};
// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;
I like the fact that there are so many ways to create a fibonacci sequence in JS. I will try to reproduce a few of them. The goal is to output a sequence to console (like {n: 6, fiboNum: 8}
)
// The IIFE form is purposefully omitted. See below._x000D_
_x000D_
const fiboGenClosure = () => {_x000D_
let [a, b] = [0, 1];_x000D_
let n = 0;_x000D_
return (fiboNum = a) => {_x000D_
[a, b] = [b, a + b];_x000D_
return {_x000D_
n: n++,_x000D_
fiboNum: fiboNum_x000D_
};_x000D_
};_x000D_
}_x000D_
_x000D_
// Gets the sequence until given nth number. Always returns a new copy of the main function, so it is possible to generate multiple independent sequences._x000D_
_x000D_
const generateFiboClosure = n => {_x000D_
const newSequence = fiboGenClosure();_x000D_
for (let i = 0; i <= n; i++) {_x000D_
console.log(newSequence());_x000D_
}_x000D_
}_x000D_
_x000D_
generateFiboClosure(21);
_x000D_
Similar to the closure pattern above, using the advantages of generator function and for..of loop.
// The 'n' argument is a substitute for index._x000D_
_x000D_
function* fiboGen(n = 0) {_x000D_
let [a, b] = [0, 1];_x000D_
while (true) {_x000D_
yield [a, n++];_x000D_
[a, b] = [b, a + b];_x000D_
}_x000D_
}_x000D_
_x000D_
// Also gives a new sequence every time is invoked._x000D_
_x000D_
const generateFibonacci = n => {_x000D_
const iterator = fiboGen();_x000D_
for (let [value, index] of iterator) {_x000D_
console.log({_x000D_
n: index,_x000D_
fiboNum: value_x000D_
});_x000D_
if (index >= n) break;_x000D_
}_x000D_
}_x000D_
_x000D_
generateFibonacci(21);
_x000D_
This one is a little tricky, because, now in late 2018, TC optimization is still an issue. But honestly – if you don't use any smart tricks to allow the default JS engine to use a really big numbers, it will get dizzy and claims that the next fibonacci number is "Infinity" by iteration 1477. The stack would probably overflow somewhere around iteration 10 000 (vastly depends on browser, memory etc…). Could be probably padded by try… catch block or check if "Infinity" was reached.
const fibonacciRTC = (n, i = 0, a = 0, b = 1) => {_x000D_
console.log({_x000D_
n: i,_x000D_
fibonacci: a_x000D_
});_x000D_
if (n === 0) return;_x000D_
return fibonacciRTC(--n, ++i, b, a + b);_x000D_
}_x000D_
_x000D_
fibonacciRTC(21)
_x000D_
It can be written as a one-liner, if we throe away the console.log
thing and simply return a number:
const fibonacciRTC2 = (n, a = 0, b = 1) => n === 0 ? a : fibonacciRTC2(n - 1, b, a + b);_x000D_
_x000D_
console.log(fibonacciRTC2(21))
_x000D_
As I found out reading this mathIsFun article, the fibonacci sequence is valid for negative numbers as well! I tried to implement that in the recursive tail call form above like that:
const fibonacciRTC3 = (n, a = 0, b = 1, sign = n >= 0 ? 1 : -1) => { _x000D_
if (n === 0) return a * sign;_x000D_
return fibonacciRTC3(n - sign, b, a + b, sign);_x000D_
}_x000D_
_x000D_
console.log(fibonacciRTC3(8)); // 21_x000D_
console.log(fibonacciRTC3(-8)); // -21
_x000D_
1
is a literal. name = value
is an assignment. 1 = value
is an assignment to a literal, which makes no sense. Why would you want 1
to mean something other than 1
?
Set the method attribute to POST because file content can't be put inside a URL parameter using a form.
Set the value of enctype to multipart/form-data because the data will be split into multiple parts, one for each file plus one for the text of the form body that may be sent with them.
Not exactly the case of this question but can be helpful. I got this exception when i call mkdirs() on new file instead of its parent
File file = new java.io.File(path);
//file.mkdirs(); // wrong!
file.getParentFile().mkdirs(); // correct!
if (!file.exists()) {
file.createNewFile();
}
wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm
rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm
wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm
rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm
maybe some URL is broken,please research it. Enjoy~~
Another way of doing this, using only JavaScript, would be this:
window.addEventListener('resize', functionName);
This fires every time the size changes, like the other answer.
functionName
is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).
If you want to make the first item unselectable, try this:
DropDownList1.Items.Insert(0, new ListItem("Select", "-1"));
DropDownList1.Items[0].Attributes.Add("disabled", "disabled");
If the Pod
is part of a Deployment
or Service
, deleting it will restart the Pod
and, potentially, place it onto another node:
$ kubectl delete po $POD_NAME
replace
it if it's an individual Pod
:
$ kubectl get po -n $namespace $POD_NAME -o yaml | kubectl replace -f -
Using MongoDB 4.0 and newer
You have two options i.e. $toInt
or $convert
. Using $toInt
, follow the example below:
filterDateStage = {
'$match': {
'Date': {
'$gt': '2015-04-01',
'$lt': '2015-04-05'
}
}
};
groupStage = {
'$group': {
'_id': '$PartnerID',
'total': { '$sum': { '$toInt': '$moop' } }
}
};
db.getCollection('my_collection').aggregate([
filterDateStage,
groupStage
])
If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use $convert
instead.
Using $convert
groupStage = {
'$group': {
'_id': '$PartnerID',
'total': {
'$sum': {
'$convert': { 'input': '$moop', 'to': 'int' }
}
}
}
};
Using Map/Reduce
With map/reduce you can use javascript functions like parseInt()
to do the conversion. As an example, you could define the map function to process each input document:
In the function, this
refers to the document that the map-reduce operation is processing. The function maps the converted moop
string value to the PartnerID
for each document and emits the PartnerID
and converted moop
pair. This is where the javascript native function parseInt()
can be applied:
var mapper = function () {
var x = parseInt(this.moop);
emit(this.PartnerID, x);
};
Next, define the corresponding reduce function with two arguments keyCustId
and valuesMoop
. valuesMoop
is an array whose elements are the integer moop
values emitted by the map function and grouped by keyPartnerID
.
The function reduces the valuesMoop
array to the sum of its elements.
var reducer = function(keyPartnerID, valuesMoop) {
return Array.sum(valuesMoop);
};
db.collection.mapReduce(
mapper,
reducer,
{
out : "example_results",
query: {
Date: {
$gt: "2015-04-01",
$lt: "2015-04-05"
}
}
}
);
db.example_results.find(function (err, docs) {
if(err) console.log(err);
console.log(JSON.stringify(docs));
});
For example, with the following sample collection of documents:
/* 0 */
{
"_id" : ObjectId("550c00f81bcc15211016699b"),
"Date" : "2015-04-04",
"PartnerID" : "123456",
"moop" : "1234"
}
/* 1 */
{
"_id" : ObjectId("550c00f81bcc15211016699c"),
"Date" : "2015-04-03",
"PartnerID" : "123456",
"moop" : "24"
}
/* 2 */
{
"_id" : ObjectId("550c00f81bcc15211016699d"),
"Date" : "2015-04-02",
"PartnerID" : "123457",
"moop" : "21"
}
/* 3 */
{
"_id" : ObjectId("550c00f81bcc15211016699e"),
"Date" : "2015-04-02",
"PartnerID" : "123457",
"moop" : "8"
}
The above Map/Reduce operation will save the results to the example_results
collection and the shell command db.example_results.find()
will give:
/* 0 */
{
"_id" : "123456",
"value" : 1258
}
/* 1 */
{
"_id" : "123457",
"value" : 29
}
I don't want to have to enable a reference library as I need my scripts to be portable. The Dim foo As New VBScript_RegExp_55.RegExp
line caused User Defined Type Not Defined
errors, but I found a solution that worked for me.
Update RE comments w/ @chrisneilsen :
I was under the impression that enabling a reference library was tied to the local computers settings, but it is in fact, tied directly to the workbook. So, you can enable a reference library, share a macro enabled workbook and the end user wouldn't have to enable the library as well. Caveat: The advantage to Late Binding is that the developer does not have to worry about the wrong version of an object library being installed on the user's computer. This likely would not be an issue w/ the VBScript_RegExp_55.RegExp
library, but I'm not sold that the "performance" benifit is worth it for me at this time, as we are talking imperceptible milliseconds in my code. I felt this deserved an update to help others understand. If you enable the reference library, you can use "early bind", but if you don't, as far as I can tell, the code will work fine, but you need to "late bind" and loose on some performance/debugging features.
Source: https://peltiertech.com/Excel/EarlyLateBinding.html
What you'll want to do is put an example string in cell A1
, then test your strPattern
. Once that's working adjust then rng
as desired.
Public Sub RegExSearch()
'https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops
'https://wellsr.com/vba/2018/excel/vba-regex-regular-expressions-guide/
'https://www.vitoshacademy.com/vba-regex-in-excel/
Dim regexp As Object
'Dim regex As New VBScript_RegExp_55.regexp 'Caused "User Defined Type Not Defined" Error
Dim rng As Range, rcell As Range
Dim strInput As String, strPattern As String
Set regexp = CreateObject("vbscript.regexp")
Set rng = ActiveSheet.Range("A1:A1")
strPattern = "([a-z]{2})([0-9]{8})"
'Search for 2 Letters then 8 Digits Eg: XY12345678 = Matched
With regexp
.Global = False
.MultiLine = False
.ignoreCase = True
.Pattern = strPattern
End With
For Each rcell In rng.Cells
If strPattern <> "" Then
strInput = rcell.Value
If regexp.test(strInput) Then
MsgBox rcell & " Matched in Cell " & rcell.Address
Else
MsgBox "No Matches!"
End If
End If
Next
End Sub
span
s are by default displayed inline, which means they don't have a height and width.
Try adding a display: block
to your span.
In jQuery, you can use event.which==13
. If you have a form
, you could use $('#formid').submit()
(with the correct event listeners added to the submission of said form).
$('#textfield').keyup(function(event){_x000D_
if(event.which==13){_x000D_
$('#submit').click();_x000D_
}_x000D_
});_x000D_
$('#submit').click(function(e){_x000D_
if($('#textfield').val().trim().length){_x000D_
alert("Submitted!");_x000D_
} else {_x000D_
alert("Field can not be empty!");_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label for="textfield">_x000D_
Enter Text:</label>_x000D_
<input id="textfield" type="text">_x000D_
<button id="submit">_x000D_
Submit_x000D_
</button>
_x000D_
This blog post discusses the best answers to this question.
As a short summary, if you can install CPAN modules then the most readable solutions are:
any(@ingredients) eq 'flour';
or
@ingredients->contains('flour');
However, a more common idiom is:
any { $_ eq 'flour' } @ingredients
But please don't use the first()
function! It doesn't express the intent of your code at all. Don't use the ~~
"Smart match" operator: it is broken. And don't use grep()
nor the solution with a hash: they iterate through the whole list.
any()
will stop as soon as it finds your value.
Check out the blog post for more details.
If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.
To do the same I did following in terminal-
$ wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
$ sudo tar -xzf postman.tar.gz -C /opt
$ rm postman.tar.gz
$ sudo ln -s /opt/Postman/Postman /usr/bin/postman
/usr/bin/
and search form "Postman"Hope will hell others too.
It is good to understand with a Venn diagramm.
here is the link to the source. There is a good description.
You can use the opt(int)
method and use a classical for
loop.
var boxSummary = from b in boxes
group b by b.Owner into g
let nrBoxes = g.Count()
let totalWeight = g.Sum(w => w.Weight)
let totalVolume = g.Sum(v => v.Volume)
select new { Owner = g.Key, Boxes = nrBoxes,
TotalWeight = totalWeight,
TotalVolume = totalVolume }
This is "How to apply ScrollBar to your TextView", using only XML.
First, you need to take a Textview control in the main.xml file and write some text into it ... like this:
<TextView
android:id="@+id/TEXT"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/long_text"/>
Next, place the text view control in between the scrollview to display the scroll bar for this text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<ScrollView
android:id="@+id/ScrollView01"
android:layout_height="150px"
android:layout_width="fill_parent">
<TextView
android:id="@+id/TEXT"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/long_text"/>
</ScrollView>
</RelativeLayout>
That's it...
you can use these commands from official page of github
https://help.github.com/en/github/using-git/changing-author-info
here is the commands
#!/bin/sh
git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
here u can change the old email to ur new user name and email address.
Thanks to the last answer
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr HAVING COUNT(title) >= ALL
(SELECT COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr)
I had the same problem: I needed to know just the records which their count match the maximus count (it could be one or several records).
I have to learn more about "ALL clause", and this is exactly the kind of simple solution that I was looking for.
I think the answer depends on which features of stored procedures you need to use.
Stored procedures returning a result set can be run using Query
; stored procedures which don't return a result set can be run using Execute
- in both cases (using EXEC <procname>
) as the SQL command (plus input parameters as necessary). See the documentation for more details.
As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT
parameters; you could add this, or alternatively construct a more complex Query
command which declared TSQL variables, executed the SP collecting OUTPUT
parameters into the local variables and finallyreturned them in a result set:
DECLARE @output int
EXEC <some stored proc> @i = @output OUTPUT
SELECT @output AS output1
Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:
uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)
WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.
The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).
Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.
To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).
Add somewhere in body
<div class="hide">
<a href="#" class="list-group-item">
<table>
<tr>
<td><img src=""></td>
<td><p class="list-group-item-text"></p></td>
</tr>
</table>
</a>
</div>
then create css
.hide { display: none; }
and add to your js
$('#output').append( $('.hide').html() );
1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:
gem 'devise', '3.0.0.rc'
Then execute:
$ bundle
2) Add the old functionality of attr_accessible
again to rails 4.0
Try to use attr_accessible
and don't comment this out.
Add this line to your application's Gemfile:
gem 'protected_attributes'
Then execute:
$ bundle
Try this:
int getYear(Date date1,Date date2){
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy");
Integer.parseInt(simpleDateformat.format(date1));
return Integer.parseInt(simpleDateformat.format(date2))- Integer.parseInt(simpleDateformat.format(date1));
}
Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase
, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:
void swapCase(char *name);
or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.
I ended creating my own functions:
@Component({
selector: 'cookie-consent',
template: cookieconsent_html,
styles: [cookieconsent_css]
})
export class CookieConsent {
private isConsented: boolean = false;
constructor() {
this.isConsented = this.getCookie(COOKIE_CONSENT) === '1';
}
private getCookie(name: string) {
let ca: Array<string> = document.cookie.split(';');
let caLen: number = ca.length;
let cookieName = `${name}=`;
let c: string;
for (let i: number = 0; i < caLen; i += 1) {
c = ca[i].replace(/^\s+/g, '');
if (c.indexOf(cookieName) == 0) {
return c.substring(cookieName.length, c.length);
}
}
return '';
}
private deleteCookie(name) {
this.setCookie(name, '', -1);
}
private setCookie(name: string, value: string, expireDays: number, path: string = '') {
let d:Date = new Date();
d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
let expires:string = `expires=${d.toUTCString()}`;
let cpath:string = path ? `; path=${path}` : '';
document.cookie = `${name}=${value}; ${expires}${cpath}`;
}
private consent(isConsent: boolean, e: any) {
if (!isConsent) {
return this.isConsented;
} else if (isConsent) {
this.setCookie(COOKIE_CONSENT, '1', COOKIE_CONSENT_EXPIRE_DAYS);
this.isConsented = true;
e.preventDefault();
}
}
}
Why you cant use default CSS classes and add some your style?
.slick-next {
/*my style*/
background: url(my-image.png);
}
and
.slick-prev {
/*my style*/
background: url(my-image.png);
}
Are you used simple background css property?
in example: http://jsfiddle.net/BNvke/1/
You can use Font Awesome too. Don't forget about CSS pseudo elements.
And don't forget jQuery, you can replace elements, add classes, etc.
instead of going through this you can always use another approach which is also fast
create a new partial view in the Shared Directory and call your partial view in your layout as
@Html.Partial("MyPartialView")
in your partial view you can call your db and perform what ever you want to do
@{
IEnumerable<HOXAT.Models.CourseCategory> categories = new HOXAT.Models.HOXATEntities().CourseCategories;
}
<div>
//do what ever here
</div>
assuming you have added your Entity Framework Database
If you want n bits specific then you could first create a bitmask and then AND
it with your number to take the desired bits.
Simple function to create mask from bit a to bit b.
unsigned createMask(unsigned a, unsigned b)
{
unsigned r = 0;
for (unsigned i=a; i<=b; i++)
r |= 1 << i;
return r;
}
You should check that a<=b.
If you want bits 12 to 16 call the function and then simply & (logical AND) r
with your number N
r = createMask(12,16);
unsigned result = r & N;
If you want you can shift the result. Hope this helps
This is far from clean, but did the job, for me.
make -p 2&>/dev/null | grep -A 100000 "# Files" | grep -v "^$" | grep -v "^\(\s\|#\|\.\)" | grep -v "Makefile:" | cut -d ":" -f 1
I use make -p
that dumps the internal database, ditch stderr, use a quick and dirty grep -A 100000
to keep the bottom of the output. Then I clean the output with a couple of grep -v
, and finally use cut
to get what's before the colon, namely, the targets.
This is enough for my helper scripts on most of my Makefiles.
EDIT: added grep -v Makefile
that is an internal rule
So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.
To push the contents of foo to origin/master, you first need to set its upstream:
git checkout foo
git branch -u origin/master
Then you can push to this branch using:
git push origin HEAD:master
In the last command you can add --force to replace the entire history of origin/master with that of foo.
You can also use a regular expression as a field separator. The following will print "bar" by using a regular expression to set the number "10" as a separator.
echo "foo 10 bar" | awk -F'[0-9][0-9]' '{print $2}'
In client application (application is not web application, e.g may be swing app)
private static ApplicationContext context = new ClassPathXmlApplicationContext("test-client.xml");
context.getBean(name);
No need of web.xml. ApplicationContext as container for getting bean service. No need for web server container. In test-client.xml there can be Simple bean with no remoting, bean with remoting.
Conclusion: In Scenario 1 applicationContext and DispatcherServlet
are not related.
In a server application (application deployed in server e.g Tomcat). Accessed service via remoting from client program (e.g Swing app)
Define listener in web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
At server startup ContextLoaderListener
instantiates beans defined in applicationContext.xml.
Assuming you have defined the following in applicationContext.xml:
<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />
The beans are instantiated from all four configuration files test1.xml, test2.xml, test3.xml, test4.xml.
Conclusion: In Scenario 2 applicationContext and DispatcherServlet
are not related.
In a web application with spring MVC.
In web.xml define:
<servlet>
<servlet-name>springweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springweb</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
When Tomcat starts, beans defined in springweb-servlet.xml are instantiated.
DispatcherServlet
extends FrameworkServlet
. In FrameworkServlet
bean instantiation takes place for springweb . In our case springweb is FrameworkServlet.
Conclusion: In Scenario 3 applicationContext and DispatcherServlet
are not related.
In web application with spring MVC. springweb-servlet.xml for servlet and applicationContext.xml for accessing the business service within the server program or for accessing DB service in another server program.
In web.xml the following are defined:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springweb</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
At server startup, ContextLoaderListener
instantiates beans defined in applicationContext.xml; assuming you have declared herein:
<import resource="test1.xml" />
<import resource="test2.xml" />
<import resource="test3.xml" />
<import resource="test4.xml" />
The beans are all instantiated from all four test1.xml, test2.xml, test3.xml, test4.xml. After the completion of bean instantiation defined in applicationContext.xml, beans defined in springweb-servlet.xml are instantiated.
So the instantiation order is: the root (application context), then FrameworkServlet.
Now it should be clear why they are important in which scenario.
I found the solution thanks to the link in Vincent's answer.
\renewcommand{\familydefault}{\sfdefault}
This changes the default font family to sans-serif.
The problem is that you are not specifying the name of the remote: Instead of
git remote add https://github.com/username/project.git
you should use:
git remote add origin https://github.com/username/project.git
It could be done in efficient time complexity using KMP algorithm in O(N + M) where N is the length of text
and M is the length of the pattern
.
This is the implementation and usage:
static class StringExtensions
{
public static IEnumerable<int> AllIndicesOf(this string text, string pattern)
{
if (string.IsNullOrEmpty(pattern))
{
throw new ArgumentNullException(nameof(pattern));
}
return Kmp(text, pattern);
}
private static IEnumerable<int> Kmp(string text, string pattern)
{
int M = pattern.Length;
int N = text.Length;
int[] lps = LongestPrefixSuffix(pattern);
int i = 0, j = 0;
while (i < N)
{
if (pattern[j] == text[i])
{
j++;
i++;
}
if (j == M)
{
yield return i - j;
j = lps[j - 1];
}
else if (i < N && pattern[j] != text[i])
{
if (j != 0)
{
j = lps[j - 1];
}
else
{
i++;
}
}
}
}
private static int[] LongestPrefixSuffix(string pattern)
{
int[] lps = new int[pattern.Length];
int length = 0;
int i = 1;
while (i < pattern.Length)
{
if (pattern[i] == pattern[length])
{
length++;
lps[i] = length;
i++;
}
else
{
if (length != 0)
{
length = lps[length - 1];
}
else
{
lps[i] = length;
i++;
}
}
}
return lps;
}
and this is an example of how to use it:
static void Main(string[] args)
{
string text = "this is a test";
string pattern = "is";
foreach (var index in text.AllIndicesOf(pattern))
{
Console.WriteLine(index); // 2 5
}
}
2019's answer as this is still actively seen today
You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.
original hack from 2015 that still works in some situations
You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.
If you cannot pull it out of the div for some reason, you should change the position style with this css:
.full-width-div {
position: absolute;
width: 100%;
left: 0;
}
Instead of absolute, you could also use fixed, but then it will not move as you scroll.
The Active Record definitely has some quirks. When you pass an array to the $this->db->where()
function it will generate an IS NULL. For example:
$this->db->where(array('archived' => NULL));
produces
WHERE `archived` IS NULL
The quirk is that there is no equivalent for the negative IS NOT NULL
. There is, however, a way to do it that produces the correct result and still escapes the statement:
$this->db->where('archived IS NOT NULL');
produces
WHERE `archived` IS NOT NULL
Please make the following part of the Collectors API:
<K, V> Collector<? super Map.Entry<K, V>, ?, Map<K, V>> toMap() {
return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
Everything in python is considered as object so functions are also objects. So you can use this method as well.
def fun1():
fun1.var = 100
print(fun1.var)
def fun2():
print(fun1.var)
fun1()
fun2()
print(fun1.var)
I had the same problem with .c files that contained functions (not main()
of my program). For example, my header files were "fact.h" and "fact.c", and my main program was "main.c" so my commands were like this:
E:\proj> gcc -c fact.c
Now I had an object file of fact.c (fact.o). after that:
E:\proj>gcc -o prog.exe fact.o main.c
Then my program (prog.exe) was ready to use and worked properly. I think that -c
after gcc
was important, because it makes object files that can attach to make the program we need. Without using -c
, gcc ties to find main in your program and when it doesn't find it, it gives you this error.
$('.page-address-edit').addClass('test1 test2 test3');
<script>
$('#tinh').click(function () {
var sumVal = 0;
var table = document.getElementById("table1");
for (var i = 1; i < (table.rows.length-1); i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
document.getElementById("valueTotal").innerHTML = sumVal;
});
</script>
The actual solution to this problem is to approach it differently.
Probably your goal is some sort of initialization which typically happens at the top level of an application.
The solution is to ensure that there is only ever one single JavaScript statement at the top level of your application. If you have only one statement at the top of your application, then you are free to use async/await at every other point everwhere (subject of course to normal syntax rules)
Put another way, wrap your entire top level in a function so that it is no longer the top level and that solves the question of how to run async/await at the top level of an application - you don't.
This is what the top level of your application should look like:
import {application} from './server'
application();
You have to change the format of the date string you are supplying in order to be able to insert it using the STRFTIME function. Reason being, there is no option for a month abbreviation:
%d day of month: 00
%f fractional seconds: SS.SSS
%H hour: 00-24
%j day of year: 001-366
%J Julian day number
%m month: 01-12
%M minute: 00-59
%s seconds since 1970-01-01
%S seconds: 00-59
%w day of week 0-6 with sunday==0
%W week of year: 00-53
%Y year: 0000-9999
%% %
The alternative is to format the date/time into an already accepted format:
Reference: SQLite Date & Time functions
I faced this issue Many time from different scenarios
one of them when I tryed Connecting to team foundation server for different Logged User
so the solution is easy Just Click Switch User
hope this help you
Simply use the .rules('add')
method immediately after creating the element...
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
// create the new input element
$('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
// declare the rule on this newly created input field
$('#FileUpload' + filenumber).rules('add', {
required: true, // <- with this you would not need 'required' attribute on input
accept: "image/jpeg, image/pjpeg"
});
filenumber++; // increment counter for next time
return false;
});
You'll still need to use .validate()
to initialize the plugin within a DOM ready handler.
You'll still need to declare rules for your static elements using .validate()
. Whatever input elements that are part of the form when the page loads... declare their rules within .validate()
.
You don't need to use .each()
, when you're only targeting ONE element with the jQuery selector attached to .rules()
.
You don't need the required
attribute on your input element when you're declaring the required
rule using .validate()
or .rules('add')
. For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required"
.
Working DEMO: http://jsfiddle.net/8dAU8/5/
Whatever code you are writing in viewDidLoad
, Add that in viewWillappear()
. This will solve your problem.
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
The below code expands upon the top answer chosen for this thread, to get rid of the bottom border and set text color:
The last two coded lines of this code set transparency. I borrowed that code from this thread and it worked perfectly!
The "clipsToBounds" property was code I found which got rid of the bottom border line with OR without transparency set (so if you decide to go with a solid white/black/etc. background instead, there will still be no border line).
The "tintColor" line (2nd coded line) set my back button to a light grey
I kept barTintColor as a backup. I don't know why transparency would not work, but if it doesn't, I want my bg white as I used to have it
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.tintColor = UIColor.lightGray
navigationBarAppearace.barTintColor = UIColor.white
navigationBarAppearace.clipsToBounds = true
navigationBarAppearace.isTranslucent = true
navigationBarAppearace.setBackgroundImage(UIImage(), for: .default)
navigationBarAppearace.shadowImage = UIImage()
why not just use export/import wizard in SSMS?
You are trying to copy the war
file to a directory below webapps
. The war file should be copied into the webapps
directory.
Remove the mkdir command, and copy the war
file like this:
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war
Tomcat will extract the war if autodeploy
is turned on.
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
You are not leveraging async / await effectively because the request thread will be blocked while executing the synchronous method ReturnAllCountries()
The thread that is assigned to handle a request will be idly waiting while ReturnAllCountries()
does it's work.
If you can implement ReturnAllCountries()
to be asynchronous, then you would see scalability benefits. This is because the thread could be released back to the .NET thread pool to handle another request, while ReturnAllCountries()
is executing. This would allow your service to have higher throughput, by utilizing threads more efficiently.
long
is equivalent to long int
, just as short
is equivalent to short int
. A long int
is a signed integral type that is at least 32 bits, while a long long
or long long int
is a signed integral type is at least 64 bits.
This doesn't necessarily mean that a long long
is wider than a long
. Many platforms / ABIs use the LP64
model - where long
(and pointers) are 64 bits wide. Win64 uses the LLP64
, where long
is still 32 bits, and long long
(and pointers) are 64 bits wide.
There's a good summary of 64-bit data models here.
long double
doesn't guarantee much other than it will be at least as wide as a double
.
The easiest method is really good but you don't get a standard Java project, i.e., the .java and .class files separated in different folders.
To get this very easily:
<Enter>
and that's it.From:
http://gking.harvard.edu/zelig/docs/How_do_I2.html (mirror)
Windows users may get the error that R has run out of memory.
If you have R already installed and subsequently install more RAM, you may have to reinstall R in order to take advantage of the additional capacity.
You may also set the amount of available memory manually. Close R, then right-click on your R program icon (the icon on your desktop or in your programs directory). Select ``Properties'', and then select the ``Shortcut'' tab. Look for the ``Target'' field and after the closing quotes around the location of the R executible, add
--max-mem-size=500M
as shown in the figure below. You may increase this value up to 2GB or the maximum amount of physical RAM you have installed.
If you get the error that R cannot allocate a vector of length x, close out of R and add the following line to the ``Target'' field:
--max-vsize=500M
or as appropriate. You can always check to see how much memory R has available by typing at the R prompt
memory.limit()
which gives you the amount of available memory in MB. In previous versions of R you needed to use: round(memory.limit()/2^20, 2)
.
In case you need both max and min from same table:
select * from (
(select city, length(city) as maxlen from station
order by maxlen desc limit 1)
union
(select city, length(city) as minlen from station
order by minlen,city limit 1))a;
is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
Here's what I do... CoffeeScript:
ready = ->
...your coffeescript goes here...
$(document).ready(ready)
$(document).on('page:load', ready)
last line listens for page load which is what turbo links will trigger.
Edit...adding Javascript version (per request):
var ready;
ready = function() {
...your javascript goes here...
};
$(document).ready(ready);
$(document).on('page:load', ready);
Edit 2...For Rails 5 (Turbolinks 5) page:load
becomes turbolinks:load
and will be even fired on initial load. So we can just do the following:
$(document).on('turbolinks:load', function() {
...your javascript goes here...
});
You can't do
LivingRoom.objects.create(user=instance)
because you have an __init__
method that does NOT take user
as argument.
You need something like
#signal function: if a user is created, add control livingroom to the user
def create_control_livingroom(sender, instance, created, **kwargs):
if created:
my_room = LivingRoom()
my_room.user = instance
Update
But, as bruno has already said it, Django's models.Model
subclass's initializer is best left alone, or should accept *args
and **kwargs
matching the model's meta fields.
So, following better principles, you should probably have something like
class LivingRoom(models.Model):
'''Living Room object'''
user = models.OneToOneField(User)
def __init__(self, *args, temp=65, **kwargs):
self.temp = temp
return super().__init__(*args, **kwargs)
Note - If you weren't using temp
as a keyword argument, e.g. LivingRoom(65)
, then you'll have to start doing that. LivingRoom(user=instance, temp=66)
or if you want the default (65), simply LivingRoom(user=instance)
would do.
try
Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen)
Disclaimer: Following points are only applicable for API calls and not the website URLs.
Security over the network: You must use HTTPS. GET and POST are equally safe in this case.
Browser History: For front-end applications like, Angular JS, React JS etc API calls are AJAX calls made by front-end. These does not become part of browser history. Hence, POST and GET are equally secure.
Server side logs: With using write set of data-masking and access logs format it is possible to hide all or only sensitive data from request-URL.
Data visibility in browser console: For someone with mallicious intent, it's almost the same efforts to view POST data as much as GET.
Hence, with right logging practices, GET API is as secure as POST API. Following POST everywhere, forces poor API definitions and should be avoided.
you can use following these component to float right
alignItems aligns children in the cross direction. For example, if children are flowing vertically, alignItems controls how they align horizontally.
alignItems: 'flex-end'
justifyContent aligns children in the main direction. For example, if children are flowing vertically, justifyContent controls how they align vertically.
justifyContent: 'flex-end'
alignSelf controls how a child aligns in the cross direction,
alignSelf : 'flex-end'
.list-wrap {
width: 355px;
height: 100%;
position: relative;
.list {
position: absolute;
top: 0;
bottom: 0;
overflow-y: auto;
width: 100%;
}
}
string = string.filter ({!" ".contains($0) })
I recommend dynamically adding the elements, and if using jQuery or other JavaScript library, it is quite simple:
also look at prepend
and append
. Otherwise if you have an image tag like that, and you want to make it validate, then you might consider using a dummy image, such as a 1px transparent gif or png.
You may face this issue if you are running your app on Android's Marshmallow or later version (API level 23 or greater), because of the new Real-time Permissions model introduced in this.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
For getting permissions at runtime, you will have to request the user. You can do that in following way.
First request for permissions.
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, WRITE_REQUEST_CODE);
And then you can check the results in
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case WRITE_REQUEST_CODE:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Permission granted.
//Continue with writing files...
}
else{
//Permission denied.
}
break;
}
}
Here is good learning source requesting-runtime-permissions-in-android-marshmallow/
Your question is a bit unclear, but I think you want (requires using System.Linq;
):
var result = yourArrayOfStrings.SelectMany(s => s).ToArray();
Another solution is:
var result = string.Concat(yourArrayOfStrings).ToCharArray();
You should either use
if str1[0] == '"' and str1[-1] == '"'
or
if str1.startswith('"') and str1.endswith('"')
but not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for...
Add white-space: nowrap;
:
.garage-title {
clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;
}
$('div.target').each(function() {
/* Measure the width of each image. */
var test = $(this).find('.scrolling img').width();
/* Find out how many images there are. */
var testimg = $(this).find('.scrolling img').length;
/* Do the maths. */
var final = (test* testimg)*1.2;
/* Apply the maths to the CSS. */
$(this).find('scrolling').width(final);
});
Here you loop through all your div's with class target and you do the calculations. Within this loop you can simply use $(this)
to indicate the currently selected <div>
tag.
I've used with success the following open source projects:
ExcelPackage for OOXML formats (Office 2007)
NPOI for .XLS format (Office 2003). NPOI 2.0 (Beta) also supports XLSX.
Take a look at my blog posts:
Try sorting index after concatenating them
result=pd.concat([df1,df2]).sort_index()
With rabbitmqadmin
you can remove them with this one-liner:
rabbitmqadmin -f tsv -q list queues name | while read queue; do rabbitmqadmin -q delete queue name=${queue}; done
Suppose your drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
There are two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:
class Test(object):
def _decorator(self, foo):
foo()
def bar(self):
pass
bar = self._decorator(bar)
It, of course, isn't valid since self
isn't defined at that point. The same goes for Test
as it won't be defined until the class itself is defined (which its in the process of). I'm showing you this code snippet because this is what your decorator snippet transforms into.
So, as you can see, accessing the instance in a decorator like that isn't really possible since decorators are applied during the definition of whatever function/method they are attached to and not during instantiation.
If you need class-level access, try this:
class Test(object):
@classmethod
def _decorator(cls, foo):
foo()
def bar(self):
pass
Test.bar = Test._decorator(Test.bar)
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
UPDATE ed
SET ed.kWh = ted.kWh
FROM energydata ed
INNER JOIN temp_energydata ted ON ted.webmeterID = ed.webmeterID
Just use this. It works only for android api >= 11 before that you'll have to use a ClipData.
ClipboardManager _clipboard = (ClipboardManager) _activity.getSystemService(Context.CLIPBOARD_SERVICE);
_clipboard.setText(YOUR TEXT);
Hope it helped you :)
[UPDATE 3/19/2015]
Just like Ujjwal Singh said it the method setText
is deprecated now, you should use, just as the docs recommande it, setPrimaryClip(clipData)
Split the words without without harming apostrophes inside words Please find the input_1 and input_2 Moore's law
def split_into_words(line):
import re
word_regex_improved = r"(\w[\w']*\w|\w)"
word_matcher = re.compile(word_regex_improved)
return word_matcher.findall(line)
#Example 1
input_1 = "computational power (see Moore's law) and "
split_into_words(input_1)
# output
['computational', 'power', 'see', "Moore's", 'law', 'and']
#Example 2
input_2 = """Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad."""
split_into_words(input_2)
#output
['Oh',
'you',
"can't",
'help',
'that',
'said',
'the',
'Cat',
"we're",
'all',
'mad',
'here',
"I'm",
'mad',
"You're",
'mad']
MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ˜ 9.5 hours).
If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed
.
MySQL suggests:
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem.
list1 = [1,2,3,4]; list2 = [0,3,3,6]
print set(list2) - set(list1)
Here is the comparison between MD5 and SHA1. You can get a clear idea about which one is better.
I encountered the same issue on Mac OSX, using a ZSH shell: in this case there is no -t
option for mv
, so I had to find another solution.
However the following command succeeded:
find .* * -maxdepth 0 -not -path '.git' -not -path '.backup' -exec mv '{}' .backup \;
The secret was to quote the braces. No need for the braces to be at the end of the exec
command.
I tested under Ubuntu 14.04 (with BASH and ZSH shells), it works the same.
However, when using the +
sign, it seems indeed that it has to be at the end of the exec
command.
I don't know if you're going to like this or not, I'm not pretty happy with this solution but it is a C++14 friendly approach because it is using template variables and abusing template specialization:
enum class MyEnum : std::uint_fast8_t {
AAA,
BBB,
CCC,
};
template<MyEnum> const char MyEnumName[] = "Invalid MyEnum value";
template<> const char MyEnumName<MyEnum::AAA>[] = "AAA";
template<> const char MyEnumName<MyEnum::BBB>[] = "BBB";
template<> const char MyEnumName<MyEnum::CCC>[] = "CCC";
int main()
{
// Prints "AAA"
std::cout << MyEnumName<MyEnum::AAA> << '\n';
// Prints "Invalid MyEnum value"
std::cout << MyEnumName<static_cast<MyEnum>(0x12345678)> << '\n';
// Well... in fact it prints "Invalid MyEnum value" for any value
// different of MyEnum::AAA, MyEnum::BBB or MyEnum::CCC.
return 0;
}
The worst about this approach is that is a pain to maintain, but it is also a pain to maintain some of other similar aproaches, aren't they?
Good points about this aproach:
Misterious user673679 you're right; the C++14 variable template approach doesn't handles the runtime case, it was my fault to forget it :(
But we can still use some modern C++ features and variable template plus variadic template trickery to achieve a runtime translation from enum value to string... it is as bothersome as the others but still worth to mention.
Let's start using a template alias to shorten the access to a enum-to-string map:
// enum_map contains pairs of enum value and value string for each enum
// this shortcut allows us to use enum_map<whatever>.
template <typename ENUM>
using enum_map = std::map<ENUM, const std::string>;
// This variable template will create a map for each enum type which is
// instantiated with.
template <typename ENUM>
enum_map<ENUM> enum_values{};
Then, the variadic template trickery:
template <typename ENUM>
void initialize() {}
template <typename ENUM, typename ... args>
void initialize(const ENUM value, const char *name, args ... tail)
{
enum_values<ENUM>.emplace(value, name);
initialize<ENUM>(tail ...);
}
The "best trick" here is the use of variable template for the map which contains the values and names of each enum entry; this map will be the same in each translation unit and have the same name everywhere so is pretty straightforward and neat, if we call the initialize
function like this:
initialize
(
MyEnum::AAA, "AAA",
MyEnum::BBB, "BBB",
MyEnum::CCC, "CCC"
);
We are asigning names to each MyEnum
entry and can be used in runtime:
std::cout << enum_values<MyEnum>[MyEnum::AAA] << '\n';
But can be improved with SFINAE and overloading <<
operator:
template<typename ENUM, class = typename std::enable_if<std::is_enum<ENUM>::value>::type>
std::ostream &operator <<(std::ostream &o, const ENUM value)
{
static const std::string Unknown{std::string{typeid(ENUM).name()} + " unknown value"};
auto found = enum_values<ENUM>.find(value);
return o << (found == enum_values<ENUM>.end() ? Unknown : found->second);
}
With the correct operator <<
now we can use the enum this way:
std::cout << MyEnum::AAA << '\n';
This is also bothersome to maintain and can be improved, but hope you get the idea.
the initial value of your data-backdrop attribute can be
"static","true", "false" .
static and true add the modal shadow, while false disable the shadow, so you just need to change this value with the first click to false . like this:
$(document).on('ready',function(){_x000D_
_x000D_
var count=0;_x000D_
_x000D_
$('#id-which-triggers-modal').on('click',function(){_x000D_
_x000D_
if(count>0){_x000D_
_x000D_
$(this).attr('data-backdrop','false')_x000D_
}_x000D_
count++;_x000D_
});_x000D_
_x000D_
_x000D_
});
_x000D_
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
Here is the typical structure of new Codeigniter project:
- application/
- system/
- user_guide/
- index.php <- this is the file you need to change
I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.
With this code you can deploy your site to your production server without changing index.php each time.
// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT')) {
switch (ENVIRONMENT) {
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
ini_set('display_errors', 0);
break;
default:
exit('The application environment is not set correctly.');
}
}