e.g.:
CREATE
, ALTER
, DROP
, TRUNCATE
, COMMIT
, etc.DML statement are affect on table. So that is the basic operations we perform in a table.
SELECT
, INSERT
, UPDATE
, etc.Below Commands are used in DML:
INSERT
, UPDATE
, SELECT
, DELETE
, etc.When a servlet 3.0 application starts the container has to scan all the classes for annotations (unless metadata-complete=true). Tomcat uses a fork (no additions, just unused code removed) of Apache Commons BCEL to do this scanning. The web app is failing to start because BCEL has come across something it doesn't understand.
If the applications runs fine on Tomcat 6, adding metadata-complete="true" in your web.xml or declaring your application as a 2.5 application in web.xml will stop the annotation scanning.
At the moment, this looks like a problem in the class being scanned. However, until we know which class is causing the problem and take a closer look we won't know. I'll need to modify Tomcat to log a more useful error message that names the class in question. You can follow progress on this point at: https://issues.apache.org/bugzilla/show_bug.cgi?id=53161
namespace Test
{
public partial class Member : Form
{
public Member()
{
InitializeComponent();
}
private bool xClicked = true;
private void btnClose_Click(object sender, EventArgs e)
{
xClicked = false;
Close();
}
private void Member_FormClosing(object sender, FormClosingEventArgs e)
{
if (xClicked)
{
// user click the X
}
else
{
// user click the close button
}
}
}
}
And there is your answer =) Try to break it, you can't!!!
function link_validate_url($text) {
$LINK_DOMAINS = 'aero|arpa|asia|biz|com|cat|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|mobi|local';
$LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode("", array( // @TODO completing letters ...
"æ", // æ
"Æ", // Æ
"À", // À
"à", // à
"Á", // Á
"á", // á
"Â", // Â
"â", // â
"å", // å
"Å", // Å
"ä", // ä
"Ä", // Ä
"Ç", // Ç
"ç", // ç
"Ð", // Ð
"ð", // ð
"È", // È
"è", // è
"É", // É
"é", // é
"Ê", // Ê
"ê", // ê
"Ë", // Ë
"ë", // ë
"Î", // Î
"î", // î
"Ï", // Ï
"ï", // ï
"ø", // ø
"Ø", // Ø
"ö", // ö
"Ö", // Ö
"Ô", // Ô
"ô", // ô
"Õ", // Õ
"õ", // õ
"Œ", // Œ
"œ", // œ
"ü", // ü
"Ü", // Ü
"Ù", // Ù
"ù", // ù
"Û", // Û
"û", // û
"Ÿ", // Ÿ
"ÿ", // ÿ
"Ñ", // Ñ
"ñ", // ñ
"þ", // þ
"Þ", // Þ
"ý", // ý
"Ý", // Ý
"¿", // ¿
)), ENT_QUOTES, 'UTF-8');
$LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode("", array(
"ß", // ß
)), ENT_QUOTES, 'UTF-8');
$allowed_protocols = array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal');
// Starting a parenthesis group with (?: means that it is grouped, but is not captured
$protocol = '((?:'. implode("|", $allowed_protocols) .'):\/\/)';
$authentication = "(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=" . $LINK_ICHARS . "]|%[0-9a-f]{2})+(?::(?:[\w". $LINK_ICHARS ."\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})*)?)?@)";
$domain = '(?:(?:[a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9'. $LINK_ICHARS_DOMAIN . '\-_\[\]])*)(\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])+\.)*('. $LINK_DOMAINS .'|[a-z]{2}))?)';
$ipv4 = '(?:[0-9]{1,3}(\.[0-9]{1,3}){3})';
$ipv6 = '(?:[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})';
$port = '(?::([0-9]{1,5}))';
// Pattern specific to external links.
$external_pattern = '/^'. $protocol .'?'. $authentication .'?('. $domain .'|'. $ipv4 .'|'. $ipv6 .' |localhost)'. $port .'?';
// Pattern specific to internal links.
$internal_pattern = "/^(?:[a-z0-9". $LINK_ICHARS ."_\-+\[\]]+)";
$internal_pattern_file = "/^(?:[a-z0-9". $LINK_ICHARS ."_\-+\[\]\.]+)$/i";
$directories = "(?:\/[a-z0-9". $LINK_ICHARS ."_\-\.~+%=&,$'#!():;*@\[\]]*)*";
// Yes, four backslashes == a single backslash.
$query = "(?:\/?\?([?a-z0-9". $LINK_ICHARS ."+_|\-\.~\/\\\\%=&,$'():;*@\[\]{} ]*))";
$anchor = "(?:#[a-z0-9". $LINK_ICHARS ."_\-\.~+%=&,$'():;*@\[\]\/\?]*)";
// The rest of the path for a standard URL.
$end = $directories .'?'. $query .'?'. $anchor .'?'.'$/i';
$message_id = '[^@].*@'. $domain;
$newsgroup_name = '(?:[0-9a-z+-]*\.)*[0-9a-z+-]*';
$news_pattern = '/^news:('. $newsgroup_name .'|'. $message_id .')$/i';
$user = '[a-zA-Z0-9'. $LINK_ICHARS .'_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\'\[\]]+';
$email_pattern = '/^mailto:'. $user .'@'.'(?:'. $domain .'|'. $ipv4 .'|'. $ipv6 .'|localhost)'. $query .'?$/';
if (strpos($text, '<front>') === 0) {
return false;
}
if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {
return false;
}
if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {
return false;
}
if (preg_match($internal_pattern . $end, $text)) {
return false;
}
if (preg_match($external_pattern . $end, $text)) {
return false;
}
if (preg_match($internal_pattern_file, $text)) {
return false;
}
return true;
}
Use:
SELECT t.contactid
FROM YOUR_TABLE t
WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
HAVING COUNT(DISTINCT t.flag) = 2
The key thing is that the counting of t.flag
needs to equal the number of arguments in the IN
clause.
The use of COUNT(DISTINCT t.flag)
is in case there isn't a unique constraint on the combination of contactid and flag -- if there's no chance of duplicates you can omit the DISTINCT from the query:
SELECT t.contactid
FROM YOUR_TABLE t
WHERE flag IN ('Volunteer', 'Uploaded')
GROUP BY t.contactid
HAVING COUNT(t.flag) = 2
A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('right,left,up,down', function(e, handler){
switch(handler.key){
case "right":console.log('right');break
case "left":console.log('left');break
case "up":console.log('up');break
case "down":console.log('down');break
}
});
try this javascript:
function checkTextAreaMaxLength(textBox,e, length)
{
var mLen = textBox["MaxLength"];
if(null==mLen)
mLen=length;
var maxLength = parseInt(mLen);
if(!checkSpecialKeys(e))
{
if(textBox.value.length > maxLength-1)
{
if(window.event)//IE
e.returnValue = false;
else//Firefox
e.preventDefault();
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
On the control invoke it like this:
<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');" TextMode="multiLine" runat="server"> </asp:TextBox>
You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.
The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....
About the libraries you could use are.
And there could be many more, but that are what I've used
About the json I don't now maybe something like this
public class GetQuestions
{
public List<Student> Questions { get; set; }
}
public class Student
{
public string Code { get; set; }
public string Questions { get; set; }
}
void Main()
{
var gq = new GetQuestions
{
Questions = new List<Student>
{
new Student {Code = "s1", Questions = "Q1,Q2"},
new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
}
};
//Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
JsonConvert.SerializeObject(gq).Dump();
}
and the result is this
{
"Questions":[
{"Code":"s1","Questions":"Q1,Q2"},
{"Code":"s2","Questions":"Q1,Q2,Q3"},
{"Code":"s3","Questions":"Q1,Q2,Q4"},
{"Code":"s4","Questions":"Q1,Q2,Q5"}
]
}
Yes I know the json is different, but the json that you want with dictionary.
void Main()
{
var f = new Foo
{
GetQuestions = new Dictionary<string, string>
{
{"s1", "Q1,Q2"},
{"s2", "Q1,Q2,Q3"},
{"s3", "Q1,Q2,Q4"},
{"s4", "Q1,Q2,Q4,Q6"},
}
};
JsonConvert.SerializeObject(f).Dump();
}
class Foo
{
public Dictionary<string, string> GetQuestions { get; set; }
}
And with Dictionary is as you want it.....
{
"GetQuestions":
{
"s1":"Q1,Q2",
"s2":"Q1,Q2,Q3",
"s3":"Q1,Q2,Q4",
"s4":"Q1,Q2,Q4,Q6"
}
}
As far as I know there is not an easy way to do this since Javascript/JQuery does not have access to the local filesystem. There are some new features in html 5 that allows you to check certain meta data such as file size but I'm not sure if you can actually get the image dimensions.
Here is an article I found regarding the html 5 features, and a work around for IE that involves using an ActiveX control. http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
If you don't see log4net.dll in %systemdrive%\windows\assembly\
on the machine you are attempting to deploy it on, it is likely you haven't successfully installed the redistributable for Crystal Reports for .Net Framework 4.0
Install (or reinstall) the latest service pack from http://scn.sap.com/docs/DOC-7824 (SAP Crystal Reports, developer version for Microsoft Visual Studio Updates & Runtime Downloads)
That runtime distribution should add log4net to the GAC along with a bunch of CrystalDecisions dll's
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
Yes this is possible. kizzie is correct with the session_start();
having to go first.
another observation I made is that you need to filter your form data using:
strip_tags($value);
and/or
stripslashes($value);
You can also add float:left; inside this class #User_Apps_Content .DLD_App a
I followed below link to fix this problem. Make sure to enable following Module.
php -r 'phpinfo();' | grep -i mysqli
Link : https://askubuntu.com/questions/773601/php-mysqli-extension-in-ubuntu-16-04-not-working-after-upgrade-to-version-7-0-6
If the application is not doing anything in that 10 seconds, this will form a bad design only to make the user wait for 10 seconds doing nothing.
If there is something going on in that, or if you wish to implement 10 seconds delay splash screen,Here is the Code :
ProgressDialog pd;
pd = ProgressDialog.show(this,"Please Wait...", "Loading Application..", false, true);
pd.setCanceledOnTouchOutside(false);
Thread t = new Thread()
{
@Override
public void run()
{
try
{
sleep(10000) //Delay of 10 seconds
}
catch (Exception e) {}
handler.sendEmptyMessage(0);
}
} ;
t.start();
//Handles the thread result of the Backup being executed.
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
pd.dismiss();
//Start the Next Activity here...
}
};
Adding the following to build.gradle solves the problem :
android {
...
compileOptions.encoding = 'ISO-8859-1'
}
A nice technique i've started using with some of my apps on express is to create an object which merges the query, params, and body fields of express's request object.
//./express-data.js
const _ = require("lodash");
class ExpressData {
/*
* @param {Object} req - express request object
*/
constructor (req) {
//Merge all data passed by the client in the request
this.props = _.merge(req.body, req.params, req.query);
}
}
module.exports = ExpressData;
Then in your controller body, or anywhere else in scope of the express request chain, you can use something like below:
//./some-controller.js
const ExpressData = require("./express-data.js");
const router = require("express").Router();
router.get("/:some_id", (req, res) => {
let props = new ExpressData(req).props;
//Given the request "/592363122?foo=bar&hello=world"
//the below would log out
// {
// some_id: 592363122,
// foo: 'bar',
// hello: 'world'
// }
console.log(props);
return res.json(props);
});
This makes it nice and handy to just "delve" into all of the "custom data" a user may have sent up with their request.
Note
Why the 'props' field? Because that was a cut-down snippet, I use this technique in a number of my APIs, I also store authentication / authorisation data onto this object, example below.
/*
* @param {Object} req - Request response object
*/
class ExpressData {
/*
* @param {Object} req - express request object
*/
constructor (req) {
//Merge all data passed by the client in the request
this.props = _.merge(req.body, req.params, req.query);
//Store reference to the user
this.user = req.user || null;
//API connected devices (Mobile app..) will send x-client header with requests, web context is implied.
//This is used to determine how the user is connecting to the API
this.client = (req.headers) ? (req.headers["x-client"] || (req.client || "web")) : "web";
}
}
Do you want the item in the list or the actual item itself (would assume the item itself).
Here are a bunch of options for you:
string result = _list.First(s => s == search);
string result = (from s in _list
where s == search
select s).Single();
string result = _list.Find(search);
int result = _list.IndexOf(search);
Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
Usage: $results = searcharray('searchvalue', searchkey, $array);
Due to the above mentioned problems, I prefer table value functions.
If you have this:
CREATE VIEW [dbo].[MyView] AS SELECT A, B FROM dbo.Something
create this:
CREATE FUNCTION MyFunction() RETURNS TABLE AS RETURN (SELECT * FROM [dbo].[MyView])
Then you simply import the function rather than the view.
For Ubuntu users, an answer can be found here. I also quote it:
The most probable cause, is that you have not installed the appropriate dependencies. Your Ubuntu system has to have some packages installed regarding conversion of LaTeX and XeTeX files, in order to save your notebook as PDF. You can install them by:
sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended pandoc
Also,
nbconvert
is another dependency that is usually automatically installed with jupyter. But you can install it just to be sure, while having your virtual environment activated:pip install -U nbconvert
just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button).
If you want the placeholder text to be red you need to target it specifically in CSS.
Write:
input::placeholder{
color: #f00;
}
You can check Visual Studio Downloads for available Visual Studio Community
, Visual Studio Professional
, Visual Studio Enterprise
and Visual Studio Code
download links.
Update!
There is no direct links of Visual Studio 2015
at Visual Studio Downloads anymore. but the below links still works.
OR simply click on direct links below (for .iso/.exe file):
VSCode area:
You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.
declare @TableVar table
(
firstCol varchar(50) NOT NULL,
secondCol varchar(50) NOT NULL
)
BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO
INSERT INTO dbo.ExistingTable
(
firstCol,
secondCol
)
SELECT firstCol,
secondCol
FROM @TableVar
GO
This is a very highly upvoted issue request in Github for Floating Windows.
Until they support it, you can try the following workarounds:
The Duplicate Workspace in new Window Command was added in v1.24 (May 2018) to sort of address this.
workbench.action.duplicateWorkspaceInNewWindow
to Ctrl + Shift + N or whatever you'd likeRather than manually open a new window and dragging the file, you can do it all with a single command.
As AllenBooTung also pointed out, you can open/drag any file in a separate blank instance.
VS Code will not allow you to open the same folder in two different instances, but you can use Workspaces to open the same directory of files in a side by side instance.
For any workaround, also consider setting setting up auto save so the documents are kept in sync by updating the files.autoSave
setting to afterDelay
, onFocusChange
, or onWindowChange
I can't say I know the best practice, but here's my perspective.
Are you using these variables for anything?
Personally, I haven't needed to change neither, on Linux nor Windows, in environments varying from development to production. Unless you are doing something particular that relies on them, chances are you could leave them alone.
catalina.sh
sets the variables that Tomcat needs to work out of the box. It also says that CATALINA_BASE
is optional:
# CATALINA_HOME May point at your Catalina "build" directory.
#
# CATALINA_BASE (Optional) Base directory for resolving dynamic portions
# of a Catalina installation. If not present, resolves to
# the same directory that CATALINA_HOME points to.
I'm pretty sure you'll find out whether or not your setup works when you start your server.
On Linux, see netem: the kernel already contains support for traffic shaping, and can simulate high latency, low bandwidth, packet losses, and all sort of other adverse conditions, even on a loopback device (so you don't need a real, physical network to test across).
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
You will need to add the jar to your local maven repository. Alternatively (better option) specify the proper repository (if one exists) so it can be automatically downloaded by maven
In either case, remove the <systemPath>
tag from the dependency
I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.
Transparent Actionbar:
values/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>
<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
<item name="android:windowContentOverlay">@null</item>
<item name="windowActionBarOverlay">true</item>
<item name="colorPrimary">@android:color/transparent</item>
</style>
<style name="AppTheme.ActionBar" parent="AppTheme">
<item name="windowActionBarOverlay">false</item>
<item name="colorPrimary">@color/default_yellow</item>
</style>
values-v21/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>
<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
<item name="colorPrimary">@android:color/transparent</item>
</style>
<style name="AppTheme.ActionBar" parent="AppTheme">
<item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
<item name="colorPrimary">@color/default_yellow</item>
</style>
Now you can use these themes in your AndroidManifest.xml
to specify which activities will have a transparent or colored ActionBar
:
<activity
android:name=".MyTransparentActionbarActivity"
android:theme="@style/AppTheme.ActionBar.Transparent"/>
<activity
android:name=".MyColoredActionbarActivity"
android:theme="@style/AppTheme.ActionBar"/>
Note: in API>=21 to get the Actionbar
transparent you need to get the Statusbar
transparent too, otherwise will not respect your colour styles and will stay light-grey.
Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
But you'll notice a funky result:
This happens because when the Statusbar
is transparent the layout will use its height. To prevent this we just need to:
SOLUTION ONE:
Add this line android:fitsSystemWindows="true"
in your layout view container of whatever you want to be placed bellow the Actionbar:
...
<LinearLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</LinearLayout>
...
SOLUTION TWO:
Add a few lines to our previous method:
protected void setStatusBarTranslucent(boolean makeTranslucent) {
View v = findViewById(R.id.bellow_actionbar);
if (v != null) {
int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
TypedValue tv = new TypedValue();
getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true);
paddingTop += TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);
}
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
Where R.id.bellow_actionbar
will be the layout container view id of whatever we want to be placed bellow the Actionbar
:
...
<LinearLayout
android:id="@+id/bellow_actionbar"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</LinearLayout>
...
So this is it, it think I'm not forgetting something.
In this example I didn't use a Toolbar
but I think it'll have the same result. This is how I customize my Actionbar
:
@Override
protected void onCreate(Bundle savedInstanceState) {
View vg = getActionBarView();
getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(getContentView());
if (vg != null) {
getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayUseLogoEnabled(false);
}
setStatusBarTranslucent(true);
}
Note: this is an abstract class
that extends ActionBarActivity
Hope it helps!
It depends how many times you're going to want to find this information, if more than once:
Set<Boolean> flags = new HashSet<Boolean>(myArray);
flags.contains(false);
Otherwise a short circuited loop:
for (i = 0; i < myArray.length; i++) {
if (!myArray[i]) return false;
}
return true;
Actually I found this more helpful for functions that return IAsyncAction.
var task = asyncFunction();
while (task.Status == AsyncStatus.Completed) ;
In my case, I found that I need the -f option. Such as the following:
git rm -f first_file.txt
to get rid of the "needs merge" error.
To unapply a specific migration(s):
dotnet ef database update LastGoodMigrationName
or
PM> Update-Database -Migration LastGoodMigrationName
To unapply all migrations:
dotnet ef database update 0
or
PM> Update-Database -Migration 0
To remove last migration:
dotnet ef migrations remove
or
PM> Remove-Migration
To remove all migrations:
just remove Migrations
folder.
To remove last few migrations (not all):
There is no a command to remove a bunch of migrations and we can't just remove these few migrations
and their *.designer.cs
files since we need to keep the snapshot file in the consistent state. We need to remove migrations one by one (see To remove last migration
above).
To unapply and remove last migration:
dotnet ef migrations remove --force
or
PM> Remove-Migration -Force
While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.
Example: you have five figures on your desktop from a previous script you ran and you use
figure(1);
plot(...)
figure(2);
plot(...)
You just plotted over the figures on your desktop. However the code
figure;
plot(...)
figure;
plot(...)
just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.
To delete the folder, this is code using Text box and a button using System.IO;
:
private void Deletebt_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text);
foreach (FileInfo file in myDirInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
dir.Delete(true);
}
}
Recursive way, not very efficient, just provide an option
(Python code)
def isPalindrome(num):
size = len(str(num))
demoninator = 10**(size-1)
return isPalindromeHelper(num, size, demoninator)
def isPalindromeHelper(num, size, demoninator):
"""wrapper function, used in recursive"""
if size <=1:
return True
else:
if num/demoninator != num%10:
return False
# shrink the size, num and denominator
num %= demoninator
num /= 10
size -= 2
demoninator /=100
return isPalindromeHelper(num, size, demoninator)
I wanted to display the login page without the layout and this works pretty good for me.(this is the _ViewStart.cshtml file) You need to set the ViewBag.Title in the Controller.
@{
if (! (ViewContext.ViewBag.Title == "Login"))
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
I know it's a little bit late but I hope this helps some body.
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
Most of the time that I use AsyncTask my business logic is on a separated business class instead of being on the UI. In that case, I couldn't have a loop at doInBackground(). An example would be a synchronization process that consumes services and persist data one after another.
I end up handing on my task to the business object so it can handle cancelation. My setup is like this:
public abstract class MyActivity extends Activity {
private Task mTask;
private Business mBusiness;
public void startTask() {
if (mTask != null) {
mTask.cancel(true);
}
mTask = new mTask();
mTask.execute();
}
}
protected class Task extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onCancelled() {
super.onCancelled();
mTask.cancel(true);
// ask if user wants to try again
}
@Override
protected Boolean doInBackground(Void... params) {
return mBusiness.synchronize(this);
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
mTask = null;
if (result) {
// done!
}
else {
// ask if user wants to try again
}
}
}
public class Business {
public boolean synchronize(AsyncTask<?, ?, ?> task) {
boolean response = false;
response = loadStuff(task);
if (response)
response = loadMoreStuff(task);
return response;
}
private boolean loadStuff(AsyncTask<?, ?, ?> task) {
if (task != null && task.isCancelled()) return false;
// load stuff
return true;
}
}
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
I put this:
@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
return !(self == nil
|| [self isKindOfClass:[NSNull class]]
|| ([self respondsToSelector:@selector(length)]
&& [(NSData *)self length] == 0)
|| ([self respondsToSelector:@selector(count)]
&& [(NSArray *)self count] == 0));
};
@end
The problem is that if self is nil, this function is never called. It'll return false, which is desired.
If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.
In my case, I was using json.load
on data incorrectly read from file by not using the encoding="utf-8"
. Trying to de-/encode the resulting string to latin-1
just does not help...
You could decide to make use of a templating engine in your project, such as:
If you don't want to include another library, John Resig offers a jQuery solution, similar to the one below.
Browsers and screen readers ignore unrecognized script types:
<script id="hidden-template" type="text/x-custom-template">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
</script>
Using jQuery, adding rows based on the template would resemble:
var template = $('#hidden-template').html();
$('button.addRow').click(function() {
$('#targetTable').append(template);
});
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
<div style='width:200px;margin:0 auto;> sometext or image tag</div>
this works horizontally
I'm using UBUNTU and I got this same error. I restarted the set up using sudo and did a custom install. This solved my problem!
--More Specific--
re-installed using # sudo ./studio.sh
then I made sure to click "Custom Install"
then I made sure all packages were selected.
And I got this message Android virtual device Nexus_5_API_22_x86 was successfully created
Factory Pattern
class Point
{
public:
static Point Cartesian(double x, double y);
private:
};
And if you compiler does not support Return Value Optimization, ditch it, it probably does not contain much optimization at all...
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
While generating the links set the target to the iframes name property and you probably wont have to deal with jquery at all.
<a href="inventory.aspx" target="contentframe" title="Title Inventory">
<iframe id="iframe1" name="contentframe" ></iframe>
Suspended. The session is waiting for an event, such as I/O, to complete.
Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.
Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.
Syntax
ALTER TRIGGER trigger Name DISABLE;
ALTER TRIGGER trigger_Name ENABLE;
I found the presented versions way to aggressive, especially if you commit patches from other developers, this will essentially steal their code.
The version below does work on all branches and changes the author and comitter separately to prevent that.
Kudos to leif81 for the all option.
#!/bin/bash
git filter-branch --env-filter '
if [ "$GIT_AUTHOR_NAME" = "<old author>" ];
then
GIT_AUTHOR_NAME="<new author>";
GIT_AUTHOR_EMAIL="<[email protected]>";
fi
if [ "$GIT_COMMITTER_NAME" = "<old committer>" ];
then
GIT_COMMITTER_NAME="<new commiter>";
GIT_COMMITTER_EMAIL="<[email protected]>";
fi
' -- --all
This will take care of the empty td:
<td style="min-width: 20px;"></td>
Same thing happened with me, when i have enabled 2-way authentication for github. Things i did to resolve:
Doing this will solve your issue.
I think that the problem is the way that you retrieve the entity.
Maybe you are doing something like this:
Person p = (Person) session.load(Person.class, new Integer(id));
Try using the method get
instead of load
Person p = (Person) session.get(Person.class, new Integer(id));
The problem is that with load method you get just a proxy but not the real object. The proxy object doesn't have the properties already loaded so when the serialization happens there are no properties to be serialized. With the get method you actually get the real object, this object could in fact be serialized.
I would definitely split them. It would be easy to sort the numbers by area code and contry code. But even if you're not going to split, just insert the numbers into the DB in one certain format. e.g. 1-555-555-1212 Your client side will be thankfull for not making it reformat your numbers.
Use a regex like ^\d
If you want to allow a user to add a bunch of new MyObjects to the list, you can do it with a for loop: Let's say I'm creating an ArrayList of Rectangle objects, and each Rectangle has two parameters- length and width.
//here I will create my ArrayList:
ArrayList <Rectangle> rectangles= new ArrayList <>(3);
int length;
int width;
for(int index =0; index <3;index++)
{JOptionPane.showMessageDialog(null, "Rectangle " + (index + 1));
length = JOptionPane.showInputDialog("Enter length");
width = JOptionPane.showInputDialog("Enter width");
//Now I will create my Rectangle and add it to my rectangles ArrayList:
rectangles.add(new Rectangle(length,width));
//This passes the length and width values to the rectangle constructor,
which will create a new Rectangle and add it to the ArrayList.
}
You can do it like this:
row_id = 5;
row = $("body").find('#'+row_id);
Top answers are saying mathlog10 faster but I got results that suggest len(str(n)) is faster.
arr = []
for i in range(5000000):
arr.append(random.randint(0,12345678901234567890))
%%timeit
for n in arr:
len(str(n))
//2.72 s ± 304 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
for n in arr:
int(math.log10(n))+1
//3.13 s ± 545 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Besides, I haven't added logic to the math way to return accurate results and I can only imagine it slows it even more.
I have no idea how the previous answers proved the maths way is faster though.
Rails 3.0.9
select options_for_select([value1, value2, value3], default)
Use these commands on a windows command prompt(cmd) with administrator privilege (run as administrator):
netsh wlan set hostednetwork mode=allow ssid=tests key=tests123
netsh wlan start hostednetwork
Then you go to Network and sharing center and click on "change adapter settings" (I'm using windows 7, it can be a little different on windows 8)
Then right click on the lan connection (internet connection that you are using), properties.
Click on sharing tab, select the wireless connection tests (the name tests you can change on the command line) and check "Allow other network users to connect through this network connection"
This done, your connection is ready to use!
Unicode support in PHP is still a huge mess. While it's capable of converting an ISO8859 string (which it uses internally) to utf8, it lacks the capability to work with unicode strings natively, which means all the string processing functions will mangle and corrupt your strings. So you have to either use a separate library for proper utf8 support, or rewrite all the string handling functions yourself.
The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF8. That's the hard part, and PHP gives you virtually no help there. (I think PHP6 is supposed to fix the worst of this, but that's still a while away)
I just did the same. I did it in helper controller, my code is:
def get_controller_name
controller_name
end
def get_action_name
action_name
end
These methods will return current contoller and action name. Hope it helps
MSK,
Have you tried setting a namespace declaration to your member variables like this? :
@XmlElement(required = true, namespace = "http://example.com/a")
protected String username;
@XmlElement(required = true, namespace = "http://example.com/a")
protected String password;
For our project, it solved namespace issues. We also had to create NameSpacePrefixMappers.
I add this answer because I think it could be useful to anybody.
I step into the problem of setting RGBA colors (that is, RGB color with an Alpha value for transparency) for color display labels in my painting application.
As I came across the first answer, I was unable to set an RGBA color. I have also tried things like:
myLabel.setStyleSheet("QLabel { background-color : %s"%color.name())
where color
is an RGBA color.
So, my dirty solution was to extend QLabel
and override paintEvent()
method filling its bounding rect.
Today, I've open up the qt-assistant
and read the style reference properties list. Affortunately, it has an example that states the following:
QLineEdit { background-color: rgb(255, 0, 0) }
Thats open up my mind in doing something like the code below, as an example:
myLabel= QLabel()
myLabel.setAutoFillBackground(True) # This is important!!
color = QtGui.QColor(233, 10, 150)
alpha = 140
values = "{r}, {g}, {b}, {a}".format(r = color.red(),
g = color.green(),
b = color.blue(),
a = alpha
)
myLabel.setStyleSheet("QLabel { background-color: rgba("+values+"); }")
Note that setAutoFillBackground()
set in False
will not make it work.
Regards,
The logic of encoding Unicode in UTF-8 is basically:
Here's a function I wrote a while back for encoding a JavaScript UTF-16 string in UTF-8:
function toUTF8Array(str) {
var utf8 = [];
for (var i=0; i < str.length; i++) {
var charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6),
0x80 | (charcode & 0x3f));
}
else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(0xe0 | (charcode >> 12),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
// surrogate pair
else {
i++;
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode = 0x10000 + (((charcode & 0x3ff)<<10)
| (str.charCodeAt(i) & 0x3ff));
utf8.push(0xf0 | (charcode >>18),
0x80 | ((charcode>>12) & 0x3f),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
}
return utf8;
}
Two issues:
You're passing the jQuery wrapper of the element into parseInt
, which isn't what you want, as parseInt
will call toString
on it and get back "[object Object]"
. You need to use val
or text
or something (depending on what the element is) to get the string you want.
You're not telling parseInt
what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt
guesses which radix to use.
Fix if the element is a form field:
// vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Fix if the element is something else and you want to use the text within it:
// vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
String result = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
Create a .htaccess file at the root of your website and add this line:
[Apache2 @ Ubuntu/Debian: use this directive]
AddType application/x-httpd-php .html .htm
Or, from comment below:
AddType application/x-httpd-php5 .html .htm
If your are running PHP as CGI (probably not the case), you should write instead:
AddHandler application/x-httpd-php .html .htm
Here is the code from MSDN and the link - Article Link, which you should check out for more detail.
<ComboBox Text="Is not open">
<ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>
In regards to JavaScript:
The === operator works the same as the == operator, but it requires that its operands have not only the same value, but also the same data type.
For example, the sample below will display 'x and y are equal', but not 'x and y are identical'.
var x = 4;
var y = '4';
if (x == y) {
alert('x and y are equal');
}
if (x === y) {
alert('x and y are identical');
}
Update database and Set fieldName=Replace (fieldName,'FindString','ReplaceString')
This solution did the trick for me
<a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>
$("#yourdropdownid option:selected").text(); // selected option text
$("#yourdropdownid").val(); // selected option value
In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.
Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html
Solr I am not sure but you can delete all the data from hbase using truncate command like below:
truncate 'table_name'
It will delete all row-keys from hbase table.
In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric
geom_segment(data=tmpp,
aes(x=start_pos,
y=lib.complexity,
xend=end_pos,
yend=lib.complexity)
)
# to
geom_segment(data=tmpp,
aes(x=as.numeric(start_pos),
y=as.numeric(lib.complexity),
xend=as.numeric(end_pos),
yend=as.numeric(lib.complexity))
)
Do you mean
.*
.
any character, except newline character, with dotall mode it includes also the newline characters
*
any amount of the preceding expression, including 0 times
Just find your form and clear before it opens!
$modal = $('#modal');
$modal.find('form')[0].reset();
You should not just try to pause 5 seconds in javascript. It doesn't work that way. You can schedule a function of code to run 5 seconds from now, but you have to put the code that you want to run later into a function and the rest of your code after that function will continue to run immediately.
For example:
function stateChange(newState) {
setTimeout(function(){
if(newState == -1){alert('VIDEO HAS STOPPED');}
}, 5000);
}
But, if you have code like this:
stateChange(-1);
console.log("Hello");
The console.log()
statement will run immediately. It will not wait until after the timeout fires in the stateChange()
function. You cannot just pause javascript execution for a predetermined amount of time.
Instead, any code that you want to run delays must be inside the setTimeout()
callback function (or called from that function).
If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). So, looping waiting for some variable to change will never work because no other code can run to change that variable.
An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Virtual Library</title>
</head>
<body>
<p>Moved to <a href="http://example.org/">example.org</a>.</p>
</body>
</html>
Please refer to the W3 standards for XML.
If you're using Joda-Time (and there are lots of good reasons to - a simple, intuitive API and thread-safety) then you can do this trivially:
(new LocalDate()).plusDays(5);
to give 5 days from today, for example.
EDIT: My current advice would be to now use the Java 8 date/time api
Here are the steps:
It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),
You can try these some steps:
Stop Mysql Service 1st
sudo /etc/init.d/mysql stop
Login as root without password
sudo mysqld_safe --skip-grant-tables &
After login mysql terminal you should need execute commands more:
use mysql;
UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';
flush privileges;
sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown
After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04
try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
Why would you use -z? To test if a string is non-empty, you typically use -n:
if test -n "$errorstatus"; then echo errorstatus is not empty fi
the loginuser class uses a trait called AuthenticatesUsers
if you open that trait you will see the functions (this applies for other controllers)
Illuminate\Foundation\Auth\AuthenticatesUsers;
here is the trait code https://github.com/laravel/framework/blob/5.1/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
sorry for the bad format, im using my phone
also Auth::routes()
it just calls a function that returns the auth routes thats it (i think)
According to the docs numpy.loadtxt
is
a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.
so there are only a few options to handle more complicated files.
As mentioned numpy.genfromtxt
has more options. So as an example you could use
import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['x', 'y', 'z'])
to read the data and assign names to the columns (or read a header line from the file with names=True
) and than plot it with
ax1.plot(data['x'], data['y'], color='r', label='the data')
I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython
or by using an IDE like spider
if you prefer to read them rendered as HTML.
Choosing the location to save the file before creating it is not possible. But it is possible, at least in Chrome, to generate files using just JavaScript. Here is an old example of mine of creating a CSV file. The user will be prompted to download it. This, unfortunately, does not work well in other browsers, especially IE.
<!DOCTYPE html>
<html>
<head>
<title>JS CSV</title>
</head>
<body>
<button id="b">export to CSV</button>
<script type="text/javascript">
function exportToCsv() {
var myCsv = "Col1,Col2,Col3\nval1,val2,val3";
window.open('data:text/csv;charset=utf-8,' + escape(myCsv));
}
var button = document.getElementById('b');
button.addEventListener('click', exportToCsv);
</script>
</body>
</html>
You can use ax.figure.savefig()
:
import pandas as pd
s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')
This has no practical benefit over ax.get_figure().savefig()
as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure()
simply returns self.figure
:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
The other answers are for AWS SDK v1. Here is a method for AWS SDK v2 (currently 2.3.9).
Note that getObjectMetadata
and doesObjectExist
methods are not currently in the v2 SDK! So those are no longer options. We are forced to use either getObject
or listObjects
.
listObjects
calls are currently 12.5 times more expensive to make than getObject
. But AWS also charges for any data downloaded, which raises the price of getObject
if the file exists. As long as the file is very unlikely to exist (for example, you have generated a new UUID key randomly and just need to double-check that it isn't taken) then calling getObject
is significantly cheaper by my calculation.
Just to be on the safe side though, I added a range()
specification to ask AWS to only send a few bytes of the file. As far as I know the SDK will always respect this and not charge you for downloading the whole file. But I haven't verified that so rely on that behavior at your own risk! (Also, I'm not sure what how range
behaves if the S3 object is 0 bytes long.)
private boolean sanityCheckNewS3Key(String bucket, String key) {
ResponseInputStream<GetObjectResponse> resp = null;
try {
resp = s3client.getObject(GetObjectRequest.builder()
.bucket(bucket)
.key(key)
.range("bytes=0-3")
.build());
}
catch (NoSuchKeyException e) {
return false;
}
catch (AwsServiceException se) {
throw se;
}
finally {
if (resp != null) {
try {
resp.close();
} catch (IOException e) {
log.warn("Exception while attempting to close S3 input stream", e);
}
}
}
return true;
}
}
Note: this code assumes s3Client
and log
are declared and initialized elsewhere. Method returns a boolean, but can throw exceptions.
you can also covert int to str first and assign index to it then again convert it to int like this:
int(str(x)[n]) //where x is an integer value
In jQuery:
$('some_element').keypress(function(e){
if(e.keyCode == 20){
//caps lock was pressed
}
});
This jQuery plugin (code) implements the same idea as in Rajesh's answer a bit more succinctly.
C++ is a language and Visual C++ is a compiler for that language. Certainly, it (and every other compiler) introduces tiny modifications to the language, but the language recognized is mainly the same.
I've tried the NullObjectPattern
but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.
NullPointerException
is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.
Now to the answer:
Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object
. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.
Of course, experience is the better way to understand and apply this suggestion.
Byte!
This is handled by adding some padding
to the top of the <body>
.
As per Bootstrap's documentation on .navbar-fixed-top
, try out your own values or use our snippet below. Tip: By default, the navbar
is 50px
high.
body {
padding-top: 70px;
}
Also, take a look at the source for this example and open starter-template.css
.
You can use a list comprehension:
[x for x in j if x >= 5]
BadImageFormatException
, in my experience, is almost always to do with x86 versus x64 compiled assemblies. It sounds like your C++ assembly is compiled for x86 and you are running on an x64 process. Is that correct?
Instead of using AnyCPU/Mixed
as the platform. Try to manually set it to x86
and see if it will run after that.
Hope this helps.
The evolving standard looks to be canvas.toBlob() not canvas.getAsFile() as Mozilla hazarded to guess.
I don't see any browser yet supporting it :(
Thanks for this great thread!
Also, anyone trying the accepted answer should be careful with BlobBuilder as I'm finding support to be limited (and namespaced):
var bb;
try {
bb = new BlobBuilder();
} catch(e) {
try {
bb = new WebKitBlobBuilder();
} catch(e) {
bb = new MozBlobBuilder();
}
}
Were you using another library's polyfill for BlobBuilder?
Here is my utility function for UTF8
, which can be replaced with ASCII
if desired:
public static byte[] MD5Hash(string message)
{
return MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(message));
}
If you are using PHP, try using <?php flush(); ?>
after </head>
and before </body>
or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.
If you need the index of the item you're working with then using a foreach
loop is the wrong method of iterating over the collection. Change the way you're looping so you have the index:
for(int i = 0; i < dt.Rows.Count; i++)
{
// your index is in i
var row = dt.Rows[i];
}
Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.
<h3>NATO Phonetic Alphabet</h3>
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th>Letter</th>
<th>Phonetic Letter</th>
</tr>
</thead>
<tr>
<th>A</th>
<th>Alpha</th>
</tr>
<tr>
<td>B</td>
<td>Bravo</td>
</tr>
<tr>
<td>C</td>
<td>Charlie</td>
</tr>
</table>
I suggest this discriminative question:
Is the open-source tool necessary in your process of making money?
First, rewrite your array like this:
var items = [523,3452,334,31,...5346];
Next, access the element in the array through its index number. The formula to determine the index number is: n-1
To replace the first item (n=1)
in the array, write:
items[0] = Enter Your New Number;
In your example, the number 3452
is in the second position (n=2)
. So the formula to determine the index number is 2-1 = 1
. So write the following code to replace 3452
with 1010
:
items[1] = 1010;
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
action(item);
}
... and call it thusly:
Each(myList, i => Console.WriteLine(i));
Simple example on JavaScript for HTML input-fields (sending to server JSON, parsing JSON in PHP and sending back to client) using AJAX:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<body>
<div align="center">
<label for="LName">Last Name</label>
<input type="text" class="form-control" name="LName" id="LName" maxlength="15"
placeholder="Last name"/>
</div>
<br/>
<div align="center">
<label for="Age">Age</label>
<input type="text" class="form-control" name="Age" id="Age" maxlength="3"
placeholder="Age"/>
</div>
<br/>
<div align="center">
<button type="submit" name="submit_show" id="submit_show" value="show" onclick="actionSend()">Show
</button>
</div>
<div id="result">
</div>
<script>
var xmlhttp;
function actionSend() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var values = $("input").map(function () {
return $(this).val();
}).get();
var myJsonString = JSON.stringify(values);
xmlhttp.onreadystatechange = respond;
xmlhttp.open("POST", "ajax-test.php", true);
xmlhttp.send(myJsonString);
}
function respond() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
</script>
</body>
</html>
PHP file ajax-test.php :
<?php
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$lName = $response[0];
$age = $response[1];
echo '
<div align="center">
<h5> Received data: </h5>
<table border="1" style="border-collapse: collapse;">
<tr> <th> First Name</th> <th> Age</th> </tr>
<tr>
<td> <center> '.$lName.'<center></td>
<td> <center> '.$age.'</center></td>
</tr>
</table></div>
';
?>
<form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="image" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-xs-12">Add</button>
</div>
</form>
My Action Is
[HttpPost]
public IActionResult AddNews(IFormFile image)
{
Tbl_News tbl_News = new Tbl_News();
if (image!=null)
{
//Set Key Name
string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//Get url To Save
string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);
using(var stream=new FileStream(SavePath, FileMode.Create))
{
image.CopyTo(stream);
}
}
return View();
}
There is another scenario where this issue reproduces (as in my case). When THE CLIENT REQUEST doesn't contain the right extension on the url, the controller can't identify the desired result format.
For example: the controller is set to respond_to :json
(as a single option, without a HTML response)- while the client call is set to /reservations
instead of /reservations.json
.
Bottom line, change the client call to /reservations.json
.
You can't.
The only way to set the value of a file input is by the user to select a file.
This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
Use array_values
to reset keys
foreach($input as &$val) {
$val = array_values($val);
}
find supports wildcard matches, just add a *
:
find / -type d -name "ora10*"
You'll need to add this to your server configuration:
AddType application/x-httpd-php .php
That is assuming you have installed PHP properly, which may not be the case since it doesn't work where it normally would immediately after installing.
It is entirely possible that you'll also have to add the php
.so/.dll file to your Apache configuration using a LoadModule
directive (usually in httpd.conf
).
You will need two things. The first is @media screen
to activate the specific code at a certain screen size, used for responsive design. The second is the use of the visibility: hidden
attribute. Once the browser/screen reaches 600pixels then #title_message
will become hidden.
@media screen and (max-width: 600px) {
#title_message {
visibility: hidden;
clear: both;
float: left;
margin: 10px auto 5px 20px;
width: 28%;
display: none;
}
}
EDIT: if you are using another CSS for mobile then just add the visibility: hidden;
to #title_message
. Hope this helps you!
WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:
using (var client = new WebClient())
{
var json = client.DownloadString("http://example.com/json");
var serializer = new JavaScriptSerializer();
SomeModel model = serializer.Deserialize<SomeModel>(json);
// TODO: do something with the model
}
There are also some REST client frameworks you may checkout such as RestSharp.
Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:
Go and set your choice as shown:
Ultimately, I want to be able to echo out a signle field like so:
$row['option_value']
So why don't you? It should work.
It depends on how hard you want to work, but yes it's possible. The problem you are going to have is that you have to learn to program along with learning java. These are two very different things. Programming is knowing how to read and write logic and Java is a language you write it in. If you have a math or physics background, this is going to be a lot easier, as you are already exposed to thinking in such a manner.
If you don't have books on beginning Java I would go buy one of those.
I would also pick up the book Code (I would try and get through this in a few days, if not over the weekend if possible). Actually with 10 weeks I would do this first as it will be a foundation for what you'll need to know to program Java.
With 10 weeks, you are going to have to pretty much study every night to get the hang of it by the time you go to class. My best advice is that when you take the class, take lots of notes, and don't expect to understand everything. Most of what gets thrown at you there will probably go over your head at first and you'll forget. That's ok. After the class if over, go back and review the notes etc until it starts to make sense.
Definately a numbers table, though tyou may want to use Mark Redman's idea of a CLR proc/assembly if you really need the performance.
How to create the table of dates (and a super fast way to create a numbers table)
/*Gets a list of integers into a temp table (Jeff Moden's idea from SqlServerCentral.com)*/
SELECT TOP 10950 /*30 years of days*/
IDENTITY(INT,1,1) as N
INTO #Numbers
FROM Master.dbo.SysColumns sc1,
Master.dbo.SysColumns sc2
/*Create the dates table*/
CREATE TABLE [TableOfDates](
[fld_date] [datetime] NOT NULL,
CONSTRAINT [PK_TableOfDates] PRIMARY KEY CLUSTERED
(
[fld_date] ASC
)WITH FILLFACTOR = 99 ON [PRIMARY]
) ON [PRIMARY]
/*fill the table with dates*/
DECLARE @daysFromFirstDateInTheTable int
DECLARE @firstDateInTheTable DATETIME
SET @firstDateInTheTable = '01/01/1998'
SET @daysFromFirstDateInTheTable = (SELECT (DATEDIFF(dd, @firstDateInTheTable ,GETDATE()) + 1))
INSERT INTO
TableOfDates
SELECT
DATEADD(dd,nums.n - @daysFromFirstDateInTheTable, CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)) as FLD_Date
FROM #Numbers nums
Now that you have a table of dates, you can use a function (NOT A PROC) like KM's to get the table of them.
CREATE FUNCTION dbo.ListDates
(
@StartDate DATETIME
,@EndDate DATETIME
)
RETURNS
@DateList table
(
Date datetime
)
AS
BEGIN
/*add some validation logic of your own to make sure that the inputs are sound.Adjust the rest as needed*/
INSERT INTO
@DateList
SELECT FLD_Date FROM TableOfDates (NOLOCK) WHERE FLD_Date >= @StartDate AND FLD_Date <= @EndDate
RETURN
END
Free tools supporting panning / zooming:
Free tools without built in pan / zoom support:
Paid tools with built in pan / zoom support:
Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.
https://github.com/FortAwesome/react-fontawesome
install fontawesome & react-fontawesome
$ npm i --save @fortawesome/fontawesome
$ npm i --save @fortawesome/react-fontawesome
$ npm i --save @fortawesome/fontawesome-free-solid
$ npm i --save @fortawesome/fontawesome-free-regular
$ npm i --save @fortawesome/fontawesome-svg-core
then in your component
import React, { Component } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheckSquare, faCoffee } from '@fortawesome/fontawesome-free-solid'
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<h1>
<FontAwesomeIcon icon={faCoffee} />
</h1>
</div>
);
}
}
export default App;
As I can see the code
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
is unreachable.
While we submit spark jobs using spark-submit utility, there is an option --jars
. Using this option, we can pass jar file to spark applications.
Take a look on that link.
You need only to install express module of node js
.
var express = require('express');
var app = express();
app.use('/Folder', express.static(__dirname + '/Folder'));
You can access your file like http://hostname/Folder/file.zip
What if you want to do a comparison for values that ARE NOT equal? Just using a "NOT" in front of the previously mentioned comparisons does not work. The best I could come up with is:
(Field1 <> Field2) OR (NULLIF(Field1, Field2) IS NOT NULL) OR (NULLIF(Field2, Field1) IS NOT NULL)
I'm surprised no one has mentioned using regular expressions via re.sub()
:
import re
print re.sub(r'([\"])', r'\\\1', 'it\'s "this"') # it's \"this\"
print re.sub(r"([\'])", r'\\\1', 'it\'s "this"') # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"') # it\'s\ \"this\"
Important things to note:
\
as well as the character(s) you're looking for.
You're going to be using \
to escape your characters, so you need to escape
that as well.([\"])
, so that the substitution
pattern can use the found character when it adds \
in front of it. (That's what
\1
does: uses the value of the first parenthesized group.)r
in front of r'([\"])'
means it's a raw string. Raw strings use different
rules for escaping backslashes. To write ([\"])
as a plain string, you'd need to
double all the backslashes and write '([\\"])'
. Raw strings are friendlier when
you're writing regular expressions.\
to distinguish it from a
backslash that precedes a substitution group, e.g. \1
, hence r'\\\1'
. To write
that as a plain string, you'd need '\\\\\\1'
— and nobody wants that.Advance for loop
works better for this case
public void deleteRow(DataRow selectedRow)
{
foreach (DataRow in StudentTable.Rows)
{
if (SR[TableColumn.StudentID.ToString()].ToString() == StudentIndex)
SR.Delete();
}
StudentTable.AcceptChanges();
}
With VSCode 1.47+ you can simply use OPT-w for this.
Utilizing built-in functionality to trigger emmet, this is the easiest way:
emmet
window opened in the command palette, type in the tag or wrapping code you need.You can use Google guava as such:
ImmutableList<char> dirs = ImmutableList.of('+', '-', '*', '^');
There is another example which I would like to share with you
:D
http://www.sommarskog.se/dynamic_sql.html#cursor0
I like doing git shortlog -s -n --all
. Gives you a "leaderboard" style list of names and number of commits.
An additional option is to go to your build folder and use the command ccmake .
This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.
The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .
When at the "Add resource folder", Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder
add "my-resource.txt" file inside the new folder. Then in your code:
InputStream res =
Main.class.getResourceAsStream("/my-resource.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(res));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
Since Sheet.getPhysicalNumberOfRows()
does not count empty rows and Sheet.getLastRowNum()
returns 0 both if there is one row or no rows, I use a combination of the two methods to accurately calculate the total number of rows.
int rowTotal = sheet.getLastRowNum();
if ((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {
rowTotal++;
}
Note: This will treat a spreadsheet with one empty row as having none but for most purposes this is probably okay.
I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do
if(!thread.Join(End-now))
throw new NotFinishedInTime();
Here is an approach using str.slice(0, -n)
.
Where n is the number of characters you want to truncate.
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
You can use the Request Desktop Site option from the app menu (to the right of the address bar) which will force the page to reload.
Simply tap it, wait for the refresh, then deselect it.
Sub button2_click()
'
' Button2_Click Macro
'
' Keyboard Shortcut: Ctrl+Shift+Q
'
ActiveSheet.Shapes("Button 2").Select
Selection.Characters.Text = "Logout"
ActiveSheet.Shapes("Button 2").Select
Selection.OnAction = "Button2_Click"
ActiveWorkbook.Saved = True
ActiveWorkbook.Save
Application.Quit
End Sub
Try
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: 'http://imageshack.us/a/img826/9489/x1my.png',
map: map
});
from here
https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom
You are declaring a local variable, not a class variable. To set an instance variable (attribute), use
class Example(object):
def the_example(self):
self.itsProblem = "problem" # <-- remember the 'self.'
theExample = Example()
theExample.the_example()
print(theExample.itsProblem)
To set a class variable (a.k.a. static member), use
class Example(object):
def the_example(self):
Example.itsProblem = "problem"
# or, type(self).itsProblem = "problem"
# depending what you want to do when the class is derived.
user3919888 pointed me in the right direction, but I needed to run Update-Package -reinstall Microsoft.AspNet.WebApi.Client
in the Package-Manager console. Basic install by itself does not recognize the problem but does recognize that the package is already installed and does not overwrite it.
I'm posting this answer because this happens so infrequently that I end up googling and reaching this page before I remember what I did last time.
In Javascript you can do the following:
Object.keys(ahash)[0];
The simpliest way
Scanner in = new Scanner(System.in);
System.out.println("Enter seconds");
int s = in.nextInt();
int sec = s % 60;
int min = (s / 60)%60;
int hours = (s/60)/60;
System.out.println(hours + ":" + min + ":" + sec);
This works in my case. I hope you can extract meaning out of it.
//div[text()='building1' and @class='wrap']/ancestor::tr/td/div/div[@class='x-grid-row-checker']
You may also try the Default encoding, which uses the current system's ANSI codepage.
StreamReader reader = new StreamReader(inputFilePath, Encoding.Default, true)
When you try using the Notepad "Save As" menu with the original file, look at the encoding combo box. It will tell you which encoding notepad guessed is used by the file.
Also, if it is an ANSI file, the detectEncodingFromByteOrderMarks parameter will probably not help much.
So upon finding that there could be a missing package in the buildpath, thus the red x against the main project, to remove this:
1) go into "Configure Buildpath" of project 2) Java Build Path -> Source Tab - you should see the red x against the missing package/file. if it no longer exists, just "remove" it.
red X begone! :)
You can use try catch block to help with not found images
getProductImage(id) {
var images = require.context('@/assets/', false, /\.jpg$/)
let productImage = ''
try {
productImage = images(`./product${id}.jpg`)
} catch (error) {
productImage = images(`./no_image.jpg`)
}
return productImage
},
It seems like you're actually trying to extract a name vice simply find a match. If this is the case, having span indexes for your match is helpful and I'd recommend using re.finditer
. As a shortcut, you know the name
part of your regex is length 5 and the is valid
is length 9, so you can slice the matching text to extract the name.
Note - In your example, it looks like s
is string with line breaks, so that's what's assumed below.
## covert s to list of strings separated by line: s2 = s.splitlines() ## find matches by line: for i, j in enumerate(s2): matches = re.finditer("name (.*) is valid", j) ## ignore lines without a match if matches: ## loop through match group elements for k in matches: ## get text match_txt = k.group(0) ## get line span match_span = k.span(0) ## extract username my_user_name = match_txt[5:-9] ## compare with original text print(f'Extracted Username: {my_user_name} - found on line {i}') print('Match Text:', match_txt)
I'm a bit surprised nobody is using the backspace character. Here's one that uses it.
import sys
import time
secs = 1000
while True:
time.sleep(1) #wait for a full second to pass before assigning a second
secs += 1 #acknowledge a second has passed
sys.stdout.write(str(secs))
for i in range(len(str(secs))):
sys.stdout.write('\b')
The Eclipse UI is a little bit confusing.
The Import -> "Existing projects into workspace" actually means import "Existing Eclipse projects into workspace". That's why you can't click on finish: the import option looks for a .project
file (the file used by Eclipse to store the project options) in the directory that you have chosen.
To import existing source code that doesn't have an Eclipse project file you have the following options (I suppose that you want to create a Java project):
New project inside the workspace dir: Create a new empty Java project into the workspace (File->New->Java Project). Then right click on the source folder and choose Import...->General->File system then choose your files, and it will make a copy of your files.
Tip: you can drag&drop your files from the Finder into the src folder.
Create an eclipse project in your existing dir: Create a new Java project, but in the "New Java Project" window:
I've faced similar problem. You can edit the configuration or create new AVD with higher RAM. Also try increasing Heap to 128. Emulator will work smoothly even without HAXM
This could be due to a face palm moment: if you switch between several clones it is easy to find yourself in the wrong source tree trying to pull a non-existent branch. It is easier when the clones have similar names, or the repos are distinct clones for the same project from each of multiple contributors. A new git clone would obviously seem to solve that "problem" when the real problem is losing focus or working context or both.
Update July 2020:
The default for the parameter stringsAsFactors
is now default.stringsAsFactors()
which in turn yields FALSE
as its default.
Assuming your list of lists is called l
:
df <- data.frame(matrix(unlist(l), nrow=length(l), byrow=TRUE))
The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:
df <- data.frame(matrix(unlist(l), nrow=132, byrow=TRUE),stringsAsFactors=FALSE)
There is one method of Collection
named retainAll
but having some side effects for you reference
Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.
true if this list changed as a result of the call
Its like
boolean b = list1.retainAll(list2);
My solution is to add this code to the app.php
define('WEB_DIRECTORY', __DIR__);
The problem is that in command line code that uses the constant will break. You can also add the constant to app/console file and the other environment front controllers
Another solution may be add an static method at AppKernel that returns DIR.'/../web/' So you can access everywhere
I found this nice write-up that clears it up pretty nicely:
The different graphic assets we request are used to highlight and promote your application in Android Market, and possibly other Google-owned properties. If you’d like to restrict the marketing of your app to just Android Market, you have the option of opting-out of marketing by selecting the "Marketing Opt-Out" in the Developer Console.
Screenshots (Required):
We require 2 screenshots.
Use: Displayed on the details page for your application in Android Market.
You may upload up to 8 screenshots.
Specs: 320w x 480h, 480w x 800h, or 480w x 854h; 24 bit PNG or JPEG (no alpha) Full bleed, no border in art.
Tips:
Landscape thumbnails are cropped, but we preserve the image’s full size and aspect ratio if the user opens it up on market client.
High Resolution Application Icon (Required):
Use: In various locations in Android Market.
Does not replace your launcher icon.
Specs: 512x512, 32-bit PNG with alpha; Max size of 1024KB.
Tips:
This does not replace your launcher icon, but should be a higher-fidelity, higher-resolution version of your application icon.
Same safe-frame as current launcher guidelines, just scaled up:
Full Asset: 512 x 512 px.
Circle or non-square icons: 426 x 426 px, centered within the PNG.
Square Icons: 398 x 398 px.
Drop shadow: black, 75% opaque, 90 degrees down, distance of 14px, size of 36px.
Tweak as necessary to fit icon style (e.g., Google Maps icon has a drop shadow of varying height).
Promotional Graphic (Optional):
Use: In various locations in Android Market.
Specs: 180w x 120h, 24 bit PNG or JPEG (no alpha), Full bleed, no border in art.
Feature Graphic (Optional):
Use: The featured section in Android Market. Will be downsized to mini or micro.
Specs: 1024w x 500h, 24 bit PNG or JPEG (no alpha) with no transparency
Tips:
Use a safe frame of 924x400 (50 pixel of safe padding on each side). All the important content of the graphic should be within this safe frame. Pixels outside of this safe frame may be cropped for stylistic purposes.
If incorporating text, use large font sizes, and keep the graphic simple, as this graphic may be scaled down from its original size.
This graphic may be displayed alone without the app icon.
Video Link (Optional):
Specs: Enter the URL to a YouTube video showcasing your app.
Tip:
Short videos (30 seconds - 2 minutes) highlighting the top features of your app work best.
Even i ran into the same issue with mysql and liquibase. So this is what the problem is: The table from which you want to reference a column of other table is different either in case of datatype or in terms of size of the datatype.
Error appears in below scenario:
Scenario 1:
Table A has column id, type=bigint
Table B column referenced_id type varchar(this column gets the value from the id column of Table A.)
Liquibase changeset for table B:
<changeset id="XXXXXXXXXXX-1" author="xyz">
<column name="referenced_id" **type="varchar"**>
</column>
</changeset>
<changeSet id="XXXXXXXXXXX-2" author="xyz">
<addForeignKeyConstraint constraintName="FK_table_A"
referencedTableName="A" **baseColumnNames="referenced_id**"
referencedColumnNames="id" baseTableName="B" />
</changeSet>
Table A changeSet:
<changeSet id="YYYYYYYYYY" author="xyz">
<column **name="id"** **type="bigint"** autoIncrement="${autoIncrement}">
<constraints primaryKey="true" nullable="false"/>
</column>
</changeSet>
Solution:
correct the type of table B to bigint because the referenced table has type bigint.
Scenrario 2:
The type might be correct but the size might not.
e.g. :
Table B : referenced column type="varchar 50"
Table A : base column type ="varchar 255"
Solution change the size of referenced column to that of base table's column size.
import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:
$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session
or
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
<?php
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[1];
}
$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
$txt = getTextBetweenTags($str, "font");
echo $txt;
?>
That should do the trick
You can achieve the following by using a single line in your spinner declaration in XML:
Just add this: style="@android:style/Widget.Holo.Light.Spinner"
This is a default generated style in android. It doesn't contain borders around it though. For that you'd better search something on google.
Hope this helps.
UPDATE: AFter a lot of digging I got something which works well for introducing border around spinner.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="8dp"
android:top="8dp">
<shape>
<solid android:color="@android:color/white" />
<corners android:radius="4dp" />
<stroke
android:width="2dp"
android:color="#9E9E9E" />
<padding
android:bottom="16dp"
android:left="8dp"
android:right="16dp"
android:top="16dp" />
</shape>
</item>
</layer-list>
Place this in the drawable folder and use it as a background for spinner. Like this:
<RelativeLayout
android:id="@+id/speaker_relative_layout"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:background="@drawable/spinner_style"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Spinner
android:id="@+id/select_speaker_spinner"
style="@style/Widget.AppCompat.DropDownItem.Spinner"
android:layout_width="match_parent"
android:layout_height="70dp"
android:entries="@array/select_speaker_spinner_array"
android:spinnerMode="dialog" />
</RelativeLayout>
I wanted to share the steps that I followed that fixed this issue for me in the hopes that it can help someone else (and also as a reminder for me in case something like this happens again)
The issues I'd been having (which were the same as OP's) may have to do with using homebrew to install Ruby.
To fix this, first I updated homebrew:
brew update && brew upgrade
brew doctor
(If brew doctor comes up with any issues, fix them first.) Then I uninstalled ruby
brew uninstall ruby
If rbenv is NOT installed at this point, then
brew install rbenv
brew install ruby-build
echo 'export RBENV_ROOT=/usr/local/var/rbenv' >> ~/.bash_profile
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
Then I used rbenv to install ruby. First, find the desired version:
rbenv install -l
Install that version (e.g. 2.2.2)
rbenv install 2.2.2
Then set the global version to the desired ruby version:
rbenv global 2.2.2
At this point you should see the desired version set for the following commands:
rbenv versions
and
ruby --version
Now you should be able to install bundler:
gem install bundler
And once in the desired project folder, you can install all the required gems:
bundle
bundle install
For those who understand that you have to overlay an invisible form over the link, but are too lazy to write, I wrote it for you. Well, for me, but might as well share. Comments are welcome.
HTML (Somewhere):
<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>
HTML (Somewhere you don't care about):
<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
</form>
</div>
JavaScript:
function pageY(el) {
var ot = 0;
while (el && el.offsetParent != el) {
ot += el.offsetTop ? el.offsetTop : 0;
el = el.offsetParent;
}
return ot;
}
function pageX(el) {
var ol = 0;
while (el && el.offsetParent != el) {
ol += el.offsetLeft ? el.offsetLeft : 0;
el = el.offsetParent;
}
return ol;
}
function fileMove() {
if (navigator.appName == "Microsoft Internet Explorer") {
return; // Don't need to do this in IE.
}
var link = document.getElementById("fileLink");
var form = document.getElementById("uploadForm");
var x = pageX(link);
var y = pageY(link);
form.style.position = 'absolute';
form.style.left = x + 'px';
form.style.top = y + 'px';
}
function fileBrowse() {
// This works in IE only. Doesn't do jack in FF. :(
var browseField = document.getElementById("uploadForm").file;
browseField.click();
}
The year()
function just retrieves the year component of the underlying Date
object, so it returns a number.
Calling format('YYYY')
will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY
, then the result will be a string containing the year.
If all you need is the year, then use the year()
function. It will be faster, as there is less work to do.
Do note that while years are the same in this regard, months are not! Calling format('M')
will return months in the range 1-12. Calling month()
will return months in the range 0-11. This is due to the same behavior of the underlying Date
object.
As long as you go into the IIS configuration and change the default location from %SystemDrive%\InetPub to %SystemDrive%\www for each of the services (web, ftp) there shouldn't be any problems. Of course, you can't protect against other applications that might install stuff into that directory by default, instead of checking the configuration.
My recommendation? Don't change it -- it's not that hard to live with, and it reduces the confusion level for the next person who has to administrate the machine.
At my Version the function to get the lenght or size was Count()
You're Welcome, hope it help someone.
as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class
public class Book {
public string Title {get; set;}
public string Author {get; set;}
}
you can read the XML file line by line with a small memory footprint, like this:
public static class XmlHelper {
public static IEnumerable<Book> StreamBooks(string uri) {
using (XmlReader reader = XmlReader.Create(uri)) {
string title = null;
string author = null;
reader.MoveToContent();
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == "Book") {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Title") {
title = reader.ReadString();
break;
}
}
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Author") {
author =reader.ReadString();
break;
}
}
yield return new Book() {Title = title, Author = author};
}
}
}
}
Example of usage:
string uri = @"c:\test.xml"; // your big XML file
foreach (var book in XmlHelper.StreamBooks(uri)) {
Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);
}
Add the image to Your project by clicking File -> "Add Files to ...".
Then choose the image in ImageView properties (Utilities -> Attributes Inspector).
the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)
=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679
So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)
On Chrome this has proven to work well for me.
<a href="newsletter_01.pdf" target="_new">Read more</a>
You must know the source encoding.
string someText = "The quick brown fox jumps over the lazy dog.";
byte[] bytes = Encoding.Unicode.GetBytes(someText);
char[] chars = Encoding.Unicode.GetChars(bytes);
The <p>
tag is a p
aragraph, and as such, it is a block element (as is, for instance, h1
and div
), whereas span
is an inline element (as, for instance, b
and a
)
Block elements by default create some whitespace above and below themselves, and nothing can be aligned next to them, unless you set a float
attribute to them.
Inline elements deal with spans of text inside a paragraph. They typically have no margins, and as such, you cannot, for instance, set a width
to it.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
RewriteRule ^(.*)$ "http://www.thenewdomain.com/" [R=301,L]
Thing is $@
will include the entire (relative) path to the source file which is in turn used to construct the object name (and thus its relative path)
We use:
#####################
# rules to build the object files
$(OBJDIR_1)/%.o: %.c
@$(ECHO) "$< -> $@"
@test -d $(OBJDIR_1) || mkdir -pm 775 $(OBJDIR_1)
@test -d $(@D) || mkdir -pm 775 $(@D)
@-$(RM) $@
$(CC) $(CFLAGS) $(CFLAGS_1) $(ALL_FLAGS) $(ALL_DEFINES) $(ALL_INCLUDEDIRS:%=-I%) -c $< -o $@
This creates an object directory with name specified in $(OBJDIR_1)
and subdirectories according to subdirectories in source.
For example (assume objs as toplevel object directory), in Makefile:
widget/apple.cpp
tests/blend.cpp
results in following object directory:
objs/widget/apple.o
objs/tests/blend.o
I wrote this helper function:
def is_module_available(module_name):
if sys.version_info < (3, 0):
# python 2
import importlib
torch_loader = importlib.find_loader(module_name)
elif sys.version_info <= (3, 3):
# python 3.0 to 3.3
import pkgutil
torch_loader = pkgutil.find_loader(module_name)
elif sys.version_info >= (3, 4):
# python 3.4 and above
import importlib
torch_loader = importlib.util.find_spec(module_name)
return torch_loader is not None
sorry for answering in old thread but may my code helps other in future.i was in same scenario that when check box will be checked then few selected inputs fields will be enable other wise disabled.
$("[id*='chkAddressChange']").click(function () {
var checked = $(this).is(':checked');
if (checked) {
$('.DisabledInputs').removeAttr('disabled');
} else {
$('.DisabledInputs').attr('disabled', 'disabled');
}
});
Guest additions are not available for Mac OS X. You can get features like clipboard sync and shared folders by using VNC and SMB. Here's my answer on a similar question.
Or, alternatively, you can take a list comprehension
approach:
>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
<input id="date" name="date" />
<script type="text/javascript">
document.getElementById("date").value = new Date();
</script>
You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.
Read up on the lock statement.
EDIT
Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.
public class Queue<T>
{
/// <summary>Used as a lock target to ensure thread safety.</summary>
private readonly Locker _Locker = new Locker();
private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();
/// <summary></summary>
public void Enqueue(T item)
{
lock (_Locker)
{
_Queue.Enqueue(item);
}
}
/// <summary>Enqueues a collection of items into this queue.</summary>
public virtual void EnqueueRange(IEnumerable<T> items)
{
lock (_Locker)
{
if (items == null)
{
return;
}
foreach (T item in items)
{
_Queue.Enqueue(item);
}
}
}
/// <summary></summary>
public T Dequeue()
{
lock (_Locker)
{
return _Queue.Dequeue();
}
}
/// <summary></summary>
public void Clear()
{
lock (_Locker)
{
_Queue.Clear();
}
}
/// <summary></summary>
public Int32 Count
{
get
{
lock (_Locker)
{
return _Queue.Count;
}
}
}
/// <summary></summary>
public Boolean TryDequeue(out T item)
{
lock (_Locker)
{
if (_Queue.Count > 0)
{
item = _Queue.Dequeue();
return true;
}
else
{
item = default(T);
return false;
}
}
}
}
EDIT 2
I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.
public class WorkState
{
private readonly Object _Lock = new Object();
private Int32 _State;
public Int32 GetState()
{
lock (_Lock)
{
return _State;
}
}
public void UpdateState()
{
lock (_Lock)
{
_State++;
}
}
}
public class Worker
{
private readonly WorkState _State;
private readonly Thread _Thread;
private volatile Boolean _KeepWorking;
public Worker(WorkState state)
{
_State = state;
_Thread = new Thread(DoWork);
_KeepWorking = true;
}
public void DoWork()
{
while (_KeepWorking)
{
_State.UpdateState();
}
}
public void StartWorking()
{
_Thread.Start();
}
public void StopWorking()
{
_KeepWorking = false;
}
}
private void Execute()
{
WorkState state = new WorkState();
Worker worker = new Worker(state);
worker.StartWorking();
while (true)
{
if (state.GetState() > 100)
{
worker.StopWorking();
break;
}
}
}
You could listen to the 'keydown'
event and then check for an enter key.
Your handler would be like:
function (e) {
if (13 == e.keyCode) {
... do whatever ...
}
}
You simply need to remove v-bind (:) from selected and required attributes. Like this :-
<template>_x000D_
<select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
<option selected>Choose Province</option>_x000D_
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
</select>_x000D_
</template>
_x000D_
You are not binding anything to the vue instance through these attributes thats why it is giving error.
You can use == to compare with a zero value composite literal because all fields are comparable:
if (Session{}) == session {
fmt.Println("is zero value")
}
Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.
The use of ==
above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.
An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use
if session.playerId == "" {
fmt.Println("is zero value")
}
Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.
The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.
C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes
Here's some code that I ended up writing, based upon @Andrei's answer but without the elegancy/simplicity. The advantage is that it allows a more complex recursive merge and also differs between elements that should be connected with rbind
and those that are just connected with c
:
# Decided to move this outside the mapply, not sure this is
# that important for speed but I imagine redefining the function
# might be somewhat time-consuming
mergeLists_internal <- function(o_element, n_element){
if (is.list(n_element)){
# Fill in non-existant element with NA elements
if (length(n_element) != length(o_element)){
n_unique <- names(n_element)[! names(n_element) %in% names(o_element)]
if (length(n_unique) > 0){
for (n in n_unique){
if (is.matrix(n_element[[n]])){
o_element[[n]] <- matrix(NA,
nrow=nrow(n_element[[n]]),
ncol=ncol(n_element[[n]]))
}else{
o_element[[n]] <- rep(NA,
times=length(n_element[[n]]))
}
}
}
o_unique <- names(o_element)[! names(o_element) %in% names(n_element)]
if (length(o_unique) > 0){
for (n in o_unique){
if (is.matrix(n_element[[n]])){
n_element[[n]] <- matrix(NA,
nrow=nrow(o_element[[n]]),
ncol=ncol(o_element[[n]]))
}else{
n_element[[n]] <- rep(NA,
times=length(o_element[[n]]))
}
}
}
}
# Now merge the two lists
return(mergeLists(o_element,
n_element))
}
if(length(n_element)>1){
new_cols <- ifelse(is.matrix(n_element), ncol(n_element), length(n_element))
old_cols <- ifelse(is.matrix(o_element), ncol(o_element), length(o_element))
if (new_cols != old_cols)
stop("Your length doesn't match on the elements,",
" new element (", new_cols , ") !=",
" old element (", old_cols , ")")
}
return(rbind(o_element,
n_element,
deparse.level=0))
return(c(o_element,
n_element))
}
mergeLists <- function(old, new){
if (is.null(old))
return (new)
m <- mapply(mergeLists_internal, old, new, SIMPLIFY=FALSE)
return(m)
}
Here's my example:
v1 <- list("a"=c(1,2), b="test 1", sublist=list(one=20:21, two=21:22))
v2 <- list("a"=c(3,4), b="test 2", sublist=list(one=10:11, two=11:12, three=1:2))
mergeLists(v1, v2)
This results in:
$a
[,1] [,2]
[1,] 1 2
[2,] 3 4
$b
[1] "test 1" "test 2"
$sublist
$sublist$one
[,1] [,2]
[1,] 20 21
[2,] 10 11
$sublist$two
[,1] [,2]
[1,] 21 22
[2,] 11 12
$sublist$three
[,1] [,2]
[1,] NA NA
[2,] 1 2
Yeah, I know - perhaps not the most logical merge but I have a complex parallel loop that I had to generate a more customized .combine
function for, and therefore I wrote this monster :-)
You can also use DateTime class:
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
Result:
1 second(s)
TortoiseSVN is an astonishingly good Windows client for the Subversion version control system. One feature which I just discovered that it has is that when you click to get a diff between versions of an Excel file, it will open both versions in Excel and highlight (in red) the cells that were changed. This is done through the magic of a vbs script, described here.
You may find this useful even if NOT using TortoiseSVN.
My solution in Header parameters with example is user="test" is:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){
System.out.println(headers.get("user"));
}
Update 2018
Bootstrap 4
Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col
class on the fluid column.
.sidebar {
width: 180px;
min-height: 100vh;
}
<div class="row">
<div class="sidebar p-2">Fixed width</div>
<div class="col bg-dark text-white pt-2">
Content
</div>
</div>
http://www.codeply.com/go/7LzXiPxo6a
Bootstrap 3..
One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...
@media (min-width:768px) {
#sidebar {
min-width: 300px;
max-width: 300px;
}
#main {
width:calc(100% - 300px);
}
}
Working Bootstrap 3 Fixed-Fluid Demo
Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?
Had a similar problem. Needed to append as many text inputs as the user wanted, to a form. The functionality of it using jQuery was the answer to the question:
<div id='inputdiv'>
<button id='mybutton'>add an input</button>
</div>
<script>
var thecounter=0; //declare and initialize the counter outside of the function
$('#mybutton').on('click', function(){
thecounter++;
$('#inputdiv').append('<input id="input'+thecounter+'" type="text/>);
});
</script>
Adding the count to each new input id resulted in unique ids which lets you get all the values using the jQuery serialize() function.
If you want to see what is run in the database use dd(DB::getQueryLog())
to see what queries were run.
Try this
BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
var visible = $(".media").visible();