virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install --user -r requirements.txt
My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.
This is the total number of connections to the server till now. To find current conection status you can use
mysqladmin -u -p extended-status | grep -wi 'threads_connected\|threads_running' | awk '{ print $2,$4}'
This will show you:
Threads_connected 12
Threads_running 1
Threads_connected: Number of connections
Threads_running: connections currently running some sql
Yes, but you can select only one column in your subselect
SELECT (SELECT id FROM bla) AS my_select FROM bla2
Forward port of .live()
for jQuery >= 1.9
Avoids refactoring JS dependencies on .live()
Uses optimized DOM selector context
/**
* Forward port jQuery.live()
* Wrapper for newer jQuery.on()
* Uses optimized selector context
* Only add if live() not already existing.
*/
if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
}
});
}
We can solve it in data.table
way with tidyr::repalce_na
function and lapply
library(data.table)
library(tidyr)
setDT(df)
df[,c("a","b","c"):=lapply(.SD,function(x) replace_na(x,0)),.SDcols=c("a","b","c")]
In this way, we can also solve paste columns with NA
string. First, we replace_na(x,"")
,then we can use stringr::str_c
to combine columns!
brew install cask
brew cask install xquartz
brew tap homebrew/science
brew install r
This way, everything is packager managed, so there's no need to manually download and install anything.
There is another possible scenario I have just come across.
I did an ajax call and got data back as null, in a string format. I had to check it like this:
if(value != 'null'){}
So, null was a string which read "null" rather than really being null.
EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.
I run npm list
and installed all the packages listed as UNMET DEPENDENCY
For instance:
+-- UNMET DEPENDENCY css-loader@^0.23.1
npm install css-loader@^0.23.1
If you've already pushed things to a remote server (and you have other developers working off the same remote branch) the important thing to bear in mind is that you don't want to rewrite history
Don't use git reset --hard
You need to revert changes, otherwise any checkout that has the removed commits in its history will add them back to the remote repository the next time they push; and any other checkout will pull them in on the next pull thereafter.
If you have not pushed changes to a remote, you can use
git reset --hard <hash>
If you have pushed changes, but are sure nobody has pulled them you can use
git reset --hard
git push -f
If you have pushed changes, and someone has pulled them into their checkout you can still do it but the other team-member/checkout would need to collaborate:
(you) git reset --hard <hash>
(you) git push -f
(them) git fetch
(them) git reset --hard origin/branch
But generally speaking that's turning into a mess. So, reverting:
The commits to remove are the lastest
This is possibly the most common case, you've done something - you've pushed them out and then realized they shouldn't exist.
First you need to identify the commit to which you want to go back to, you can do that with:
git log
just look for the commit before your changes, and note the commit hash. you can limit the log to the most resent commits using the -n
flag: git log -n 5
Then reset your branch to the state you want your other developers to see:
git revert <hash of first borked commit>..HEAD
The final step is to create your own local branch reapplying your reverted changes:
git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .
Continue working in my-new-branch
until you're done, then merge it in to your main development branch.
The commits to remove are intermingled with other commits
If the commits you want to revert are not all together, it's probably easiest to revert them individually. Again using git log
find the commits you want to remove and then:
git revert <hash>
git revert <another hash>
..
Then, again, create your branch for continuing your work:
git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .
Then again, hack away and merge in when you're done.
You should end up with a commit history which looks like this on my-new-branch
2012-05-28 10:11 AD7six o [my-new-branch] Revert "Revert "another mistake""
2012-05-28 10:11 AD7six o Revert "Revert "committing a mistake""
2012-05-28 10:09 AD7six o [master] Revert "committing a mistake"
2012-05-28 10:09 AD7six o Revert "another mistake"
2012-05-28 10:08 AD7six o another mistake
2012-05-28 10:08 AD7six o committing a mistake
2012-05-28 10:05 Bob I XYZ nearly works
Better way®
Especially that now that you're aware of the dangers of several developers working in the same branch, consider using feature branches always for your work. All that means is working in a branch until something is finished, and only then merge it to your main branch. Also consider using tools such as git-flow to automate branch creation in a consistent way.
The Ascii codes for arrow characters are the following: ? 24 ? 25 ? 26 ? 27
Had the same problem with laravel 5.3... This is how I did it and very easy. for example logo in the blade page view
****<image img src="/img/logo.png" alt="Logo"></image>****
Create a login for the user
Drop and re-create the user, WITH the login you created.
There are other topics discussing how to replicate the permissions of your user. I recommend that you take the opportunity to define those permissions in a Role and call sp_addrolemember to add the user to the Role.
I solved this another way. First of all I installed cuda 10.1 toolkit from this link
Where i selected installer type(exe(local)) and installed 10.1 in custom mode means (without visual studio integration, NVIDIA PhysX because previously I installed CUDA 10.2 so required dependencies were installed automatically)
After installation, From the Following Path (C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin) , in my case, I copied 'cudart64_101.dll' file and pasted in (C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\bin).
Then importing Tensorflow worked smoothly.
N.B. Sorry for Bad English
/**
import java liberary class
*/
import java.util.Scanner;
/* class to find factorial of a number
*/
public class factorial
{
public static void main(String[] args)
{
// scanner method for read keayboard values
Scanner factor= new Scanner(System.in);
int n;
double total = 1;
double sum= 1;
System.out.println("\nPlease enter an integer: ");
n = factor.nextInt();
// evaluvate the integer is greater than zero and calculate factorial
if(n==0)
{
System.out.println(" Factorial of 0 is 1");
}
else if (n>0)
{
System.out.println("\nThe factorial of " + n + " is " );
System.out.print(n);
for(int i=1;i<n;i++)
{
do // do while loop for display each integer in the factorial
{
System.out.print("*"+(n-i) );
}
while ( n == 1);
total = total * i;
}
// calculate factorial
sum= total * n;
// display sum of factorial
System.out.println("\n\nThe "+ n +" Factorial is : "+" "+ sum);
}
// display invalid entry, if enter a value less than zero
else
{
System.out.println("\nInvalid entry!!");
}System.exit(0);
}
}
You can use this
<button type="submit" class="btn btn-primary btn-block w-50 mx-auto">Search</button>
Complete Form code -
<form id="submit">
<input type="text" class="form-control mt-5" id="search-city"
placeholder="Search City">
<button type="submit" class="btn btn-primary mt-3 btn-sm btn-block w-50
mx-auto">Search</button>
</form>
Use fabs() instead of abs(), it's the same but for floats instead of integers.
This worked for me
class _SplashScreenState extends State<SplashScreen> {
@override
Widget build(BuildContext context) {
return Container(
child: FittedBox(
child: Image.asset("images/my_image.png"),
fit: BoxFit.fill,
),);
}
}
The stream should really by disposed of even if there's an exception (quite likely on file I/O) - using clauses are my favourite approach for this, so for writing your MemoryStream, you can use:
using (FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write)) {
memoryStream.WriteTo(file);
}
And for reading it back:
using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read)) {
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
}
If the files are large, then it's worth noting that the reading operation will use twice as much memory as the total file size. One solution to that is to create the MemoryStream from the byte array - the following code assumes you won't then write to that stream.
MemoryStream ms = new MemoryStream(bytes, writable: false);
My research (below) shows that the internal buffer is the same byte array as you pass it, so it should save memory.
byte[] testData = new byte[] { 104, 105, 121, 97 };
var ms = new MemoryStream(testData, 0, 4, false, true);
Assert.AreSame(testData, ms.GetBuffer());
try
states.split()
it returns the list
['Alaska',
'Alabama',
'Arkansas',
'American',
'Samoa',
'Arizona',
'California',
'Colorado']
and this returns the random element of the list
import random
random.choice(states.split())
split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example
states.split('Ari')
returns
['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']
Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here
I see you are probably new to python, so I'd give you some advice how to use python's great documentation
Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language
I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this
I realize this question is old but I didn't understand Antak's answer and didn't want to use a library so I rolled my own solution.
Solution assumes records is a 2D array, records are all the same length, and that fields are all strings.
def stringifyRecords(records):
column_widths = [0] * len(records[0])
for record in records:
for i, field in enumerate(record):
width = len(field)
if width > column_widths[i]: column_widths[i] = width
s = ""
for record in records:
for column_width, field in zip(column_widths, record):
s += field.ljust(column_width+1)
s += "\n"
return s
Mark Longair's answer (using git show
) is close to what is desired in the question. However, it also includes the commit pointed at by the tag, along with the full patch for that commit. Since the commit can be somewhat unrelated to the tag (it's only one commit that the tag is attempting to capture), this may be undesirable. I believe the following is a bit nicer:
for t in `git tag -l`; do git cat-file -p `git rev-parse $t`; done
Try the following:
int[][] multi = new int[5][10];
... which is a short hand for something like this:
int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];
Note that every element will be initialized to the default value for int
, 0
, so the above are also equivalent to:
int[][] multi = new int[][]{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
Remove the coma at the end of your SELECT statement (VALUE,), and also remove the one at the end of your FROM statement (rrf b,)
You can also use XPath's text()
node test to get the text nodes only. For example
var target = document.querySelector('div.title');
var iter = document.evaluate('text()', target, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);
var node;
var want = '';
while (node = iter.iterateNext()) {
want += node.data;
}
You can use the mask to copy only the region of interest of an original image to a destination one:
cvCopy(origImage,destImage,mask);
where mask
should be an 8-bit single channel array.
See more at the OpenCV docs
There are a few ways to do this.
You could use type="number"
:
<input type="number" />
Alternatively - I created a reuseable directive for this that uses a regular expression.
Html
<div ng-app="myawesomeapp">
test: <input restrict-input="^[0-9-]*$" maxlength="20" type="text" class="test" />
</div>
Javascript
;(function(){
var app = angular.module('myawesomeapp',[])
.directive('restrictInput', [function(){
return {
restrict: 'A',
link: function (scope, element, attrs) {
var ele = element[0];
var regex = RegExp(attrs.restrictInput);
var value = ele.value;
ele.addEventListener('keyup',function(e){
if (regex.test(ele.value)){
value = ele.value;
}else{
ele.value = value;
}
});
}
};
}]);
}());
if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:
select
psat.schemaname,
psat.relname,
pa.attname,
psat.relid
from
pg_catalog.pg_stat_all_tables psat,
pg_catalog.pg_attribute pa
where
psat.relid = pa.attrelid
change schema name:
ALTER SCHEMA "XXXXX" RENAME TO xxxxx;
change table names:
ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;
change column names:
ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;
I made this generic state machine out of Juliet's code. It's working awesome for me.
These are the benefits:
TState
and TCommand
, TransitionResult<TState>
to have more control over the output results of [Try]GetNext()
methodsStateTransition
only through AddTransition(TState, TCommand, TState)
making it easier to work with itCode:
public class StateMachine<TState, TCommand>
where TState : struct, IConvertible, IComparable
where TCommand : struct, IConvertible, IComparable
{
protected class StateTransition<TS, TC>
where TS : struct, IConvertible, IComparable
where TC : struct, IConvertible, IComparable
{
readonly TS CurrentState;
readonly TC Command;
public StateTransition(TS currentState, TC command)
{
if (!typeof(TS).IsEnum || !typeof(TC).IsEnum)
{
throw new ArgumentException("TS,TC must be an enumerated type");
}
CurrentState = currentState;
Command = command;
}
public override int GetHashCode()
{
return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode();
}
public override bool Equals(object obj)
{
StateTransition<TS, TC> other = obj as StateTransition<TS, TC>;
return other != null
&& this.CurrentState.CompareTo(other.CurrentState) == 0
&& this.Command.CompareTo(other.Command) == 0;
}
}
private Dictionary<StateTransition<TState, TCommand>, TState> transitions;
public TState CurrentState { get; private set; }
protected StateMachine(TState initialState)
{
if (!typeof(TState).IsEnum || !typeof(TCommand).IsEnum)
{
throw new ArgumentException("TState,TCommand must be an enumerated type");
}
CurrentState = initialState;
transitions = new Dictionary<StateTransition<TState, TCommand>, TState>();
}
/// <summary>
/// Defines a new transition inside this state machine
/// </summary>
/// <param name="start">source state</param>
/// <param name="command">transition condition</param>
/// <param name="end">destination state</param>
protected void AddTransition(TState start, TCommand command, TState end)
{
transitions.Add(new StateTransition<TState, TCommand>(start, command), end);
}
public TransitionResult<TState> TryGetNext(TCommand command)
{
StateTransition<TState, TCommand> transition = new StateTransition<TState, TCommand>(CurrentState, command);
TState nextState;
if (transitions.TryGetValue(transition, out nextState))
return new TransitionResult<TState>(nextState, true);
else
return new TransitionResult<TState>(CurrentState, false);
}
public TransitionResult<TState> MoveNext(TCommand command)
{
var result = TryGetNext(command);
if(result.IsValid)
{
//changes state
CurrentState = result.NewState;
}
return result;
}
}
This is the return type of TryGetNext method:
public struct TransitionResult<TState>
{
public TransitionResult(TState newState, bool isValid)
{
NewState = newState;
IsValid = isValid;
}
public TState NewState;
public bool IsValid;
}
This is how you can create a OnlineDiscountStateMachine
from the generic class:
Define an enum OnlineDiscountState
for its states and an enum OnlineDiscountCommand
for its commands.
Define a class OnlineDiscountStateMachine
derived from the generic class using those two enums
Derive the constructor from base(OnlineDiscountState.InitialState)
so that the initial state is set to OnlineDiscountState.InitialState
Use AddTransition
as many times as needed
public class OnlineDiscountStateMachine : StateMachine<OnlineDiscountState, OnlineDiscountCommand>
{
public OnlineDiscountStateMachine() : base(OnlineDiscountState.Disconnected)
{
AddTransition(OnlineDiscountState.Disconnected, OnlineDiscountCommand.Connect, OnlineDiscountState.Connected);
AddTransition(OnlineDiscountState.Disconnected, OnlineDiscountCommand.Connect, OnlineDiscountState.Error_AuthenticationError);
AddTransition(OnlineDiscountState.Connected, OnlineDiscountCommand.Submit, OnlineDiscountState.WaitingForResponse);
AddTransition(OnlineDiscountState.WaitingForResponse, OnlineDiscountCommand.DataReceived, OnlineDiscountState.Disconnected);
}
}
use the derived state machine
odsm = new OnlineDiscountStateMachine();
public void Connect()
{
var result = odsm.TryGetNext(OnlineDiscountCommand.Connect);
//is result valid?
if (!result.IsValid)
//if this happens you need to add transitions to the state machine
//in this case result.NewState is the same as before
Console.WriteLine("cannot navigate from this state using OnlineDiscountCommand.Connect");
//the transition was successfull
//show messages for new states
else if(result.NewState == OnlineDiscountState.Error_AuthenticationError)
Console.WriteLine("invalid user/pass");
else if(result.NewState == OnlineDiscountState.Connected)
Console.WriteLine("Connected");
else
Console.WriteLine("not implemented transition result for " + result.NewState);
}
By mid-2016 the Chromium engine (v53) supports just 3 emphasis styles:
Plain text, bold, and super-bold...
<div style="font:normal 400 14px Arial;">Testing</div>
<div style="font:normal 700 14px Arial;">Testing</div>
<div style="font:normal 800 14px Arial;">Testing</div>
from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME
FILENAME is w/o the suffix
<style>
.nowrap {
white-space: nowrap;
}
</style>
...
<label for="id1" class="nowrap">label1:
<input type="text" id="id1"/>
</label>
Wrap your inputs within the label tag
Another way: (Since SQL Server 2012)
SELECT
DATEFROMPARTS(YEAR(GETDATE()), 1, 1) FirstDay,
DATEFROMPARTS(YEAR(GETDATE()),12,31) LastDay
Does not solve the problem of network going down between checking and running your code but is fairly reliable
public static bool IsAvailableNetworkActive()
{
// only recognizes changes related to Internet adapters
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
// however, this will include all adapters -- filter by opstatus and activity
NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
return (from face in interfaces
where face.OperationalStatus == OperationalStatus.Up
where (face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)
select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
}
return false;
}
Just return object: it will be parser to JSON.
public Object Get(string id)
{
return new { id = 1234 };
}
You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:
UPDATE messages
SET status=10
WHERE ID in (SELECT TOP (10) Id
FROM Table
WHERE status=0
ORDER BY priority DESC);
the rest was fairly easy.
Simply go to this folder: C:\Users{UserName}\AppData\Local\Microsoft\Team Foundation\4\Cache and delete all that's in the folder.
I thought Activity was deprecated
No.
So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?
Activity
is the baseline. Every activity inherits from Activity
, directly or indirectly.
FragmentActivity
is for use with the backport of fragments found in the support-v4
and support-v13
libraries. The native implementation of fragments was added in API Level 11, which is lower than your proposed minSdkVersion
values. The only reason why you would need to consider FragmentActivity
specifically is if you want to use nested fragments (a fragment holding another fragment), as that was not supported in native fragments until API Level 17.
AppCompatActivity
is from the appcompat-v7
library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need AppCompatActivity
for that. However, current versions of appcompat-v7
also add a limited backport of the Material Design aesthetic, in terms of the action bar and various widgets. There are pros and cons of using appcompat-v7
, well beyond the scope of this specific Stack Overflow answer.
ActionBarActivity
is the old name of the base activity from appcompat-v7
. For various reasons, they wanted to change the name. Unless some third-party library you are using insists upon an ActionBarActivity
, you should prefer AppCompatActivity
over ActionBarActivity
.
So, given your minSdkVersion
in the 15-16 range:
If you want the backported Material Design look, use AppCompatActivity
If not, but you want nested fragments, use FragmentActivity
If not, use Activity
Just adding from comment as note: AppCompatActivity
extends FragmentActivity
, so anyone who needs to use features of FragmentActivity
can use AppCompatActivity
.
var propInfo = typeof(Class1).GetProperty("Name");
var displayNameAttribute = propInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false);
var displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
displayName
variable now holds the property's value.
In Internet Explorer, parentElement
is undefined for SVG elements, whereas parentNode
is defined.
This is how I do it:
CSS:
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table
}
#content {
display: table-cell;
text-align: center;
vertical-align: middle
}
HTML:
<div id="content">
Content goes here
</div>
See
and
You may try this, I have developed a tool to generate hive scripts from a csv file. Following are few examples on how files are generated. Tool -- https://sourceforge.net/projects/csvtohive/?source=directory
Select a CSV file using Browse and set hadoop root directory ex: /user/bigdataproject/
Tool Generates Hadoop script with all csv files and following is a sample of generated Hadoop script to insert csv into Hadoop
#!/bin/bash -v
hadoop fs -put ./AllstarFull.csv /user/bigdataproject/AllstarFull.csv
hive -f ./AllstarFull.hive
hadoop fs -put ./Appearances.csv /user/bigdataproject/Appearances.csv
hive -f ./Appearances.hive
hadoop fs -put ./AwardsManagers.csv /user/bigdataproject/AwardsManagers.csv
hive -f ./AwardsManagers.hive
Sample of generated Hive scripts
CREATE DATABASE IF NOT EXISTS lahman;
USE lahman;
CREATE TABLE AllstarFull (playerID string,yearID string,gameNum string,gameID string,teamID string,lgID string,GP string,startingPos string) row format delimited fields terminated by ',' stored as textfile;
LOAD DATA INPATH '/user/bigdataproject/AllstarFull.csv' OVERWRITE INTO TABLE AllstarFull;
SELECT * FROM AllstarFull;
Thanks Vijay
I use both windows and linux, but the solution core.autocrlf true
didn't help me. I even got nothing changed after git checkout <filename>
.
So I use workaround to substitute git status
- gitstatus.sh
#!/bin/bash
git status | grep modified | cut -d' ' -f 4 | while read x; do
x1="$(git show HEAD:$x | md5sum | cut -d' ' -f 1 )"
x2="$(cat $x | md5sum | cut -d' ' -f 1 )"
if [ "$x1" != "$x2" ]; then
echo "$x NOT IDENTICAL"
fi
done
I just compare md5sum
of a file and its brother at repository.
Example output:
$ ./gitstatus.sh
application/script.php NOT IDENTICAL
application/storage/logs/laravel.log NOT IDENTICAL
One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.
One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).
Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.
-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
ID INT IDENTITY(1, 1) NOT NULL,
CallTime DATETIME NOT NULL DEFAULT GETDATE(),
CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
ID INT IDENTITY(1, 1) NOT NULL,
CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
Subject VARCHAR(250) NOT NULL,
Notes VARCHAR(8000) NOT NULL,
Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)
Here's a brief tutorial on how __doPostBack()
works.
To be honest, I don't use it much; at least directly. Many server controls, (e.g., Button
, LinkButton
, ImageButton
, parts of the GridView
, etc.) use __doPostBack
as their post back mechanism.
I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":
The first one has been explained very well. For the second one, please study following example:
var MyClosureObject = (function (){
var MyName = 'Michael Jackson RIP';
return {
getMyName: function () { return MyName;},
setMyName: function (name) { MyName = name}
}
}());
Attention 1: We are not assigning a function to MyClosureObject
, further more the result of invoking that function. Be aware of ()
in the last line.
Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.
Let us try some experiments:
I can get MyName
using getMyName
and it works:
console.log(MyClosureObject.getMyName());
// Michael Jackson RIP
The following ingenuous approach would not work:
console.log(MyClosureObject.MyName);
// undefined
But I can set an another name and get the expected result:
MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName());
// George Michael RIP
Edit: In the example above MyClosureObject
is designed to be used without the new
prefix, therefore by convention it should not be capitalized.
Make sure the user has a localhost entry in the users table. That was the problem I was having. EX:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
A lambda function is an anonymous function that you create in-line. It can capture variables as some have explained, (e.g. http://www.stroustrup.com/C++11FAQ.html#lambda) but there are some limitations. For example, if there's a callback interface like this,
void apply(void (*f)(int)) {
f(10);
f(20);
f(30);
}
you can write a function on the spot to use it like the one passed to apply below:
int col=0;
void output() {
apply([](int data) {
cout << data << ((++col % 10) ? ' ' : '\n');
});
}
But you can't do this:
void output(int n) {
int col=0;
apply([&col,n](int data) {
cout << data << ((++col % 10) ? ' ' : '\n');
});
}
because of limitations in the C++11 standard. If you want to use captures, you have to rely on the library and
#include <functional>
(or some other STL library like algorithm to get it indirectly) and then work with std::function instead of passing normal functions as parameters like this:
#include <functional>
void apply(std::function<void(int)> f) {
f(10);
f(20);
f(30);
}
void output(int width) {
int col;
apply([width,&col](int data) {
cout << data << ((++col % width) ? ' ' : '\n');
});
}
try With this --- worked for me in Xcode-beta 4 7.0
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
Also one more option, if you want to disable ATS you can use this :
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
But this is not recommended at all. The server should have the SSL certificates and so that there is no privacy leaks.
For Windows Users :
If this issue occurs on your self hosted server (eg: your custom CDN) and the browser (Chrome) says something like ... ('text/plain') is not executable ...
when trying to load your javascript file ...
Here is what you need to do :
Win + R > regedit
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.js
application/javascript
or not application/javascript
and try again Easiest way:
param_a = 1
param_b = 2
result = param_a === param_b ? 'Same!' : 'Not same!'
since param_a
is not equal to param_b
then the result
's value will be Not same!
function getAge(birthday) {
var today = new Date();
var thisYear = 0;
if (today.getMonth() < birthday.getMonth()) {
thisYear = 1;
} else if ((today.getMonth() == birthday.getMonth()) && today.getDate() < birthday.getDate()) {
thisYear = 1;
}
var age = today.getFullYear() - birthday.getFullYear() - thisYear;
return age;
}
When you want to test a state of application and in case of a problem return HTTP error I would suggest a filter. The filter below handles all HTTP requests. The shortest solution in Spring Boot with a javax filter.
In the implementation can be various conditions. In my case the applicationManager testing if the application is ready.
import ...ApplicationManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SystemIsReadyFilter implements Filter {
@Autowired
private ApplicationManager applicationManager;
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!applicationManager.isApplicationReady()) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The service is booting.");
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {}
}
I got the same error in my microservice project.The property itself missed in my yml file.So I added property name and value that resolves my problem
To complete my previous "diff.external" config answer above:
As mentioned by Jakub, Git1.6.3 introduced git difftool, originally proposed in September 2008:
USAGE='[--tool=tool] [--commit=ref] [--start=ref --end=ref] [--no-prompt] [file to merge]'
(See --extcmd
in the last part of this answer)
$LOCAL
contains the contents of the file from the starting revision and $REMOTE
contains the contents of the file in the ending revision.
$BASE
contains the contents of the file in the wor
It's basically
git-mergetool
modified to operate on the git index/worktree.The usual use case for this script is when you have either staged or unstaged changes and you'd like to see the changes in a side-by-side diff viewer (e.g.
xxdiff
,tkdiff
, etc).
git difftool [<filename>*]
Another use case is when you'd like to see the same information but are comparing arbitrary commits (this is the part where the revarg parsing could be better)
git difftool --start=HEAD^ --end=HEAD [-- <filename>*]
The last use case is when you'd like to compare your current worktree to something other than HEAD (e.g. a tag)
git difftool --commit=v1.0.0 [-- <filename>*]
Note: since Git 2.5, git config diff.tool winmerge
is enough!
See "git mergetool winmerge"
And since Git 1.7.11, you have the option --dir-diff
, in order to to spawn external diff tools that can compare two directory hierarchies at a time after populating two temporary directories, instead of running an instance of the external tool once per a file pair.
Before Git 2.5:
Practical case for configuring difftool
with your custom diff tool:
C:\myGitRepo>git config --global diff.tool winmerge
C:\myGitRepo>git config --global difftool.winmerge.cmd "winmerge.sh \"$LOCAL\" \"$REMOTE\""
C:\myGitRepo>git config --global difftool.prompt false
With winmerge.sh stored in a directory part of your PATH:
#!/bin/sh
echo Launching WinMergeU.exe: $1 $2
"C:/Program Files/WinMerge/WinMergeU.exe" -u -e "$1" "$2" -dl "Local" -dr "Remote"
If you have another tool (kdiff3, P4Diff, ...), create another shell script, and the appropriate difftool.myDiffTool.cmd
config directive.
Then you can easily switch tools with the diff.tool
config.
You have also this blog entry by Dave to add other details.
(Or this question for the winmergeu
options)
The interest with this setting is the winmerge.sh
script: you can customize it to take into account special cases.
See for instance David Marble's answer below for an example which deals with:
As Kem Mason mentions in his answer, you can also avoid any wrapper by using the --extcmd
option:
--extcmd=<command>
Specify a custom command for viewing diffs.
git-difftool
ignores the configured defaults and runs$command $LOCAL $REMOTE
when this option is specified.
For instance, this is how gitk
is able to run/use any diff
tool.
The CSS element()
function may eventually help some people here, even though it's not a direct answer to the question. It allows you to use an element (and all children, including videos, cross-domain iframes, etc.) as a background image (and anywhere else that you'd normally use url(...)
in your CSS code). Here's a blog post that shows what you can do with it.
It has been implemented in Firefox since 2011, and is being considered in Chromium/Chrome (don't forget to give the issue a star if you care about this functionality).
(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)
Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:
There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
The cURL extension defines another two resource types:
... a cURL handle and a cURL multi handle.
When var_dump
ed, the values look like this:
$resource = curl_init();
var_dump($resource);
resource(1) of type (curl)
That's all most resources are, a numeric identifier ((1)
) of a certain type ((curl)
).
You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.
The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returned false
instead. For instance, the fopen
function has this description:
Return Values
Returns a file pointer resource on success, or
FALSE
on error.
So in this code, $fp
will either be a resource(x) of type (stream)
or false
:
$fp = fopen(...);
If you do not check whether the fopen
operation succeed or failed and hence whether $fp
is a valid resource or false
and pass $fp
to another function which expects a resource, you may get the above error:
$fp = fopen(...);
$data = fread($fp, 1024);
Warning: fread() expects parameter 1 to be resource, boolean given
You always need to error check the return value of functions which are trying to allocate a resource and may fail:
$fp = fopen(...);
if (!$fp) {
trigger_error('Failed to allocate resource');
exit;
}
$data = fread($fp, 1024);
Related Errors:
you can try like This
ArrayList<String> dtlst = new ArrayList<String>();
String qry1 = "select dt_tracker from gs";
Statement prepst = conn.createStatement();
ResultSet rst = prepst.executeQuery(qry1);
while(rst.next())
{
String dt = "";
try
{
dt = rst.getDate("dt_tracker")+" "+rst.getTime("dt_tracker");
}
catch(Exception e)
{
dt = "0000-00-00 00:00:00";
}
dtlst.add(dt);
}
The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.
It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.
So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.
Otherwise, some users may not enjoy the smooth scrolling of your website / platform.
I can give a simpler example on how it can be applicable.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
// Add smooth scrolling to all links_x000D_
$("a").on('click', function(event) {_x000D_
// Make sure this.hash has a value before overriding default behavior_x000D_
if (this.hash !== "") {_x000D_
// Prevent default anchor click behavior_x000D_
event.preventDefault();_x000D_
// Store hash_x000D_
var hash = this.hash;_x000D_
// Using jQuery's animate() method to add smooth page scroll_x000D_
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area_x000D_
$('html, body').animate({_x000D_
scrollTop: $(hash).offset().top_x000D_
}, 800, function(){_x000D_
// Add hash (#) to URL when done scrolling (default click behavior)_x000D_
window.location.hash = hash;_x000D_
});_x000D_
} // End if_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
<style>_x000D_
#section1 {_x000D_
height: 600px;_x000D_
background-color: pink;_x000D_
}_x000D_
#section2 {_x000D_
height: 600px;_x000D_
background-color: yellow;_x000D_
}_x000D_
</style>
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<h1>Smooth Scroll</h1>_x000D_
<div class="main" id="section1">_x000D_
<h2>Section 1</h2>_x000D_
<p>Click on the link to see the "smooth" scrolling effect.</p>_x000D_
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>_x000D_
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>_x000D_
</div>_x000D_
<div class="main" id="section2">_x000D_
<h2>Section 2</h2>_x000D_
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
If we have list like below:
list = [2,2,3,4]
two ways to copy it into another list.
1.
x = [list] # x =[] x.append(list) same
print("length is {}".format(len(x)))
for i in x:
print(i)
length is 1 [2, 2, 3, 4]
2.
x = [l for l in list]
print("length is {}".format(len(x)))
for i in x:
print(i)
length is 4 2 2 3 4
Here you be able to get date like "2020-03-11T20:16:17" and return "11/Mar/2020 - 20:16"
private String transformLocalDateTimeBrazillianUTC(String dateJson) throws ParseException {
String localDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat formatInput = new SimpleDateFormat(localDateTimeFormat);
//Here is will set the time zone
formatInput.setTimeZone(TimeZone.getTimeZone("UTC-03"));
String brazilianFormat = "dd/MMM/yyyy - HH:mm";
SimpleDateFormat formatOutput = new SimpleDateFormat(brazilianFormat);
Date date = formatInput.parse(dateJson);
return formatOutput.format(date);
}
Addition to the answer of Brett DeWoody: (which is updated now)
var dataValue = obj.srcElement.attributes.data.nodeValue;
Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:
var dataValue = obj.currentTarget.attributes.data.nodeValue;
Works in IE, Chrome and FF, I did not test Safari.
You can simulate it with using varargs, however then you should check it for too many arguments.
public void foo(int param1, int ... param2)
{
int param2_
if(param2.length == 0)
param2_ = 2
else if(para2.length == 1)
param2_ = param2[0]
else
throw new TooManyArgumentsException(); // user provided too many arguments,
// rest of the code
}
However this approach is not a good way of doing this, therefore it is better to use overloading.
check your closing tags in your model, it may be that you have defined a callback in another callback
just add the class navbar-fixed-bottom to your footer.
<div class="footer navbar-fixed-bottom">
Update for Bootstrap 4 -
as mentioned by Sara Tibbetts - class is fixed-bottom
<div class="footer fixed-bottom">
Works for every browser.
<button type="button" onClick="Refresh()">Close</button>
<script>
function Refresh() {
window.parent.location = window.parent.location.href;
}
</script>
set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.
If you don't want to use numpy or a collections module you can use a dictionary:
d = dict()
a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
for item in a:
try:
d[item]+=1
except KeyError:
d[item]=1
result:
>>>d
{0: 8, 1: 4}
Of course you can also use an if/else statement. I think the Counter function does almost the same thing but this is more transparant.
You could also use regex to delete all the console.log() calls in your code if they're no longer required. Any decent IDE will allow you to search and replace these across an entire project, and allow you to preview the matches before committing the change.
\s*console\.log\([^)]+\);
I Have a same Problem.I'm Used the WCF Service in class library and calling the class library from windows Application project.but I'm Forget Change <system.serviceModel>
In Config File of windows application Project same the <system.serviceModel>
of Class Library's app.Config file.
solution: change Configuration of outer project same the class library's wcf configuration.
You can use Include Directives
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<%@include file="<%="includes/" + p +".jsp"%>"%>
<%
}
%>
or JSP Include Action
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<jsp:include page="<%="includes/"+p+".jsp"%>"/>
<%
}
%>
the different is include directive includes a file during the translation phase. while JSP Include Action includes a file at the time the page is requested
I recommend Spring MVC Framework as your controller to manipulate things. use url pattern instead of parameter.
example:
www.yourwebsite.com/products
instead of
www.yourwebsite.com/?p=products
Watch this video Spring MVC Framework
Check the code below and the link to MDN
// var ts_hms = new Date(UTC);
// ts_hms.format("%Y-%m-%d %H:%M:%S")
// exact format
console.log(new Date().toISOString().replace('T', ' ').substring(0, 19))
// other formats
console.log(new Date().toUTCString())
console.log(new Date().toLocaleString('en-US'))
console.log(new Date().toString())
_x000D_
__FILE__
is the filename with extension of the file containing the code being executed.
In foo.rb
, __FILE__
would be "foo.rb".
If foo.rb
were in the dir /home/josh
then File.dirname(__FILE__)
would return /home/josh
.
No. Well, not really. There are a couple of selectors that can get you somewhat close, but probably won't work in your example and don't have the best browser compatibility.
:only-child
The :only-child
is one of the few true counting selectors in the sense that it's only applied when there is one child of the element's parent. Using your idealized example, it acts like children(1)
probably would.
:nth-child
The :nth-child
selector might actually get you where you want to go depending on what you're really looking to do. If you want to style all elements if there are 8 children, you're out of luck. If, however, you want to apply styles to the 8th and later elements, try this:
p:nth-child( n + 8 ){
/* add styles to make it pretty */
}
Unfortunately, these probably aren't the solutions you're looking for. In the end, you'll probably need to use some Javascript wizardry to apply the styles based on the count - even if you were to use one of these, you'd need to have a hard look at browser compatibility before going with a pure CSS solution.
W3 CSS3 Spec on pseudo-classes
EDIT I read your question a little differently - there are a couple other ways to style the parent, not the children. Let me throw a few other selectors your way:
:empty
and :not
This styles elements that have no children. Not that useful on its own, but when paired with the :not
selector, you can style only the elements that have children:
div:not(:empty) {
/* We know it has stuff in it! */
}
You can't count how many children are available with pure CSS here, but it is another interesting selector that lets you do cool things.
I doubt it but maybe running svn cleanup on your working directory will help.
They can make deleting records more cumbersome - you can't delete the "master" record where there are records in other tables where foreign keys would violate that constraint. You can use triggers to have cascading deletes.
If you chose your primary key unwisely, then changing that value becomes even more complex. For example, if I have the PK of my "customers" table as the person's name, and make that key a FK in the "orders" table", if the customer wants to change his name, then it is a royal pain... but that is just shoddy database design.
I believe the advantages in using fireign keys outweighs any supposed disadvantages.
$(document).ready(function(e) {
// executes when HTML-Document is loaded and DOM is ready
console.log("page is loading now");
});
$(document).load(function(e) {
//when html page complete loaded
console.log("completely loaded");
});
<?php
function fWriteFile($sFileName,$sFileContent="No Data",$ROOT)
{
$word = new COM("word.application") or die("Unable to instantiate Word");
//bring it to front
$word->Visible = 1;
//open an empty document
$word->Documents->Add();
//do some weird stuff
$word->Selection->TypeText($sFileContent);
$word->Documents[1]->SaveAs($ROOT."/".$sFileName.".doc");
//closing word
$word->Quit();
//free the object
$word = null;
return $sFileName;
}
?>
<?php
$PATH_ROOT=dirname(__FILE__);
$Return ="<table>";
$Return .="<tr><td>Row[0]</td></tr>";
$Return .="<tr><td>Row[1]</td></tr>";
$sReturn .="</table>";
fWriteFile("test",$Return,$PATH_ROOT);
?>
Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')
It's not enough to have just compile project("xy")
dependency.
You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).
Create a settings.gradle file in the root of your project and add this:
include ':progressfragment'
to that file. Then sync Gradle and it should work.
Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.
(DEMO)
Codes:
.backimage {width:99%; height:98%; position:absolute; background:transparent url("http://upload.wikimedia.org/wikipedia/commons/4/41/Brickwall_texture.jpg") repeat scroll 0% 0%; }
and
<div>
<div class="backimage"></div>
YOUR OTHER CONTENTTT
</div>
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
The Simplest solution is here: If you are using Visual Studio, from the Solution Explorer
, right click on your project file. Choose Properties
. Select Icon and manifest
then Browse your .ico
file.
I think by using the content"."; The dot becomes too squared if made too big, thus I believe that this is a better solution, here you can decide the size of the "disc" without affecting the font size.
li {_x000D_
list-style: none;_x000D_
display: list-item;_x000D_
margin-left: 50px;_x000D_
}_x000D_
_x000D_
li:before {_x000D_
content: "";_x000D_
border: 5px #000 solid !important;_x000D_
border-radius: 50px;_x000D_
margin-top: 5px;_x000D_
margin-left: -20px;_x000D_
position: absolute;_x000D_
}
_x000D_
<h2>Look at these examples!</h2>_x000D_
<li>This is an example</li>_x000D_
<li>This is another example</li>
_x000D_
You edit the size of the disk by editing the size of the border px. and you can adjust the distance to the text by how much - margin left you give it. As well as adjust the y position by editing the margin top.
Add the following line in your .profile
file in your home directory (using vi ~/.profile
):
PATH=$PATH:/home/me/play
export PATH
Then, for the change to take effect, simply type in your terminal:
$ . ~/.profile
Alternatively, you can give the "full location" to the database in your queries a la:
SELECT photo_id FROM [my database name].photogallery;
If using one more often than others, use USE
. Even if you do, you can still use the database.table
syntax.
Hack solution
You can read the text file into a String var. Then split the String into an array using a single whitespace as the delimiter StringVar.Split(" ").
The Array count would equal the number of "Words" in the file. Of course this wouldnt give you a count of line numbers.
echo"==================PS COMMAND SNAPSHOT=============================================================="
needs to be
echo "==================PS COMMAND SNAPSHOT=============================================================="
Else, a program or command named echo"===...
is searched.
If you do a grep (-A1: + 1 line context)
grep -A1 "if " cldtest.sh
you find some embedded ifs, and 4 if/then blocks.
grep "fi " cldtest.sh
only reveals 3 matching fi statements. So you forgot one fi too.
I agree with camh, that correct indentation from the beginning helps to avoid such errors. Finding the desired way later means double work in such spaghetti code.
Inserting \n
p="${var1}\n${var2}"
echo -e "${p}"
Inserting a new line in the source code
p="${var1}
${var2}"
echo "${p}"
Using $'\n'
(only bash and zsh)
p="${var1}"$'\n'"${var2}"
echo "${p}"
\n
p="${var1}\n${var2}"
echo -e "${p}"
echo -e
interprets the two characters "\n"
as a new line.
var="a b c"
first_loop=true
for i in $var
do
p="$p\n$i" # Append
unset first_loop
done
echo -e "$p" # Use -e
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p\n$i" # After -> Append
unset first_loop
done
echo -e "$p" # Use -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p\n$i" # Append
done
echo -e "$p" # Use -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
var="a b c"
for i in $var
do
p="$p
$i" # New line directly in the source code
done
echo "$p" # Double quotes required
# But -e not required
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p
$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p
$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
$'\n'
(less portable)bash and zsh interprets $'\n'
as a new line.
var="a b c"
for i in $var
do
p="$p"$'\n'"$i"
done
echo "$p" # Double quotes required
# But -e not required
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p"$'\n'"$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p"$'\n'"$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
a
b
c
Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.
EDIT
for
loop in above bash snippets.Simple way to read cookies in ES6.
function getCookies() {
var cookies = {};
for (let cookie of document.cookie.split('; ')) {
let [name, value] = cookie.split("=");
cookies[name] = decodeURIComponent(value);
}
console.dir(cookies);
}
thank you, your first error guides me here and the solution solve mine too!
for permission error, f = open('output', 'w+')
, change it into f = open(output+'output', 'w+')
.
or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.
for sure, you could probably running python/your script as administrator to pass permission error though
All you need to do is use getCheckedRadioButtonId()
and isChecked()
method,
if(gender.getCheckedRadioButtonId()==-1)
{
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
Toast.makeText(getApplicationContext(), selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}
https://developer.android.com/guide/topics/ui/controls/radiobutton.html
I think you should understand what delayed expansion is. The existing answers don't explain it (sufficiently) IMHO.
Typing SET /?
explains the thing reasonably well:
Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed. The following example demonstrates the problem with immediate variable expansion:
set VAR=before if "%VAR%" == "before" ( set VAR=after if "%VAR%" == "after" @echo If you see this, it worked )
would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement. So the IF inside the compound statement is really comparing "before" with "after" which will never be equal. Similarly, the following example will not work as expected:
set LIST= for %i in (*) do set LIST=%LIST% %i echo %LIST%
in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found. Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty. So the actual FOR loop we are executing is:
for %i in (*) do set LIST= %i
which just keeps setting LIST to the last file found.
Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:
set VAR=before if "%VAR%" == "before" ( set VAR=after if "!VAR!" == "after" @echo If you see this, it worked ) set LIST= for %i in (*) do set LIST=!LIST! %i echo %LIST%
Another example is this batch file:
@echo off
setlocal enabledelayedexpansion
set b=z1
for %%a in (x1 y1) do (
set b=%%a
echo !b:1=2!
)
This prints x2
and y2
: every 1 gets replaced by a 2.
Without setlocal enabledelayedexpansion
, exclamation marks are just that, so it will echo !b:1=2!
twice.
Because normal environment variables are expanded when a (block) statement is read, expanding %b:1=2%
uses the value b
has before the loop: z2
(but y2
when not set).
There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:
import paramiko
ip='server ip'
port=22
username='username'
password='password'
cmd='some useful command'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)
stdin,stdout,stderr=ssh.exec_command('some really useful command')
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)
As an addendum to this, I've strings of the form: Some words 303
where I'd like to split off the numerical part from the tail of the string. This seems to point to a possible solution:
http://lists.mysql.com/mysql/222421
The problem however, is that you only get the answer "yes, it matches", and not the start index of the regexp match.
The best thing to do is to install the Tampermonkey extension.
This will allow you to easily install Greasemonkey scripts, and to easily manage them. Also it makes it easier to install userscripts directly from sites like OpenUserJS, MonkeyGuts, etc.
Finally, it unlocks most all of the GM functionality that you don't get by installing a GM script directly with Chrome. That is, more of what GM on Firefox can do, is available with Tampermonkey.
But, if you really want to install a GM script directly, it's easy a right pain on Chrome these days...
You can still drag a file to the extensions page and it will work... Until you restart Chrome. Then it will be permanently disabled. See Continuing to "protect" Chrome users from malicious extensions for more information. Again, Tampermonkey is the smart way to go. (Or switch browsers altogether to Opera or Firefox.)
Chrome is changing the way extensions are installed. Userscripts are pared-down extensions on Chrome but. Starting in Chrome 21, link-click behavior is disabled for userscripts. To install a user script, drag the **.user.js* file into the Extensions page (chrome://extensions
in the address input).
Merely drag your **.user.js* files into any Chrome window. Or click on any Greasemonkey script-link.
You'll get an installation warning:
Click Continue.
You'll get a confirmation dialog:
Click Add.
Notes:
By default, Chrome installs scripts in the Extensions folder1, full of cryptic names and version numbers. And, if you try to manually add a script under this folder tree, it will be wiped the next time Chrome restarts.
To control the directories and filenames to something more meaningful, you can:
Create a directory that's convenient to you, and not where Chrome normally looks for extensions. For example, Create: C:\MyChromeScripts\
.
For each script create its own subdirectory. For example, HelloWorld
.
In that subdirectory, create or copy the script file. For example, Save this question's code as: HelloWorld.user.js
.
You must also create a manifest file in that subdirectory, it must be named: manifest.json
.
For our example, it should contain:
{
"manifest_version": 2,
"content_scripts": [ {
"exclude_globs": [ ],
"include_globs": [ "*" ],
"js": [ "HelloWorld.user.js" ],
"matches": [ "https://stackoverflow.com/*",
"https://stackoverflow.com/*"
],
"run_at": "document_end"
} ],
"converted_from_user_script": true,
"description": "My first sensibly named script!",
"name": "Hello World",
"version": "1"
}
The manifest.json
file is automatically generated from the meta-block by Chrome, when an user script is installed. The values of @include
and @exclude
meta-rules are stored in include_globs
and exclude_globs
, @match
(recommended) is stored in the matches
list. "converted_from_user_script": true
is required if you want to use any of the supported GM_*
methods.
Now, in Chrome's Extension manager (URL = chrome://extensions/), Expand "Developer mode".
Click the Load unpacked extension... button.
For the folder, paste in the folder for your script, In this example it is: C:\MyChromeScripts\HelloWorld
.
Your script is now installed, and operational!
If you make any changes to the script source, hit the Reload link for them to take effect:
1 The folder defaults to:
Windows XP: Chrome : %AppData%\..\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\ Chromium: %AppData%\..\Local Settings\Application Data\Chromium\User Data\Default\Extensions\ Windows Vista/7/8: Chrome : %LocalAppData%\Google\Chrome\User Data\Default\Extensions\ Chromium: %LocalAppData%\Chromium\User Data\Default\Extensions\ Linux: Chrome : ~/.config/google-chrome/Default/Extensions/ Chromium: ~/.config/chromium/Default/Extensions/ Mac OS X: Chrome : ~/Library/Application Support/Google/Chrome/Default/Extensions/ Chromium: ~/Library/Application Support/Chromium/Default/Extensions/
Although you can change it by running Chrome with the --user-data-dir=
option.
It is also possible to pass environment variables explicitly through ssh. It does require some server-side set-up through, so this this not a universal answer.
In my case, I wanted to pass a backup repository encryption key to a command on the backup storage server without having that key stored there, but note that any environment variable is visible in ps
! The solution of passing the key on stdin would work as well, but I found it too cumbersome. In any case, here's how to pass an environment variable through ssh:
On the server, edit the sshd_config
file, typically /etc/ssh/sshd_config
and add an AcceptEnv
directive matching the variables you want to pass. See man sshd_config
. In my case, I want to pass variables to borg backup so I chose:
AcceptEnv BORG_*
Now, on the client use the -o SendEnv
option to send environment variables. The following command line sets the environment variable BORG_SECRET
and then flags it to be sent to the client machine (called backup
). It then runs printenv
there and filters the output for BORG variables:
$ BORG_SECRET=magic-happens ssh -o SendEnv=BORG_SECRET backup printenv | egrep BORG
BORG_SECRET=magic-happens
You should use setTimestamp instead, if you hardcode it:
$start_date = new DateTime();
$start_date->setTimestamp(1372622987);
in your case
$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);
SELECT CONVERT(
VARCHAR(32),
HASHBYTES(
'MD5',
CAST(prescrip.IsExpressExamRX AS VARCHAR(250))
+ CAST(prescrip.[Description] AS VARCHAR(250))
),
2
) MD5_Value;
works for me.
//insert this php code, at the end after your closing html tag.
<?php
//setting connection to database
$con = mysqli_connect("localhost","your-username","your-
passowrd","your-dbname");
if(isset($_POST['submit_button'])){
$txt_area = $_POST['update'];
$Our_query= "INSERT INTO your-table-name (field1name, field2name)
VALUES ('abc','def')"; // values should match data
// type to field names
$insert_query = mysqli_query($con, $Our_query);
if($insert_query){
echo "<script>window.open('form.php','_self') </script>";
// supposing form.php is where you have created this form
}
} //if statement close
?>
Hope this helps.
You want:
dir > a.txt 2>&1
The syntax 2>&1
will redirect 2
(stderr) to 1
(stdout). You can also hide messages by redirecting to NUL
, more explanation and examples on MSDN.
From the documentation:
We can add to a list in many ways:
assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
//equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]
list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
You can also do:
def myNewList = myList << "fifth"
After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).
A quick rerun of your data:
In [25]: df.hist(column='Trip_distance')
Prints out absolutely fine.
The df.hist
function comes with an optional keyword argument bins=10
which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:
In [34]: df.hist(column='Trip_distance', bins=50)
keep textarea code with no additional white spaces inside
moreover if you see extra blank lines there is solution in meta language:
<textarea>
for line in lines:
echo line.replace('\n','\r')
endfor
</textarea>
it will print lines without additional blank lines of course it depends if your lines ending with '\n', '\r\n' or '' - please adapt
Create a role add this role to users, and then you can grant execute to all the routines in one shot to this role.
CREATE ROLE <abc>
GRANT EXECUTE TO <abc>
EDIT
This works in SQL Server 2005, I'm not sure about backward compatibility of this feature, I'm sure anything later than 2005 should be fine.
adapter.notifyDataSetChanged();
When I was managing a large multi-user planning system backed by Oracle, our DBA had a weekly job that gathered statistics. Also, when we rolled out a significant change that could affect or be affected by statistics, we would force the job to run out of cycle to get things caught up.
You have no combinator (space, >
, +
...) so no children will get involved, ever.
However, you could avoid the need for jQuery by using an ID
and getElementById
, or you could use the old getElementsByName("frmSave")[0]
or the even older document.forms['frmSave']
. jQuery is unnecessary here.
echo $this->bb;
The variable is inherited and is not private, so it is a part of the current object.
Here is additional information in response to your request for more information about using parent::
:
Use parent::
when you want add extra functionality to a method from the parent class. For example, imagine an Airplane
class:
class Airplane {
private $pilot;
public function __construct( $pilot ) {
$this->pilot = $pilot;
}
}
Now suppose we want to create a new type of Airplane that also has a navigator. You can extend the __construct() method to add the new functionality, but still make use of the functionality offered by the parent:
class Bomber extends Airplane {
private $navigator;
public function __construct( $pilot, $navigator ) {
$this->navigator = $navigator;
parent::__construct( $pilot ); // Assigns $pilot to $this->pilot
}
}
In this way, you can follow the DRY principle of development but still provide all of the functionality you desire.
ddlutils is my best choice:http://db.apache.org/ddlutils/api/org/apache/ddlutils/platform/SqlBuilder.html
here is create example(groovy):
Platform platform = PlatformFactory.createNewPlatformInstance("oracle");//db2,...
//create schema
def db = new Database();
def t = new Table(name:"t1",description:"XXX");
def col1 = new Column(primaryKey:true,name:"id",type:"bigint",required:true);
t.addColumn(col1);
t.addColumn(new Column(name:"c2",type:"DECIMAL",size:"8,2"));
t.addColumn( new Column(name:"c3",type:"varchar"));
t.addColumn(new Column(name:"c4",type:"TIMESTAMP",description:"date"));
db.addTable(t);
println platform.getCreateModelSql(db, false, false)
//you can read Table Object from platform.readModelFromDatabase(....)
def sqlbuilder = platform.getSqlBuilder();
println "insert:"+sqlbuilder.getInsertSql(t,["id":1,c2:3],false);
println "update:"+sqlbuilder.getUpdateSql(t,["id":1,c2:3],false);
println "delete:"+sqlbuilder.getDeleteSql(t,["id":1,c2:3],false);
//http://db.apache.org/ddlutils/database-support.html
The absolutely best way: Just let your activity implement View.OnClickListener
, and write your onClick
method like this:
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.button1:
// your code for button1 here
break;
case R.id.button2:
// your code for button2 here
break;
// even more buttons here
}
}
Then, in your XML layout file, you can set the click listeners directly using the attribute android:onClick
:
<Button
android:id="@+id/button1"
android:onClick="onClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
That is the most cleanest way of how to do it. I use it in all of mine projects today, as well.
This is what I did:
This trick works for me.
You don't have this problem on remote server, because on remote server, the last insert command waits for the result of previous command to execute. It's not the case on same server.
Profit that situation for a workaround.
If you have the right permission to create a Linked Server, do it. Create the same server as linked server.
now your Sql command in the SP1 is
insert into @myTempTable
exec THISSERVER.MY_DATABASE_NAME.MY_SCHEMA.SP2
Believe me, it works even you have dynamic insert in SP2
If you have date as a datetime.datetime
(or a datetime.date
) instance and want to combine it via a time from a datetime.time
instance, then you can use the classmethod datetime.datetime.combine
:
import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)
Use the mapfile
command:
mapfile -t myArray < file.txt
The error is using for
-- the idiomatic way to loop over lines of a file is:
while IFS= read -r line; do echo ">>$line<<"; done < file.txt
See BashFAQ/005 for more details.
Note also that installing Git for Windows from git-scm.com also installs Curl. You can then run Curl from Git for Windows' BASH terminal (not the default Windows CMD terminal).
Seems to me like the main obstacle is defining a "porn image". If you can define it easily, you could probably write something that would work. But even humans can't agree on what is porn. How will the application know? User moderation is probably your best bet.
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
A lot of people create very strange responses to these questions that make alot more work than necessary.
The easiest way to do this consists of the following
In actual code, an example will be (combining all steps together):
var input = document.getElementById("input").value;
document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);
output.value is going to be the area where you will want to display a beautified JSON.
cmd
in program startset PATH="%PATH%;C:\Program Files\Java\jdk1.6.0_18\bin"
Sliding the space bar only works if you gave more then one input language selected.
In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.
This is easy fast and changes the dictionary at the same time.
First response seems the mist accurate.
Regards
your data snippet need to be expanded a little, and it has to be this way to be proper json. notice I just include the array name attribute "item"
{"item":[
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}]}
your java script is simply
var objCount = json.item.length;
for ( var x=0; x < objCount ; xx++ ) {
var curitem = json.item[x];
}
Use the System.Web.Helpers.Crypto
NuGet package from Microsoft. It automatically adds salt to the hash.
You hash a password like this: var hash = Crypto.HashPassword("foo");
You verify a password like this: var verified = Crypto.VerifyHashedPassword(hash, "foo");
This isn't added out of the box because the Angular team wants Angular 2 to run minified. OrderBy runs off of reflection which breaks with minification. Check out Miško Heverey's response on the matter.
I've taken the time to create an OrderBy pipe that supports both single and multi-dimensional arrays. It also supports being able to sort on multiple columns of the multi-dimensional array.
<li *ngFor="let person of people | orderBy : ['-lastName', 'age']">{{person.firstName}} {{person.lastName}}, {{person.age}}</li>
This pipe does allow for adding more items to the array after rendering the page, and still sort the arrays with the new items correctly.
I have a write up on the process here.
And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info
EDIT: Added new demo to http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby
EDIT 2: Updated ngFor to new syntax
exit
is a helper for the interactive shell - sys.exit
is intended for use in programs.
The
site
module (which is imported automatically during startup, except if the-S
command-line option is given) adds several constants to the built-in namespace (e.g.exit
). They are useful for the interactive interpreter shell and should not be used in programs.
Technically, they do mostly the same: raising SystemExit
. sys.exit
does so in sysmodule.c:
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
PyObject *exit_code = 0;
if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
return NULL;
/* Raise SystemExit so callers may catch it or clean up. */
PyErr_SetObject(PyExc_SystemExit, exit_code);
return NULL;
}
While exit
is defined in site.py and _sitebuiltins.py, respectively.
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()
).
If you are using ASP.NET Core you could try out the nuget package SaidOut.AspNetCore.HttpsWithStrictTransportSecurity.
Then you only need to add
app.UseHttpsWithHsts(HttpsMode.AllowedRedirectForGet, configureRoutes: routeAction);
This will also add HTTP StrictTransportSecurity header to all request made using https scheme.
Example code and documentation https://github.com/saidout/saidout-aspnetcore-httpswithstricttransportsecurity#example-code
You can use an npm module called depcheck (requires at least version 10 of Node).
Install the module:
npm install depcheck -g
or
yarn global add depcheck
Run it and find the unused dependencies:
depcheck
The good thing about this approach is that you don't have to remember the find
or grep
command.
To run without installing use npx
:
npx depcheck
Short answer:
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Explanation:
(based on this question about LocalDate
)
Despite its name, java.util.Date
represents an instant on the time-line, not a "date". The actual data stored within the object is a long
count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).
The equivalent class to java.util.Date
in JSR-310 is Instant
, thus there are convenient methods to provide the conversion to and fro:
Date input = new Date();
Instant instant = input.toInstant();
Date output = Date.from(instant);
A java.util.Date
instance has no concept of time-zone. This might seem strange if you call toString()
on a java.util.Date
, because the toString
is relative to a time-zone. However that method actually uses Java's default time-zone on the fly to provide the string. The time-zone is not part of the actual state of java.util.Date
.
An Instant
also does not contain any information about the time-zone. Thus, to convert from an Instant
to a local date-time it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault()
- or it might be a time-zone that your application controls, such as a time-zone from user preferences. LocalDateTime
has a convenient factory method that takes both the instant and time-zone:
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
In reverse, the LocalDateTime
the time-zone is specified by calling the atZone(ZoneId)
method. The ZonedDateTime
can then be converted directly to an Instant
:
LocalDateTime ldt = ...
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date output = Date.from(zdt.toInstant());
Note that the conversion from LocalDateTime
to ZonedDateTime
has the potential to introduce unexpected behaviour. This is because not every local date-time exists due to Daylight Saving Time. In autumn/fall, there is an overlap in the local time-line where the same local date-time occurs twice. In spring, there is a gap, where an hour disappears. See the Javadoc of atZone(ZoneId)
for more the definition of what the conversion will do.
Summary, if you round-trip a java.util.Date
to a LocalDateTime
and back to a java.util.Date
you may end up with a different instant due to Daylight Saving Time.
Additional info: There is another difference that will affect very old dates. java.util.Date
uses a calendar that changes at October 15, 1582, with dates before that using the Julian calendar instead of the Gregorian one. By contrast, java.time.*
uses the ISO calendar system (equivalent to the Gregorian) for all time. In most use cases, the ISO calendar system is what you want, but you may see odd effects when comparing dates before year 1582.
Apart from what is being mentioned above, .uniform()
can also be used for generating multiple random numbers that too with the desired shape which is not possible with .random()
np.random.seed(99)
np.random.random()
#generates 0.6722785586307918
while the following code
np.random.seed(99)
np.random.uniform(0.0, 1.0, size = (5,2))
#generates this
array([[0.67227856, 0.4880784 ],
[0.82549517, 0.03144639],
[0.80804996, 0.56561742],
[0.2976225 , 0.04669572],
[0.9906274 , 0.00682573]])
This can't be done with random(...), and if you're generating the random(...) numbers for ML related things, most of the time, you'll end up using .uniform(...)
yield is more flexible than map(), see example below
val aList = List( 1,2,3,4,5 )
val res3 = for ( al <- aList if al > 3 ) yield al + 1
val res4 = aList.map( _+ 1 > 3 )
println( res3 )
println( res4 )
yield will print result like: List(5, 6), which is good
while map() will return result like: List(false, false, true, true, true), which probably is not what you intend.
An alternative is to use
mysqladmin variables
Just use the rjust method of the string object.
This example will make a string of 10 characters long, padding as necessary.
>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'
I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.
attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))
Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.
The accepted answer works for me only for the first 30 characters. This works for me:
select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name
I know this question is old but populating Excell Cells with Dates via VSTO has a couple of gotchas.
Formatting the entire column did NOT work for me.
Not even this approach from Microsoft worked: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.namedrange.numberformat.aspx
I found Formula's don't work on dates with yyyy-mmm-dd format - even though the cells were DATE FORMAT! You have to translate Dates to a dd/mm/yyyy format for use in formula's.
For example the dates I am getting come back from SQL Analysis Server and I had to flip them and then format them:
using (var dateRn = xlApp.Range["A1"].WithComCleanup())
{
dateRn.Resource.Value2 = Convert.ToDateTime(dateRn.Resource.Value2).ToString("dd-MMM-yyyy");
}
using (var rn = xlApp.Range["A1:A10"].WithComCleanup())
{
rn.Resource.Select();
rn.Resource.NumberFormat = "d-mmm-yyyy;@";
}
Otherwise formula's using Dates doesn't work - the formula in cell C4 is the same as C3:
testvar[1] is the value of that array index, which is the number 2. Numbers don't have a length property, and you're checking for 2.length which is undefined. If you want the length of the array just check testvar.length
Use >
and <
for 'greater-than' and 'less-than' respectively
When maven is working outside of Eclipse, but giving this error after a JDK change, Go to your Maven Run Configuration, and at the bottom of the Main page, there's a 'Maven Runtime' option. Mine was using the Embedded Maven, so after switching it to use my external maven, it worked.
If you run the server in normal mode you can recover the log by restarting the main project in debug mode. It seems that NB opens a new server log when the server run mode changes.
This was the fix for me when trying to install Laravel on a fresh WSL installation:
sudo apt-get install php7.2-gd
sudo apt-get install php7.2-intl
sudo apt-get install php7.2-xsl
sudo apt-get install php7.2-zip
There's a simple way to get rid of this restriction by using the datePicker component provided by jQuery.
Include jQuery and jQuery UI libraries (I'm still using an old one)
Use the following snip
$(function() {
$( "#id_of_the_component" ).datepicker({ dateFormat: 'yy-mm-dd'});
});
See jQuery UI DatePicker - Change Date Format if needed.
Without destructuring, you can create a defaults params and pass it in
interface Name {
firstName: string;
lastName: string;
}
export const defaultName extends Omit<Name, 'firstName'> {
lastName: 'Smith'
}
sayName({ ...defaultName, firstName: 'Bob' })
This should do it:
WHERE `date` = CURDATE() - INTERVAL 1 DAY
There's the possibility of a mis-understanding here. The WinForms framework in .Net automatically designates the first window created (e.g., Application.Run(new SomeForm())
) as the MainWindow
. The win32 API, however, doesn't recognize the idea of a "main window" per process. The message loop is entirely capable of handling as many "main" windows as system and process resources will let you create. So, your process doesn't have a "main window". The best you can do in the general case is use EnumWindows()
to get all the non-child windows active on a given process and try to use some heuristics to figure out which one is the one you want. Luckily, most processes are only likely to have a single "main" window running most of the time, so you should get good results in most cases.
i would recommend using a MaterialButton, than you can do it like this:
new MaterialButton(
height: 40.0,
minWidth: 70.0,
color: Theme.of(context).primaryColor,
textColor: Colors.white,
child: new Text("push"),
onPressed: () => {},
splashColor: Colors.redAccent,
)
Just a minor change to Jesse Crossen's answer that made it work perfectly for me:
instead of:
CGSize titleSize = button.titleLabel.frame.size;
I have used this:
CGSize titleSize = [button.titleLabel.text sizeWithAttributes: @{NSFontAttributeName:button.titleLabel.font}];
the reverse function comes in handy here:
myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
print x
.live()
has been deprecated as of jQuery 1.7
Use .on()
instead and specify a descendant selector
$("table").on({
mouseenter: function(){
$(this).addClass("inside");
},
mouseleave: function(){
$(this).removeClass("inside");
}
}, "tr"); // descendant selector
Margin
is returning a struct, which means that you are editing a copy. You will need something like:
var margin = MyControl.Margin;
margin.Left = 10;
MyControl.Margin = margin;
To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.
If you have image in the form of bitmap then use
imageview.setImageBitmap(bm);
If you have image in the form of drawable then use
imageview.setImageDrawable(drawable);
If you have image in your resource example if image is present in drawable folder then use
imageview.setImageResource(R.drawable.image);
If you have path of image then use
imageview.setImageURI(Uri.parse("pathofimage"));
Here's another alternative. This one was originally written in C++, so it can be backported to C++ for a finite-precision integer (e.g. __int64). The advantage is (1) it involves only integer operations, and (2) it avoids bloating the integer value by doing successive pairs of multiplication and division. I've tested the result with Nas Banov's Pascal triangle, it gets the correct answer:
def choose(n,r):
"""Computes n! / (r! (n-r)!) exactly. Returns a python long int."""
assert n >= 0
assert 0 <= r <= n
c = 1L
denom = 1
for (num,denom) in zip(xrange(n,n-r,-1), xrange(1,r+1,1)):
c = (c * num) // denom
return c
Rationale: To minimize the # of multiplications and divisions, we rewrite the expression as
n! n(n-1)...(n-r+1)
--------- = ----------------
r!(n-r)! r!
To avoid multiplication overflow as much as possible, we will evaluate in the following STRICT order, from left to right:
n / 1 * (n-1) / 2 * (n-2) / 3 * ... * (n-r+1) / r
We can show that integer arithmatic operated in this order is exact (i.e. no roundoff error).
Late answer: In my case, it was my session files under
/var/lib/php/sessions
that were using Inodes.
I was even unable to open my crontab or making a new directory let alone triggering the deletion operation.
Since I use PHP, we have this guide where I copied the code from example 1 and set up a cronjob to execute that part of the code.
<?php
// Note: This script should be executed by the same user of web server
process.
// Need active session to initialize session data storage access.
session_start();
// Executes GC immediately
session_gc();
// Clean up session ID created by session_gc()
session_destroy();
?>
If you're wondering how did I manage to open my crontab, then well, I deleted some sessions manually through CLI.
Hope this helps!
The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved. For safety try bulinding for 32bit x86 architecture because it is the most compatible.
It's not a map. It's simply an Object
.
Edit: below code is worse than OP's, as Amit pointed out in comments.
You can "iterate over the values" by actually iterating over the keys with:
var value;
Object.keys(map).forEach(function(key) {
value = map[key];
console.log(value);
});
When using CardView for children problem with spaces between items can by solved by setting app:cardUseCompatPadding to true.
For bigger margins enlarge item elevation. CardElevation is optional (use default value).
<androidx.cardview.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardUseCompatPadding="true"
app:cardElevation="2dp">
Here is one solution :
public static boolean containsAny(String str, String[] words)
{
boolean bResult=false; // will be set, if any of the words are found
//String[] words = {"word1", "word2", "word3", "word4", "word5"};
List<String> list = Arrays.asList(words);
for (String word: list ) {
boolean bFound = str.contains(word);
if (bFound) {bResult=bFound; break;}
}
return bResult;
}
similar problem found here: https://bugzilla.redhat.com/show_bug.cgi?id=1456202 I've tried the mentioned solution and it actually works.
The solutions in the previous questions may work. But I think this is an easy way to fix it.
Try to reinstall the package libwbclient
in fedora:
dnf reinstall libwbclient
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
Range("A1").value = Environ("Username")
This is better than Application.Username
, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.
Application Username
is the name of the User set in Excel > Tools > Options Environ("Username")
is the name you registered for Windows; see Control Panel >SystemTo add to wflynny's answer above, you can find the available colormaps here
Example:
import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)
or alternatively,
plt.scatter(x, y, c=t, cmap='jet')
A couple of days ago I found a very nice solution of this problem. Read about it here. In two words Mike created a AsyncTaskManager that mediates ProgressDialog and AsyncTask. It's very easy to use this solution. You just need to include in your project several interfaces and several classes and in your activity write some simple code and nest your new AsyncTask from BaseTask. I also advice you to read comments because there are some useful tips.
You can use .attr() as a part of however you plan to toggle it:
$("button").attr("aria-expanded","true");
I was in SLES12 and for me it worked after upgrading to wget 1.14, using --secure-protocol=TLSv1.2 and using --auth-no-challenge.
wget --no-check-certificate --secure-protocol=TLSv1.2 --user=satul --password=xxx --auth-no-challenge -v --debug https://jenkins-server/artifact/build.x86_64.tgz
Use .Date of a DateTime object will ignore the time portion.
Here is code:
DateTime dateA = DateTime.Now;
DateTime dateB = DateTime.Now.AddHours(1).AddMinutes(10).AddSeconds(14);
Console.WriteLine("Date A: {0}",dateA.ToString("o"));
Console.WriteLine("Date B: {0}", dateB.ToString("o"));
Console.WriteLine(String.Format("Comparing objects A==B? {0}", dateA.Equals(dateB)));
Console.WriteLine(String.Format("Comparing ONLY Date property A==B? {0}", dateA.Date.Equals(dateB.Date)));
Console.ReadLine();
Output:
>Date A: 2014-09-04T07:53:14.6404013+02:00
>Date B: 2014-09-04T09:03:28.6414014+02:00
>Comparing objects A==B? False
>Comparing ONLY Date property A==B? True
Though asynchronous style may be the nature of node.js and generally you should not do this, there are some times you want to do this.
I'm writing a handy script to check an API and want not to mess it up with callbacks.
Javascript cannot execute synchronous requests, but C libraries can.
Here's a workaround for installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit MS Office version installed:
Now you can start a 32-bit MS Office application without the "re-configuring" issue. Note that the "mso.dll" registry value will already be present if a 64-bit version of MS Office is installed. In this case the value should not be deleted or renamed.
Also if you do not want to use the "/passive" command line parameter you can edit the AceRedist.msi file to remove the MS Office architecture check:
You can now use this file to install the Microsoft Access Database Engine 2010 redistributable on a system where a "conflicting" version of MS Office is installed (e.g. 64-bit version on system with 32-bit MS Office version) Make sure that you rename the "mso.dll" registry value as explained above (if needed).
None of the above answers worked for me.
This was the solution, from the parent directory run:
git submodule update --init;
cd submodule-directory;
git pull;
cd ..;
git add submodule-directory;
now you can git commit
and git push
As an alternative which saves from full scanning each table twice and also gives you an easy way to tell which table had more rows with a combination of values than the other:
SELECT col1
, col2
-- (include all columns that you want to compare)
, COUNT(src1) CNT1
, COUNT(src2) CNT2
FROM (SELECT a.col1
, a.col2
-- (include all columns that you want to compare)
, 1 src1
, TO_NUMBER(NULL) src2
FROM tab_a a
UNION ALL
SELECT b.col1
, b.col2
-- (include all columns that you want to compare)
, TO_NUMBER(NULL) src1
, 2 src2
FROM tab_b b
)
GROUP BY col1
, col2
HAVING COUNT(src1) <> COUNT(src2) -- only show the combinations that don't match
Credit goes here: http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1417403971710
The following code is to retrieve all the links available in a webpage using urllib2
and BeautifulSoup4
:
import urllib2
from bs4 import BeautifulSoup
url = urllib2.urlopen("http://www.espncricinfo.com/").read()
soup = BeautifulSoup(url)
for line in soup.find_all('a'):
print(line.get('href'))
I'm going to answer my own question.
Therefore, the following works for me
$qb->select('c')
->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
->where('c.username = :username');
or
$qb->select('c')
->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
->where('c.username = :username');
I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.
<div id="main" class="container" role="main">
<div class="row">
<div class="span5 offset1">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
<div class="span6">
Image Here (TODO)
</div>
</div>
Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.
I think I know what you are doing wrong. If you are applying padding to the span6
like this:
<div class="span6" style="padding-left:5px;">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
It is wrong. What you have to do is add padding to the elements inside:
<div class="span6">
<h2 style="padding-left:5px;">Welcome</h2>
<p style="padding-left:5px;">Hello and welcome to my website.</p>
</div>
I had significant headaches with these methods before, I recommend you avoid any variant of UrlEncode
, and instead use Uri.EscapeDataString
- at least that one has a comprehensible behavior.
Let's see...
HttpUtility.UrlEncode(" ") == "+" //breaks ASP.NET when used in paths, non-
//standard, undocumented.
Uri.EscapeUriString("a?b=e") == "a?b=e" // makes sense, but rarely what you
// want, since you still need to
// escape special characters yourself
But my personal favorite has got to be HttpUtility.UrlPathEncode - this thing is really incomprehensible. It encodes:
It also has the lovelily specific MSDN documentation "Encodes the path portion of a URL string for reliable HTTP transmission from the Web server to a client." - without actually explaining what it does. You are less likely to shoot yourself in the foot with an Uzi...
In short, stick to Uri.EscapeDataString.
SSIS Integration with Visual Studio 2017 available from Aug 2017.
SSIS designer is now available for Visual Studio 2017! ARCHIVE
I installed in July 2018 and appears working fine. See Download link
Often times configmaps or secrets are injected as configuration files in containers. Depending on the application a restart may be required should those be updated with a subsequent helm upgrade
, but if the deployment spec itself didn't change the application keeps running with the old configuration resulting in an inconsistent deployment.
The sha256sum
function can be used together with the include
function to ensure a deployments template section is updated if another spec changes:
kind: Deployment
spec:
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
[...]
In my case, for some reasons, $.Template.BasePath
didn't work but $.Chart.Name
does:
spec:
replicas: 1
template:
metadata:
labels:
app: admin-app
annotations:
checksum/config: {{ include (print $.Chart.Name "/templates/" $.Chart.Name "-configmap.yaml") . | sha256sum }}
For --driver-class-path
option you can use :
as delimeter to pass multiple jars.
Below is the example with spark-shell
command but I guess the same should work with spark-submit
as well
spark-shell --driver-class-path /path/to/example.jar:/path/to/another.jar
Spark version: 2.2.0
In most cases JOIN
s are faster than sub-queries and it is very rare for a sub-query to be faster.
In JOIN
s RDBMS can create an execution plan that is better for your query and can predict what data should be loaded to be processed and save time, unlike the sub-query where it will run all the queries and load all their data to do the processing.
The good thing in sub-queries is that they are more readable than JOIN
s: that's why most new SQL people prefer them; it is the easy way; but when it comes to performance, JOINS are better in most cases even though they are not hard to read too.
Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.
The .project
file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)
The .classpath
file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings
directory inside the project); the .classpath
file is just one of them. Specifically, the .classpath
file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).
Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath
file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath
file portability.
Use:
document.location.href = "http://yoursite.com" + document.getElementById('somefield');
That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.
You can try below code. it’s very easy method for push new fragment from old fragment.
private int mContainerId;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private final static String TAG = "DashBoardActivity";
public void replaceFragment(Fragment fragment, String TAG) {
try {
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commitAllowingStateLoss();
} catch (Exception e) {
// TODO: handle exception
}
}
ActiveX resolved in Chrome!
Hello all this is not the solution but the successful workaround and I have implemented as well.
This required some implementation on client machine as well that why is most suitable for intranet environment and not recommended for public sites. Even though one can implement it for public sites as well the only problem is end user has to download/implement solution.
Lets understand the key problem
Chrome cannot communicate with ActiceX
Solution: Since Chorme cannot communicate with ActiveX but still it can communicate with the API hosted on the client machine. So develop API using .Net MVC or any other technology so that through Ajax call it can communicate with the API and API communicate with the ActiveX object situated on the client machine. Since API also resides in Client machine that why there is no problem in communication. This API works as mediator between Chrome browser and ActiveX.
During API implementation you might encounter CORS issues, Use JSONP to deal with it.
Pictorial view of the solution
Other solution : Use URI Scheme like MailTo: or MS-Word to deal with outlook and word application. If your requirement is different then you can implement your customized URI Scheme.
I met this problem with typescript
but forgot to add ts
and tsx
suffix to resolve
entry.
module.exports = {
...
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
};
This does the job for me
Increment the MAX number from a column. For Example :
df1 = [sort_ID, Column1,Column2]
print(df1)
My output :
Sort_ID Column1 Column2
12 a e
45 b f
65 c g
78 d h
MAX = df1['Sort_ID'].max() #This returns my Max Number
Now , I need to create a column in df2 and fill the column values which increments the MAX .
Sort_ID Column1 Column2
79 a1 e1
80 b1 f1
81 c1 g1
82 d1 h1
Note : df2 will initially contain only the Column1 and Column2 . we need the Sortid column to be created and incremental of the MAX from df1 .
Here are a few options:
Have a look at the palette
function:
palette(rainbow(6)) # six color rainbow
(palette(gray(seq(0,.9,len = 25)))) #grey scale
And the colorRampPalette
function:
##Move from blue to red in four colours
colorRampPalette(c("blue", "red"))( 4)
Look at the RColorBrewer
package (and website). If you want diverging colours, then select diverging on the site. For example,
library(RColorBrewer)
brewer.pal(7, "BrBG")
The I want hue web site gives lots of nice palettes. Again, just select the palette that you need. For example, you can get the rgb colours from the site and make your own palette:
palette(c(rgb(170,93,152, maxColorValue=255),
rgb(103,143,57, maxColorValue=255),
rgb(196,95,46, maxColorValue=255),
rgb(79,134,165, maxColorValue=255),
rgb(205,71,103, maxColorValue=255),
rgb(203,77,202, maxColorValue=255),
rgb(115,113,206, maxColorValue=255)))
For the filestream:
//Check if the directory exists
if (!System.IO.Directory.Exists(@"C:\yourDirectory"))
{
System.IO.Directory.CreateDirectory(@"C:\yourDirectory");
}
//Write the file
using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(@"C:\yourDirectory\yourFile.txt"))
{
outfile.Write(yourFileAsString);
}
The size_t
type is the unsigned integer type that is the result of the sizeof
operator (and the offsetof
operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).
The size_t
type may be bigger than, equal to, or smaller than an unsigned int
, and your compiler might make assumptions about it for optimization.
You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in pdf format, or in the C11 standard, section 7.19, also available as a pdf draft.
If you allow me, it works fine also for multi-attachments, the 1st above answer of NINCOMPOOP, with just a little modification like follows:
DataSource source,source2,source3,source4, ...;
source = new FileDataSource(myfile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(myfile);
multipart.addBodyPart(messageBodyPart);
source2 = new FileDataSource(myfile2);
messageBodyPart.setDataHandler(new DataHandler(source2));
messageBodyPart.setFileName(myfile2);
multipart.addBodyPart(messageBodyPart);
source3 = new FileDataSource(myfile3);
messageBodyPart.setDataHandler(new DataHandler(source3));
messageBodyPart.setFileName(myfile3);
multipart.addBodyPart(messageBodyPart);
source4 = new FileDataSource(myfile4);
messageBodyPart.setDataHandler(new DataHandler(source4));
messageBodyPart.setFileName(myfile4);
multipart.addBodyPart(messageBodyPart);
...
message.setContent(multipart);
In System.Diagnostics
,
Debug.Write()
Debug.WriteLine()
etc. will print to the Output window in VS.
You can also check it using jQuery.. It's quite easy:
<html>
<head>
<title>jQuery: Check if Textbox is empty</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>
<body>
<form name="form1" method="post" action="">
<label for="city">City:</label>
<input type="text" name="city" id="city">
</form>
<button id="check">Check</button>
<script type="text/javascript">
$('#check').click(function () {
if ($('#city').val() == '') {
alert('Empty!!!');
} else {
alert('Contains: ' + $('#city').val());
}
});
</script>
</body>
</html>
Exactly like this
window.open("www.youraddress.com","_self")
Look at git stash to put all of your local changes into a "stash file" and revert to the last commit. At that point, you can apply your stashed changes, or discard them.
blur event: when the element loses focus.
focusout event: when the element, or any element inside of it, loses focus.
As there is nothing inside the filter element, both blur and focusout will work in this case.
$(function() {
$('#filter').blur(function() {
$('#options').hide();
});
})
jsfiddle with blur: http://jsfiddle.net/yznhb8pc/
$(function() {
$('#filter').focusout(function() {
$('#options').hide();
});
})
jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/
This does the foreach in python 3
test = [0,1,2,3,4,5,6,7,8,"test"]
for fetch in test:
print(fetch)
Environment variables are 'evaluated' (ie. they are attributed) in the following order:
Every process has an environment block that contains a set of environment variables and their values. There are two types of environment variables: user environment variables (set for each user) and system environment variables (set for everyone). A child process inherits the environment variables of its parent process by default.
Programs started by the command processor inherit the command processor's environment variables.
Environment variables specify search paths for files, directories for temporary files, application-specific options, and other similar information. The system maintains an environment block for each user and one for the computer. The system environment block represents environment variables for all users of the particular computer. A user's environment block represents the environment variables the system maintains for that particular user, including the set of system environment variables.
You have by default the static
endpoint for static files. Also Flask
application has the following arguments:
static_url_path
: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder
folder.
static_folder
: the folder with static files that should be served at static_url_path
. Defaults to the 'static' folder in the root path of the application.
It means that the filename
argument will take a relative path to your file in static_folder
and convert it to a relative path combined with static_url_default
:
url_for('static', filename='path/to/file')
will convert the file path from static_folder/path/to/file
to the url path static_url_default/path/to/file
.
So if you want to get files from the static/bootstrap
folder you use this code:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">
Which will be converted to (using default settings):
<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">
Also look at url_for
documentation.
select a.ip, a.os, a.hostname, a.port, a.protocol,
b.state
from a
left join b on a.ip = b.ip
and a.port = b.port
The following example in JavaScript/Jquery will do that-
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function count(text, event) {
var keyCode = event.keyCode;
//THIS IS FOR CONTROL KEY
var ctrlDown = event.ctrlKey;
var maxlength = $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val().length;
if (maxlength < 200) {
event.returnValue = true;
}
else {
if ((keyCode == 8) || (keyCode == 9) || (keyCode == 46) || (keyCode == 33) || (keyCode == 27) || (keyCode == 145) || (keyCode == 19) || (keyCode == 34) || (keyCode == 37) || (keyCode == 39) || (keyCode == 16) || (keyCode == 18) ||
(keyCode == 38) || (keyCode == 40) || (keyCode == 35) || (keyCode == 36) || (ctrlDown && keyCode == 88) || (ctrlDown && keyCode == 65) || (ctrlDown && keyCode == 67) || (ctrlDown && keyCode == 86))
{
event.returnValue = true;
}
else {
event.returnValue = false;
}
}
}
function substr(text)
{
var txtWebAdd = $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val();
var substrWebAdd;
if (txtWebAdd.length > 200)
{
substrWebAdd = txtWebAdd.substring(0, 200);
$("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val('');
$("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val(substrWebAdd);
}
}
Using Swift, it would be:
if myDic[KEY] != nil {
// key exists
}