is it still actual?
As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>
, then you wrote <target name="build-subprojects"/>
(it does nothing). Could it be a reason?
Does this <echo message="${ant.project.name}: ${ant.file}"/>
print appropriate message? If no then target is not running.
Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277
The following steps worked for me.
1) Cut all the contents from pom.xml file and keep it another file and save the pom.xml
2) Just delete .m2 folder(entire maven repository) and restart the eclipse(or jbdevstudio)
3) paste the previous pom.xml file content(from the cut file) and all the error are gone.
The following code works very well.Try this as a java application with javamail-1.4.5.jar
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class MailSender
{
final String senderEmailID = "[email protected]";
final String senderPassword = "typesenderpassword";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public MailSender(
String receiverEmailID,
String emailSubject,
String emailBody
) {
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
public static void main(String[] args)
{
MailSender mailSender=new
MailSender("[email protected]",emailSubject,emailBody);
}
}
The short answer is adding a class directly to the element you want to style is indeed the most efficient way to target and style that Element. BUT, in real world scenarios it is so negligible that it is not an issue at all to worry about.
To quote Steve Ouders (CSS optimization expert) http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/:
Based on tests I have the following hypothesis: For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs.
Maintainability of code is much more important in real world scenarios. Since the underlying topic here is front-end performance; the real performance boosters for speedy page rendering are found in:
Source: http://stevesouders.com/docs/web20expo-20090402.ppt
So just to confirm, the answer is yes, example below is indeed faster but be aware of the bigger picture:
<div class="column">
<img class="custom-style" alt="appropriate alt text" />
</div>
With C++17 you can use std::optional
to check if a variable is initialized:
#include <optional>
#include <iostream> // needed only for std::cout
int main() {
std::optional<int> variable;
if (!variable) {
std::cout << "variable is NOT initialized\n";
}
variable = 3;
if (variable) {
std::cout << "variable IS initialized and is set to " << *variable << '\n';
}
return 0;
}
This will produce the output:
variable is NOT initialized
variable IS initialized and is set to 3
To use std::optional
in the code snipped you provided, you'll have to include the <optional>
standard library header and add std::optional<...>
to the respective variable declarations:
#include <optional>
class MyClass
{
void SomeMethod();
std::optional<char> mCharacter;
std::optional<double> mDecimal;
};
void MyClass::SomeMethod()
{
if ( mCharacter )
{
std::cout << *mCharacter; // do something with mCharacter.
}
if ( ! mDecimal )
{
mDecimal = 3.14159; // define mDecimal.
}
}
You can do quite a lot with plain css...the css property background-size
can be set to a number of things as well as just cover
as Ranjith pointed out.
The background-size: cover
setting scales the image to cover the entire screen but may mean that some of the image is off screen if the aspect ratio of the screen and image are different.
A good alternative is background-size: contain
which resizes the background image to fit the smaller of width and height, ensuring that the whole image is visible but may lead to letterboxing if the aspect ratios are different.
For example:
body {
background: url(/images/bkgd.png) no-repeat rgb(30,30,30) fixed center center;
background-size: contain;
}
The other options that I find less useful are:
background-size: length <widthpx> <heightpx>
which sets the absolute size of the background image.
background-size: percentage <width> <height>
background image is a percentage of the window size.
(see w3schools.com's page)
$ string="test"
$ string="${string}test2"
$ echo $string
testtest2
This is for jQuery UI 1.12. I added the following configuration setting for 'classes' option
classes: {
'ui-dialog-titlebar-close': 'hidden',
},
the whole dialog initialization looks like this:
ConfirmarSiNo(titulo, texto, idPadre, fnCerrar) {
const DATA_RETORNO = 'retval';
$('confirmar-si-no').dialog({
title: titulo,
modal: true,
classes: {
'ui-dialog-titlebar-close': 'hidden',
},
appendTo: `#${idPadre}`,
open: function fnOpen() { $(this).text(texto); },
close: function fnClose() {
let eligioSi = $(this).data(DATA_RETORNO) == true;
setTimeout(function () { fnCerrar(eligioSi); }, 30);
},
buttons: {
'Si, por favor': function si() { $(this).data(DATA_RETORNO, true); $(this).dialog("close"); },
'No, gracias': function no() { $(this).data(DATA_RETORNO, false); $(this).dialog("close"); }
}
});
}
I use following script call to show it:
ConfirmarSiNo('Titulo',
'¿Desea actualizar?',
idModalPadre,
(eligioSi) => {
if (eligioSi) {
this.$tarifa.val(tarifa.tarifa);
this.__ActualizarTarifa(tarifa);
}
});
whithin Html body I have the following div that contains the dialog:
<div class="modal" id="confirmar-si-no" title="" aria-labelledby="confirmacion-label">
mensaje
</div>
final result is:
function 'ConfirmarSiNo' is based on 'Whome' answer on post How to implement “confirmation” dialog in Jquery UI dialog?
This code may help you:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
For people from Brazil
There is a security software called Warsaw (used for home banking) that must be uninstalled! After you can install it back again.
After thousand times trying, installing, uninstalling, cleanning-up the regedit that finally solved the problem.
View:
<ListView x:Class="MyNamspace.MyListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
ItemsSource="{Binding Items}"
GridViewColumnHeader.Click="ListViewColumnHeaderClick">
<ListView.Resources>
<Style TargetType="Grid" x:Key="HeaderGridStyle">
<Setter Property="Height" Value="20" />
</Style>
<Style TargetType="TextBlock" x:Key="HeaderTextBlockStyle">
<Setter Property="Margin" Value="5,0,0,0" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style TargetType="Path" x:Key="HeaderPathStyle">
<Setter Property="StrokeThickness" Value="1" />
<Setter Property="Fill" Value="Gray" />
<Setter Property="Width" Value="20" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="Margin" Value="5,0,5,0" />
<Setter Property="SnapsToDevicePixels" Value="True" />
</Style>
<DataTemplate x:Key="HeaderTemplateDefault">
<Grid Style="{StaticResource HeaderGridStyle}">
<TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplateArrowUp">
<Grid Style="{StaticResource HeaderGridStyle}">
<Path Data="M 7,3 L 13,3 L 10,0 L 7,3" Style="{StaticResource HeaderPathStyle}" />
<TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplateArrowDown">
<Grid Style="{StaticResource HeaderGridStyle}">
<Path Data="M 7,0 L 10,3 L 13,0 L 7,0" Style="{StaticResource HeaderPathStyle}" />
<TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
</Grid>
</DataTemplate>
</ListView.Resources>
<ListView.View>
<GridView ColumnHeaderTemplate="{StaticResource HeaderTemplateDefault}">
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding NameProperty}" />
<GridViewColumn Header="Type" Width="45" DisplayMemberBinding="{Binding TypeProperty}"/>
<!-- ... -->
</GridView>
</ListView.View>
</ListView>
Code Behinde:
public partial class MyListView : ListView
{
GridViewColumnHeader _lastHeaderClicked = null;
public MyListView()
{
InitializeComponent();
}
private void ListViewColumnHeaderClick(object sender, RoutedEventArgs e)
{
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
if (headerClicked == null)
return;
if (headerClicked.Role == GridViewColumnHeaderRole.Padding)
return;
var sortingColumn = (headerClicked.Column.DisplayMemberBinding as Binding)?.Path?.Path;
if (sortingColumn == null)
return;
var direction = ApplySort(Items, sortingColumn);
if (direction == ListSortDirection.Ascending)
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowUp"] as DataTemplate;
}
else
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowDown"] as DataTemplate;
}
// Remove arrow from previously sorted header
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
{
_lastHeaderClicked.Column.HeaderTemplate =
Resources["HeaderTemplateDefault"] as DataTemplate;
}
_lastHeaderClicked = headerClicked;
}
public static ListSortDirection ApplySort(ICollectionView view, string propertyName)
{
ListSortDirection direction = ListSortDirection.Ascending;
if (view.SortDescriptions.Count > 0)
{
SortDescription currentSort = view.SortDescriptions[0];
if (currentSort.PropertyName == propertyName)
{
if (currentSort.Direction == ListSortDirection.Ascending)
direction = ListSortDirection.Descending;
else
direction = ListSortDirection.Ascending;
}
view.SortDescriptions.Clear();
}
if (!string.IsNullOrEmpty(propertyName))
{
view.SortDescriptions.Add(new SortDescription(propertyName, direction));
}
return direction;
}
}
This is happening because there is an unhandled exception in your Web service, and the .NET runtime is spitting out its HTML yellow screen of death server error/exception dump page, instead of XML.
Since the consumer of your Web service was expecting a text/xml header and instead got text/html, it throws that error.
You should address the cause of your timeouts (perhaps a lengthy SQL query?).
Also, checkout this blog post on Jeff Atwood's blog that explains implementing a global unhandled exception handler and using SOAP exceptions.
Set the height for the parent element.
To develop the answer of @Caumons:
Imagine one father class has many children and there is a need to add a common field into that class. If you consider the mentioned approach, you should go to each children class one by one and refactor their constructors for the new field. therefore that solution is not a promising solution in this scenario
Now take a look at this solution.
A father can receive an self object from each children. Here is a father class:
public class Father {
protected String fatherField;
public Father(Father a){
fatherField = a.fatherField;
}
//Second constructor
public Father(String fatherField){
this.fatherField = fatherField;
}
//.... Other constructors + Getters and Setters for the Fields
}
Here is our child class that should implement one of its father constructor, in this case the aforementioned constructor :
public class Child extends Father {
protected String childField;
public Child(Father father, String childField ) {
super(father);
this.childField = childField;
}
//.... Other constructors + Getters and Setters for the Fields
@Override
public String toString() {
return String.format("Father Field is: %s\nChild Field is: %s", fatherField, childField);
}
}
Now we test out application:
public class Test {
public static void main(String[] args) {
Father fatherObj = new Father("Father String");
Child child = new Child(fatherObj, "Child String");
System.out.println(child);
}
}
And here is the result :
Father Field is: Father String
Child Field is: Child String
Now you can easily add new fields to father class without being worried of your children codes to break;
attr_accessor
is (as @pst stated) just a method. What it does is create more methods for you.
So this code here:
class Foo
attr_accessor :bar
end
is equivalent to this code:
class Foo
def bar
@bar
end
def bar=( new_value )
@bar = new_value
end
end
You can write this sort of method yourself in Ruby:
class Module
def var( method_name )
inst_variable_name = "@#{method_name}".to_sym
define_method method_name do
instance_variable_get inst_variable_name
end
define_method "#{method_name}=" do |new_value|
instance_variable_set inst_variable_name, new_value
end
end
end
class Foo
var :bar
end
f = Foo.new
p f.bar #=> nil
f.bar = 42
p f.bar #=> 42
I think you are looking for
svn info -r HEAD
Can you shell to that command?
You'll probably need to supply login credentials with the repository as well.
I think you should put
`
(backtick) symbols around your variable.
Squash commits locally with
git rebase -i origin/master~4 master
and then force push with
git push origin +master
--force
and +
From the documentation of git push
:
Note that
--force
applies to all the refs that are pushed, hence using it withpush.default
set tomatching
or with multiple push destinations configured withremote.*.push
may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a+
in front of the refspec to push (e.ggit push origin +master
to force a push to themaster
branch).
The current platform version of a cordova app can be checked by the following command
cordova platform version android
And can be upgraded using the command
cordova platform update android
You can replace android by any of your platform choice like "ios" or some else.
This only applies to android platform. I have not checked. You can try replacing android in the code segments to try for other platforms.
you can align your content using flex box with minimum code
HTML
<div class="image-container">
<img src="https://image.freepik.com/free-vector/modern-abstract-background_1048-1003.jpg" width="100px">
</div>
CSS
.image-container{
width:100%;
background:green;
display:flex;
.image-container{_x000D_
width:100%;_x000D_
background:green;_x000D_
display:flex;_x000D_
justify-content: center;_x000D_
align-items:center;_x000D_
}
_x000D_
<div class="image-container">_x000D_
<img src="https://image.freepik.com/free-vector/modern-abstract-background_1048-1003.jpg" width="100px"> _x000D_
</div>
_x000D_
js fiddle link https://jsfiddle.net/7un6ku2m/
Yes, you can achieve this by using the following commands:
sqlite> .headers on
sqlite> .mode column
The result of a select on your table will then look like:
id foo bar age street address
---------- ---------- ---------- ---------- ---------- ----------
1 val1 val2 val3 val4 val5
2 val6 val7 val8 val9 val10
looks like bad architecture all the way. also you have not specified the type of app you need to notify to (web app / console app / winforms / service etc etc)
nevertheless, to answer your question, there are multiple ways of solving this. you could use:
1) timestamps if you were just interested in ensuring the next set of updates from the second app dont conflict with the updates from the first app
2) sql dependency object - see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx for more info
3) a custom push notification service which multiple clients (web / winform / service) can subscribe to and get notified on changes
in short, you need to use the simplest and easiest and cheapest (in terms of efforts) solution based on how complex your notification requirements are and for what purpose you need to use them. dont try to build an overly complex notification system if a simple data concurrency is your only requirement (in that case go for a simple timestamp based solution)
Where do you want to see the output?
Messages being output via Debug.Print
will be displayed in the immediate window which you can open by pressing Ctrl+G.
You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar
You can use array.slice(0,1) // First index is removed and array is returned.
Enter the original date into a Date
object and then print out the result with a DateFormat
. You may have to split up the string into smaller pieces to create the initial Date
object, if the automatic parse method does not accept your format.
Pseudocode:
Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);
In the future, you will be able to use a --from-lock-file
(or similar) flag to install only from the package-lock.json
without modifying it.
This will be useful for CI, etc. environments where reproducible builds are important.
See https://github.com/npm/npm/issues/18286 for tracking of the feature.
i import the material design dialog module , so i created aboutcomponent for dialog the call this component from openDialog method then i got this error , i just put this
declarations: [
AppComponent,
ExampleDialogComponent
],
entryComponents: [
ExampleDialogComponent
],
As other noted you have several options. If you want only mathematical functions. You can import only Darwin.
import Darwin
If you want mathematical functions and other standard classes and functions. You can import Foundation.
import Foundation
If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.
For OS X, you need import Cocoa.
import Cocoa
For iOS, you need import UIKit.
import UIKit
You can easily discover your playground platform by opening File Inspector (??1).
The public
keyword is an access modifier, which allows the programmer to control
the visibility of class members. When a class member is preceded by public
, then that
member may be accessed by code outside the class in which it is declared.
The opposite of public
is private
, which prevents a member from being used by code defined outside of its class.
In this case, main()
must be declared as public
, since it must be called
by code outside of its class when the program is started.
The keyword static
allows
main()
to be called without having to instantiate a particular instance of the class. This is necessary since main()
is called by the Java interpreter before any objects are made.
The keyword void
simply tells the compiler that main()
does not return a value.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class readFile {
/**
* feel free to make any modification I have have been here so I feel you
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
File dir = new File(".");// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}`enter code here`
}
You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus
See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.
Tested on both spark-shell
version 1.6.3
and spark2-shell
version 2.3.0.2.6.5.179-4
, you can directly pipe to the shell's stdin like
spark-shell <<< "1+1"
or in your use case,
spark-shell < file.spark
A scrolling comes from a box with class pre-scrollable
<div class="pre-scrollable"></div>
There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.
Multiple backgrounds!
body {_x000D_
background: #eb01a5;_x000D_
background-image: url("IMAGE_URL"); /* fallback */_x000D_
background-image: url("IMAGE_URL"), linear-gradient(#eb01a5, #d13531); /* W3C */_x000D_
}
_x000D_
These 2 lines are the fallback for any browser that doesn't do gradients. See notes for stacking images only IE < 9 below.
The final line sets a background image and gradient for browsers that can handle them.
Nearly all current browsers have support for multiple background images and css backgrounds. See http://caniuse.com/#feat=css-gradients for browser support. For a good post on why you don't need multiple browser prefixes, see http://codepen.io/thebabydino/full/pjxVWp/
Layer Stack
It should be noted that the first defined image will be topmost in the stack. In this case, the image is on TOP of the gradient.
For more information about background layering see http://www.w3.org/TR/css3-background/#layering.
Stacking images ONLY (no gradients in the declaration) For IE < 9
IE9 and up can stack images this same way. You could use this to create a gradient image for ie9, though personally, I wouldn't. However to be noted when using only images, ie < 9 will ignore the fallback statement and not show any image. This does not happen when a gradient is included. To use a single fallback image in this case I suggest using Paul Irish's wonderful Conditional HTML element along with your fallback code:
.lte9 #target{ background-image: url("IMAGE_URL"); }
Background position, sizing etc.
Other properties that would apply to a single image may also be comma separated. If only 1 value is supplied, that will be applied to all stacked images including the gradient. background-size: 40px;
will constrain both the image and the gradient to 40px height and width. However using background-size: 40px, cover;
will make the image 40px and the gradient will cover the element. To only apply a setting to one image, set the default for the other: background-position: 50%, 0 0;
or for browsers that support it use initial
: background-position: 50%, initial;
You may also use the background shorthand, however this removes the fallback color and image.
body{
background: url("IMAGE_URL") no-repeat left top, linear-gradient(#eb01a5, #d13531);
}
The same applies to background-position, background-repeat, etc.
That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).
Check out the documentation for more: clicky
@Robusto's solution was the simplest for what I was trying to do, I suggest you use it. I was trying to do the same thing for images in an unordered list to make a gallery... I made a js fiddle to fool around with it. Feel free to try it here.
[it was set up using robusto's sample code]
HTML:
<div id="centerDiv">
<ul class="centerUL">
<li><a href="http://www.amazon.com"><img src="http://placehold.it/200x150> </a> </li>
<li><a href="http://www.amazon.com"><img src="http://placehold.it/200x150"></a> </li>
<li><a href="http://www.amazon.com"><img src="http://placehold.it/200x150"></a></li>
</ul>
</div>
CSS:
div#centerDiv {
width: 700px;
text-align: center;
border: 1px solid red;
}
ul.centerUL {
margin: 2px auto;
line-height: 1.4;
}
.centerUL li {
display: inline;
text-align: center;
}
The Answer from AaronM using the shell one-liner is good, but actually, there is yet another bug, where spaces will corrupt the user names if there are different amounts of white spaces between the user name and the date. The corrupted user names will give multiple rows for user counts and you have to sum them up yourself.
This small change fixed the issue for me:
git ls-files -z | xargs -0n1 git blame -w --show-email | perl -n -e '/^.*?\((.*?)\s+[\d]{4}/; print $1,"\n"' | sort -f | uniq -c | sort -n
Notice the + after \s which will consume all whitespaces from the name to the date.
Actually adding this answer as much for my own rememberance as for helping anyone else, since this is at least the second time I google the subject :)
--show-email
to git blame -w
to aggregate on email instead, since some people use different Name
formats on different computers, and sometimes two people with the same name are working in the same git.The special target .PHONY:
allows to declare phony targets, so that make
will not check them as actual file names: it will work all the time even if such files still exist.
You can put several .PHONY:
in your Makefile
:
.PHONY: all
all : prog1 prog2
...
.PHONY: clean distclean
clean :
...
distclean :
...
There is another way to declare phony targets : simply put ::
without prerequisites :
all :: prog1 prog2
...
clean ::
...
distclean ::
...
The ::
has other special meanings, see here, but without prerequisites it always execute the recipes, even if the target already exists, thus acting as a phony target.
I think you can use Padding like: Hope this one can help you.
.loginButton {
background:url(images/loginBtn-center.jpg) repeat-x;
width:175px;
height:65px;
margin:20px auto;
border-radius:10px;
-webkit-border-radius:10px;
box-shadow:0 1px 2px #5e5d5b;
<!--Using padding to align text in box or image-->
padding: 3px 2px;
}
Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)
You can recursively iterate through subviews, store an array of all UITextFields, and then loop through them and resign them all.
Not really a great solution, especially if you have a lot of subviews, but for simple apps it should do the trick.
I solved this in a much more complicated, but much more performant way, but using a singleton/manager for the animation engine of my app, and any time a text field became the responder, I would assign assign it to a static which would get swept up (resigned) based on certain other events... its almost impossible for me to explain in a paragraph.
Be creative, it only took me 10 minutes to think through this for my app after I found this question.
X-UA-Compatible
will only override the Document Mode, not the Browser Mode, and will not work for all intranet sites; if this is your case, the best solution is to disable "Display intranet sites in Compatibility View" and set a group policy setting to specify which intranet sites need compatibility mode.
Maybe it is little bit of an extreme, but I am using this super short version:
curl -svo. <URL>
Explanation:
-v
print debug information (which does include headers)
-o.
send web page data (which we want to ignore) to a certain file, .
in this case, which is a directory and is an invalid destination and makes the output to be ignored.
-s
no progress bar, no error information (otherwise you would see Warning: Failed to create the file .: Is a directory
)
warning: result always fails (in terms of error code, if reachable or not). Do not use in, say, conditional statements in shell scripting...
(df.groupby(['col5', 'col2']).size()
.sort_values(ascending=False)
.reset_index(name='count')
.drop_duplicates(subset='col2'))
col5 col2 count
0 3 A 3
1 1 D 3
2 5 B 2
6 3 C 1
Explanation
The result of the groupby size
method is a Series with col5
and col2
in the index. From here, you can use another groupby method to find the maximum value of each value in col2
but it is not necessary to do. You can simply sort all the values descendingly and then keep only the rows with the first occurrence of col2
with the drop_duplicates
method.
If you want to do this solely using javascript, I would do the following. Give the span an id attribute (so that it can easily be retrieved from the DOM) and place all the content in an attribute named 'content':
<span id='myDataId' style='text-overflow: ellipsis; overflow : hidden;
white-space: nowrap; width: 71;' content='{$myData}'>${myData}</span>
Then, in your javascript, you can do the following after the element has been inserted into the DOM.
var elemInnerText, elemContent;
elemInnerText = document.getElementById("myDataId").innerText;
elemContent = document.getElementById("myDataId").getAttribute('content')
if(elemInnerText.length <= elemContent.length)
{
document.getElementById("myDataId").setAttribute('title', elemContent);
}
Of course, if you're using javascript to insert the span into the DOM, you could just keep the content in a variable before inserting it. This way you don't need a content attribute on the span.
There are more elegant solutions than this if you want to use jQuery.
I used this:
$('.nav-list li.active').removeClass('active');
$(this).parent().addClass('active');
Since the active class is in the <li>
element and what is clicked is the <a>
element, the first line removes .active
from all <li>
and the second one (again, $(this)
represents <a>
which is the clicked element) adds .active
to the direct parent, which is <li>
.
This is an old inquiry, but since I was looking for the answer I ran across it. Some of the answers made me remember I use S3 Browser to manage data. You can click on a bucket and hit properties and it shows you the total. Pretty simple. I highly recommend the browser: https://s3browser.com/default.aspx?v=6-1-1&fam=x64
For linux (I have fixed bugs in code above):
void remove_dir(char *path)
{
struct dirent *entry = NULL;
DIR *dir = NULL;
dir = opendir(path);
while(entry = readdir(dir))
{
DIR *sub_dir = NULL;
FILE *file = NULL;
char* abs_path new char[256];
if ((*(entry->d_name) != '.') || ((strlen(entry->d_name) > 1) && (entry->d_name[1] != '.')))
{
sprintf(abs_path, "%s/%s", path, entry->d_name);
if(sub_dir = opendir(abs_path))
{
closedir(sub_dir);
remove_dir(abs_path);
}
else
{
if(file = fopen(abs_path, "r"))
{
fclose(file);
remove(abs_path);
}
}
}
delete[] abs_path;
}
remove(path);
}
For windows:
void remove_dir(const wchar_t* folder)
{
std::wstring search_path = std::wstring(folder) + _T("/*.*");
std::wstring s_p = std::wstring(folder) + _T("/");
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
if (hFind != INVALID_HANDLE_VALUE) {
do {
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (wcscmp(fd.cFileName, _T(".")) != 0 && wcscmp(fd.cFileName, _T("..")) != 0)
{
remove_dir((wchar_t*)(s_p + fd.cFileName).c_str());
}
}
else {
DeleteFile((s_p + fd.cFileName).c_str());
}
} while (::FindNextFile(hFind, &fd));
::FindClose(hFind);
_wrmdir(folder);
}
}
datetime
:':0>8'
format:from datetime import timedelta
"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
':0>8'
format:"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
time
:from time import gmtime
from time import strftime
# NOTE: The following resets if it goes over 23:59:59!
strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'
strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'
strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'
strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong
You need to use javascript for this.
<form id="form1" action="showMessage.jsp" method="post">
<a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
<input type="hidden" name="mess" value=<%=n%>/>
</form>
As long as checker
is not null
, you may use !checker
as posted. This is possible since Java 5, because this Boolean
variable will be autoboxed to the primivite boolean
value.
TLDR; Uninstall and re-install using admin account.
I encountered this error after installing Oracle Express 11g 64 bit using a standard account. After looking for a fix on various sites I realized that the issue was most likely caused by an incorrect setting. Different people suggested editing various files which I was not interested in doing. I found one person who claimed that the issue was a registry setting. Since I used a standard account to install I thought that maybe the registry setting could not be altered using a standard account. So I uninstalled and re-installed using an admin account and it just worked.
To fetch only current date excluding time stamp:
in lower versions, looks like hive CURRENT_DATE is not available, hence you can use (it worked for me on Hive 0.14)
select TO_DATE(FROM_UNIXTIME(UNIX_TIMESTAMP()));
In higher versions say hive 2.0, you can use :
select CURRENT_DATE;
Swift version:
extension UIColor {
convenience init?(var hex: String) {
hex = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
hex = (hex.hasPrefix("#")) ? hex.substringFromIndex(advance(hex.startIndex, 1)) : hex
var value: UInt32 = 0
if NSScanner(string: hex).scanHexInt(&value) {
if count(hex) == 8 {
self.init(red: CGFloat((value & 0xFF000000) >> 24) / 255.0,
green: CGFloat((value & 0x00FF0000) >> 16) / 255.0,
blue: CGFloat((value & 0x0000FF00) >> 8) / 255.0,
alpha: CGFloat((value & 0x000000FF)) / 255.0)
return
} else if count(hex) == 6 {
self.init(red: CGFloat((value & 0xFF0000) >> 16) / 255.0,
green: CGFloat((value & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(value & 0x0000FF) / 255.0,
alpha: 1.0)
return
}
}
self.init()
return nil
}
}
Be aware that need to change both location:
File > Settings... > Editor > Code Style > "Hard Wrap at"
and
File > Settings... > Editor > Code Style > (your language) > Wrapping and Braces > Hard wrap at
$.ajax({
type: "POST",
data: formData,
url: "/Forms/GetJobData",
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
if (response.success) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
Controller:
[HttpPost]
public ActionResult GetJobData(Jobs jobData)
{
var mimeType = jobData.File.ContentType;
var isFileSupported = IsFileSupported(mimeType);
if (!isFileSupported){
// Send "false"
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
else
{
// Send "Success"
return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
}
}
---Supplement:---
basically you can send multiple parameters this way:
Controller:
return Json(new {
success = true,
Name = model.Name,
Phone = model.Phone,
Email = model.Email
},
JsonRequestBehavior.AllowGet);
Html:
<script>
$.ajax({
type: "POST",
url: '@Url.Action("GetData")',
contentType: 'application/json; charset=utf-8',
success: function (response) {
if(response.success){
console.log(response.Name);
console.log(response.Phone);
console.log(response.Email);
}
},
error: function (response) {
alert("error!");
}
});
dict.iteritems() in python 2 is equivalent to dict.items() in python 3.
I've recently made a page loader in vanilla .js
for a project, just wanted to share it as all the other answers are jQuery based. It's a plug and play, one-liner.
It automatically creates a <div>
tag prepended to the <body>
, with a <svg>
loader. If you want to customize the color you just have to update the t
variable at the beginning of the script.
var t="#106CF6",u=document.querySelector("*"),s=document.createElement("style"),a=document.createElement("aside"),m="http://www.w3.org/2000/svg",g=document.createElementNS(m,"svg"),c=document.createElementNS(m,"circle");document.head.appendChild(s),(s.innerHTML="#sailor {background:"+t+";color:"+t+";display:flex;align-items:center;justify-content:center;position:fixed;top:0;height:100vh;width:100vw;z-index:2147483647}@keyframes swell{to{transform:rotate(360deg)}}#sailor svg{animation:.3s swell infinite linear}"),a.setAttribute("id","sailor"),document.body.prepend(a),g.setAttribute("height","50"),g.setAttribute("filter","brightness(175%)"),g.setAttribute("viewBox","0 0 100 100"),a.prepend(g),c.setAttribute("cx","50"),c.setAttribute("cy","50"),c.setAttribute("r","35"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-dasharray","165 57"),c.setAttribute("stroke-width","10"),g.prepend(c),(u.style.pointerEvents="none"),(u.style.userSelect="none"),(u.style.cursor="wait"),window.addEventListener("load",function(){setTimeout(function(){(u.style.pointerEvents=""),(u.style.userSelect=""),(u.style.cursor="");a.remove()},100)})
You can see the full project and documentation on the GitHub
Function.prototype.applyAsync = function(params, cb){
var function_context = this;
setTimeout(function(){
var val = function_context.apply(undefined, params);
if(cb) cb(val);
}, 0);
}
// usage
var double = function(n){return 2*n;};
var display = function(){console.log(arguments); return undefined;};
double.applyAsync([3], display);
Although not fundamentally different than the other solutions, I think my solution does a few additional nice things:
Function.prototype
allowing a nicer way to call itAlso, the similarity to the built-in function Function.prototype.apply
seems appropriate to me.
if you want to copy in same Jenkins but in different subfolders, create new item -> use copy from. new Job will be cloned in same directory. Then use move option to move it in desired directory
You can use different syntax to achieve different things. If it is windows authentication you want, you could try this:
sqlcmd /S /d -E
If you want to use SQL Server authentication you could try this:
sqlcmd /S /d -U -P
Definitions:
/S = the servername/instance name. Example: Pete's Laptop/SQLSERV
/d = the database name. Example: Botlek1
-E = Windows authentication.
-U = SQL Server authentication/user. Example: Pete
-P = password that belongs to the user. Example: 1234
Hope this helps!
I'm using rescu with Kotlin and resolved it by using @ConstructorProperties
data class MyResponse @ConstructorProperties("message", "count") constructor(
val message: String,
val count: Int
)
Jackson uses @ConstructorProperties. This should fix Lombok @Data as well.
I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.
Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.
I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.
This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.
This is my angular controller.
var angularJsApp= angular.module('angularJsApp',[]);
angularJsApp.controller('MainCtrl', function ($scope ,$http) {
$scope.userName ="Victoria";
$scope.password ="password"
$http({
method :'POST',
url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
data: { username : $scope.userName , password: $scope.password},
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
console.log('status',status);
console.log('data',status);
console.log('headers',status);
});
});
This is my php back-end laravel controller.
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
This is my laravel routing
Route::post('httpTest','HttpTestController@httpTest');
The result in browser is
status 200
data JSON_CALLBACK({"username":"Victoria","password":"password","callback":"JSON_CALLBACK"}); httpTesting.js:18 headers function (c){a||(a=sc(b));return c?a[K(c)]||null:a}
There is chrome extension called postman. You can use to test your back-end url whether it is working or not. https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
hopefully, my answer will help you.
TextView text = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
now set the textview
properties..
text.setTypeface(null, Typeface.BOLD); //-- for only bold the text
text.setTypeface(null, Typeface.BOLD_ITALIC); //-- for bold & italic the text
text.setTypeface(null, Typeface.ITALIC); // -- for italic the text
You can't style the <tr>
s themselves, but you can give the <td>
s inside the "highlight" <tr>
s a style, like this
tr.highlight td {padding-top: 10px; padding-bottom:10px}
To get public static void main(String[] args) line in eclipse without typing the whole line type "main" and press Ctrl + space then, you will get the option for the main method select it.
Here is the msdn documentation on the listview object and the listviewItem object.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.aspx
I would highly recommend that you at least take the time to skim the documentation on any objects you use from the .net framework. While the documentation can be pretty poor at some times it is still invaluable especially when you run into situations like this.
But as James Atkinson said it's simply a matter of adding subitems to a listviewitem like so:
ListViewItem i = new ListViewItem("column1");
i.SubItems.Add("column2");
i.SubItems.Add("column3");
const formData = new FormData(form);
let formDataJSON = {};
for (const [key, value] of formData.entries()) {
formDataJSON[key] = value;
}
A one-liner, just to get the status-code would be:
curl -s -i https://www.google.com | head -1
Changing it to head -2
will give the time as well.
If you want a while-true loop over it, it would be:
URL="https://www.google.com"
while true; do
echo "------"
curl -s -i $URL | head -2
sleep 2;
done
Which produces the following, until you do cmd+C
(or ctrl+C
in Windows).
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:38 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:41 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:43 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:45 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:47 GMT
------
HTTP/2 200
date: Sun, 07 Feb 2021 20:03:49 GMT
You can use the folowing to get the full path to your program like this:
Environment.CurrentDirectory
Most problems can be solved using (i) just locks, (ii) just semaphores, ..., or (iii) a combination of both! As you may have discovered, they're very similar: both prevent race conditions, both have acquire()
/release()
operations, both cause zero or more threads to become blocked/suspected...
Really, the crucial difference lies solely on how they lock and unlock.
For both locks/semaphores, trying to call acquire()
while the primitive is in state 0 causes the invoking thread to be suspended. For locks - attempts to acquire the lock is in state 1 are successful. For semaphores - attempts to acquire the lock in states {1, 2, 3, ...} are successful.
For locks in state state 0, if same thread that had previously called acquire()
, now calls release, then the release is successful. If a different thread tried this -- it is down to the implementation/library as to what happens (usually the attempt ignored or an error is thrown). For semaphores in state 0, any thread can call release and it will be successful (regardless of which thread previous used acquire to put the semaphore in state 0).
From the preceding discussion, we can see that locks have a notion of an owner (the sole thread that can call release is the owner), whereas semaphores do not have an owner (any thread can call release on a semaphore).
What causes a lot of confusion is that, in practice they are many variations of this high-level definition.
Important variations to consider:
acquire()
/release()
be called? -- [Varies massively]These depends on your book / lecturer / language / library / environment.
Here's a quick tour noting how some languages answer these details.
pthread_mutex_t
. By default, they can't be shared with any other processes (PTHREAD_PROCESS_PRIVATE
), however mutex's have an attribute called pshared. When set, so the mutex is shared between processes (PTHREAD_PROCESS_SHARED
). sem_t
. Similar to mutexes, semaphores can be shared between threasds of many processes or kept private to the threads of one single process. This depends on the pshared argument provided to sem_init
. threading.RLock
) is mostly the same as C/C++ pthread_mutex_t
s. Both are both reentrant. This means they may only be unlocked by the same thread that locked it. It is the case that sem_t
semaphores, threading.Semaphore
semaphores and theading.Lock
locks are not reentrant -- for it is the case any thread can perform unlock the lock / down the semaphore.threading.Semaphore
) is mostly the same as sem_t
. Although with sem_t
, a queue of thread ids is used to remember the order in which threads became blocked when attempting to lock it while it is locked. When a thread unlocks a semaphore, the first thread in the queue (if there is one) is chosen to be the new owner. The thread identifier is taken off the queue and the semaphore becomes locked again. However, with threading.Semaphore
, a set is used instead of a queue, so the order in which threads became blocked is not stored -- any thread in the set may be chosen to be the next owner.java.util.concurrent.ReentrantLock
) is mostly the same as C/C++ pthread_mutex_t
's, and Python's threading.RLock
in that it also implements a reentrant lock. Sharing locks between processes is harder in Java because of the JVM acting as an intermediary. If a thread tries to unlock a lock it doesn't own, an IllegalMonitorStateException
is thrown.java.util.concurrent.Semaphore
) is mostly the same as sem_t
and threading.Semaphore
. The constructor for Java semaphores accept a fairness boolean parameter that control whether to use a set (false) or a queue (true) for storing the waiting threads. In theory, semaphores are often discussed, but in practice, semaphores aren't used so much. A semaphore only hold the state of one integer, so often it's rather inflexible and many are needed at once -- causing difficulty in understanding code. Also, the fact that any thread can release a semaphore is sometimes undesired. More object-oriented / higher-level synchronization primitives / abstractions such as "condition variables" and "monitors" are used instead.
I faced the same issue where I started a node app in port 3000 and it didn't close correctly and the process kept running even after restart.
None of the taskkill or powershell commands running in Administrator mode worked for me.
I used MS Process Expoler > Properties > Image > Current directory (which was supposed to be the my project directory).
Finally, I had to reboot in SafeMode and rename the project folder and restart. The Node processes which were consuming port 3000 killed itself.
I'm pretty certain that you can't change the datetime format in mysql. The phpmyadmin setting is probably applying a custom format as it reads the datetime (using DATE_FORMAT or something from php). It shouldn't matter what format the database uses, format in the application to display it as you wish.
Date formatting is a pretty common task. I typically like to abstract it out into internationalization code or, if you don't need to deal with i18n, into a common date utility library. It helps keep things consistent and makes it easier to change later (or add i18n support).
There's a book in Martin Fowler's Signature Series called Refactoring Databases. That provides a list of techniques for refactoring databases. I can't say I've heard a list of database patterns so much.
I would also highly recommend David C. Hay's Data Model Patterns and the follow up A Metadata Map which builds on the first and is far more ambitious and intriguing. The Preface alone is enlightening.
Also a great place to look for some pre-canned database models is Len Silverston's Data Model Resource Book Series Volume 1 contains universally applicable data models (employees, accounts, shipping, purchases, etc), Volume 2 contains industry specific data models (accounting, healthcare, etc), Volume 3 provides data model patterns.
Finally, while this book is ostensibly about UML and Object Modelling, Peter Coad's Modeling in Color With UML provides an "archetype" driven process of entity modeling starting from the premise that there are 4 core archetypes of any object/data model
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
With ES6 the most performant way would be to use a Map.
var myMap = new Map();
myMap.set(1, 'myVal');
myMap.set(2, { catName: 'Meow', age: 3 });
myMap.get(1);
myMap.get(2);
You can use ES6 features today using a shim (https://github.com/es-shims/es6-shim).
Performance will vary depending on the browser and scenario. But here is one example where Map
is most performant: https://jsperf.com/es6-map-vs-object-properties/2
REFERENCE https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
Actually, this has nothing to do with the usual Windows / Unix \r\n
vs \n
issue. The TELNET procotol itself defines \r\n
as the end-of-line sequence, independently of the operating system. See RFC854.
If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:
plt.axes[0].get_lines()[0].set_color('black')
Things are a little different if you're using two-factor authentication as I am. Since I didn't find a good answer elsewhere, I'll stick one here so that maybe I can find it later.
If you're using two-factor authentication, then specifying username/password won't even work - you get access denied. But you can use an application access token and use Git's credential helper to cache that for you. Here are the pertinent links:
And I don't remember where I saw this, but when you're asked for your username - that's where you stick the application access token. Then leave the password blank. It worked on my Mac.
You can use Node.js for Mobile Apps.
It works on Android devices and simulators, with pre-built binaries for armeabi-v7a, x86, arm64-v8a, x86_64. It also works on iOS, though that's outside the scope of this question.
Like JXcore, it is used to host a Node.js engine in the same process as the app, in a dedicated thread. Unlike JXcore, it is basically pure Node.js, built as a library, with a few portability fixes to run on Android. This means that it's much easier to keep the project up to date with mainline Node.js.
Plugins for Cordova and React Native are also available. The plugins provide a communication layer between the JavaScript side of those frameworks and the Node.js side. They also simplify development by taking care of a few things automatically, like packaging modules and cross-compiling native modules at build time.
Full disclosure: I work for the company that develops Node.js for Mobile Apps.
Your rewrite rule looks almost ok.
First make sure that your .htaccess
file is in your document root (the same place as index.php
) or it'll only affect the sub-folder it's in (and any sub-folders within that - recursively).
Next make a slight change to your rule so it looks something like:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
At the moment you're just matching on .
which is one instance of any character, you need at least .*
to match any number of instances of any character.
The $_GET['path']
variable will contain the fake directory structure, so /mvc/module/test
for instance, which you can then use in index.php to determine the Controller and actions you want to perform.
If you want the whole shebang installed in a sub-directory, such as /mvc/
or /framework/
the least complicated way to do it is to change the rewrite rule slightly to take that into account.
RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]
And ensure that your index.php
is in that folder whilst the .htaccess
file is in the document root.
Alternative to $_GET['path']
(updated Feb '18 and Jan '19)
It's not actually necessary (nor even common now) to set the path as a $_GET
variable, many frameworks will rely on $_SERVER['REQUEST_URI']
to retrieve the same information - normally to determine which Controller to use - but the principle is exactly the same.
This does simplify the RewriteRule
slightly as you don't need to create the path parameter (which means the OP's original RewriteRule
will now work):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
However, the rule about installing in a sub-directory still applies, e.g.
RewriteRule ^.*$ /mvc/index.php [L,QSA]
The flags:
NC
= No Case (not case sensitive, not really necessary since there are no characters in the pattern)
L
= Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)
QSA
= Query String Append, just in case you've got something like ?like=penguins
on the end which you want to keep and pass to index.php.
To keep jQuery and the DOM in sync, a simple option may be
$('#mydiv').data('myval',20).attr('data-myval',20);
I know it’s totally stupid and you normally really shouldn’t use tables when not creating tables, but:
Table cells can align multiple lines of text vertically centered and even do this by default. So a solution which works quite fine could be something like this:
HTML:
<div class="box">
<table class="textalignmiddle">
<tr>
<td>lorem ipsum ...</td>
</tr>
</table>
</div>
CSS (make the table item always fit to the box div):
.box {
/* For example */
height: 300px;
}
.textalignmiddle {
width: 100%;
height: 100%;
}
See here: http://www.cssdesk.com/LzpeV
To put HTML/Word in an Excel Shape and locate it on an Excel Cell:
In this way, even HTML with tables and other stuff does not get split over multiple cells.
private void btnPutHTMLIntoExcelShape_Click(object sender, EventArgs e)
{
var fFile = new FileInfo(@"C:\Temp\temp.html");
StreamWriter SW = fFile.CreateText();
SW.Write(hecNote.DocumentHtml);
SW.Close();
Word.Application wrdApplication;
Word.Document wrdDocument;
wrdApplication = new Word.Application();
wrdApplication.Visible = true;
wrdDocument = wrdApplication.Documents.Add(@"C:\Temp\temp.html");
wrdDocument.ActiveWindow.Selection.WholeStory();
wrdDocument.ActiveWindow.Selection.Copy();
Excel.Application excApplication;
Excel.Workbook excWorkbook;
Excel._Worksheet excWorksheet;
Excel.Range excRange = null;
excApplication = new Excel.Application();
excApplication.Visible = true;
excWorkbook = excApplication.Workbooks.Add(Type.Missing);
excWorksheet = (Excel.Worksheet)excWorkbook.Worksheets.get_Item(1);
excWorksheet.Name = "Work";
excRange = excWorksheet.get_Range("A1");
excRange.Select();
excWorksheet.PasteSpecial("Microsoft Word Document Object");
Excel.Shape O = excWorksheet.Shapes.Item(1);
this.Text = $"{O.Height} x {O.Width}";
((Excel.Range)excWorksheet.Rows[1, Type.Missing]).RowHeight = O.Height;
}
Checkout the tutorial from Ourcodeworld Ourcodeworld - encode and decode html entities with javascript
Most importantly, the he library example
he.encode('foo © bar ? baz ???? qux');
// ? 'foo © bar ≠ baz 𝌆 qux'
// Passing an `options` object to `encode`, to explicitly encode all symbols:
he.encode('foo © bar ? baz ???? qux', {
'encodeEverything': true
});
he.decode('foo © bar ≠ baz 𝌆 qux');
// ? 'foo © bar ? baz ???? qux'
This library would probably make your coding easier and better managed. It is popular, regularly updated and follows the HTML spec. It itself has no dependencies, as can be seen in the package.json
Remove lib from Podfile, then pod install
again.
The await
inside your asynchronous method is trying to come back to the UI thread.
Since the UI thread is busy waiting for the entire task to complete, you have a deadlock.
Moving the async call to Task.Run()
solves the issue.
Because the async call is now running on a thread pool thread, it doesn't try to come back to the UI thread, and everything therefore works.
Alternatively, you could call StartAsTask().ConfigureAwait(false)
before awaiting the inner operation to make it come back to the thread pool rather than the UI thread, avoiding the deadlock entirely.
I solved my problem in AngularJS as follows:
var configPopOver = {
animation: 500,
container: 'body',
placement: function (context, source) {
var elBounding = source.getBoundingClientRect();
var pageWidth = angular.element('body')[0].clientWidth
var pageHeith = angular.element('body')[0].clientHeith
if (elBounding.left > (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
return "left";
}
if (elBounding.left < (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
return "right";
}
if (elBounding.top < 110){
return "bottom";
}
return "top";
},
html: true
};
This function do the position of Bootstrap popover float to the best position, based on element position.
var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');_x000D_
var date = moment(strdate).format('DD.MM.YYYY');_x000D_
$("#result").text(date); //07.02.2017
_x000D_
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>_x000D_
_x000D_
<div id="result"></div>
_x000D_
Convert Date To String
Use name Space
using System.Globalization;
Code
string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");
You're using junit.framework.Assert
instead of org.junit.Assert
.
You could use the PEAR Mail classes and methods, which allows you to check for errors via:
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
You can find an example here.
valdyr, hope this will help you:
CGPoint bottomOffset = CGPointMake(0, [textView contentSize].height - textView.frame.size.height);
if (bottomOffset.y > 0)
[textView setContentOffset: bottomOffset animated: YES];
$a = array( 'one', 'two', 'three', 'four' );
$b = in_array( 'ONE', $a, false );
Full join in mysql :(left union right) or (right unoin left)
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
left JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
Union
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
Right JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
You could simply convert the datetime. Something like:
@Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.Returndate))
In you case here, if you want to right-align that green button, just change the one div to have everything right-aligned:
<div class="action_buttons_header" style="text-align: right;">
The div is already taking up the full width of that section, so just shift the green button the right by right-aligning the text.
I would like to propose a significantly faster (and memory efficient) alternative: strtok
rather than preg_split
.
$separator = "\r\n";
$line = strtok($subject, $separator);
while ($line !== false) {
# do something with $line
$line = strtok( $separator );
}
Testing the performance, I iterated 100 times over a test file with 17 thousand lines: preg_split
took 27.7 seconds, whereas strtok
took 1.4 seconds.
Note that though the $separator
is defined as "\r\n"
, strtok
will separate on either character - and as of PHP4.1.0, skip empty lines/tokens.
See the strtok manual entry: http://php.net/strtok
Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.
With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/google_blue" />
Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.
In a class component context...
handleChange(e){
this.setState({[e.target.name]:[e.target.value]});
}
it can be used such as this...onChange={(e)=>this.handleChange(e)}
<input type="text" name="any" value={this.state.any} onChange={(e)=>this.handleChange(e)}></input>
handle = (e) =>{
this.setState({[e.target.name]:[e.target.value]});
}
it can be used like this... onChange={this.handle}
<input type="text" name="any2" value={this.state.any2} onChange={this.handle} ></input>
And this solved my "Can't type in React input text field" problem.
As of Alpha 6 you can create the following sass file:
@each $breakpoint in map-keys($grid-breakpoints) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
col, td, th {
@for $i from 1 through $grid-columns {
&.col#{$infix}-#{$i} {
flex: none;
position: initial;
}
}
@include media-breakpoint-up($breakpoint, $grid-breakpoints) {
@for $i from 1 through $grid-columns {
&.col#{$infix}-#{$i} {
width: 100% / $grid-columns * $i;
}
}
}
}
}
I would recommend using the Chrome extension Clockwork with the Laravel package https://github.com/itsgoingd/clockwork. It's easy to install and use.
Clockwork is a Chrome extension for PHP development, extending Developer Tools with a new panel providing all kinds of information useful for debugging and profiling your PHP scripts, including information on request, headers, GET and POST data, cookies, session data, database queries, routes, visualisation of application runtime and more. Clockwork includes out of the box support for Laravel 4 and Slim 2 based applications, you can add support for any other or custom framework via an extensible API.
import java.util.AbstractList;
import java.util.List;
/**
* The {@code ConcatList} is a lightweight view of two {@code List}s.
* <p>
* This implementation is <em>not</em> thread-safe even though the underlying lists can be.
*
* @param <E>
* the type of elements in this list
*/
public class ConcatList<E> extends AbstractList<E> {
/** The first underlying list. */
private final List<E> list1;
/** The second underlying list. */
private final List<E> list2;
/**
* Constructs a new {@code ConcatList} from the given two lists.
*
* @param list1
* the first list
* @param list2
* the second list
*/
public ConcatList(final List<E> list1, final List<E> list2) {
this.list1 = list1;
this.list2 = list2;
}
@Override
public E get(final int index) {
return getList(index).get(getListIndex(index));
}
@Override
public E set(final int index, final E element) {
return getList(index).set(getListIndex(index), element);
}
@Override
public void add(final int index, final E element) {
getList(index).add(getListIndex(index), element);
}
@Override
public E remove(final int index) {
return getList(index).remove(getListIndex(index));
}
@Override
public int size() {
return list1.size() + list2.size();
}
@Override
public boolean contains(final Object o) {
return list1.contains(o) || list2.contains(o);
}
@Override
public void clear() {
list1.clear();
list2.clear();
}
/**
* Returns the index within the corresponding list related to the given index.
*
* @param index
* the index in this list
*
* @return the index of the underlying list
*/
private int getListIndex(final int index) {
final int size1 = list1.size();
return index >= size1 ? index - size1 : index;
}
/**
* Returns the list that corresponds to the given index.
*
* @param index
* the index in this list
*
* @return the underlying list that corresponds to that index
*/
private List<E> getList(final int index) {
return index >= list1.size() ? list2 : list1;
}
}
Some might encounter this error either locally or on the server:
syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);
This means that their environment does not support short tags the solution is to use this instead:
<?php echo $jsonTable; ?>
And everything should work fine!
Sure:
try {
throw new Exception('Something bad');
} catch (Exception $e) {
// Do nothing
}
You might want to go have a read of the PHP documentation on Exceptions.
You can try something like:
var str = "a,d,k";
str.replace(/,/g, "");
There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:
with open(filename, 'r') as f:
next(f)
for line in f:
and:
with open(filename,'r') as f:
lines = f.readlines()[1:]
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
on success: function (response) { alert(response.d); }
If you are trying to pull the value from a field, you could use:
select extract(month from [field_name])
from [table_name]
You can also insert day or year for the "month" extraction value above.
I understand the need for packages in certain situations, but the base language is so elegant and so proven (and debugged and optimized).
Why not:
dt <- as.Date("2014-03-16")
dt2 <- as.POSIXlt(dt)
dt2$yday
[1] 74
And then your choice whether the first week of the year is zero (as in indexing in C) or 1 (as in indexing in R).
No packages to learn, update, worry about bugs in.
do you mean like so:
DateTime datetime = new DateTime();
if (datetime == DateTime.MinValue)
{
//unassigned
}
or you could use Nullable
DateTime? datetime = null;
if (!datetime.HasValue)
{
//unassigned
}
I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.
Probably on Opera, IE and Edge as well but I haven't tested it yet.
Just get the notify.js file from here https://github.com/gravmatt/js-notify and put it into your page.
Get it on Bower
$ bower install js-notify
This is how it works:
notify('title', {
body: 'Notification Text',
icon: 'path/to/image.png',
onclick: function(e) {}, // e -> Notification object
onclose: function(e) {},
ondenied: function(e) {}
});
You have to set the title but the json object as the second argument is optional.
Have a look at either Left or Substring if you need to chop it up even more.
Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.
No need to do so much works..
var query = from c in obj.tbCourses
where ...
select c;
Then you can use:
List<course> list_course= query.ToList<course>();
It works fine for me.
Like Obediah Stane said, it's necessary to create your own format
method. But I would change a few things:
Create a subclass directly derived from Formatter
, not from SimpleFormatter
. The SimpleFormatter
has nothing to add anymore.
Be careful with creating a new Date
object! You should make sure to represent the date of the LogRecord
. When creating a new Date
with the default constructor, it will represent the date and time the Formatter
processes the LogRecord
, not the date that the LogRecord
was created.
The following class can be used as formatter in a Handler
, which in turn can be added to the Logger
. Note that it ignores all class and method information available in the LogRecord
.
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public final class LogFormatter extends Formatter {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(new Date(record.getMillis()))
.append(" ")
.append(record.getLevel().getLocalizedName())
.append(": ")
.append(formatMessage(record))
.append(LINE_SEPARATOR);
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) {
// ignore
}
}
return sb.toString();
}
}
I believe you could do it like this :
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Notes:
Setting processData
to false
lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.
Setting the contentType
to false
is imperative, since otherwise jQuery will set it incorrectly.
Actually found this answer on superuser.com, but I had to copy tools.jar from my JDK\lib directory to the JRE\lib directory.
Makes ZERO sense...only thing I can think of is Sun introduced this bug in the latest Java runtime (Java 7 Update 11) or a bug in Ant in how it reads the current JDK location (the JRE is more updated than the JDK obviously which is also stupid of Sun...they should release the JDK each time they update the JRE).
My JAVA_HOME was set correctly. I confirmed by doing "set JAVA_HOME". It pointed to my JDK directory and was spelled correctly. However, Ant was claiming it couldn't find javac, but thought JAVA_HOME was in my JRE directory.
My system worked fine before the latest Sun JRE7 updates (10 and 11). Ant is version 1.8.4
It depends on how you want to use it. Using a Join is one way. Another way of doing it is let the thread notify the caller of the thread by using an event. For instance when you have your graphical user interface (GUI) thread that calls a process which runs for a while and needs to update the GUI when it finishes, you can use the event to do this. This website gives you an idea about how to work with events:
http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx
Remember that it will result in cross-threading operations and in case you want to update the GUI from another thread, you will have to use the Invoke
method of the control which you want to update.
Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds
):
Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.
--depth <depth>::
Create a 'shallow' clone with a history truncated to the specified number of revisions.
That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.
All the details are in "shallow.c
: the 8 steps to select new commits for .git/shallow
".
Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)
Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster
-- in commit 7e3e80a, 20 Jan 2016)
This is "Documentation/user-manual.txt
"
A
<<def_shallow_clone,shallow clone>>
is created by specifying thegit-clone --depth
switch.
The depth can later be changed with thegit-fetch --depth
switch, or full history restored with--unshallow
.Merging inside a
<<def_shallow_clone,shallow clone>>
will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.
Update 2020:
git fetch --shallow-exclude=
to prevent fetching all historygit fetch --shallow-since=
to prevent fetching old commits.For more on the shallow clone update process, see "How to update a git shallow clone?".
As commented by Richard Michael:
to backfill history:
git pull --unshallow
And Olle Härstedt adds in the comments:
To backfill part of the history:
git fetch --depth=100
.
Convert your IList
into List<T>
or some other generic collection and then you can easily query/sort it using System.Linq
namespace (it will supply bunch of extension methods)
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();
If you put an asterisk in for build and revision visual studio uses the number of days since Jan. 1st 2000 as the build number, and the number of seconds since midnight divided by 2 as the revision.
A MUCH better life saver solution is http://autobuildversion.codeplex.com/
It works like a charm and it's VERY flexible.
delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=?
and then telling jQuery that you want to use jsonp_callback
instead.
Using shell_exec:
<?php
$output = shell_exec('ping -c1 google.com');
echo "<pre>$output</pre>";
?>
For increasing execution time and file size, you need to mention below values in your .htaccess file. It will work.
php_value upload_max_filesize 80M
php_value post_max_size 80M
php_value max_input_time 18000
php_value max_execution_time 18000
You can try this line of code:
pdDataFrame = pd.DataFrame([np.nan] * 7)
This will create a pandas dataframe of size 7 with NaN of type float:
if you print pdDataFrame
the output will be:
0
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
Also the output for pdDataFrame.dtypes
is:
0 float64
dtype: object
The problem with your query is that when using a GROUP BY clause (which you essentially do by using distinct) you can only use columns that you group by or aggregate functions. You cannot use the column id because there are potentially different values. In your case there is always only one value because of the HAVING clause, but most RDBMS are not smart enough to recognize that.
This should work however (and doesn't need a join):
UPDATE sales
SET status='ACTIVE'
WHERE id IN (
SELECT MIN(id) FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(id) = 1
)
You could also use MAX or AVG instead of MIN, it is only important to use a function that returns the value of the column if there is only one matching row.
(replicated this answer from my other post in case someone is looking for this solution here)
Using VS2013 just tested this and it appears reliable and consistent. This is similar to some comments above but adds another method that's quicker.
(1st) In Windows File Explorer highlight and copy all 3 Form files (.vb or .cs, .designer, .resx)
(2nd) This can be accomplished 2 ways:
(2a-1) In File Explorer paste the 3 files into the project folder with your other forms
(2a-2) In VS Solution Explorer, turn 'Show All Files' on, Right Click on the pasted form & 'Include in Project'. It should work without other changes.
Or, I think better:
(2b-1) In VS, click into Solution Explorer and paste w/Control-C. (For some reason the right-click context menu in Solution Explorer may not show a paste option, but it works from the keyboard.) This method adds the form to the project directly without having to 'Include in Project' as above. With this method you can add as many forms at a time as you like (all 3 files for each) in a single step.
Just add those as said above:
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit ="marquee_forever"
AND!! you must use TextView.setSelected(true) inside your java code.
The reason for marquee not working with some of the guys in this article , If you have an input form with an EditText ( which is an input), The EditText will be the one with focus and selection by default in the form. Now, if you force it thru TextView.setSelected(true), TextView will eventually do marquee no matter what.
So the whole idea is to make the TextView widget focused and selected to make marquee work.
A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.
<div class="container">
<div class="row">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--×-->
<h4 class="modal-title text-center" id="addContact">Add Contact</h4>
</div>
<div class="modal-body">
<div class="row">
<ul class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
</li>
<li>
<a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
</li>
</ul>
<div class="tab-content">
<div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
<div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-info" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
</div>
</div>
Internally, the rm command must test for file existence anyway,
so why add another test? Just issue
rm filename
and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.
If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.
If you only need to check the first element you can peek on it without iterating the whole collection:
public List<object> Foo(IEnumerable<object> objects)
{
object firstObject;
if (objects == null || !TryPeek(ref objects, out firstObject))
throw new ArgumentException();
var list = DoSomeThing(firstObject);
var secondList = DoSomeThingElse(objects);
list.AddRange(secondList);
return list;
}
public static bool TryPeek<T>(ref IEnumerable<T> source, out T first)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
IEnumerator<T> enumerator = source.GetEnumerator();
if (!enumerator.MoveNext())
{
first = default(T);
source = Enumerable.Empty<T>();
return false;
}
first = enumerator.Current;
T firstElement = first;
source = Iterate();
return true;
IEnumerable<T> Iterate()
{
yield return firstElement;
using (enumerator)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
}
try this
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
Thank you so much for that class, Cristian.
I made a minor tweak to it so that the custom loading view is optional, like so:
@Override
public View getVideoLoadingProgressView() // Video will start loading, only called in the case of VideoView (typically API level 10-)
{
if (loadingView == null)
{
return super.getVideoLoadingProgressView();
}
else
{
loadingView.setVisibility(View.VISIBLE);
return loadingView;
}
}
I also added a new constructor that just takes two parameters. Anyway, just a minor simplification if you don't need the loading view. Thanks again for providing this.
I am going to take a different approach here and suggest that it is just as important for your fellow developers to understand your code as it is for the compiler/database to. Using boolean may do the same thing as using tinyint, however it has the advantage of semantically conveying what your intention is, and that's worth something.
If you use a tinyint, it's not obvious that the only values you should see are 0 and 1. A boolean is ALWAYS true or false.
Here's also nice way to achieve this via UI.
0) Right click on PowerShell icon when on task bar
1) Shift + right click on Windows PowerShell
2) "Run as different user"
cd /var/log/nginx/
cat error.log
import urllib
import json
url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
result = json.load(urllib.urlopen(url))
As the error message says, non-default argument til
should not follow default argument hgt
.
Changing order of parameters (function call also be adjusted accordingly) or making hgt
non-default parameter will solve your problem.
def a(len1, hgt=len1, til, col=0):
->
def a(len1, hgt, til, col=0):
UPDATE
Another issue that is hidden by the SyntaxError.
os.system
accepts only one string parameter.
def a(len1, hgt, til, col=0):
system('mode con cols=%s lines=%s' % (len1, hgt))
system('title %s' % til)
system('color %s' % col)
Add a parameter of type UriComponentsBuilder
to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo
to point at a different controller using the same prefix).
@marcio-junior's answer (https://stackoverflow.com/a/6497462/4038790) works perfectly, but I wanted to explain for those who don't understand why it works:
@a7omiton Along with @psyren89's response to your question
Think of the outer div
as a movie screen and the inner div
as the setting in which the characters move around. If you were viewing the setting in person, that is without a screen around it, you would be able to see all of the characters at once assuming your eyes have a large enough field of vision. That would mean the setting wouldn't have to scroll (move left to right) in order for you to see more of it and so it would stay still.
However, you are not at the setting in person, you are viewing it from your computer screen which has a width of 500px while the setting has a width of 1000px. Thus, you will need to scroll (move left to right) the setting in order to see more of the characters inside of it.
I hope that helps anyone who was lost on the principle.
Issue:
.Net application code aborts before it starts its execution [Console application or Windows application]
Error received: Aborted with Error code "E0434352"
Exception: Unknown exception
Scenario 1:
When an application is already executed, which have used some of the dependent resources and those resources are still in use with the application executed, when another application or the same exe is triggered from some other source then one of the app throws the error
Scenario 2:
When an application is triggered by scheduler or automatic jobs, it may be in execution state at background, meanwhile when you try to trigger the same application again, the error may be triggered.
Solution:
Create an application, when & where the application release all its resources as soon as completed Kill all the background process once the application is closed Check and avoid executing the application from multiple sources like Batch Process, Task Scheduler and external tools at same time. Check for the Application and resource dependencies and clean up the code if needed.
In SQL 2005, this is simple: 1. Open SQL Server management studio and copy the sql statement you need into the TSQL , such as exec sp_whatever 2. Query->Results to Grid 3. Highlight the sql statement and run it 4. Highlight the data results (left-click on upper left area of results grid) 5. Now right-click and select Save Results As 6. Select CSV in the Save as type, enter a file name, select a location and click Save.
Easy!
The best way to get First Date and Last Date of a year Is
SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '01' + '-' + '01' AS DATE) FIRST_DATE
SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '12' + '-' + '31' AS DATE) LAST_DATE
Xamarin.Android
port: (C#
)
public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M
? Looper.MainLooper.IsCurrentThread
: Looper.MyLooper() == Looper.MainLooper;
Usage:
if (IsMainThread) {
// you are on UI/Main thread
}
I open the project,.csproj, using a notepad and delete that missing file reference.
Use @ symbol before starting the string. like
string s = @"this is a really
long string
and this is
the rest of it";
Your first example is perfectly fine. Even the official Python documentation recommends this style known as EAFP.
Personally, I prefer to avoid nesting when it's not necessary:
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
except AttributeError:
pass # Fallback to dict
try:
return self.dict[item]
except KeyError:
raise AttributeError("The object doesn't have such attribute") from None
PS. has_key()
has been deprecated for a long time in Python 2. Use item in self.dict
instead.
You need to set Opacity first for standards-compliant browsers, then the various versions of IE. See Example:
but this opacity code not work in ie8
.slidedownTrigger
{
cursor: pointer;
opacity: .75; /* Standards Compliant Browsers */
filter: alpha(opacity=75); /* IE 7 and Earlier */
/* Next 2 lines IE8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=75);
}
Note that I eliminated -moz as Firefox is a Standards Compliant browser and that line is no longer necessary. Also, -khtml is depreciated, so I eliminated that style as well.
Furthermore, IE's filters will not validate to w3c standards, so if you want your page to validate, separate your standards stylesheet from your IE stylesheet by using an if IE statement like below:
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="http://www.mysite.com/css/ie.css" />
<![endif]-->
If you separate the ie quirks, your site will validate just fine.
You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
from a file deployed at http://run.jsbin.com
due to the same-origin policy.
As the source (aka origin) page and the target URL are at different domains (run.jsbin.com
and www.ecb.europa.eu
), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET
.
In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.
A page at http://www.example.com/myPage.html
can only directly request services that are at http://www.example.com
, like http://www.example.com/api/myService
. If the service is hosted at another domain (say http://www.ok.com/api/myService
), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a (CORS) request* across different domains, your browser:
Origin
header in the original request (with the page's domain as value) and perform it as usual; and thenAccess-Control-Allow-Origin
is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com
it will only make regular calls to www.example.com
! Other URLs, such as api.example.com
or even example.com
or www.example.com:8080
are considered different domains by the browser! Yes, if the port is different, then it is a different domain!
Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin
) to the server's responses. (Each server/language has a way to do that - check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.
I can give you two advices:
I'm using VS2013 for Winforms, the below solution worked for me.
Download : http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=23734
Then Set VS Target Platform to x86.
For example, here's a table that has a primary key but is not AUTO_INCREMENT
:
mysql> CREATE TABLE foo (
id INT NOT NULL,
PRIMARY KEY (id)
);
mysql> INSERT INTO foo VALUES (1), (2), (5);
You can MODIFY
the column to redefine it with the AUTO_INCREMENT
option:
mysql> ALTER TABLE foo MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;
Verify this has taken effect:
mysql> SHOW CREATE TABLE foo;
Outputs:
CREATE TABLE foo (
`id` INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
Note that you have modified the column definition in place, without requiring creating a second column and dropping the original column. The PRIMARY KEY
constraint is unaffected, and you don't need to mention in in the ALTER TABLE
statement.
Next you can test that an insert generates a new value:
mysql> INSERT INTO foo () VALUES (); -- yes this is legal syntax
mysql> SELECT * FROM foo;
Outputs:
+----+
| id |
+----+
| 1 |
| 2 |
| 5 |
| 6 |
+----+
4 rows in set (0.00 sec)
I tested this on MySQL 5.0.51 on Mac OS X.
I also tested with ENGINE=InnoDB
and a dependent table. Modifying the id
column definition does not interrupt referential integrity.
To respond to the error 150 you mentioned in your comment, it's probably a conflict with the foreign key constraints. My apologies, after I tested it I thought it would work. Here are a couple of links that may help to diagnose the problem:
Have you tried this?
<appSettings>
<add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
<appSettings>
You're looking for the wrong selector id:
$("#submitter").text(submitter_name);
should be
$("#submittername").text(submitter_name);
Use a JSON parser, like JSON.NET
string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();
If you need to know if a word exists in a string you can use this. As it is not clear from your question if you just want to know if the variable is a string or not. Where 'word' is the word you are searching in the string.
if (strpos($a,'word') !== false) {
echo 'true';
}
or use the is_string method. Whichs returns true or false on the given variable.
<?php
$a = '';
is_string($a);
?>
I run into same problem.
What I found from documentation, we should use namedspace.
in your case {% url login:login_view %}
This will give you the contents of a file separated, line-by-line in a list:
with open('xyz.txt') as f_obj:
f_obj.readlines()
You can type sudo install (name of script) /usr/local/bin/(what you want to type to execute said script)
ex: sudo install quickcommit.sh /usr/local/bin/quickcommit
enter password
now can run without .sh and in any directory
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
you never set d[a]
to any value.
Because of this, d[a]
evaluates to undefined
, and you can't set properties on undefined
.
If you add d[a] = {}
right after d = {}
things should work as expected.
Alternatively, you could use an object initializer:
d[a] = {
greetings: b,
data: c
};
Or you could set all the properties of d
in an anonymous function instance:
d = new function () {
this[a] = {
greetings: b,
data: c
};
};
If you're in an environment that supports ES2015 features, you can use computed property names:
d = {
[a]: {
greetings: b,
data: c
}
};
In Java you can only import class Names, or static methods/fields.
To import class use
import full.package.name.of.SomeClass;
to import static methods/fields use
import static full.package.name.of.SomeClass.staticMethod;
import static full.package.name.of.SomeClass.staticField;
You can try installing one of the following localhost softwares:
There are many more such softwares but the best among them are the ones mentioned above. they also allow domain names (for example: example.com
)
Example fetch with authorization header:
fetch('URL_GOES_HERE', {
method: 'post',
headers: new Headers({
'Authorization': 'Basic '+btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: 'A=1&B=2'
});
It turns out there's a very important distinction between the two methods: first() will emit an error if the stream completes before a value is emitted. Or, if you've provided a predicate (i.e. first(value => value === 'foo'))
, it will emit an error if the stream completes before a value that passes the predicate is emitted.
take(1), on the other hand, will happily carry on if a value is never emitted from the stream. Here's a simple example:
const subject$ = new Subject();
// logs "no elements in sequence" when the subject completes
subject$.first().subscribe(null, (err) => console.log(err.message));
// never does anything
subject$.take(1).subscribe(console.log);
subject$.complete();
Another example, using a predicate:
const observable$ = of(1, 2, 3);
// logs "no elements in sequence" when the observable completes
observable$
.first((value) => value > 5)
.subscribe(null, (err) => console.log(err.message));
// the above can also be written like this, and will never do
// anything because the filter predicate will never return true
observable$
.filter((value) => value > 5);
.take(1)
.subscribe(console.log);
As a newcomer to RxJS, this behavior was very confusing to me, although it was my own fault because I made some incorrect assumptions. If I had bothered to check the docs, I would have seen that the behavior is clearly documented:
Throws an error if
defaultValue
was not provided and a matching element is not found.
The reason I've run into this so frequently is a fairly common Angular 2 pattern where observables are cleaned up manually during the OnDestroy
lifecycle hook:
class MyComponent implements OnInit, OnDestroy {
private stream$: Subject = someDelayedStream();
private destroy$ = new Subject();
ngOnInit() {
this.stream$
.takeUntil(this.destroy$)
.first()
.subscribe(doSomething);
}
ngOnDestroy() {
this.destroy$.next(true);
}
}
The code looks harmless at first, but problems arise when the component in destroyed before stream$
can emit a value. Because I'm using first()
, an error is thrown when the component is destroyed. I'm usually only subscribing to a stream to get a value that is to be used within the component, so I don't care if the component gets destroyed before the stream emits. Because of this, I've started using take(1)
in almost all places where I would have previously used first()
.
filter(fn).take(1)
is a bit more verbose than first(fn)
, but in most cases I prefer a little more verbosity over handling errors that ultimately have no impact on the application.
Also important to note: The same applies for last()
and takeLast(1)
.
Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile
.
With inconsistent versions, specifically with one being Client Profile
and the other not, then it works at design time but fails at compile time. A real gotcha.
There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile
, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...
Lets say ClassOne
is defined as:
public class ClassOne
{
protected $arg1;
protected $arg2;
//Contructor
public function __construct($arg1, $arg2)
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function echoArgOne
{
echo $this->arg1;
}
}
Using PHP Reflection;
$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);
Create a new Instance:
$instance = $class->newInstanceArgs(["Banana", "Apple")]);
Call a method:
$instance->echoArgOne();
//prints "Banana"
Use a variable as a method:
$method = "echoArgOne";
$instance->$method();
//prints "Banana"
Using Reflection instead of just using the raw string to create an object gives you better control over your object and easier testability (PHPUnit relies heavily on Reflection)
I've been dealing with 01 - which is a numeric.
string(number($v)) != string($v)
makes the segregation
steps 1 in the user variable and system variable
C:\Program Files\nodejs
then check both node -v
and the npm -v
then try to update the the npm i -g npm
One of the difference is that merge
is creating a new index, and join
is keeping the left side index. It can have a big consequence on your later transformations if you wrongly assume that your index isn't changed with merge
.
For example:
import pandas as pd
df1 = pd.DataFrame({'org_index': [101, 102, 103, 104],
'date': [201801, 201801, 201802, 201802],
'val': [1, 2, 3, 4]}, index=[101, 102, 103, 104])
df1
date org_index val
101 201801 101 1
102 201801 102 2
103 201802 103 3
104 201802 104 4
-
df2 = pd.DataFrame({'date': [201801, 201802], 'dateval': ['A', 'B']}).set_index('date')
df2
dateval
date
201801 A
201802 B
-
df1.merge(df2, on='date')
date org_index val dateval
0 201801 101 1 A
1 201801 102 2 A
2 201802 103 3 B
3 201802 104 4 B
-
df1.join(df2, on='date')
date org_index val dateval
101 201801 101 1 A
102 201801 102 2 A
103 201802 103 3 B
104 201802 104 4 B
Use keyup
instead of keypress
. This gets all the key codes when the user presses something
That would be the ALL_DIRECTORIES view:
http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_1075.htm#i1576965
You can use the .charAt(int) function with Strings to retrieve the char value at any index. If you want to convert the String to a char array, try calling .toCharArray() on the String. If the string is 1 character long, just take that character by calling .charAt(0) (or .First() in C#).
There should be a binary called "pip2.7" installed at some location included within your $PATH variable.
You can find that out by typing
which pip2.7
This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
Now, you should be all set, and
which pip2.7
should return the correct output.
When displaying, you can use (for example)
>> '%.2f' % 2.3465
=> "2.35"
If you want to store it rounded, you can use
>> (2.3465*100).round / 100.0
=> 2.35
package main
type Proxy struct {
Address string
Port string
}
type Configuration struct {
Proxy
Val string
}
func main() {
c := &Configuration{
Val: "test",
Proxy: Proxy {
Address: "addr",
Port: "80",
},
}
}
This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one
public boolean isEmpty() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.get(this)!=null) {
return false;
}
} catch (Exception e) {
System.out.println("Exception occured in processing");
}
}
return true;
}
I suggest you check out chunked
and disk.frame
. They both have functions for reading in CSVs chunk-by-chunk.
In particular, disk.frame::csv_to_disk.frame
may be the function you are after?
I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:
$(".bgHeaderH2").text();
Camera camera;
if (Camera.getNumberOfCameras() >= 2) {
//if you want to open front facing camera use this line
camera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
//if you want to use the back facing camera
camera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
}
try {
camera.setPreviewDisplay("your surface holder here");
camera.startPreview();
} catch (Exception e) {
camera.release();
}
/* This is not the proper way, this is a solution for older devices that run Android 4.0 or older. This can be used for testing purposes, but not recommended for main development. This solution can be considered as a temporary solution only. But this solution has helped many so I don't intend to delete this answer*/
Quick and dirty, and store it in a variable:
USER=somebody
USER_HOME="$(echo -n $(bash -c "cd ~${USER} && pwd"))"
This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here
You should convert the stream into byte array and then you can read file content
Please refer following link
http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]
Hope this helps
UPDATE :
The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.
Taken from here
// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
string result = System.Text.Encoding.UTF8.GetString(binData);
You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.
Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };
JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);
This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.
There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.
Use getopt
Why getopt?
To parse elaborated command-line arguments to avoid confusion and clarify the options we are parsing so that reader of the commands can understand what's happening.
What is getopt?
getopt
is used to break up (parse) options in command lines for easy parsing by shell procedures, and to check for legal options. It uses the GNU getopt(3)
routines to do this.
getopt
can have following types of options.
Note: In this document, during explaining syntax:
HOW TO USE getopt
?
Syntax: First Form
getopt optstring parameters
Examples:
# This is correct
getopt "hv:t::" "-v 123 -t123"
getopt "hv:t::" "-v123 -t123" # -v and 123 doesn't have whitespace
# -h takes no value.
getopt "hv:t::" "-h -v123"
# This is wrong. after -t can't have whitespace.
# Only optional params cannot have whitespace between key and value
getopt "hv:t::" "-v 123 -t 123"
# Multiple arguments that takes value.
getopt "h:v:t::g::" "-h abc -v 123 -t21"
# Multiple arguments without value
# All of these are correct
getopt "hvt" "-htv"
getopt "hvt" "-h -t -v"
getopt "hvt" "-tv -h"
Here h,v,t are the options and -h -v -t is how options should be given in command-line.
In optional param, value cannot have whitespace separation with the option. So, in "-t123" example, -t is option 123 is value.
Syntax: Second Form
getopt [getopt_options] [--] [optstring] [parameters]
Here after getopt is split into five parts
Examples
getopt -l "name:,version::,verbose" -- "n:v::V" "--name=Karthik -version=5.2 -verbose"
Syntax: Third Form
getopt [getopt_options] [-o options] [--] [optstring] [parameters]
Here after getopt is split into five parts
Examples
getopt -l "name:,version::,verbose" -a -o "n:v::V" -- "-name=Karthik -version=5.2 -verbose"
GETOPT_OPTIONS
getopt_options changes the way command-line params are parsed.
Below are some of the getopt_options
Option: -l or --longoptions
Means getopt command should allow multi-character options to be recognised. Multiple options are separated by comma.
For example, --name=Karthik
is a long option sent in command line. In getopt, usage of long options are like
getopt "name:,version" "--name=Karthik"
Since name: is specified, the option should contain a value
Option: -a or --alternative
Means getopt command should allow long option to have a single dash '-' rather than double dash '--'.
Example, instead of --name=Karthik
you could use just -name=Karthik
getopt "name:,version" "-name=Karthik"
A complete script example with the code:
#!/bin/bash
# filename: commandLine.sh
# author: @theBuzzyCoder
showHelp() {
# `cat << EOF` This means that cat should stop reading when EOF is detected
cat << EOF
Usage: ./installer -v <espo-version> [-hrV]
Install Pre-requisites for EspoCRM with docker in Development mode
-h, -help, --help Display help
-v, -espo-version, --espo-version Set and Download specific version of EspoCRM
-r, -rebuild, --rebuild Rebuild php vendor directory using composer and compiled css using grunt
-V, -verbose, --verbose Run script in verbose mode. Will print out each step of execution.
EOF
# EOF is found above and hence cat command stops reading. This is equivalent to echo but much neater when printing out.
}
export version=0
export verbose=0
export rebuilt=0
# $@ is all command line parameters passed to the script.
# -o is for short options like -v
# -l is for long options with double dash like --version
# the comma separates different long options
# -a is for long options with single dash like -version
options=$(getopt -l "help,version:,verbose,rebuild,dryrun" -o "hv:Vrd" -a -- "$@")
# set --:
# If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters
# are set to the arguments, even if some of them begin with a ‘-’.
eval set -- "$options"
while true
do
case $1 in
-h|--help)
showHelp
exit 0
;;
-v|--version)
shift
export version=$1
;;
-V|--verbose)
export verbose=1
set -xv # Set xtrace and verbose mode.
;;
-r|--rebuild)
export rebuild=1
;;
--)
shift
break;;
esac
shift
done
Running this script file:
# With short options grouped together and long option
# With double dash '--version'
bash commandLine.sh --version=1.0 -rV
# With short options grouped together and long option
# With single dash '-version'
bash commandLine.sh -version=1.0 -rV
# OR with short option that takes value, value separated by whitespace
# by key
bash commandLine.sh -v 1.0 -rV
# OR with short option that takes value, value without whitespace
# separation from key.
bash commandLine.sh -v1.0 -rV
# OR Separating individual short options
bash commandLine.sh -v1.0 -r -V
You can add an atrribute in linearLayout : android:scrollbars="vertical"
FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:
String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
=> will produce "oau"
That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.
That's JSON, or JavaScript Object Notation. It's a quick way of describing an object, or a hash map. The thing before the colon is the property name, and the thing after the colon is its value. So in this example, there's a property "r", whose value is whatever's in the variable r. Same for t.
You can just check for truthy on this:
if(uemail) {
console.log("I have something");
} else {
console.log("Nothing here...");
}
Go and check out the answer from here: Is there a standard function to check for null, undefined, or blank variables in JavaScript?
Hope this helps!
If you really want to use PHP as your backend for WebSockets, these links can get you on your way:
If you add the extension .SH
to the environment variable PATHEXT
, you will be able to run shell scripts from PowerShell by only using the script name with arguments:
PS> .\script.sh args
If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:
PS> script args
Note: sh.exe or another *nix shell must be associated with the .sh extension.
This happened because by mistake I removed some core file of GIT. Try this its worked for me.
re-initialize git
git init
fetch data from remote
git fetch
Now check all your changes and git status by
git status
The encryption methods described are symmetric key block ciphers.
Data Encryption Standard (DES) is the predecessor, encrypting data in 64-bit blocks using a 56 bit key. Each block is encrypted in isolation, which is a security vulnerability.
Triple DES extends the key length of DES by applying three DES operations on each block: an encryption with key 0, a decryption with key 1 and an encryption with key 2. These keys may be related.
DES and 3DES are usually encountered when interfacing with legacy commercial products and services.
AES is considered the successor and modern standard. http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
I believe the use of Blowfish is discouraged.
It is highly recommended that you do not attempt to implement your own cryptography and instead use a high-level implementation such as GPG for data at rest or SSL/TLS for data in transit. Here is an excellent and sobering video on encryption vulnerabilities http://rdist.root.org/2009/08/06/google-tech-talk-on-common-crypto-flaws/
hostname
and uname
will give you the name of the host. Then use nslookup
to translate that to an IP address.
@ Robert: I have tried to adapt your code with a relative path, and created a batch file to run the VBS.
The VBS starts and closes but doesn't launch the macro... Any idea of where the issue could be?
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFilePath = objFSO.GetAbsolutePathName(".")
Set xlBook = xlApp.Workbooks.Open(strFilePath, "Excels\CLIENTES.xlsb") , 0, True)
xlApp.Run "open_form"
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
I removed the "Application.Quit" because my macro is calling a userform taking care of it.
Cheers
EDIT
I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:
Issues I was facing:
1 - I did not want to use the Workbook_Open Event as the excel is locked in read only. 2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.
I first wrote a macro to launch my userform while hiding the application:
Sub open_form()
Application.Visible = False
frmAddClient.Show vbModeless
End Sub
I then created a vbs to launch this macro (doing it with a relative path has been tricky):
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"
And I finally did a batch file to execute the VBS...
@echo off
pushd %~dp0
cscript Add_Client.vbs
Note that I have also included the "Set back to visible" in my Userform_QueryClose
:
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
ThisWorkbook.Close SaveChanges:=True
Application.Visible = True
Application.Quit
End Sub
Anyway, thanks for your help, and I hope this will help if someone needs it
In Windows, you can do it in this way:
import ctypes
PROCESS_QUERY_INFROMATION = 0x1000
def checkPid(pid):
processHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0,pid)
if processHandle == 0:
return False
else:
ctypes.windll.kernel32.CloseHandle(processHandle)
return True
First of all, in this code you try to get a handle for process with pid given. If the handle is valid, then close the handle for process and return True; otherwise, you return False. Documentation for OpenProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx
With C++11 you can use std::regex
like so:
#include <regex>
...
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");
The double backslash is required for escaping an escape character.