If you want to make a branch from some another branch then follow bellow steps:
Assumptions:
BranchExisting
is the name of branch from which you need to make a new branch with name BranchMyNew
.Steps:
Fetch the branch to your local machine.
$ git fetch origin BranchExisting : BranchExisting
This command will create a new branch in your local with same branch name.
Now, from master branch checkout to the newly fetched branch
$ git checkout BranchExisting
You are now in BranchExisting. Now create a new branch from this existing branch.
$ git checkout -b BranchMyNew
Here you go!
You can add 1 to each example New = 5; old = 0;
(1+new) - (old+1) / (old +1) 5/ 1 * 100 ==> 500%
Like @SharadHolani said. This won't match every word beginning with "stop"
. Only if it's at the beginning of a line like "stop going". @Waxo gave the right answer:
This one is slightly better, if you want to match any word beginning with "stop" and containing nothing but letters from A to Z.
\bstop[a-zA-Z]*\b
This would match all
stop (1)
stop random (2)
stopping (3)
want to stop (4)
please stop (5)
But
/^stop[a-zA-Z]*/
would only match (1) until (3), but not (4) & (5)
Add this code to your jquery
$('.dropdown').click(function(){
$('.dropdown-menu').toggleClass('show');
});
Using the request module solved the issue.
// Include the request library for Node.js
var request = require('request');
// Basic Authentication credentials
var username = "vinod";
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
console.log(body); } );
You need to do something when it fails to handle the issue. Right now you are returning the actual exception. For example, if its not a problem that the user exists already and you want to use it as a get_or_create function maybe you handle the issue by returning the existing user object.
try:
user = iam_conn.create_user(UserName=username)
return user
except botocore.exceptions.ClientError as e:
#this exception could actually be other things other than exists, so you want to evaluate it further in your real code.
if e.message.startswith(
'enough of the exception message to identify it as the one you want')
print('that user already exists.')
user = iam_conn.get_user(UserName=username)
return user
elif e.message.some_other_condition:
#something else
else:
#unhandled ClientError
raise(e)
except SomeOtherExceptionTypeYouCareAbout as e:
#handle it
# any unhandled exception will raise here at this point.
# if you want a general handler
except Exception as e:
#handle it.
That said, maybe it is a problem for your app, in which case you want to want to put the exception handler around the code that called your create user function and let the calling function determine how to deal with it, for example, by asking the user to input another username, or whatever makes sense for your application.
If you want to change the range to [0, 1], make sure the output data type is float
.
image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR) # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
Though it is answered above and it is right to use
<meta name="viewport" content="width=device-width, initial-scale=1">
but if you are using React and webpack then don't forget to close the element tag
<meta name="viewport" content="width=device-width, initial-scale=1" />
Use a custom Listview.
You can also customize how row looks by having a custom background. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#0095FF"> //background color
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="@android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
MainActivity
Define populateString() in MainActivity
public class MainActivity extends Activity {
String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data_array = populateString();
ListView ll = (ListView) findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter();
ll.setAdapter(cus);
}
class CustomAdapter extends BaseAdapter
{
LayoutInflater mInflater;
public CustomAdapter()
{
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data_array.length;//listview item count.
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder vh;
vh= new ViewHolder();
if(convertView==null )
{
convertView=mInflater.inflate(R.layout.row, parent,false);
//inflate custom layour
vh.tv2= (TextView)convertView.findViewById(R.id.textView2);
}
else
{
convertView.setTag(vh);
}
//vh.tv2.setText("Position = "+position);
vh.tv2.setText(data_array[position]);
//set text of second textview based on position
return convertView;
}
class ViewHolder
{
TextView tv1,tv2;
}
}
}
row.xml. Custom layout for each row.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Header" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TextView" />
</LinearLayout>
Inflate a custom layout. Use a view holder for smooth scrolling and performance.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about listview performance by android developers.
From SQL Server 2016 you can just use
DROP TABLE IF EXISTS ##CLIENTS_KEYWORD
On previous versions you can use
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You could also consider truncating the table instead rather than dropping and recreating.
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
For UWP, it is not so simple: You must jump through an extra hoop to pass a field value as a parameter.
Example 1
Valid for both WPF and UWP.
<MyControl>
<MyControl.MyProperty>
<Binding Converter="{StaticResource EnumToBooleanConverter}" Path="AnotherProperty">
<Binding.ConverterParameter>
<MyLibrary:MyEnum>Field</MyLibrary:MyEnum>
</Binding.ConverterParameter>
</MyControl>
</MyControl.MyProperty>
</MyControl>
Example 2
Valid for both WPF and UWP.
...
<MyLibrary:MyEnum x:Key="MyEnumField">Field</MyLibrary:MyEnum>
...
<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={StaticResource MyEnumField}}"/>
Example 3
Valid only for WPF!
<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static MyLibrary:MyEnum.Field}}"/>
UWP doesn't support x:Static
so Example 3 is out of the question; assuming you go with Example 1, the result is more verbose code. Example 2 is slightly better, but still not ideal.
Solution
public abstract class EnumToBooleanConverter<TEnum> : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var Parameter = parameter as string;
if (Parameter == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(typeof(TEnum), value) == false)
return DependencyProperty.UnsetValue;
return Enum.Parse(typeof(TEnum), Parameter).Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
var Parameter = parameter as string;
return Parameter == null ? DependencyProperty.UnsetValue : Enum.Parse(typeof(TEnum), Parameter);
}
}
Then, for each type you wish to support, define a converter that boxes the enum type.
public class MyEnumToBooleanConverter : EnumToBooleanConverter<MyEnum>
{
//Nothing to do!
}
The reason it must be boxed is because there's seemingly no way to reference the type in the ConvertBack
method; the boxing takes care of that. If you go with either of the first two examples, you can just reference the parameter type, eliminating the need to inherit from a boxed class; if you wish to do it all in one line and with least verbosity possible, the latter solution is ideal.
Usage resembles Example 2, but is, in fact, less verbose.
<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource MyEnumToBooleanConverter}, ConverterParameter=Field}"/>
The downside is you must define a converter for each type you wish to support.
The Clear
method is defined as
public void Clear() {
Text = null;
}
The Text
property's setter starts with
set {
if (value == null) {
value = "";
}
I assume this answers your question.
The C++ 11 way is to use std::stod and std::to_string. Both work in Visual Studio 11.
first copy the cumber inside the file then remove it: rm /your_project_path/tmp/pids/server.pid then create it again. touch /YOUR_PROJECT_PATH/tmp/pids/server.pid It worked for me.
The following solution works for me, you can try it:
Write to run : regedit
Then open
HKEY_LOCAL_MACHINE -> SOFTWARE -> Microsoft -> Windows NT -> Perflib
Under the /009 and /01F files, right click and select new and choose "multi string value" named it as "Counter" and do these steps again to create "Help" named file. (Important!! it is case sensitive)
Copy contents of "Counter" and "Help" files under the "CurrentLanguage" to the /009 and /01F files.
You can use double quotes if ANSI SQL mode is enabled
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
"key" TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
or the proprietary back tick escaping otherwise. (Where to find the `
character on various keyboard layouts is covered in this answer)
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
It is important that your datetime is in the correct ISO format when using any of the momentjs queries: isBefore
, isAfter
, isSameOrBefore
, isSameOrAfter
, isBetween
So instead of 2014-03-24T01:14:000, your datetime should be either:
2014-03-24T01:14:00 or 2014-03-24T01:14:00.000Z
otherwise you may receive the following deprecation warning and the condition will evaluate to false:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
// https://momentjs.com/docs/#/query/_x000D_
_x000D_
const dateIsAfter = moment('2014-03-24T01:15:00.000Z').isAfter(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsSame = moment('2014-03-24T01:15:00.000Z').isSame(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
const dateIsBefore = moment('2014-03-24T01:15:00.000Z').isBefore(moment('2014-03-24T01:14:00.000Z'));_x000D_
_x000D_
console.log(`Date is After: ${dateIsAfter}`);_x000D_
console.log(`Date is Same: ${dateIsSame}`);_x000D_
console.log(`Date is Before: ${dateIsBefore}`);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"_x000D_
></script>
_x000D_
<iframe width="420" height="315"
src="https://www.youtube.com/embed/aNOgO7aNslo?rel=0">
</iframe>
You're supposed to put the characters ?rel=0
after the YouTube video unique link and before the quotations. it worked for me
Have you looked under Advanced Security Settings?
something like below image change permissions of folder to IIS_IUSRS
Position absolute takes it out of the flow, and places it at 0x0 to the parent ( Last block element to have a position absolute or position relative ).
I'm not sure what exactly you what you are trying to accomplish, It might be best to set the li to a position:relative
and that will center them. Given your current CSS
Check out http://jsfiddle.net/rtgibbons/ejRTU/ to play with it
Try this. It will check to see if the file already exists in the destination folder, and if it does will check if the file is read-only. If the file is read-only it will change it to read-write, replace the file, and make it read-only again.
Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "c:\sourcefolder\anyfile.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
If fso.FileExists(DestinationFile) Then
'Check to see if the file is read-only
If Not fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is not read-only. Safe to replace the file.
fso.CopyFile SourceFile, "C:\destfolder\", True
Else
'The file exists and is read-only.
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
'Replace the file
fso.CopyFile SourceFile, "C:\destfolder\", True
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Else
'The file does not exist in the destination folder. Safe to copy file to this folder.
fso.CopyFile SourceFile, "C:\destfolder\", True
End If
Set fso = Nothing
localhost/web is equal to localhost:80/web OR to 127.0.0.1:80/web
localhost:8080/web is equal to localhost:8080/web OR to 127.0.0.1:8080/web
You can try also:
document.body.offsetHeight
document.body.offsetWidth
Go to this file in: WampFolder\apps\phpmyadmin[phpmyadmin version]\config.inc.php
Usually wamp is in your main hard drive folder C:\wamp\
You will see something like:
$cfg['Servers'][$i]['user'] = 'YOUR USER NAME IS HERE';
$cfg['Servers'][$i]['password'] = 'AND YOU PASSWORD IS HERE';
Try using the password and username that you have on that file.
SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
SELECT MAX(p2.PAYM_DATE)
FROM user_payments as p2
WHERE p2.USER_ID = p.USER_ID
)
The accepted answer was fundamentally flawed, it has since been deleted. The correct answer is:
function scrolled(e) {
if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) {
scrolledToBottom(e);
}
}
Tested this in Firefox, Chrome and Opera. It works.
In seeking to fix the problem of pop-up, I discovered that Apple had a way around this concern.
Indeed, when you click on this link, if you installed the application, it is rerouted to it; otherwise, you will be redirected to the webpage, without any pop-up.
The right way to add further configurations to the Spring Boot peconfigured ObjectMapper is to define a Jackson2ObjectMapperBuilderCustomizer. Else you are overwriting Springs configuration, which you do not want to lose.
@Configuration
public class MyJacksonConfigurer implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.deserializerByType(LocalDate.class, new MyOwnJsonLocalDateTimeDeserializer());
}
}
<img src="https://drive.google.com/uc?export=view&id=Your_Image_ID" alt="">
I use on my wordpress site as storing image files on local host takes up to much space and slows down my site
I use textmate as it is easy to edit multiple URLs at same time using the 'alt/option' button
Open the source tab in 'Developer Tools', click on a line number in a script that is running, this will create a breakpoint and the debugger will break there.
try below:
var temp_datetime_obj = new Date();
collection.find({
start_date:{
$gte: new Date(temp_datetime_obj.toISOString())
}
}).toArray(function(err, items) {
/* you can console.log here */
});
In my opinion i had missed to map my local branch with remote repo. i did below and it worked fine.
git checkout master
git remote add origin https://github.com/yourrepo/project.git
git push -u origin master
git pull
git merge myBranch1FromMain
A lazy unmount will do the job for you.
umount -l <mount path>
For this you can use .9 Patch Image and just simply set it in to background.
android:background="@drawable/spin"
Here i'll give you .9patch image. try with this.
Right click on image and click Save Image as
set image name like this : anyname.9.png and hit save.
Enjoy.. Happy Coading. :)
Uri.parse(STRING);
See doc:
String: an RFC 2396-compliant, encoded URI
Url must be canonicalized before using, like this:
Uri.parse(Uri.decode(STRING));
You're on the right track with using document.getElementById()
as you have done for your first two text boxes. Use something like document.getElementById("textbox3")
to retrieve the element. Then you can just set its value property: document.getElementById("textbox3").value = answer;
For the "Your answer is: --", I'd recommend wrapping the "--" in a <span/>
(e.g. <span id="answerDisplay">--</span>
). Then use document.getElementById("answerDisplay").textContent = answer;
to display it.
Try this, This was the solution that worked for me:
<div class="modal-dialog" style="min-width: 1500px" role="document">
Adding a link with the thumbnail, originally used by YouTube is a solution, that works. The thumbnail, used by YouTube is accessible the following way:
https://www.youtube.com/watch?v=5yLzZikS15k
https://img.youtube.com/vi/5yLzZikS15k/0.jpg
Following this logic, the code below produces flawless results:
<div align="left">
<a href="https://www.youtube.com/watch?v=5yLzZikS15k">
<img src="https://img.youtube.com/vi/5yLzZikS15k/0.jpg" style="width:100%;">
</a>
</div>
_x000D_
In older versions of jquery you'll have to do it the "javascript way" using settimeout
setTimeout( function(){$('div').hide();} , 4000);
or
setTimeout( "$('div').hide();", 4000);
Recently with jquery 1.4 this solution has been added:
$("div").delay(4000).hide();
Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.
This solved the issue:
remove.packages(c("ggplot2", "data.table"))
install.packages('Rcpp', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)
install.packages('data.table', dependencies = TRUE)
This error you are receiving :
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
is because the number of elements in $values
& $matches
is not the same or $matches
contains more than 1 element.
If $matches
contains more than 1 element, than the insert will fail, because there is only 1 column name referenced in the query(hash
)
If $values
& $matches
do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches
.
I believe you will also need to ensure the column hash has a unique index on it as well.
Try the code here:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
$values[] = '?';
}
// INSERT INTO DATABASE
$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);
//Error reporting if something went wrong...
var_dump($dbh->errorInfo());
?>
You will need to adapt it a little.
Table structure I used is here:
CREATE TABLE IF NOT EXISTS `hashes` (
`hashid` int(11) NOT NULL AUTO_INCREMENT,
`hash` varchar(250) NOT NULL,
PRIMARY KEY (`hashid`),
UNIQUE KEY `hash1` (`hash`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.
I hope this helps.
With Bootstrap >4.1 it's just a case of using the flexbox utility classes. Just have a flexbox container inside your column, and then give all the elements within it the "flex-fill" class. As with inline forms you'll need to set the margins/padding on the elements yourself.
.prop-label {_x000D_
margin: .25rem 0 !important;_x000D_
}_x000D_
_x000D_
.prop-field {_x000D_
margin-left: 1rem;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
<div class="col-12">_x000D_
<div class="d-flex">_x000D_
<label class="flex-fill prop-label">Label:</label>_x000D_
<input type="text" class="flex-fill form-control prop-field">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.
#include<stdio.h>
#include<conio.h>
void main()
{
int len=0,revnum,i,dup=0,j=0,k=0;
long int gvalue;
char ones[] [10]={"one","Two","Three","Four","Five","Six","Seven","Eight","Nine","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen",""};
char twos[][10]={"Ten","Twenty","Thirty","Fourty","fifty","Sixty","Seventy","eighty","Ninety",""};
clrscr();
printf("\n Enter value");
scanf("%ld",&gvalue);
if(gvalue==10)
printf("Ten");
else if(gvalue==100)
printf("Hundred");
else if(gvalue==1000)
printf("Thousand");
dup=gvalue;
for(i=0;dup>0;i++)
{
revnum=revnum*10+dup%10;
len++;
dup=dup/10;
}
while(j<len)
{
if(gvalue<10)
{
printf("%s ",ones[gvalue-1]);
}
else if(gvalue>10&&gvalue<=19)
{
printf("%s ",ones[gvalue-2]);
break;
}
else if(gvalue>19&&gvalue<100)
{
k=gvalue/10;
gvalue=gvalue%10;
printf("%s ",twos[k-1]);
}
else if(gvalue>100&&gvalue<1000)
{
k=gvalue/100;
gvalue=gvalue%100;
printf("%s Hundred ",ones[k-1]);
}
else if(gvalue>=1000&&gvlaue<9999)
{
k=gvalue/1000;
gvalue=gvalue%1000;
printf("%s Thousand ",ones[k-1]);
}
else if(gvalue>=11000&&gvalue<=19000)
{
k=gvalue/1000;
gvalue=gvalue%1000;
printf("%s Thousand ",twos[k-2]);
}
else if(gvalue>=12000&&gvalue<100000)
{
k=gvalue/10000;
gvalue=gvalue%10000;
printf("%s ",ones[gvalue-1]);
}
else
{
printf("");
}
j++;
getch();
}
if (x instanceof Collection<?>){
}
if (x instanceof Map<?,?>){
}
It turned out that there's a simple, standard way to achieve what I wanted:
import java.net.Authenticator;
import java.net.PasswordAuthentication;
Authenticator myAuth = new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("german", "german".toCharArray());
}
};
Authenticator.setDefault(myAuth);
No custom "sun" classes or external dependencies, and no manually encode anything.
I'm aware that BASIC security is not, well, secure, but we are also using HTTPS.
if you didn't get those above suggestions working, I use this, as it gets any date I ran this expression through 50 links, and it got all the dates on each page.
^20\d\d-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(0[1-9]|[1-2][0-9]|3[01])$
As you read through the examples below, just keep in mind this difference
true === true // true
"string" === true // false
1 === true // false
{} === true // false
But
Boolean("string") === true // true
Boolean(1) === true // true
Boolean({}) === true // true
Assertion passes when the statement passed to expect()
evaluates to true
expect(true).toBe(true) // pass
expect("123" === "123").toBe(true) // pass
In all other cases cases it would fail
expect("string").toBe(true) // fail
expect(1).toBe(true); // fail
expect({}).toBe(true) // fail
Even though all of these statements would evaluate to true
when doing Boolean()
:
So you can think of it as 'strict' comparison
This one does exactly the same type of comparison as .toBe(true)
, but was introduced in Jasmine recently in version 3.5.0
on Sep 20, 2019
toBeTruthy
on the other hand, evaluates the output of the statement into boolean first and then does comparison
expect(false).toBeTruthy() // fail
expect(null).toBeTruthy() // fail
expect(undefined).toBeTruthy() // fail
expect(NaN).toBeTruthy() // fail
expect("").toBeTruthy() // fail
expect(0).toBeTruthy() // fail
And IN ALL OTHER CASES it would pass, for example
expect("string").toBeTruthy() // pass
expect(1).toBeTruthy() // pass
expect({}).toBeTruthy() // pass
1- It's good if you use webpack for configurations but you can simply use image path and react will find out that that it's in public directory.
<img src="/image.jpg">
2- If you want to use webpack which is a standard practice in React. You can use these rules in your webpack.config.dev.js file.
module: {
rules: [
{
test: /\.(jpe?g|gif|png|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 10000
}
}
]
}
],
},
then you can import image file in react components and use it.
import image from '../../public/images/logofooter.png'
<img src={image}/>
To clarify examples given above,
"You need to use the files parameter to send a multipart form POST request even when you do not need to upload any files."
files={}
won't work, unfortunately.
You will need to put some dummy values in, e.g.
files={"foo": "bar"}
I came up against this when trying to upload files to Bitbucket's REST API and had to write this abomination to avoid the dreaded "Unsupported Media Type" error:
url = "https://my-bitbucket.com/rest/api/latest/projects/FOO/repos/bar/browse/foobar.txt"
payload = {'branch': 'master',
'content': 'text that will appear in my file',
'message': 'uploading directly from python'}
files = {"foo": "bar"}
response = requests.put(url, data=payload, files=files)
:O=
In XAML:
<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
<TextBox Name="Box" />
</StackPanel>
I would really recommend anyone entering this subject to read Addy Osmani's free book:
"Learning JavaScript Design Patterns".
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
Basically, it works like,
<table align="center">
...
But, you can do it in better way using CSS, and this will be a better approach to use CSS as it provides dynamic behavior to a web page and is responsive.
<table style="text-align:center;">
Also, if you need to display only table on a page then you can go with body tag alignment only as shown below,
<body style="text-align:center;">
<table>
...
</table>
If you want any other suggestions please let me know. Will surely help you on this. Also using bootstrap features this would be more easy and interactive.
Had a quick snoop around for this one, but this looks like it should work. I haven't tested it yet though.
File f = new File("."); // current directory
File[] files = f.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
Android icons require five separate sizes for different screen pixel densities. Icons for lower resolution are created automatically from the baseline.
mdpi (Baseline): 160 dpi 1×
hdpi: 240 dpi 1.5×
xhdpi: 320 dpi 2×
xxhdpi: 480 dpi 3×
xxxhdpi: 640 dpi 4× (launcher icon only)
Launcher icons (.Png)
48 × 48 (mdpi)
72 × 72 (hdpi)
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google Play store)
Action bar, Dialog & Tab icons
24 × 24 area in 32 × 32 (mdpi)
36 × 36 area in 48 × 48 (hdpi)
48 × 48 area in 64 × 64 (xhdpi)
72 × 72 area in 96 × 96 (xxhdpi)
96 × 96 area in 128 × 128 (xxxhdpi)*
Notification icons
22 × 22 area in 24 × 24 (mdpi)
33 × 33 area in 36 × 36 (hdpi)
44 × 44 area in 48 × 48 (xhdpi)
66 × 66 area in 72 × 72 (xxhdpi)
88 × 88 area in 96 × 96 (xxxhdpi)*
Small Contextual Icons
16 × 16 (mdpi)
24 × 24 (hdpi)
32 × 32 (xhdpi)
48 × 48 (xxhdpi)
64 × 64 (xxxhdpi)*
The xxxhdpi size needed only by the launcher icon as the Supporting multiple Screens official site says.
(function() {
var ev = new $.Event('display'),
orig = $.fn.css;
$.fn.css = function() {
orig.apply(this, arguments);
$(this).trigger(ev);
}
})();
$('#element').bind('display', function(e) {
alert("display has changed to :" + $(this).attr('style') );
});
$('#element').css("display", "none")// i change the style in this line !!
$('#element').css("display", "block")// i change the style in this line !!
http://fiddle.jshell.net/prollygeek/gM8J2/3/
changes will be alerted.
For those who fear to mess anything up in your vscode json settings this is pretty easy to follow.
Open "File -> Preferences -> Keyboard Shortcuts"
or "Code -> Preferences -> Keyboard Shortcuts"
for Mac Users
In the search bar type transform
.
By default you will not have anything under Keybinding
. Now double-click on Transform to Lowercase
or Transform to Uppercase
.
Press your desired combination of keys to set your keybinding. In this case if copying off of Sublime i will press ctrl+shift+u
for uppercase or ctrl+shift+l
for lowercase.
Press Enter
on your keyboard to save and exit. Do same for the other option.
Enjoy KEYBINDING
aString = "hello world"
aString.startswith("hello")
More info about startswith
.
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.
Note that in an XML Declaration the encoding
and standalone
are both optional. Only the version
is mandatory. Also, these are not attributes, so if they are present they must be in that order: version
, followed by any encoding
, followed by any standalone
.
<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" standalone="yes"?>
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.
The standalone
indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.
Update:
A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.
Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?>
which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding
and simply say <?xml version="1.0"?>
. You could also edit it to say encoding="UTF-16"
but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.
Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!
Looks like you missed some options, try to add:
position: relative;
top: 25px;
echo do_shortcode('[CONTACT-US-FORM]');
Use this in your template.
Look here for more: Do Shortcode
for x in y[:-1]
If y
is a generator, then the above will not work.
I have done a microbenchmark (JMH) to compare Moneta (java currency JSR 354 implementation) against BigDecimal in terms of performance.
Surprisingly, BigDecimal performance seems to be better than moneta's. I have used following moneta config:
org.javamoney.moneta.Money.defaults.precision=19 org.javamoney.moneta.Money.defaults.roundingMode=HALF_UP
package com.despegar.bookedia.money;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.openjdk.jmh.annotations.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.concurrent.TimeUnit;
@Measurement(batchSize = 5000, iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS)
@Warmup(iterations = 2)
@Threads(value = 1)
@Fork(value = 1)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
public class BigDecimalBenchmark {
private static final Money MONEY_BASE = Money.of(1234567.3444, "EUR");
private static final Money MONEY_SUBSTRACT = Money.of(232323, "EUR");
private static final FastMoney FAST_MONEY_SUBSTRACT = FastMoney.of(232323, "EUR");
private static final FastMoney FAST_MONEY_BASE = FastMoney.of(1234567.3444, "EUR");
MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
@Benchmark
public void bigdecimal_string() {
new BigDecimal("1234567.3444").subtract(new BigDecimal("232323")).multiply(new BigDecimal("3.4"), mc).divide(new BigDecimal("5.456"), mc);
}
@Benchmark
public void bigdecimal_valueOf() {
BigDecimal.valueOf(12345673444L, 4).subtract(BigDecimal.valueOf(232323L)).multiply(BigDecimal.valueOf(34, 1), mc).divide(BigDecimal.valueOf(5456, 3), mc);
}
@Benchmark
public void fastmoney() {
FastMoney.of(1234567.3444, "EUR").subtract(FastMoney.of(232323, "EUR")).multiply(3.4).divide(5.456);
}
@Benchmark
public void money() {
Money.of(1234567.3444, "EUR").subtract(Money.of(232323, "EUR")).multiply(3.4).divide(5.456);
}
@Benchmark
public void money_static(){
MONEY_BASE.subtract(MONEY_SUBSTRACT).multiply(3.4).divide(5.456);
}
@Benchmark
public void fastmoney_static() {
FAST_MONEY_BASE.subtract(FAST_MONEY_SUBSTRACT).multiply(3.4).divide(5.456);
}
}
Resulting in
Benchmark Mode Cnt Score Error Units
BigDecimalBenchmark.bigdecimal_string thrpt 10 479.465 ± 26.821 ops/s
BigDecimalBenchmark.bigdecimal_valueOf thrpt 10 1066.754 ± 40.997 ops/s
BigDecimalBenchmark.fastmoney thrpt 10 83.917 ± 4.612 ops/s
BigDecimalBenchmark.fastmoney_static thrpt 10 504.676 ± 21.642 ops/s
BigDecimalBenchmark.money thrpt 10 59.897 ± 3.061 ops/s
BigDecimalBenchmark.money_static thrpt 10 184.767 ± 7.017 ops/s
Please feel free to correct me if i'm missing something
Don't pass id(pk) to persist method or try save() method instead of persist().
Here's what I found at https://perldoc.perl.org/perlvar.html:
$\ The output record separator for the print operator. If defined, this value is printed after the last of print's arguments. Default is undef.
You cannot call output_record_separator() on a handle, only as a static method. See IO::Handle.
Mnemonic: you set $\ instead of adding "\n" at the end of the print. Also, it's just like $/ , but it's what you get "back" from Perl.
example:
$\ = "\n";
print "a newline will be appended to the end of this line automatically";
z-index
property enables you to take your control at front. the bigger number you set the upper your element you get.
position
property should be relative
because position of html-element
should be position relatively against other controls in all dimensions.
element.style {
position:relative;
z-index:1000; //change your number as per elements lies on your page.
}
Using the Script console at https://my-jenkins/script
import hudson.model.Job
import org.jenkinsci.plugins.workflow.job.WorkflowRun
Collection<Job> jobs = Jenkins.instance.getItem('My-Folder').getAllJobs()
for (int i = 0; i < jobs.size(); i++) {
def job = jobs[i]
for (int j = 0; j < job.builds.size(); j++) {
WorkflowRun build = job.builds[j]
if (build.isBuilding()) {
println("Stopping $job ${build.number}")
build.setResult(Result.FAILURE)
}
}
}
To visualise, take your keyboard's numpad. If the key '5' represents your rectangle, then all the keys 1-9 represent the 9 quadrants of space divided by the lines that make up your rectangle (with 5 being the inside.)
1) If the circle's center is in quadrant 5 (i.e. inside the rectangle) then the two shapes intersect.
With that out of the way, there are two possible cases: a) The circle intersects with two or more neighboring edges of the rectangle. b) The circle intersects with one edge of the rectangle.
The first case is simple. If the circle intersects with two neighboring edges of the rectangle, it must contain the corner connecting those two edges. (That, or its center lies in quadrant 5, which we have already covered. Also note that the case where the circle intersects with only two opposing edges of the rectangle is covered as well.)
2) If any of the corners A, B, C, D of the rectangle lie inside the circle, then the two shapes intersect.
The second case is trickier. We should make note of that it may only happen when the circle's center lies in one of the quadrants 2, 4, 6 or 8. (In fact, if the center is on any of the quadrants 1, 3, 7, 8, the corresponding corner will be the closest point to it.)
Now we have the case that the circle's center is in one of the 'edge' quadrants, and it only intersects with the corresponding edge. Then, the point on the edge that is closest to the circle's center, must lie inside the circle.
3) For each line AB, BC, CD, DA, construct perpendicular lines p(AB,P), p(BC,P), p(CD,P), p(DA,P) through the circle's center P. For each perpendicular line, if the intersection with the original edge lies inside the circle, then the two shapes intersect.
There is a shortcut for this last step. If the circle's center is in quadrant 8 and the edge AB is the top edge, the point of intersection will have the y-coordinate of A and B, and the x-coordinate of center P.
You can construct the four line intersections and check if they lie on their corresponding edges, or find out which quadrant P is in and check the corresponding intersection. Both should simplify to the same boolean equation. Be wary of that the step 2 above did not rule out P being in one of the 'corner' quadrants; it just looked for an intersection.
Edit: As it turns out, I have overlooked the simple fact that #2 is a subcase of #3 above. After all, corners too are points on the edges. See @ShreevatsaR's answer below for a great explanation. And in the meanwhile, forget #2 above unless you want a quick but redundant check.
wmic product get name
Just gets the cmd stuck... still flashing _ after a couple minutes
in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
, if you can find the folder with the software name you are trying to install (not the one named with ProductCode), the UninstallString points to the application's own uninstaller C:\Program Files\Zune\ZuneSetup.exe /x
Watch this... http://www.asp.net/mvc/videos/mvc-2/how-do-i/aspnet-mvc-2-areas
Then this picture (hope u like my drawings)
You forgot to call startActivity. It should look like this:
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + bundle.getString("mobilePhone")));
context.startActivity(intent);
An intent by itself is simply an object that describes something. It doesn't do anything.
Don't forget to add the relevant permission to your manifest:
<uses-permission android:name="android.permission.CALL_PHONE" />
function isPrime(num) {
for(var i = 2; i < num; i++)
if(num % i === 0) return false;
return num ;
}
function primes(n){
var array_of_primes=[];
for(var i = 2; i < n; i++){
if(isPrime(i)) array_of_primes.push(i)>1;
}
return array_of_primes;
}
document.write(primes(10000));
you can write for all user list :
sudo crontab -u userName -l
,
You can also go to
cd /etc/cron.daily/
ls -l
cat filename
this file will list the schedules
cd /etc/cron.d/
ls -l
cat filename
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
exports
and module.exports
are the same unless you reassign exports
within your module.
The easiest way to think about it, is to think that this line is implicitly at the top of every module.
var exports = module.exports = {};
If, within your module, you reassign exports
, then you reassign it within your module and it no longer equals module.exports
. This is why, if you want to export a function, you must do:
module.exports = function() { ... }
If you simply assigned your function() { ... }
to exports
, you would be reassigning exports
to no longer point to module.exports
.
If you don't want to refer to your function by module.exports
every time, you can do:
module.exports = exports = function() { ... }
Notice that module.exports
is the left most argument.
Attaching properties to exports
is not the same since you are not reassigning it. That is why this works
exports.foo = function() { ... }
This might not be applicable to all scenarios, but I found that the position: sticky
(same thing with position: fixed
) only works on old iPhones when the scrolling container is not the body, but inside something else.
Example pseudo html:
body <- scrollbar
relative div
sticky div
The sticky div will be sticky on desktop browsers, but with certain devices, tested with: Chromium: dev tools: device emultation: iPhone 6/7/8, and with Android 4 Firefox, it will not.
What will work, however, is
body
div overflow=auto <- scrollbar
relative div
sticky div
npm install -g @angular/cli
helped for me instead of npm install @angular/cli
To me the problem was related with the project that I was working on. It took me a while to figure it out, so I hope this helps:
Original folder structure:
root/
__init__.py # Empty
folder/
__init__.py # Empty
sub_folder_b/
my_code.py
sub_folder_c/
another_code.py
In another_code.py:
from folder.sub_folder_b import my_code.py
This didn't trigger the intellisense in Visual Studio Code, but it did execute OK.
On the other hand, adding "root" on the import path, did make the intellisense work, but raised ModuleNotFoundError when executing:
from root.folder.sub_folder_b import my_code.py
The solution was to remove the _init_.py file inside the "folder" directory, leaving only the _init_.py located at /root
.
What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.
To do this after half day searching did it using:
docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb
This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.
To login in mysql after that can use:
mysql -u root -proot -h 127.0.0.1 -P3301
Used sources are:
The answer of Iarks in this article /using -it -d was the key :) /
how-to-install-and-use-docker-on-ubuntu-16-04
installing-and-using-mariadb-via-docker
mariadb-and-docker-use-cases-part-1
Good luck all!
I use this:
function strip_word_html($text, $allowed_tags = '<a><ul><li><b><i><sup><sub><em><strong><u><br><br/><br /><p><h2><h3><h4><h5><h6>')
{
mb_regex_encoding('UTF-8');
//replace MS special characters first
$search = array('/‘/u', '/’/u', '/“/u', '/”/u', '/—/u');
$replace = array('\'', '\'', '"', '"', '-');
$text = preg_replace($search, $replace, $text);
//make sure _all_ html entities are converted to the plain ascii equivalents - it appears
//in some MS headers, some html entities are encoded and some aren't
//$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
//try to strip out any C style comments first, since these, embedded in html comments, seem to
//prevent strip_tags from removing html comments (MS Word introduced combination)
if(mb_stripos($text, '/*') !== FALSE){
$text = mb_eregi_replace('#/\*.*?\*/#s', '', $text, 'm');
}
//introduce a space into any arithmetic expressions that could be caught by strip_tags so that they won't be
//'<1' becomes '< 1'(note: somewhat application specific)
$text = preg_replace(array('/<([0-9]+)/'), array('< $1'), $text);
$text = strip_tags($text, $allowed_tags);
//eliminate extraneous whitespace from start and end of line, or anywhere there are two or more spaces, convert it to one
$text = preg_replace(array('/^\s\s+/', '/\s\s+$/', '/\s\s+/u'), array('', '', ' '), $text);
//strip out inline css and simplify style tags
$search = array('#<(strong|b)[^>]*>(.*?)</(strong|b)>#isu', '#<(em|i)[^>]*>(.*?)</(em|i)>#isu', '#<u[^>]*>(.*?)</u>#isu');
$replace = array('<b>$2</b>', '<i>$2</i>', '<u>$1</u>');
$text = preg_replace($search, $replace, $text);
//on some of the ?newer MS Word exports, where you get conditionals of the form 'if gte mso 9', etc., it appears
//that whatever is in one of the html comments prevents strip_tags from eradicating the html comment that contains
//some MS Style Definitions - this last bit gets rid of any leftover comments */
$num_matches = preg_match_all("/\<!--/u", $text, $matches);
if($num_matches){
$text = preg_replace('/\<!--(.)*--\>/isu', '', $text);
}
$text = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $text);
return $text;
}
If anyone else simply wants to display a black image as a background, here e.g. for 500x500 px:
import cv2
import numpy as np
black_screen = np.zeros([500,500,3])
cv2.imshow("Simple_black", black_screen)
cv2.waitKey(0)
For those, who faced
stat: unrecognized option: format
when executed the line from Heppo's answer (find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
)
Please try the -c
key to replace --format
and finally the call will be:
find $1 -type f -exec stat -c '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
That worked for me inside of some Docker containers, where stat
was not able to use --format
option.
then is a method callback stack which is available after a promise is resolved it is part of library like jQuery but now it is available in native JavaScript and below is the detail explanation how it works
You can do a Promise in native JavaScript : just like there are promises in jQuery, Every promise can be stacked and then can be called with Resolve and Reject callbacks, This is how you can chain asynchronous calls.
I forked and Edited from MSDN Docs on Battery charging status..
What this does is try to find out if user laptop or device is charging battery. then is called and you can do your work post success.
navigator
.getBattery()
.then(function(battery) {
var charging = battery.charging;
alert(charging);
})
.then(function(){alert("YeoMan : SINGH is King !!");});
function fetchAsync (url, timeout, onData, onError) {
…
}
let fetchPromised = (url, timeout) => {
return new Promise((resolve, reject) => {
fetchAsync(url, timeout, resolve, reject)
})
}
Promise.all([
fetchPromised("http://backend/foo.txt", 500),
fetchPromised("http://backend/bar.txt", 500),
fetchPromised("http://backend/baz.txt", 500)
]).then((data) => {
let [ foo, bar, baz ] = data
console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
}, (err) => {
console.log(`error: ${err}`)
})
Definition :: then is a method used to solve Asynchronous callbacks
this is introduced in ES6
Please find the proper documentation here Es6 Promises
No.
You need to write a wrapper in PHP, and then export the returned data (probably as Json). NEVER, get from your "_GET" the SQL code, as this is called an SQL injection (people who learn this will have full control over your database).
This is an example I wrote:
function getJsonData()
{
global $db;
if (!$db->isConnected()) {
return "Not connected";
}
$db->query("SELECT * FROM entries");
$values = array();
while( $v = $db->fetchAssoc()){
$values[] = $v;
}
return json_encode($values);
}
switch (@$_GET["cmd"]){
case 'data':
print getJsonData();
exit;
default:
print getMainScreen();
exit;
}
Do learn about SQL injections please.
Markdown really changes everything to html and html collapses spaces so you really can't do anything about it. You have to use the
for it. A funny example here that I'm writing in markdown and I'll use couple of here.
Above there are some
without backticks
The following also can be tried:
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
or use the other setting options in the DataGridViewAutoSizeColumnsMode Enum
Why remove value? its useful, but why not try CSS
input[submit] {
font-size: 0 !important;
}
Value is important to check & validate ur PHP
To correctly save the instance state of Fragment
you should do the following:
1. In the fragment, save instance state by overriding onSaveInstanceState()
and restore in onActivityCreated()
:
class MyFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
if (savedInstanceState != null) {
//Restore the fragment's state here
}
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's state here
}
}
2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState()
and restore in onCreate()
.
class MyActivity extends Activity {
private MyFragment
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
//Restore the fragment's instance
mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
...
}
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
}
}
Hope this helps.
You can use HttpRequestMessagesExtensions.CreateErrorResponse (System.Net.Http
namespace), like so:
public IHttpActionResult Get()
{
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Message describing the error here"));
}
It is preferable to create responses based on the request to take advantage of Web API's content negotiation.
Do I use one of these then cast to an Int?
Yes. There is no problem doing that. Decimals and doubles can represent integers exactly, so there will be no representation error. (You won't get a case, for instance, where Round returns 4.999... instead of 5.)
The datetime
module will do all the work for you:
>>> import datetime
>>> a = datetime.datetime.now()
>>> # ...wait a while...
>>> b = datetime.datetime.now()
>>> print(b-a)
0:03:43.984000
If you don't want to display the microseconds, just use (as gnibbler suggested):
>>> a = datetime.datetime.now().replace(microsecond=0)
>>> b = datetime.datetime.now().replace(microsecond=0)
>>> print(b-a)
0:03:43
$blog is an object not an array
try using $blog->id
instead of $blog['id']
Have you checked MZTools?? It does a lot of cool stuff...
If I'm not wrong, one of the functionalities it offers is to set your own shortcuts.
Here are the steps provided by the Gitlab:
cd existing_repo
git remote rename origin old-origin
git remote add origin https://gitlab.example.com/rmishra/demoapp.git
git push -u origin --all
git push -u origin --tags
All above answers are good but for information, we can use int.TryParse
which is safe to convert string to int , example
// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
Console.WriteLine(j);
else
Console.WriteLine("String could not be parsed.");
// Output: -105
TryParse never throws an exception—even on invalid input and null. It is overall preferable to int.Parse in most program contexts.
Source: How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)
In linux, just run it, no problem. In Windows, you want to use the pythonw executable.
Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?
$ nohup mypythonprog &
C:/> start pythonw mypythonprog
I think that's right. In any case, now you can close the terminal.
Though I tend to agree with @AlekDavis' comment, there are nonetheless several ways to do this in the NT shell.
The approach I would take advantage of the SHIFT command and IF conditional branching, something like this...
@ECHO OFF
SET man1=%1
SET man2=%2
SHIFT & SHIFT
:loop
IF NOT "%1"=="" (
IF "%1"=="-username" (
SET user=%2
SHIFT
)
IF "%1"=="-otheroption" (
SET other=%2
SHIFT
)
SHIFT
GOTO :loop
)
ECHO Man1 = %man1%
ECHO Man2 = %man2%
ECHO Username = %user%
ECHO Other option = %other%
REM ...do stuff here...
:theend
Steve Jessop's answer did not work for me. I read the help files for SVN and if you just have an image you probably don't want to check it in again unless you're doing Photoshop, so export is a better command than checkout as it's unversioned (but that is minor).
And the --depth ARG should not be empty but files to get the files in the immediate directory. So you'll get all the fields, not just the one, but empty returns nothing from the repository.
svn co --depth files <source> <local dest>
or
svn export --depth files <source> <local dest>
As for the other answers, cat lets you read the content which is good only for text, not images of all things.
Let's say you have already set up your origin
as the remote repository. Then,
git diff <local branch> <origin>/<remote branch name>
try this
provider = new CultureInfo("en-US");
DateTime.ParseExact("9/1/2009", "M/d/yyyy", provider);
Bye.
This works:
myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");
You can use the _contains function from the underscore.js library to achieve this:
if (_.contains(haystack, needle)) {
console.log("Needle found.");
};
You can loop the array with a for loop and the object properties with for-in loops.
for (var i=0; i<result.length; i++)
for (var name in result[i]) {
console.log("Item name: "+name);
console.log("Source: "+result[i][name].sourceUuid);
console.log("Target: "+result[i][name].targetUuid);
}
For me just worked iisreset (run cmd as administrator -> iisreset). Maybe somebody could give it a try.
I ran into a similar issue today - my ruby version didn't match my rvm installs.
> ruby -v
ruby 2.0.0p481
> rvm list
rvm rubies
ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
ruby-2.2.3 [ x86_64 ]
Also, rvm current
failed.
> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...
The error message recommended this useful command, which resolved the issue for me:
> rvm get stable --auto-dotfiles
I would use:
val, idx = min((val, idx) for (idx, val) in enumerate(my_list))
Then val
will be the minimum value and idx
will be its index.
The standard library includes the ordered and the unordered map (std::map
and std::unordered_map
) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.
An example with (ordered) std::map
:
#include <map>
#include <iostream>
#include <cassert>
int main(int argc, char **argv)
{
std::map<std::string, int> m;
m["hello"] = 23;
// check if key is present
if (m.find("world") != m.end())
std::cout << "map contains key world!\n";
// retrieve
std::cout << m["hello"] << '\n';
std::map<std::string, int>::iterator i = m.find("hello");
assert(i != m.end());
std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
return 0;
}
Output:
23 Key: hello Value: 23
If you need ordering in your container and are fine with the O(log n) runtime then just use std::map
.
Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map
, which has a similar to std::map
API (e.g. in the above example you just have to search and replace map
with unordered_map
).
The unordered_map
container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11
to the CXXFLAGS).
Even before the C++11 release GCC supported unordered_map
- in the namespace std::tr1
. Thus, for old GCC compilers you can try to use it like this:
#include <tr1/unordered_map>
std::tr1::unordered_map<std::string, int> m;
It is also part of boost, i.e. you can use the corresponding boost-header for better portability.
Here is my answer in Python 2.7
from datetime import datetime
import tzlocal # pip install tzlocal
print datetime.now(tzlocal.get_localzone()).strftime("%Y-%m-%d %H:%M:%S %z")
from datetime import datetime
import pytz # pip install pytz
print datetime.now(pytz.timezone('Asia/Taipei')).strftime("%Y-%m-%d %H:%M:%S %z")
It will print something like
2017-08-10 20:46:24 +0800
Assuming your sequence alternates increments between 1 and 3
numbers = [1]
while numbers[-1] < 100:
numbers.append(numbers[-1] + 1)
numbers.append(numbers[-1] + 3)
print ', '.join(map(str, numbers))
This could be easier to modify if your sequence is different but I think poke or BlaXpirit are nicer answers than mine.
Always use tax_query to get posts/products from a particular category or any other taxonomy. You can also get the products using ID/slug of particular taxonomy...
$the_query = new WP_Query( array(
'post_type' => 'product',
'tax_query' => array(
array (
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories',
)
),
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
the_title(); echo "<br>";
endwhile;
wp_reset_postdata();
If you would like to indent text within a div without changing the size of the div use the CSS text-indent
instead of padding-left
.
.indent {_x000D_
text-indent: 1em;_x000D_
}_x000D_
.border {_x000D_
border-style: solid;_x000D_
}
_x000D_
<div class="border">_x000D_
Non indented_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="border indent">_x000D_
Indented_x000D_
</div>
_x000D_
Rotate by 90 degress around 0,0:
x' = -y
y' = x
Rotate by 90 degress around px,py:
x' = -(y - py) + px
y' = (x - px) + py
Use SQL Server's date styles to pre-format your date values.
SELECT
CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero -- Date Style 101 = mm/dd/yyyy
,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero -- Date Style 103 = dd/mm/yyyy
Use echo to insert the tab for you grep "$(echo -e \\t)"
Romain Guy is where it's at.
Minified version as follows.
Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.image)).getBitmap();
Bitmap bitmapRounded = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
Canvas canvas = new Canvas(bitmapRounded);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
canvas.drawRoundRect((new RectF(0.0f, 0.0f, bitmap.getWidth(), bitmap.getHeight())), 10, 10, paint);
imageView.setImageBitmap(bitmapRounded);
The problem
I was seeing lots of cells say #REF!
. These are cells in a sheet that I copied from another Google Sheet doc using "Copy to > Existing Worksheet". If I press Enter in any cell, it recalculates correctly, But I don't want to do that for millions of cells.
My answer
I ran this recalcSheet()
script. It takes almost 0.5 seconds per cell, which is very slow but is faster than manually fixing each cell.
function recalcSheet(){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet = spreadsheet.getSheetByName("put_your_sheet_name_here"); // https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheetbynamename
// var range = sheet.getSelection().getActiveRange();
// var range = sheet.getRange('A6:D6');
var range = sheet.getDataRange();
recalcRange(range, spreadsheet);
}
function recalcRange(range, spreadsheet){
// following structure of https://stackoverflow.com/a/52123839/470749
Logger.log('Range: ' + range.getA1Notation());
var numRows = range.getNumRows();
var numCols = range.getNumColumns();
var startRow = range.getRow();
var startCol = range.getColumn();
Logger.log('row: ' + startRow);
Logger.log('col: ' + startCol);
Logger.log('numRows: ' + numRows);
Logger.log('numCols: ' + numCols);
for (var r = 1; r <= numRows; r+=1) {
for (var c = 1; c <= numCols; c+=1) {
var originalFormula = range.getCell(r, c).getFormula(); // https://developers.google.com/apps-script/reference/spreadsheet/range#getFormula()
Logger.log(`r,c ${r}, ${c}; originalFormula: ${originalFormula}`);
if(originalFormula){
range.getCell(r, c).setFormula('');
//SpreadsheetApp.flush(); // https://webapps.stackexchange.com/a/35970/27487
range.getCell(r, c).setFormula(originalFormula);
}
}
}
spreadsheet.toast('Each cell in the range has been recalculated.', "Finished!"); // https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#toast(String)
}
In addition to above answers, another way of doing it is $_SERVER['PHP_SELF']
or simply using an empty string is to use __DIR__
.
OR
If you're on a lower PHP version (<5.3), a more common alternative is to use dirname(__FILE__)
Both returns the folder name of the file in context.
EDIT
As Boann pointed out that this returns the on-disk location of the file. WHich you would not ideally expose as a url. In that case dirname($_SERVER['PHP_SELF'])
can return the folder name of the file in context.
<Route name="app" path="/" handler={App}>
<Route name="dashboards" path="dashboards" handler={Dashboard}>
<Route name="exploreDashboard" path="exploreDashboard" handler={ExploreDashboard} />
<Route name="searchDashboard" path="searchDashboard" handler={SearchDashboard} />
<DefaultRoute handler={DashboardExplain} />
</Route>
<Redirect from="/*" to="/" />
</Route>
Here's my solution to the problem using MooTools which works in Firefox 3.6, Safari 4.0.4 and Internet Explorer 7:
var iframe_container = $('iframe_container_id');
var iframe_style = {
height: 300,
width: '100%'
};
if (!Browser.Engine.trident) {
// IE has hasLayout issues if iframe display is none, so don't use the loading class
iframe_container.addClass('loading');
iframe_style.display = 'none';
}
this.iframe = new IFrame({
frameBorder: 0,
src: "http://www.youriframeurl.com/",
styles: iframe_style,
events: {
'load': function() {
var innerDoc = (this.contentDocument) ? this.contentDocument : this.contentWindow.document;
var h = this.measure(function(){
return innerDoc.body.scrollHeight;
});
this.setStyles({
height: h.toInt(),
display: 'block'
});
if (!Browser.Engine.trident) {
iframe_container.removeClass('loading');
}
}
}
}).inject(iframe_container);
Style the "loading" class to show an Ajax loading graphic in the middle of the iframe container. Then for browsers other than Internet Explorer, it will display the full height IFRAME once the loading of its content is complete and remove the loading graphic.
if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:
set.seed(10)
x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]
cor(x)
Error in cor(x) : 'x' must be numeric
but
cor(x[sapply(x, is.numeric)])
V1 V2 V3 V4 V5 V6 V7
V1 1.00000000 0.3025766 -0.22473884 -0.72468776 0.18890578 0.14466161 0.05325308
V2 0.30257657 1.0000000 -0.27871430 -0.29075170 0.16095258 0.10538468 -0.15008158
V3 -0.22473884 -0.2787143 1.00000000 -0.22644156 0.07276013 -0.35725182 -0.05859479
V4 -0.72468776 -0.2907517 -0.22644156 1.00000000 -0.19305921 0.16948333 -0.01025698
V5 0.18890578 0.1609526 0.07276013 -0.19305921 1.00000000 0.07339531 -0.31837954
V6 0.14466161 0.1053847 -0.35725182 0.16948333 0.07339531 1.00000000 0.02514081
V7 0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954 0.02514081 1.00000000
V8 0.44705527 0.1698571 0.39970105 -0.42461411 0.63951574 0.23065830 -0.28967977
V9 0.21006372 -0.4418132 -0.18623823 -0.25272860 0.15921890 0.36182579 -0.18437981
V10 0.02326108 0.4618036 -0.25205899 -0.05117037 0.02408278 0.47630138 -0.38592733
V8 V9 V10
V1 0.447055266 0.210063724 0.02326108
V2 0.169857120 -0.441813231 0.46180357
V3 0.399701054 -0.186238233 -0.25205899
V4 -0.424614107 -0.252728595 -0.05117037
V5 0.639515737 0.159218895 0.02408278
V6 0.230658298 0.361825786 0.47630138
V7 -0.289679766 -0.184379813 -0.38592733
V8 1.000000000 0.001023392 0.11436143
V9 0.001023392 1.000000000 0.15301699
V10 0.114361431 0.153016985 1.00000000
McAfee was blocking it for me. I had to allow the program in the access protection rules
See http://www.symantec.com/connect/articles/we-are-unable-send-your-email-caused-mcafee
In case this helps anyone who was in my situation: I recently installed Fiddler, which (unbeknownst to me) added a network proxy through 127.0.0.1:8866
. I went into my Ubuntu network settings, clicked into the "Network Proxy" settings, and disabled it, and then all was back to normal.
So in general, check to make sure you haven't got a network proxy set up due to a side-effect of something else you were doing.
static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly defined in classes, as well as to perform standard conversions between fundamental types:
double d = 3.14159265;
int i = static_cast<int>(d);
for(n in 1:5) {
if(n==3) next # skip 3rd iteration and go to next iteration
cat(n)
}
My preferred method:
if (*ptr == 0) // empty string
Probably more common:
if (strlen(ptr) == 0) // empty string
The way that Magento themes handle actual url's is as such (in view partials - phtml files):
echo $this->getSkinUrl('images/logo.png');
If you need the actual base path on disk to the image directory use:
echo Mage::getBaseDir('skin');
Some more base directory types are available in this great blog post:
move.CompleteMove()
does not return a value (perhaps it just prints something). Any method that does not return a value returns None
, and you have assigned None
to self.values
.
Here is an example of this:
>>> def hello(x):
... print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>
You'll note y
doesn't print anything, because its None
(the only value that doesn't print anything on the interactive prompt).
import string
import random
def random_char(y):
return ''.join(random.choice(string.ascii_letters+string.digits+li) for x in range(y))
no=int(input("Enter the number of character for your password= "))
li = random.choice('!@#$%^*&( )_+}{')
print(random_char(no)+li)
You need this tool and you can find the transaction and reverse it.
This error comes with Android Studio lower than 2.4 when you try to enable Java 8 features in gradle settings following the instruction. Error can be reproduced in a new project with those gradle settings.
A higher version is needed, or a preview one.
def Hanoi(n, A, B, C):
if(n==1): print "move plates to empty peg"
else:
Hanoi(n-1, A, B, C)
print "move"+str(n)+" to peg "+C
Hanoi(n-1, B, C, A)
I've found this useful:
select translate('your string','_0123456789','_') from dual
If the result is NULL, it's numeric (ignoring floating point numbers.)
However, I'm a bit baffled why the underscore is needed. Without it the following also returns null:
select translate('s123','0123456789', '') from dual
There is also one of my favorite tricks - not perfect if the string contains stuff like "*" or "#":
SELECT 'is a number' FROM dual WHERE UPPER('123') = LOWER('123')
try this package, works wonders, and was made for date/time...
library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)
I was able to get rid of my scroll bar on the body of text by removing my max-height attribute of my class.
Some times there are problems with funtion/features that do not interact with the DOM
try to change the value sharply and then assign the $scope
document.getElementById ("textWidget") value = "<NewVal>";
$scope.widget.title = "<NewVal>";
If you're in a Navigation Controller:
ViewController *viewController = [[ViewController alloc] init];
[self.navigationController pushViewController:viewController animated:YES];
or if you just want to present a new view:
ViewController *viewController = [[ViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild
ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers
parameter. Then each process will start 25 threads determined by ThreadsPerChild
parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit
parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients
is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients
. This also means that if I set MaxClients
to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient
parameter. In this case, we need to also increase ServerLimit
to 1000/25 i.e. MaxClients/ThreadsPerChild=40
So this is the optmized configuration to server 1000 clients
<IfModule mpm_worker_module>
ServerLimit 40
StartServers 2
MaxClients 1000
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
Full description how to use resources: WPF Application Resource, Content, and Data Files
And how to reference them, read "Pack URIs in WPF".
In short, there is even means to reference resources from referenced/referencing assemblies.
just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:
<form name='add'>
Age: <select name='age'>
<option value='1_sre'>23</option>
<option value='2_sam>24</option>
<option value='5_john>25</option>
</select>
<input type='submit' name='submit'/>
</form>
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]
You can try this:
$( 'select' ).each( function () {
if ( $( this ).children().length > 0 ) {
$( $( this ).children()[0] ).attr( 'selected', 'selected' );
$( this ).change();
}
} );
first select datagrid and then go to properties find Datagrid_AutoGeneratingColumn and the double click And then use this code
Datagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "Your column name")
(e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
if (e.PropertyName == "Your column name")
(e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
}
I try it it works on WPF
See also question: Can I create a custom classpath on a per application basis in Tomcat
Tomcat 7 Context hold Loader element. According to docs deployment descriptor (what in <Context>
tag) can be placed in:
$CATALINA_BASE/conf/server.xml
- bad - require server restarts in order to reread config$CATALINA_BASE/conf/context.xml
- bad - shared across all applications$CATALINA_BASE/work/$APP.war:/META-INF/context.xml
- bad - require repackaging in order to change config$CATALINA_BASE/work/[enginename]/[hostname]/$APP/META-INF/context.xml
- nice, but see last option!!$CATALINA_BASE/webapps/$APP/META-INF/context.xml
- nice, but see last option!!$CATALINA_BASE/conf/[enginename]/[hostname]/$APP.xml
- best - completely out of application and automatically scanned for changes!!!Here my config which demonstrate how to use development version of project files out of $CATALINA_BASE
hierarchy (note that I place this file into src/test/resources
dir and intruct Maven to preprocess ${basedir}
placeholders through pom.xml
<filtering>true</filtering>
so after build in new environment I copy it to $CATALINA_BASE/conf/Catalina/localhost/$APP.xml
):
<Context docBase="${basedir}/src/main/webapp"
reloadable="true">
<!-- http://tomcat.apache.org/tomcat-7.0-doc/config/context.html -->
<Resources className="org.apache.naming.resources.VirtualDirContext"
extraResourcePaths="/WEB-INF/classes=${basedir}/target/classes,/WEB-INF/lib=${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
<Loader className="org.apache.catalina.loader.VirtualWebappLoader"
virtualClasspath="${basedir}/target/classes;${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
<JarScanner scanAllDirectories="true"/>
<!-- Use development version of JS/CSS files. -->
<Parameter name="min" value="dev"/>
<Environment name="app.devel.ldap" value="USER" type="java.lang.String" override="true"/>
<Environment name="app.devel.permitAll" value="true" type="java.lang.String" override="true"/>
</Context>
UPDATE Tomcat 8 change syntax for <Resources>
and <Loader>
elements, corresponding part now look like:
<Resources>
<PostResources className="org.apache.catalina.webresources.DirResourceSet"
webAppMount="/WEB-INF/classes" base="${basedir}/target/classes" />
<PostResources className="org.apache.catalina.webresources.DirResourceSet"
webAppMount="/WEB-INF/lib" base="${basedir}/target/${project.build.finalName}/WEB-INF/lib" />
</Resources>
you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)
<script>
var time = 3670;
window.setInterval(function(){
// Time calculations for days, hours, minutes and seconds
var h = Math.floor(time / 3600);
var m = Math.floor(time % 3600 / 60);
var s = Math.floor(time % 3600 % 60);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = h + "h "
+ m + "m " + s + "s ";
// If the count down is finished, write some text
if (time < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
time--;
}, 1000);
</script>
data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")
You can also create shapes directly inside the item
tag, in case you want to add some more details to your view, like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="#81ba73" />
<corners android:radius="6dp" />
</shape>
<ripple android:color="#c62828"/>
</item>
<item android:state_enabled="false">
<shape>
<solid android:color="#788e73" />
<corners android:radius="6dp" />
</shape>
</item>
<item>
<shape>
<solid android:color="#add8a3" />
<corners android:radius="6dp" />
</shape>
</item>
</selector>
Beware that Android will cycle through the items from top to bottom, therefore, you must place the item
without condition on the bottom of the list (so it acts like a default/fallback).
The easiest workaround is create dummy labels in IB, give them the text the color you like and set to hidden. You can then reference this color in your code to set your label to the desired color.
yourLabel.textColor = hiddenLabel.textColor
The only way I could change the text color programmatically was by using the standard colors, UIColor.white
, UIColor.green
...
If you mean a python script, just do something like this:
import importlib.util
import sys
# For illustrative purposes.
name = 'itertools'
if name in sys.modules:
print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
# If you choose to perform the actual import ...
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
print(f"{name!r} has been imported")
else:
print(f"can't find the {name!r} module")
try:
import mymodule
except ImportError as e:
pass # module doesn't exist, deal with it.
try:
import mymodule
except ImportError, e:
pass # module doesn't exist, deal with it.
It seems that there is no official solution for this problem, but there is a workaround posted here https://github.com/savoirfairelinux/python-docx/commit/afd9fef6b2636c196761e5ed34eb05908e582649
just update this file "...\site-packages\docx\oxml_init_.py"
# add
import re
import sys
# add
def remove_hyperlink_tags(xml):
if (sys.version_info > (3, 0)):
xml = xml.decode('utf-8')
xml = xml.replace('</w:hyperlink>', '')
xml = re.sub('<w:hyperlink[^>]*>', '', xml)
if (sys.version_info > (3, 0)):
xml = xml.encode('utf-8')
return xml
# update
def parse_xml(xml):
"""
Return root lxml element obtained by parsing XML character string in
*xml*, which can be either a Python 2.x string or unicode. The custom
parser is used, so custom element classes are produced for elements in
*xml* that have them.
"""
root_element = etree.fromstring(remove_hyperlink_tags(xml), oxml_parser)
return root_element
and of course don't forget to mention in the documentation that use are changing the official library
There's a very short with "fast answer" here : How to test if remote TCP port is opened from Shell script?
nc -z <host> <port>; echo $?
I use it with 127.0.0.1 as "remote" address.
this returns "0" if the port is open and "1" if the port is closed
e.g.
nc -z 127.0.0.1 80; echo $?
-z Specifies that nc should just scan for listening daemons, without sending any data to them. It is an error to use this option in conjunc- tion with the -l option.
Use the -isEqualToString:
method to compare the value of two strings. Using the C ==
operator will simply compare the addresses of the objects.
if ([category isEqualToString:@"Some String"])
{
// Do stuff...
}
It's all about the input seed. Same seed give the same results all the time. Even you re-run your program again and again it's the same output.
public static void main(String[] args) {
randomString(-229985452);
System.out.println("------------");
randomString(-229985452);
}
private static void randomString(int i) {
Random ran = new Random(i);
System.out.println(ran.nextInt());
System.out.println(ran.nextInt());
System.out.println(ran.nextInt());
System.out.println(ran.nextInt());
System.out.println(ran.nextInt());
}
Output
-755142161
-1073255141
-369383326
1592674620
-1524828502
------------
-755142161
-1073255141
-369383326
1592674620
-1524828502
1) For me that's the most simple way passing parameters to async task is like this
// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);
Declare and use the async task like here
private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean...pParams)
{
Boolean param1, param2, param3;
//
param1=pParams[0];
param2=pParams[1];
param3=pParams[2];
....
}
2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.
/* Generic Async Task */
interface MyGenericMethod {
int execute(String param);
}
protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
public String mParam; // member variable to parameterize the function
@Override
protected Void doInBackground(MyGenericMethod... params) {
// do something here
params[0].execute("Myparameter");
return null;
}
}
// to start the asynctask do something like that
public void startAsyncTask()
{
//
AsyncTask<MyGenericMethod, Void, Void> mytest = new testtask().execute(new MyGenericMethod() {
public int execute(String param) {
//body
return 1;
}
});
}
I think that we can await for the value just returning first null and then get the real value, so in the case of Pure MVVM (PCL project for instance) I think the following is the most elegant solution:
private IEnumerable myList;
public IEnumerable MyList
{
get
{
if(myList == null)
InitializeMyList();
return myList;
}
set
{
myList = value;
NotifyPropertyChanged();
}
}
private async void InitializeMyList()
{
MyList = await AzureService.GetMyList();
}
Find the total size of both array and set array1and2 to the total size of both array added. Then loop array1 and then array2 and add the values into array1and2.
Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)
import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1
u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0
#option 1
#keep index of t
u.index = t.index
#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)
#now concat will keep number of rows
r=pd.concat([t,u], axis=1)
try this [0-9a-zA-Z]+ for only alpha and num with one char at-least
..
may need modification so test on it
http://www.regexplanet.com/advanced/java/index.html
Pattern pattern = Pattern.compile("^[0-9a-zA-Z]+$");
Matcher matcher = pattern.matcher(phoneNumber);
if (matcher.matches()) {
}
Use BOOST_BINARY (Yes, you can use it in C).
#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);
This macro is expanded to an octal literal during preprocessing.
You can add an undecorated JDialog like this:
import java.awt.event.*;
import javax.swing.*;
public class TestSwing {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Parent");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
final JDialog dialog = new JDialog(frame, "Child", true);
dialog.setSize(300, 200);
dialog.setLocationRelativeTo(frame);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(button);
dialog.setUndecorated(true);
dialog.setVisible(true);
}
}
If you're looking for the RPM.
rpm -qa | grep MySQL
Most of it's data is stored in /var/lib/mysql so that's another good place to look.
If it is installed
which mysql
will give you the location of the binary.
You could also do an
updatedb
and a
locate mysql
to find any mysql files.
Seems like your view is typed dynamic
. Set the right type on the view and you'll see the error go away.
I figured it out myself with the help of someone's answer. But he deleted it for some reason.
Here's the solution:
Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact
$(function(){
var windowH = $(window).height();
var wrapperH = $('#wrapper').height();
if(windowH > wrapperH) {
$('#wrapper').css({'height':($(window).height())+'px'});
}
$(window).resize(function(){
var windowH = $(window).height();
var wrapperH = $('#wrapper').height();
var differenceH = windowH - wrapperH;
var newH = wrapperH + differenceH;
var truecontentH = $('#truecontent').height();
if(windowH > truecontentH) {
$('#wrapper').css('height', (newH)+'px');
}
})
});
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.I think the purpose for regex is much different from indexOf
.
indexOf
simply find the occurance of a certain string while in regex you can use wildcards like [A-Z]
which means it will find any capital character in the word without stating the actual character.
Example:
var index = "This is a string".indexOf("is");_x000D_
console.log(index);_x000D_
var length = "This is a string".match(/[a-z]/g).length;_x000D_
// where [a-z] is a regex wildcard expression thats why its slower_x000D_
console.log(length);
_x000D_
The majority of answers to this question are outdated, incomplete, or unnecessarily complex.
A submodule cloned using git 1.7.8 or newer will leave at most four traces of itself in your local repo. The process for removing those four traces is given by the three commands below:
# Remove the submodule entry from .git/config
git submodule deinit -f path/to/submodule
# Remove the submodule directory from the superproject's .git/modules directory
rm -rf .git/modules/path/to/submodule
# Remove the entry in .gitmodules and remove the submodule directory located at path/to/submodule
git rm -f path/to/submodule
For object iteration we usually use a for..in
loop. This structure will loop through all enumerable properties, including ones who are inherited via prototypal inheritance. For example:
let obj = {_x000D_
prop1: '1',_x000D_
prop2: '2'_x000D_
}_x000D_
_x000D_
for(let el in obj) {_x000D_
console.log(el);_x000D_
console.log(obj[el]);_x000D_
}
_x000D_
However, for..in
will loop over all enumerable elements and this will not able us to split the iteration in chunks. To achieve this we can use the built in Object.keys()
function to retrieve all the keys of an object in an array. We then can split up the iteration into multiple for loops and access the properties using the keys array. For example:
let obj = {_x000D_
prop1: '1',_x000D_
prop2: '2',_x000D_
prop3: '3',_x000D_
prop4: '4',_x000D_
};_x000D_
_x000D_
const keys = Object.keys(obj);_x000D_
console.log(keys);_x000D_
_x000D_
_x000D_
for (let i = 0; i < 2; i++) {_x000D_
console.log(obj[keys[i]]);_x000D_
}_x000D_
_x000D_
_x000D_
for (let i = 2; i < 4; i++) {_x000D_
console.log(obj[keys[i]]);_x000D_
}
_x000D_
I have been reading about using model concerns to skin-nize fat models as well as DRY up your model codes. Here is an explanation with examples:
Consider a Article model, a Event model and a Comment model. An article or an event has many comments. A comment belongs to either Article or Event.
Traditionally, the models may look like this:
Comment Model:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
has_many :comments, as: :commentable
def find_first_comment
comments.first(created_at DESC)
end
def self.least_commented
#return the article with least number of comments
end
end
Event Model
class Event < ActiveRecord::Base
has_many :comments, as: :commentable
def find_first_comment
comments.first(created_at DESC)
end
def self.least_commented
#returns the event with least number of comments
end
end
As we can notice, there is a significant piece of code common to both Event and Article. Using concerns we can extract this common code in a separate module Commentable.
For this create a commentable.rb file in app/models/concerns.
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
end
# for the given article/event returns the first comment
def find_first_comment
comments.first(created_at DESC)
end
module ClassMethods
def least_commented
#returns the article/event which has the least number of comments
end
end
end
And now your models look like this :
Comment Model:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
include Commentable
end
Event Model:
class Event < ActiveRecord::Base
include Commentable
end
Consider a Event model. A event has many attenders and comments.
Typically, the event model might look like this
class Event < ActiveRecord::Base
has_many :comments
has_many :attenders
def find_first_comment
# for the given article/event returns the first comment
end
def find_comments_with_word(word)
# for the given event returns an array of comments which contain the given word
end
def self.least_commented
# finds the event which has the least number of comments
end
def self.most_attended
# returns the event with most number of attendes
end
def has_attendee(attendee_id)
# returns true if the event has the mentioned attendee
end
end
Models with many associations and otherwise have tendency to accumulate more and more code and become unmanageable. Concerns provide a way to skin-nize fat modules making them more modularized and easy to understand.
The above model can be refactored using concerns as below:
Create a attendable.rb
and commentable.rb
file in app/models/concerns/event folder
attendable.rb
module Attendable
extend ActiveSupport::Concern
included do
has_many :attenders
end
def has_attender(attender_id)
# returns true if the event has the mentioned attendee
end
module ClassMethods
def most_attended
# returns the event with most number of attendes
end
end
end
commentable.rb
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments
end
def find_first_comment
# for the given article/event returns the first comment
end
def find_comments_with_word(word)
# for the given event returns an array of comments which contain the given word
end
module ClassMethods
def least_commented
# finds the event which has the least number of comments
end
end
end
And now using Concerns, your Event model reduces to
class Event < ActiveRecord::Base
include Commentable
include Attendable
end
* While using concerns its advisable to go for 'domain' based grouping rather than 'technical' grouping. Domain Based grouping is like 'Commentable', 'Photoable', 'Attendable'. Technical grouping will mean 'ValidationMethods', 'FinderMethods' etc
I personally found Josh's jQuery-based answer above to be the best I saw, and worked perfectly for my application... of course, I was already using jQuery... I certainly wouldn't have included the whole jQ library just for that one purpose.
Cheers!
EDIT: OK... so mere seconds after posting this, I saw another answer just below mine (not sure if still below me after an edit) that said to use:
document.getElementById('your_element_ID_here').scrollIntoView();
This works perfectly and in so much less code than the jQuery version! I had no idea that there was a built-in function in JS called .scrollIntoView(), but there it is! So, if you want the fancy animation, go jQuery. Quick n' dirty... use this one!
your understanding is right. For detailed info on {} see bash ref - parameter expansion
'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.
With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done
in essence manage everything about the iteration yourself
It's a hexadecimal number.
0x6400 translates to 4*16^2 + 6*16^3 = 25600
input[type="text"], textarea {
background-color : #d1d1d1;
}
Hope that helps :)
Edit: working example, http://jsfiddle.net/C5WxK/
Just ran into this issue - if you updated a bunch of files and don't want to do git mv
all of them this also works:
/dir/RenamedFile.js
to /whatever/RenamedFile.js
.git add -A
to stage that change/dir/RenamedFile.js
.git add -A
again, will re-stage vs that change, forcing git to pick up the filename change.Basically you do the counts as sub-queries within a standard select.
An example would be the following, this returns 1 row, two columns
SELECT
(SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount,
(SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount,
I have a full explanation already posted here
Basically, General guidelines for designing images are:
ldpi is 0.75x dimensions of mdpi
hdpi is 1.5x dimensions of mdpi
xhdpi is 2x dimensinons of mdpi
Usually, I design mdpi images for a 320x480 screen and then multiply the dimensions as per the above rules to get images for other resolutions.
Please refer to the full explanation for a more detailed answer.
../
takes you one folder up the directory tree. Then, select the appropriate folder and its contents.
../images/logo.png
Better code with adding a subclass AuthorizeRole.cs
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params Rolenames[] roles)
{
this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
}
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Unauthorized" },
{ "controller", "Home" },
{ "area", "" }
}
);
//base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Login" },
{ "controller", "Account" },
{ "area", "" },
{ "returnUrl", HttpContext.Current.Request.Url }
}
);
}
}
}
How to use this
[AuthorizeRole(Rolenames.Admin,Rolenames.Member)]
public ActionResult Index()
{
return View();
}
Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!
You will have to do this via AJAX. I HEAVILY reccommend you use jQuery to make this easier for you....
$("#idOfElement").on('click', function(){
$.ajax({
url: 'pathToPhpFile.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
)};
This is what you should do. Please do not use stringify
nor < >
.
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length !== b.length) return false;
// If you don't care about the order of the elements inside
// the array, you should sort both arrays here.
// Please note that calling sort on an array will modify that array.
// you might want to clone your array first.
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
This work for me!
$(document).ready(function() {
$(document).on("click", "#tableId tbody tr", function() {
//some think
});
});
Try this:
@if(collect(explode('/',\Illuminate\Http\Request::capture()->url()))->last() === 'yourURL')
<li class="pull-right"><a class="intermitente"><i class="glyphicon glyphicon-alert"></i></a></li>
@endif
Instant.now() // Capture the current moment in UTC.
.atZone( ZoneId.systemDefault() ) // Adjust into the JVM's current default time zone. Same moment, different wall-clock time. Produces a `ZonedDateTime` object.
.toInstant() // Extract a `Instant` (always in UTC) object from the `ZonedDateTime` object.
.atZone( ZoneId.of( "Europe/Paris" ) ) // Adjust the `Instant` into a specific time zone. Renders a `ZonedDateTime` object. Same moment, different wall-clock time.
.toInstant() // And back to UTC again.
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes (Date
, Calendar
, etc.).
Your use of the word "local" contradicts the usage in the java.time class. In java.time, "local" means any locality or all localities, but not any one particular locality. The java.time classes with names starting with "Local…" all lack any concept of time zone or offset-from-UTC. So they do not represent a specific moment, they are not a point on the timeline, whereas your Question is all about moments, points on the timeline viewed through various wall-clock times.
Get the current system time (local time)
If you want to capture the current moment in UTC, use Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Adjust into a time zone by applying a ZoneId
to get a ZonedDateTime
. Same moment, same point on the timeline, different wall-clock time.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
As a shortcut, you can skip the usage of Instant
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Convert Local time to UTC // Works Fine Till here
You can adjust from the zoned date-time to UTC by extracting an Instant
from a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Instant instant = zdt.toInstant() ;
Reverse the UTC time, back to local time.
As shown above, apply a ZoneId
to adjust the same moment into another wall-clock time used by the people of a certain region (a time zone).
Instant instant = Instant.now() ; // Capture current moment in UTC.
ZoneId zDefault = ZoneId.systemDefault() ; // The JVM's current default time zone.
ZonedDateTime zdtDefault = instant.atZone( zDefault ) ;
ZoneId zTunis = ZoneId.of( "Africa/Tunis" ) ; // The JVM's current default time zone.
ZonedDateTime zdtTunis = instant.atZone( zTunis ) ;
ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ; // The JVM's current default time zone.
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;
Going back to UTC from a zoned date-time, call ZonedDateTime::toInstant
. Think of it conceptually as: ZonedDateTime = Instant + ZoneId.
Instant instant = zdtAuckland.toInstant() ;
All of these objects, the Instant
and the three ZonedDateTime
objects all represent the very same simultaneous moment, the same point in history.
Followed 3 different approaches (listed below) but all the 3 approaches retains the time in UTC only.
Forget about trying to fix code using those awful Date
, Calendar
, and GregorianCalendar
classes. They are a wretched mess of bad design and flaws. You need never touch them again. If you must interface with old code not yet updated to java.time, you can convert back-and-forth via new conversion methods added to the old classes.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
LayoutInflator
do?When I first started Android programming, I was really confused by LayoutInflater
and findViewById
. Sometimes we used one and sometimes the other.
LayoutInflater
is used to create a new View
(or Layout
) object from one of your xml layouts.findViewById
just gives you a reference to a view than has already been created. You might think that you haven't created any views yet, but whenever you call setContentView
in onCreate
, the activity's layout along with its subviews gets inflated (created) behind the scenes.So if the view already exists, then use findViewById
. If not, then create it with a LayoutInflater
.
Here is a mini project I made that shows both LayoutInflater
and findViewById
in action. With no special code, the layout looks like this.
The blue square is a custom layout inserted into the main layout with include
(see here for more). It was inflated automatically because it is part of the content view. As you can see, there is nothing special about the code.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Now let's inflate (create) another copy of our custom layout and add it in.
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, mainLayout, false);
To inflate the new view layout, all I did was tell the inflater the name of my xml file (my_layout
), the parent layout that I want to add it to (mainLayout
), and that I don't actually want to add it yet (false
). (I could also set the parent to null
, but then the layout parameters of my custom layout's root view would be ignored.)
Here it is again in context.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// inflate the main layout for the activity
setContentView(R.layout.activity_main);
// get a reference to the already created main layout
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.activity_main_layout);
// inflate (create) another copy of our custom layout
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, mainLayout, false);
// make changes to our custom layout and its subviews
myLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
TextView textView = (TextView) myLayout.findViewById(R.id.textView);
textView.setText("New Layout");
// add our custom layout to the main layout
mainLayout.addView(myLayout);
}
}
Notice how findViewById
is used only after a layout has already been inflated.
Here is the xml for the example above.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<!-- Here is the inserted layout -->
<include layout="@layout/my_layout"/>
</LinearLayout>
my_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@color/colorPrimary">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="5dp"
android:textColor="@android:color/white"
android:text="My Layout"/>
</RelativeLayout>
RecyclerView
. (See these RecyclerView
examples for a list or a grid.) You have to inflate a new layout for every single visible item in the list or grid.See my solution here: "Junit and java 7."
In this article I describe how to run junit tests in order - "just as in your source code". Tests will be run, in order as your test methods appears in class file.
http://intellijava.blogspot.com/2012/05/junit-and-java-7.html
But as Pascal Thivent said, this is not a good practise.
You are not specifying a language or framework, but the following header is used for file downloads:
"Content-Disposition: attachment; filename=abc.csv"
Remember that settings.py is a live code file. Assuming that you don't have DEBUG set on production (which is a best practice), you can do something like:
if DEBUG:
STATIC_PATH = /path/to/dev/files
else:
STATIC_PATH = /path/to/production/files
Pretty basic, but you could, in theory, go up to any level of complexity based on just the value of DEBUG - or any other variable or code check you wanted to use.
gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.
This worked for me.
header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(i for i in header)
for j in some_list:
writer.writerow(j)
One very unknown feature of Python is the ability to import zip
files:
library.zip
|-library
|--__init__.py
The file __init__.py
of the package contains the following:
def dummy():
print 'Testing things out...'
We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.
import sys
sys.path.append(r'library.zip')
import library
def run():
library.dummy()
run()
Again with the inverting, you could simply use the following code:
for k,v in pairs(t) do
if not isstring(k) then
-- do something to t[k] when k is not a string
end
If your browser supports debugging, you can use the console.log() method to display JavaScript values.
Activate debugging in your browser with F12, and select "Console" in the debugger menu.
Console in JavaScript. Try to fix, or "debug," a non-functioning JavaScript program, and practice using the console.log() command. There are shortcuts that is going to help you to access to the JavaScript console, based on the browser that you are using:
Chrome Console Keyboard Shortcuts
Windows: Ctrl + Shift + J
Mac: Cmd + Option + J
Firefox Console Keyboard Shortcuts
Windows: Ctrl + Shift + K
Mac: Cmd + Option + K
Internet Explorer Console Keyboard Shortcuts
F12 key
Safari Console Keyboard Shortcuts
Cmd + Option + C
Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests. These code should be added in the top of body element to create listener before any form rendered and submitted.
In example I set hidden field to any form on page on its submission even if it happens before page load.
//Handles jquery, dojo, etc. ajax requests
(function (send) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
XMLHttpRequest.prototype.send = function (data) {
if (isNotEmptyString(token) && isNotEmptyString(header)) {
this.setRequestHeader(header, token);
}
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
//Handles javascript submit
(function (submit) {
HTMLFormElement.prototype.submit = function (data) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(this);
submit.call(this, data);
};
})(HTMLFormElement.prototype.submit);
//Handles html submit
document.body.addEventListener('submit', function (event) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(event.target);
}, false);
I had this exact problem with my GoDaddy account.
I am running the Linux hosting with cPanel
follow these steps and you should be fine if you are running the same hosting as me:
first, go to you Manage Your Hosting -> Manage
then you will see a section called Files, click on File Manager
you can select the Document Root for: yourwebsite.com then click GO
this should bring you right away in the public_html folder
in that folder, you can add a file (by clicking the +File in top left corner), call it phpinfo.php
right click that new file, and select edit :
right this in it and save changes:
<?php phpinfo(); ?>
it the same public_html folder, add another file called php.ini
edit this one too, right those lines:
max_execution_time 600
memory_limit 128M
post_max_size 32M
upload_max_filesize 32M
now, go back to your Manage Your Hosting -> Manage, look for PHP Process
click Kill Process, this will allows a refresh with your new settings. you are good to go
side note: you can see your new settings by navigating to yourwebiste.com/phpinfo.php
I do it this way
System.setProperty("spring.profiles.default", "dev");
in the very beginning of main(...)
Try this:
UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:
mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> UPDATE business AS b
-> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
-> SET b.mapx = g.latitude,
-> b.mapy = g.longitude
-> WHERE (b.mapx = '' or b.mapx = 0) and
-> g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
See? No syntax error. I tested against MySQL 5.5.8.
IF you want to derive usg Boolean true False need to add "[]" around value
<form [formGroup]="form">
<input type="radio" [value]=true formControlName="gender" >Male
<input type="radio" [value]=false formControlName="gender">Female
</form>