Disclaimer: As of early 2015, there is a great comparison of IoC Container features from Jimmy Bogard, here is a summary:
Compared Containers:
The scenario is this: I have an interface, IMediator, in which I can send a single request/response or a notification to multiple recipients:
public interface IMediator
{
TResponse Send<TResponse>(IRequest<TResponse> request);
Task<TResponse> SendAsync<TResponse>(IAsyncRequest<TResponse> request);
void Publish<TNotification>(TNotification notification)
where TNotification : INotification;
Task PublishAsync<TNotification>(TNotification notification)
where TNotification : IAsyncNotification;
}
I then created a base set of requests/responses/notifications:
public class Ping : IRequest<Pong>
{
public string Message { get; set; }
}
public class Pong
{
public string Message { get; set; }
}
public class PingAsync : IAsyncRequest<Pong>
{
public string Message { get; set; }
}
public class Pinged : INotification { }
public class PingedAsync : IAsyncNotification { }
I was interested in looking at a few things with regards to container support for generics:
Setup for generic variance (registering handlers for base INotification/creating request pipelines) My handlers are pretty straightforward, they just output to console:
public class PingHandler : IRequestHandler<Ping, Pong> { /* Impl */ }
public class PingAsyncHandler : IAsyncRequestHandler<PingAsync, Pong> { /* Impl */ }
public class PingedHandler : INotificationHandler<Pinged> { /* Impl */ }
public class PingedAlsoHandler : INotificationHandler<Pinged> { /* Impl */ }
public class GenericHandler : INotificationHandler<INotification> { /* Impl */ }
public class PingedAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }
public class PingedAlsoAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }
Autofac
var builder = new ContainerBuilder();
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterAssemblyTypes(typeof (IMediator).Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof (Ping).Assembly).AsImplementedInterfaces();
Ninject
var kernel = new StandardKernel();
kernel.Components.Add<IBindingResolver, ContravariantBindingResolver>();
kernel.Bind(scan => scan.FromAssemblyContaining<IMediator>()
.SelectAllClasses()
.BindDefaultInterface());
kernel.Bind(scan => scan.FromAssemblyContaining<Ping>()
.SelectAllClasses()
.BindAllInterfaces());
kernel.Bind<TextWriter>().ToConstant(Console.Out);
Simple Injector
var container = new Container();
var assemblies = GetAssemblies().ToArray();
container.Register<IMediator, Mediator>();
container.Register(typeof(IRequestHandler<,>), assemblies);
container.Register(typeof(IAsyncRequestHandler<,>), assemblies);
container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
StructureMap
var container = new Container(cfg =>
{
cfg.Scan(scanner =>
{
scanner.AssemblyContainingType<Ping>();
scanner.AssemblyContainingType<IMediator>();
scanner.WithDefaultConventions();
scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
scanner.AddAllTypesOf(typeof(IAsyncRequestHandler<,>));
scanner.AddAllTypesOf(typeof(INotificationHandler<>));
scanner.AddAllTypesOf(typeof(IAsyncNotificationHandler<>));
});
});
Unity
container.RegisterTypes(AllClasses.FromAssemblies(typeof(Ping).Assembly),
WithMappings.FromAllInterfaces,
GetName,
GetLifetimeManager);
/* later down */
static bool IsNotificationHandler(Type type)
{
return type.GetInterfaces().Any(x => x.IsGenericType && (x.GetGenericTypeDefinition() == typeof(INotificationHandler<>) || x.GetGenericTypeDefinition() == typeof(IAsyncNotificationHandler<>)));
}
static LifetimeManager GetLifetimeManager(Type type)
{
return IsNotificationHandler(type) ? new ContainerControlledLifetimeManager() : null;
}
static string GetName(Type type)
{
return IsNotificationHandler(type) ? string.Format("HandlerFor" + type.Name) : string.Empty;
}
Windsor
var container = new WindsorContainer();
container.Register(Classes.FromAssemblyContaining<IMediator>().Pick().WithServiceAllInterfaces());
container.Register(Classes.FromAssemblyContaining<Ping>().Pick().WithServiceAllInterfaces());
container.Kernel.AddHandlersFilter(new ContravariantFilter());
I just so happen to be in the process of yanking out home grown DI code and replacing it with an IOC. I have probably removed well over 200 lines of code and replaced it with about 10. Yes, I had to do a little bit of learning on how to use the container (Winsor), but I'm an engineer working on internet technologies in the 21st century so I'm used to that. I probably spent about 20 minutes looking over the how tos. This was well worth my time.
Standard way:
@RestController
public class Main {
UserService userService;
public Main(){
userService = new UserServiceImpl();
}
@GetMapping("/")
public String index(){
return userService.print("Example test");
}
}
User service interface:
public interface UserService {
String print(String text);
}
UserServiceImpl class:
public class UserServiceImpl implements UserService {
@Override
public String print(String text) {
return text + " UserServiceImpl";
}
}
Output: Example test UserServiceImpl
That is a great example of tight coupled classes, bad design example and there will be problem with testing (PowerMockito is also bad).
Now let's take a look at SpringBoot dependency injection, nice example of loose coupling:
Interface remains the same,
Main class:
@RestController
public class Main {
UserService userService;
@Autowired
public Main(UserService userService){
this.userService = userService;
}
@GetMapping("/")
public String index(){
return userService.print("Example test");
}
}
ServiceUserImpl class:
@Component
public class UserServiceImpl implements UserService {
@Override
public String print(String text) {
return text + " UserServiceImpl";
}
}
Output: Example test UserServiceImpl
and now it's easy to write test:
@RunWith(MockitoJUnitRunner.class)
public class MainTest {
@Mock
UserService userService;
@Test
public void indexTest() {
when(userService.print("Example test")).thenReturn("Example test UserServiceImpl");
String result = new Main(userService).index();
assertEquals(result, "Example test UserServiceImpl");
}
}
I showed @Autowired
annotation on constructor but it can also be used on setter or field.
The namespace name http://www.w3.org/1999/xhtml
is intended for use in various specifications such as:
Recommendations:
XHTML™ 1.0: The Extensible HyperText Markup Language
XHTML Modularization
XHTML 1.1
XHTML Basic
XHTML Print
XHTML+RDFa
Check here for more detail
From your service method:
function serviceMethod() {
return $timeout(function() {
return {
property: 'value'
};
}, 1000);
}
And in your controller:
serviceName
.serviceMethod()
.then(function(data){
//handle the success condition here
var x = data.property
});
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:
Mouse.OverrideCursor = Cursors.Wait;
try
{
// do stuff
}
finally
{
Mouse.OverrideCursor = null;
}
This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.
If you want to ensure that your intent is handled only by an email app (and not other text messaging or social apps), then use the ACTION_SENDTO
action and include the "mailto:" data scheme. For example:
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
I found this in https://developer.android.com/guide/components/intents-common.html#Email
$this->config->item('config_var')
did not work for my case.
I could only use the config_item('config_var');
to echo variables in the view
You can use row_number()
to get the row number of the row. It uses the over
command - the partition by
clause specifies when to restart the numbering and the order by
selects what to order the row number on. Even if you added an order by
to the end of your query, it would preserve the ordering in the over
command when numbering.
select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1
string[] array = { "cat", "dot", "perls" };
// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perls");
bool b = Array.Exists(array, element => element == "python");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));
// Display bools.
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
----------------------------output-----------------------------------
1)True 2)False 3)True 4)False
In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.
find /home/baumerf/public_html/ -mmin -60 -not -name error_log
If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:
find /home/baumerf/public_html/ -mmin -60 -not -name \*.log
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
python -m pip install --user opencv-contrib-python
After doing this just Restart your system and then if you are on Opencv >= 4.* use :
recognizer = cv2.face.LBPHFaceRecognizer_create()
This should solve 90% of the problem.
This is a sample implementation that i did for the same requirement and concurrency works well. Might be useful for someone.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author Vivekananthan M
*
* @param <K>
* @param <V>
*/
public class WeakConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {
private static final long serialVersionUID = 1L;
private Map<K, Long> timeMap = new ConcurrentHashMap<K, Long>();
private long expiryInMillis = 1000;
private static final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss:SSS");
public WeakConcurrentHashMap() {
initialize();
}
public WeakConcurrentHashMap(long expiryInMillis) {
this.expiryInMillis = expiryInMillis;
initialize();
}
void initialize() {
new CleanerThread().start();
}
@Override
public V put(K key, V value) {
Date date = new Date();
timeMap.put(key, date.getTime());
System.out.println("Inserting : " + sdf.format(date) + " : " + key + " : " + value);
V returnVal = super.put(key, value);
return returnVal;
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (K key : m.keySet()) {
put(key, m.get(key));
}
}
@Override
public V putIfAbsent(K key, V value) {
if (!containsKey(key))
return put(key, value);
else
return get(key);
}
class CleanerThread extends Thread {
@Override
public void run() {
System.out.println("Initiating Cleaner Thread..");
while (true) {
cleanMap();
try {
Thread.sleep(expiryInMillis / 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void cleanMap() {
long currentTime = new Date().getTime();
for (K key : timeMap.keySet()) {
if (currentTime > (timeMap.get(key) + expiryInMillis)) {
V value = remove(key);
timeMap.remove(key);
System.out.println("Removing : " + sdf.format(new Date()) + " : " + key + " : " + value);
}
}
}
}
}
Git Repo Link (With Listener Implementation)
https://github.com/vivekjustthink/WeakConcurrentHashMap
Cheers!!
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public List<StudentEntity> findAllByOrderByIdAsc();
}
The code above should work. I'm using something similar:
public List<Pilot> findTop10ByOrderByLevelDesc();
It returns 10 rows with the highest level.
IMPORTANT: Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:
findAllByOrderByIdAsc(); // don't miss "by"
^
.bashrc
is not meant to be executed but sourced. Try this instead:
. ~/.bashrc
Cheers!
You can get current Playstore Version using JSoup
with some modification like below:
@Override
protected String doInBackground(Void... voids) {
String newVersion = null;
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=it")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select(".hAyfc .htlgb")
.get(7)
.ownText();
return newVersion;
} catch (Exception e) {
return newVersion;
}
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
Log.d("update", "playstore version " + onlineVersion);
}
answer of @Tarun is not working anymore.
Use a function to get rid off some limitation in the ~z
operator. It is especially useful with a for
loop:
@echo off
set size=0
call :filesize "C:\backup\20120714-0035\error.log"
echo file size is %size%
goto :eof
:: Set filesize of first argument in %size% variable, and return
:filesize
set size=%~z1
exit /b 0
You can search for “bullet” when using e.g. BabelPad (which has a Character Map where you can search by character name), but you will hardly find anything larger than U+2022 BULLET (though the size depends on font). Searching for “circle” finds many characters, too many, as the string appears in so many names. The largest simple circle is probably U+25CF BLACK CIRCLE “?”. If it’s too large U+26AB MEDIUM BLACK CIRCLE “?” might be suitable.
Beware that few fonts contain these characters.
I had same issue after installing mariadb via HomeBrew, brew doctor
suggested to run brew link mariadb
- which fixed the issue.
subprocess.call
and other methods in the subprocess
module have a cwd
parameter.
This parameter determines the working directory where you want to execute your process.
So you can do something like this:
subprocess.call('ls', shell=True, cwd='path/to/wanted/dir/')
Check out docs subprocess.popen-constructor
On Ubuntu 12
you might try to install the vim-gnome
package:
sudo apt-get install vim-gnome
I tried it, because vim --version
told me that it would have the flag xterm_clipboard disabled (indicated by - ), which is needed in order to use the clipboard functionality.
-> installing the vim-gnome package on Ubuntu 12 also installed a console based version of vim, that has this option enabled (indicated by a + before the xterm_clipboard flag)
On Arch Linux
you may install vim-clipboard
for the same reason.
If you run neovim then you should install xclip
(as explained by help clipboard-tool
)
If you don't have this ipython_notebook_config.py file, you can create one by following the readme and typing
ipython profile create
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
@echo off
net use z: /delete
cmdkey /add:servername /user:userserver /pass:userstrongpass
net use z: \\servername\userserver /savecred /persistent:yes
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\userserver_in_server.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "Z:\" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%
cscript /nologo %SCRIPT%
del %SCRIPT%
SELECT id, COUNT(id) FROM table1 GROUP BY id HAVING COUNT(id)>1;
I think this will work properly to search repeated values in a particular column.
Sadly git is so unrelable :( I just lost 2 days of work :(
It's best to manual backup anything before doing commit. I just did "git commit" and git just destroy all my changes without saying anything.
I learned my lesson - next time backup first and only then commit. Never trust git for anything.
You can use the start (^
) and end ($
) of line indicators:
^[0-9]{2}$
Some language also have functions that allows you to match against an entire string, where-as you were using a find
function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^
and $
will be redundant.
You had it nearly right in the last line. You want
str(bytes_string, 'utf-8')
because the type of bytes_string
is bytes
, the same as the type of b'abc'
.
Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array. http://api.jquery.com/map/
The detailed steps are as follow.
Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security
You could use the Export->Java->Runnable Jar to create a jar that includes its dependencies
Alternatively, you could use the fatjar eclipse plugin as well to bundle jars together
Without reading you can't do this. But you can use a work around like below.
You can use mark() and reset() methods to do this.
mark(int readlimit) method marks the current position in this input stream.
reset() method repositions this stream to the position at the time the mark method was last called on this input stream.
Before you can use the mark and reset, you need to test out whether these operations are supported on the inputstream you’re reading off. You can do that with markSupported.
The mark method accepts an limit (integer), which denotes the maximum number of bytes that are to be read ahead. If you read more than this limit, you cannot return to this mark.
To apply this functionalities for this use case, we need to mark the position as 0 and then read the input stream. There after we need to reset the input stream and the input stream will be reverted to the original one.
if (inputStream.markSupported()) {
inputStream.mark(0);
if (inputStream.read() != -1) {
inputStream.reset();
} else {
//Inputstream is empty
}
}
Here if the input stream is empty then read() method will return -1.
If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:
The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.
You can use Date.parse(), but the input formats that it accepts are implementation-dependent. However, if you can convert the date to ISO format (YYYY-MM-DD), most implementations should understand it.
The obj
directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin
directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.
You can change the actual directories used for both purposes within the project settings, if you like.
Try:
output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output
Wrapping your command in $( )
tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)
I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.
Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:
jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD
jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD
It should be pretty obvious from your question that you're actually just asking about the difference between git merge
and git rebase
.
So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:
- o - o - o - H - A - B - C (master)
\
P - Q - R (origin/master)
If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:
- o - o - o - H - A - B - C - X (master)
\ /
P - Q - R --- (origin/master)
If on the other hand you did the appropriate rebase, you'd end up with this:
- o - o - o - H - P - Q - R - A' - B' - C' (master)
|
(origin/master)
The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R
), instead of where you originally committed (H
). You should never use the rebase approach if someone else has already pulled from your master branch.
Finally, note that you can actually set up git pull
for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase
to true. You can also do this for a single pull using git pull --rebase
.
Accidentally i stumbled upon another way to do a force kill on Unix (for those who use Weblogic). This is cheaper and more elegant than running /bin/kill -9 via Runtime.exec().
import weblogic.nodemanager.util.Platform;
import weblogic.nodemanager.util.ProcessControl;
...
ProcessControl pctl = Platform.getProcessControl();
pctl.killProcess(pid);
And if you struggle to get the pid, you can use reflection on java.lang.UNIXProcess, e.g.:
Process proc = Runtime.getRuntime().exec(cmdarray, envp);
if (proc instanceof UNIXProcess) {
Field f = proc.getClass().getDeclaredField("pid");
f.setAccessible(true);
int pid = f.get(proc);
}
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
Below is the fixed code:
#!/bin/ksh
safeRunCommand() {
typeset cmnd="$*"
typeset ret_code
echo cmnd=$cmnd
eval $cmnd
ret_code=$?
if [ $ret_code != 0 ]; then
printf "Error : [%d] when executing command: '$cmnd'" $ret_code
exit $ret_code
fi
}
command="ls -l | grep p"
safeRunCommand "$command"
Now if you look into this code few things that I changed are:
typeset
is not necessary but a good practice. It make cmnd
and ret_code
local to safeRunCommand
ret_code
is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
safeRunCommand "$command"
. If you dont then cmnd
will get only the value ls
and not ls -l
. And it is even more important if your command contains pipes.typeset cmnd="$*"
instead of typeset cmnd="$1"
if you want to keep the spaces. You can try with both depending upon how complex is your command argument.NOTE: Do remember some commands give 1 as return code even though there is no error like grep
. If grep
found something it will return 0 else 1.
I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.
For Android Studio:
Right click on res, new Image Asset
Select the image radio button in 3rd option i.e Asset Type
Select the path of the image and click next and then finish
All the images are added to the respective folder, its very simple
A combination of what NailItDown and Victor said. The preferred/easiest way is to use your Global.Asax to store the error and then redirect to your custom error page.
Global.asax:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception ex = Server.GetLastError();
Application["TheException"] = ex; //store the error for later
Server.ClearError(); //clear the error so we can continue onwards
Response.Redirect("~/myErrorPage.aspx"); //direct user to error page
}
In addition, you need to set up your web.config:
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="~/myErrorPage.aspx">
</customErrors>
</system.web>
And finally, do whatever you need to with the exception you've stored in your error page:
protected void Page_Load(object sender, EventArgs e)
{
// ... do stuff ...
//we caught an exception in our Global.asax, do stuff with it.
Exception caughtException = (Exception)Application["TheException"];
//... do stuff ...
}
If you have main.s file.
you can generate object file by GCC
and also as
# gcc -c main.s
# as main.s -o main.o
check this link, it will help you learn some binutils of GCC http://www.thegeekstuff.com/2017/01/gnu-binutils-commands/
To get the list of fields for which there are multiple records, you can use..
select field1,field2,field3, count(*)
from table_name
group by field1,field2,field3
having count(*) > 1
Check this link for more information on how to delete the rows.
http://support.microsoft.com/kb/139444
There should be a criterion for deciding how you define "first rows" before you use the approach in the link above. Based on that you'll need to use an order by clause and a sub query if needed. If you can post some sample data, it would really help.
In regedit.exe
go to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate
It's given as the number of seconds since January 1, 1970. (Note: for Windows 10, this date will be when the last feature update was installed, not the original install date.)
To convert that number into a readable date/time just paste the decimal value in the field "UNIX TimeStamp:" of this Unix Time Conversion online tool.
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
Or you can try transform
:
newbob <- transform(bob, phenotype = as.character(phenotype))
Just be sure to put every factor you'd like to convert to character.
Or you can do something like this and kill all the pests with one blow:
newbob_char <- as.data.frame(lapply(bob[sapply(bob, is.factor)], as.character), stringsAsFactors = FALSE)
newbob_rest <- bob[!(sapply(bob, is.factor))]
newbob <- cbind(newbob_char, newbob_rest)
It's not good idea to shove the data in code like this, I could do the sapply
part separately (actually, it's much easier to do it like that), but you get the point... I haven't checked the code, 'cause I'm not at home, so I hope it works! =)
This approach, however, has a downside... you must reorganize columns afterwards, while with transform
you can do whatever you like, but at cost of "pedestrian-style-code-writting"...
So there... =)
I would use the get_cmap method. Ex.:
import matplotlib.pyplot as plt
plt.imshow(matrix, cmap=plt.get_cmap('gray'))
I think the best way is to store them in some yml file and then load that file using this command in intializer file
APP_CONFIG = YAML.load_file("#{Rails.root}/config/CONFIG.yml")[Rails.env].to_hash
you can easily access environment related config variables.
Your Yml file key value structure:
development:
app_key: 'abc'
app_secret: 'abc'
production:
app_key: 'xyz'
app_secret: 'ghq'
<?php
echo "<script>window.opener.location.reload();</script>";
echo "<script>window.close();</script>";
?>
Using "groupby" and list comprehension:
Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.
DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]
accessing the separated DF like this:
ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF
accessing the column value of the separated DF like this:
ansI_chr=ans[i].chr
In place of 1.+ use the latest version of crashlytics -
dependencies {
classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
}
you should use this way -
dependencies {
classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:2.6.8'
}
your problem will be resolved for sure. Happy coding !!
Similar to above, using filter
from dplyr
:
filter(df, fct %in% vc)
This code is work for me
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// add your action here that you want
return true;
}
else if (id==R.id.login)
{
// add your action here that you want
}
return super.onOptionsItemSelected(item);
}
If you try to iterate with for ($col = 2; $col <= 'AC'; ++ $col){...}
, or with foreach(range('A','AC') as $col) {...}
it will work for columns from A to Z, but it fails pass the Z (Ex. iterate between 'A' to 'AC').
In order to iterate pass 'Z', you need to convert the column to integer, increment, compare, and get it as string again:
$MAX_COL = $sheet->getHighestDataColumn();
$MAX_COL_INDEX = PHPExcel_Cell::columnIndexFromString($MAX_COL);
for($index=0 ; $index <= $MAX_COL_INDEX ; $index++){
$col = PHPExcel_Cell::stringFromColumnIndex($index);
// do something, like set the column width...
$sheet->getColumnDimension($col)->setAutoSize(TRUE);
}
With this, you easy iterate pass the 'Z' column and set autosize to every column.
Responsive meta tag
To ensure proper rendering and touch zooming for all devices, add the responsive viewport meta tag to your <head>
.
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
ExecuteScalar()
is what you need here
The solutions above are great for interactive use, where you can eyeball the result and weed out false positives that way.
False positives can occur if the executable itself happens to match, or any arguments that are not script names match - the likelihood is greater with scripts that have no filename extensions.
Here's a more robust solution for scripting, using a shell function:
getscript() {
pgrep -lf ".[ /]$1( |\$)"
}
Example use:
# List instance(s) of script "aa.sh" that are running.
getscript "aa.sh" # -> (e.g.): 96112 bash /Users/jdoe/aa.sh
# Use in a test:
if getscript "aa.sh" >/dev/null; then
echo RUNNING
fi
-i
to the pgrep
call to make it case-insensitive; on Linux, that is not an option.)getscript
function also works with full or partial paths that include the filename component; partial paths must not start with /
and each component specified must be complete. The "fuller" the path specified, the lower the risk of false positives. Caveat: path matching will only work if the script was invoked with a path - this is generally true for scripts in the $PATH that are invoked directly.ps
nor pgrep
reflect the original quoting applied to the command line. All the function guarantees is that any match is not the first token (which is the interpreter), and that it occurs as a separate word, optionally preceded by a path.bash
) as well - assuming it is known; e.g.# List instance(s) of a running *bash* script.
getbashscript() {
pgrep -lf "(^|/)bash( | .*/)$1( |\$)"
}
If you're willing to make further assumptions - such as script-interpreter paths never containing embedded spaces - the regexes could be made more restrictive and thus further reduce the risk of false positives.
A little update to Evan Mulawski answer to make it shorter
List<string> allLinesText = File.ReadAllLines(fileName).ToList()
Here are steps:
It should work.
Git keeps all of its files in the .git directory. Just remove that one and init again.
This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu
If it's a server socket, you should call listen()
on your socket, and then getsockname()
to find the port number on which it is listening:
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(sin.sin_port));
As for the IP address, if you use INADDR_ANY
then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname()
on the socket for a specific connection (which you get from accept()
) in order to find out which local IP address is being used on that connection.
Make sure they're really tabs! In bash, you can insert a tab using C-v TAB
$ echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED
You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL
I think my code is perfect ...
/**_x000D_
* @param {string} s_x000D_
* @return {boolean}_x000D_
*/_x000D_
var isNumber = function(s) {_x000D_
return s.trim()!=="" && !isNaN(Number(s));_x000D_
};
_x000D_
Short answer without importing matplotlib as mpl
plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))
Modified from @AlexG's answer
This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.
In the context of a multi-pages template, I modify the content of a <div id="foo">...</div>
in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:
$(document).bind("pagebeforeshow", function(event,pdata) {
var parsedUrl = $.mobile.path.parseUrl( location.href );
switch ( parsedUrl.hash ) {
case "#p_02":
... some modifications of the content of the <div> here ...
$("#foo").trigger("create");
break;
}
});
For new comers please try
display: flex;
align-items: center;
justify-content: center;
Polished version + case ignoring support:
public static int[] AllIndexesOf(string str, string substr, bool ignoreCase = false)
{
if (string.IsNullOrWhiteSpace(str) ||
string.IsNullOrWhiteSpace(substr))
{
throw new ArgumentException("String or substring is not specified.");
}
var indexes = new List<int>();
int index = 0;
while ((index = str.IndexOf(substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) != -1)
{
indexes.Add(index++);
}
return indexes.ToArray();
}
If you always add to the end, then each element will be added to the end and stay that way until you change it.
If you always insert at the start, then each element will appear in the reverse order you added them.
If you insert them in the middle, the order will be something else.
There is no float
type. Looks like you want float64
. You could also use float32
if you only need a single-precision floating point value.
package main
import "fmt"
func main() {
i := 5
f := float64(i)
fmt.Printf("f is %f\n", f)
}
You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...
<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />
The above assumes that you have a folder called CSS
in the root of your website like this:
http://www.website.com/CSS/Style.css
You can't do it client-side. You'll have to do it on the server.
Edit: This answer is outdated!
As the time of this edit, HTML file API is now supported on all major browsers.
I'd provide an update with solution, but @mark.inman.winning already did it.
Keep in mind that even if it's now possible to validate on the client, you should still validate it on the server, though. All client side validations can be bypassed.
This answer relates to the questions asked in the comments of the OP's post:
To force a view to appear in a given oriention put the following in viewWillAppear:
UIApplication* application = [UIApplication sharedApplication];
if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
{
UIViewController *c = [[UIViewController alloc]init];
[self presentModalViewController:c animated:NO];
[self dismissModalViewControllerAnimated:NO];
}
It's a bit of a hack, but this forces the UIViewController
to be presented in portrait even if the previous controller was landscape
UPDATE for iOS7
The methods above are now deprecated, so for iOS 7 use the following:
UIApplication* application = [UIApplication sharedApplication];
if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
{
UIViewController *c = [[UIViewController alloc]init];
[c.view setBackgroundColor:[UIColor redColor]];
[self.navigationController presentViewController:c animated:NO completion:^{
[self.navigationController dismissViewControllerAnimated:YES completion:^{
}];
}];
}
Interestingly, at the time of writing, either the present or dismiss must be animated. If neither are, then you will get a white screen. No idea why this makes it work, but it does! The visual effect is different depending on which is animated.
I would recomment the Fixed-Point ("F") format specifier (as mentioned by Ehsan). See the Standard Numeric Format Strings.
With this option you can even have a configurable number of decimal places:
public string ValueAsString(double value, int decimalPlaces)
{
return value.ToString($"F{decimalPlaces}");
}
This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:
<script>
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>
Don't enter in the python shall, Install in the command directory.
Not inside the python pip cannot be installed inside the python.
Even in the version 3.+ you don't have to write the python 3 instead just python.
which looks like
python -m pip install --upgrade pip
and then install others
python -m pip install jupyter
Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
You can use it to raise errors as part of error-checking:
if (a < b):
raise ValueError()
Or handle some errors, and then pass them on as part of error-handling:
try:
f = open('file.txt', 'r')
except IOError:
# do some processing here
# and then pass the error on
raise
df.ix[10,:]
gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]
. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive
With Hibernate's NativeQuery, you need to return a ResultList instead of a SingleResult, because Hibernate modifies a native query
INSERT INTO bla (a,b) VALUES (2,3) RETURNING id
like
INSERT INTO bla (a,b) VALUES (2,3) RETURNING id LIMIT 1
if you try to get a single result, which causes most databases (at least PostgreSQL) to throw a syntax error. Afterwards, you may fetch the resulting id from the list (which usually contains exactly one item).
Just use this:
var date_str=('0'+date.getDate()).substr(-2,2)+' '+('0'+date.getMonth()).substr(-2,2)+' '+('0'+date.getFullYear()).substr(-2,2);
The correct answer is SYSDATE().
INSERT INTO servers (
server_name, online_status, exchange, disk_space,
network_shares, date_time
)
VALUES (
'm1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE', SYSDATE()
);
We can change this behavior and make NOW()
behave in the same way as SYSDATE()
by setting sysdate_is_now command line argument to True
.
Note that NOW()
(which has CURRENT_TIMESTAMP()
as an alias), differs from SYSDATE()
in a subtle way:
SYSDATE() returns the time at which it executes. This differs from the behavior for NOW(), which returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.)
As indicated by Erandi, it is best to create your table with the DEFAULT
clause so that the column gets populated automatically with the timestamp when you insert a new row:
date_time datetime NOT NULL DEFAULT SYSDATE()
If you want the current date in epoch format, then you can use UNIX_TIMESTAMP(). For example:
select now(3), sysdate(3), unix_timestamp();
would yield
+-------------------------+-------------------------+------------------+
| now(3) | sysdate(3) | unix_timestamp() |
+-------------------------+-------------------------+------------------+
| 2018-11-27 01:40:08.160 | 2018-11-27 01:40:08.160 | 1543282808 |
+-------------------------+-------------------------+------------------+
Related:
In layman's terms, I've always said an API is like a translator between two people who speak different languages. In software, data can be consumed or distributed using an API (or translator) so that two different kinds of software can communicate. Good software has a strong translator (API) that follows rules and protocols for security and data cleanliness.
I"m a Marketer, not a coder. This all might not be quite right, but it's what I"ve tried to express for about 10 years now...
I think you can use JSON.stringify:
// after your each loop
JSON.stringify(values);
If you would like to execute the parent controller's parentmethod function inside a child controller, call it:
$scope.$parent.parentmethod();
You can try it over here
Try
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
It's used for proxying requests to other servers.
An example from http://wiki.nginx.org/LoadBalanceExample is:
http {
upstream myproject {
server 127.0.0.1:8000 weight=3;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
server_name www.domain.com;
location / {
proxy_pass http://myproject;
}
}
}
This means all requests for / go to the any of the servers listed under upstream XXX, with a preference for port 8000.
I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.
So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:
var countdown = 99;
function annoy(){
if(countdown>0){
alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
countdown--;
// Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
setTimeout(function(){
annoy();
}, 1000);
}
}
// Don't alert right away or Chrome will catch you
setTimeout(function(){
annoy();
}, 1000);
Starting
start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)
Stopping
stop-dfs.sh
stop-mapred.sh
If I understand correctly, you want to know how to convert bytes encoded as a hex string to its form as an ASCII text, like "537461636B" would be converted to "Stack", in such case then the following code should solve your problem.
Have not run any benchmarks but I assume it is not the peak of efficiency.
static char ByteToAscii(const char *input) {
char singleChar, out;
memcpy(&singleChar, input, 2);
sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
return out;
}
int HexStringToAscii(const char *input, unsigned int length,
char **output) {
int mIndex, sIndex = 0;
char buffer[length];
for (mIndex = 0; mIndex < length; mIndex++) {
sIndex = mIndex * 2;
char b = ByteToAscii(&input[sIndex]);
memcpy(&buffer[mIndex], &b, 1);
}
*output = strdup(buffer);
return 0;
}
In Ubuntu, you can install libtool
which resolves the libraries automatically.
$ sudo apt-get install libtool
This resolved a problem with ltdl
for me, which had been installed as libltdl.so.7
and wasn't found as simply -lltdl
in the make.
PostgreSQL drivers jars are included in Central Repository of Maven:
For PostgreSQL up to 9.1, use:
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>VERSION</version>
</dependency>
or for 9.2+
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>VERSION</version>
</dependency>
(Thanks to @Caspar for the correction)
I was able to get this working with CSS only.
The trick is to use display: flex;
and flex-direction: column-reverse;
The browser treats the bottom like its the top. Assuming the browsers you're targeting support flex-box
, the only caveat is that the markup has to be in reverse order.
Here is a working example. https://codepen.io/jimbol/pen/YVJzBg
There is no exists
for a SCALAR in Perl, anyway. The Perl way is
defined( $x )
and the equivalent Java is
anInteger != null
Those are the equivalents.
exists $hash{key}
Is like the Java
map.containsKey( "key" )
From your example, I think you're looking for
if ( startIn != null ) { ...
It might be also helpful to consider what they do from a semantic point of view:
will assign the values of the properties of its second parameter and so on,
as properties with the same name of the first parameter. (shallow copy & override)
merge is like assign but does not assign objects but replicates them instead.
(deep copy)
provides default values for missing values.
so will assign only values for keys that do not exist yet in the source.
works like _defaults but like merge will not simply copy objects
and will use recursion instead.
I believe that learning to think of those methods from the semantic point of view would let you better "guess" what would be the behavior for all the different scenarios of existing and non existing values.
I will group the options based on output. Assume the following vector for all the examples.
v <- c('z', 'a','b','a','e')
For checking presence:
%in%
> 'a' %in% v
[1] TRUE
any()
> any('a'==v)
[1] TRUE
is.element()
> is.element('a', v)
[1] TRUE
For finding first occurance:
match()
> match('a', v)
[1] 2
For finding all occurances as vector of indices:
which()
> which('a' == v)
[1] 2 4
For finding all occurances as logical vector:
==
> 'a' == v
[1] FALSE TRUE FALSE TRUE FALSE
Edit: Removing grep() and grepl() from the list for reason mentioned in comments
Since you're comfortable with regular expressions, you probably want to use the REGEXP_REPLACE function. If you want to eliminate anything that matches the [:space:] POSIX class
REGEXP_REPLACE( my_value, '[[:space:]]', '' )
SQL> ed
Wrote file afiedt.buf
1 select '|' ||
2 regexp_replace( 'foo ' || chr(9), '[[:space:]]', '' ) ||
3 '|'
4* from dual
SQL> /
'|'||
-----
|foo|
If you want to leave one space in place for every set of continuous space characters, just add the +
to the regular expression and use a space as the replacement character.
with x as (
select 'abc 123 234 5' str
from dual
)
select regexp_replace( str, '[[:space:]]+', ' ' )
from x
Great Thanks to @Massimo Cafaro and Shaybc I was able achieve below tasks
in iOS 8 :
Record audio & Save
Play Saved Recording
1.Add "AVFoundation.framework" to your project
in .h file
2.Add below import statement 'AVFoundation/AVFoundation.h'.
3.Define "AVAudioRecorderDelegate"
4.Create a layout with Record, Play buttons and their action methids
5.Define Recorder and Player etc.
Here is the complete example code which may help you.
ViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController <AVAudioRecorderDelegate>
@property(nonatomic,strong) AVAudioRecorder *recorder;
@property(nonatomic,strong) NSMutableDictionary *recorderSettings;
@property(nonatomic,strong) NSString *recorderFilePath;
@property(nonatomic,strong) AVAudioPlayer *audioPlayer;
@property(nonatomic,strong) NSString *audioFileName;
- (IBAction)startRecording:(id)sender;
- (IBAction)stopRecording:(id)sender;
- (IBAction)startPlaying:(id)sender;
- (IBAction)stopPlaying:(id)sender;
@end
Then do the job in
ViewController.m
#import "ViewController.h"
#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
@interface ViewController ()
@end
@implementation ViewController
@synthesize recorder,recorderSettings,recorderFilePath;
@synthesize audioPlayer,audioFileName;
#pragma mark - View Controller Life cycle methods
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Audio Recording
- (IBAction)startRecording:(id)sender
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err)
{
NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err)
{
NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
return;
}
recorderSettings = [[NSMutableDictionary alloc] init];
[recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
// Create a new audio file
audioFileName = @"recordingTestFile";
recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName] ;
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&err];
if(!recorder){
NSLog(@"recorder: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning" message: [err localizedDescription] delegate: nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return;
}
//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle: @"Warning"message: @"Audio input hardware not available"
delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[cantRecordAlert show];
return;
}
// start recording
[recorder recordForDuration:(NSTimeInterval) 60];//Maximum recording time : 60 seconds default
NSLog(@"Recroding Started");
}
- (IBAction)stopRecording:(id)sender
{
[recorder stop];
NSLog(@"Recording Stopped");
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{
NSLog (@"audioRecorderDidFinishRecording:successfully:");
}
#pragma mark - Audio Playing
- (IBAction)startPlaying:(id)sender
{
NSLog(@"playRecording");
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
[audioPlayer play];
NSLog(@"playing");
}
- (IBAction)stopPlaying:(id)sender
{
[audioPlayer stop];
NSLog(@"stopped");
}
@end
Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.
For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:
For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.
In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.
Something like this perhaps?
x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)
You should use small caps "or" and "and" instead of OR and AND.
And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).
Here is a code sample with your three keywords working fine:
Here is the file ts.txt
:
*** test cases ***
mytest
${color} = set variable Red
Run Keyword If '${color}' == 'Red' log to console \nexecuted with single condition
Run Keyword If '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink' log to console \nexecuted with multiple or
${color} = set variable Blue
${Size} = set variable Small
${Simple} = set variable Simple
${Design} = set variable Simple
Run Keyword If '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}' log to console \nexecuted with multiple and
${Size} = set variable XL
${Design} = set variable Complicated
Run Keyword Unless '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple' log to console \nexecuted with unless and multiple or
and here is what I get when I execute it:
$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest | PASS |
------------------------------------------------------------------------------
myCars.TakeWhile(car => !myCondition(car)).Count();
It works! Think about it. The index of the first matching item equals the number of (not matching) item before it.
I too dislike the horrible standard solution you already suggested in your question. Like the accepted answer I went for a plain old loop although with a slight modification:
public static int FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate) {
int index = 0;
foreach (var item in items) {
if (predicate(item)) break;
index++;
}
return index;
}
Note that it will return the number of items instead of -1
when there is no match. But let's ignore this minor annoyance for now. In fact the horrible standard solution crashes in that case and I consider returning an index that is out-of-bounds superior.
What happens now is ReSharper telling me Loop can be converted into LINQ-expression. While most of the time the feature worsens readability, this time the result was awe-inspiring. So Kudos to the JetBrains.
new
ing anonymous objectsTherefore I consider it optimal in time and space while remaining readable.
-1
when there is no matchOf course you can always hide it behind an extension method. And what to do best when there is no match heavily depends on the context.
Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol ....link :http://csapp.cs.cmu.edu/public/ch7-preview.pdf
This type of code create problem while porting.
For some reason, setting all the correct permissions did not help in my case. I had a file db.bak
that I was not able to restore due to the 5(Access is denied.)
error. The file was placed in the same folder as several other backup files and all the permissions were identical to other files. I was able to restore all the other files except this db.bak
file. I even tried to change the SQL Server service log on user — still the same result. I've tried copying the file with no effect.
Then I attempted to just create an identical file by executing
type db.bak > db2.bak
instead of copying the file. And voila it worked! db2.bak
restored successfully.
I suspect that some other problems with reading the backup file may be erroniously reported as 5(Access is denied.)
by MS SQL.
based on Mihai's solution, if anyone has the problem of saving images on the server like what happened on my server. change the Bitmap to bytebuffer part to :
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
byte[] pixels = bos.toByteArray();
Or simply use
ng-show="v.hasOwnProperty('secId')"
See updated solution here:
Try this:
To accept theirs changes: git merge --strategy-option theirs
To accept yours: git merge --strategy-option ours
Please, try this code:
import serial
ports = serial.tools.list_ports.comports(include_links=False)
for port in ports :
print(port.device)
first of all, you need to import package for serial port communication, so:
import serial
then you create the list of all the serial ports currently available:
ports = serial.tools.list_ports.comports(include_links=False)
and then, walking along whole list, you can for example print port names:
for port in ports :
print(port.device)
This is just an example how to get the list of ports and print their names, but there some other options you can do with this data. Just try print different variants after
port.
I believe the problem occurs when targeting by ID, because Chosen will copy the ID from the original select
onto it's newly created div
, leaving you with 2 elements of the same (now not-unique) ID on the current page.
When targeting Chosen by ID, use a selector specific to the select
:
$( 'select#yourID' ).on( 'change', function() {
console.log( $( this ).val() );
} );
...instead of...
$( '#yourID' ).on( 'change', function() {
console.log( $( this ).val() );
} );
This works because Chosen mirrors its selected items back to the original (now hidden) select
element, even in multi-mode.
(It also continues to work with or without Chosen, say... if you decide to go a different direction in your application.)
No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity
If your subplots also have titles, you may need to adjust the main title size:
plt.suptitle("Main Title", size=16)
Swift 2.0 Compability
func listWithFilter () {
let fileManager = NSFileManager.defaultManager()
// We need just to get the documents folder url
let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
do {
// if you want to filter the directory contents you can do like this:
if let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants) {
print(directoryUrls)
........
}
}
}
OR
func listFiles() -> [String] {
var theError = NSErrorPointer()
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if dirs != nil {
let dir = dirs![0]
do {
let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir)
return fileList as [String]
}catch {
}
}else{
let fileList = [""]
return fileList
}
let fileList = [""]
return fileList
}
Try this css
.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
content: " ";
display: table-cell;
}
ul.nav {
float: none;
margin-bottom: 0;
margin-left: auto;
margin-right: auto;
margin-top: 0;
width: 240px;
}
I had the same problem as you do and I could solve it by following @CarlosRojas instructions with a little difference. Instead of create a new firewall rule I edited the default-allow-internal
one to accept traffic from anywhere since creating new rules didn't make any difference.
After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:
In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:
http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html
Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.
Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .
Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:
@Resource
private SessionContext sessionContext;
With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation
EJB.
I also looked around for the best way to logout. The best one that I've found is using a Servlet:
@WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
public class LogoutServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
// Destroys the session for this user.
if (session != null)
session.invalidate();
// Redirects back to the initial page.
response.sendRedirect(request.getContextPath());
}
}
Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.
Ciao,
Vítor Souza
CSS :
ul{
list-style-type:none;
}
You can take a look at W3School
.a
files are created with the ar
utility, and they are libraries. To use it with gcc
, collect all .a files
in a lib/
folder and then link with -L lib/
and -l<name of specific library>
.
Collection of all .a files into lib/
is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
You can do that using the descendant selectors:
$("#a #b")
However, id values are supposed to be unique on a page.
You could use sed -n 5p file
.
You can also get a range, e.g., sed -n 5,10p file
.
The @Context
annotation (see answers in this question :What does context annotation do in Spring?) will cause it to be injected for you.
I had to use
@Context
private HttpServletRequest request;
I attended a coursera course, there was lesson in which, we were taught about design recipe.
Below docstring format I found preety useful.
def area(base, height): '''(number, number ) -> number #**TypeContract** Return the area of a tring with dimensions base #**Description** and height >>>area(10,5) #**Example ** 25.0 >>area(2.5,3) 3.75 ''' return (base * height) /2
I think if docstrings are written in this way, it might help a lot to developers.
Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI
rbind.fill
from the package plyr
might be what you are looking for.
An adventage of use ExpectedException Rule (version 4.7) is that you can test exception message and not only the expected exception.
And using Matchers, you can test the part of message you are interested:
exception.expectMessage(containsString("income: -1000.0"));
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently:
$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...
As an alias:
$ alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"
$ serve
Serving HTTP on 0.0.0.0 port 8000 ...
Please note that I control my Python version via conda environments, because of that I can use python
instead of python3
for using Python 3.
On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE
, can be tampered with so always use server side validation.
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
evt.preventDefault();
}
}, false);
</script>
On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize
. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE
has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.
On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES
array to find out the upload size. (Docs on the contents of $_FILES
can be found below the MAX_FILE_SIZE
docs)
upload.php
<?php
if(isset($_FILES['file'])) {
if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
// File too big
} else {
// File within size restrictions
}
}
I was having the same issue with an SVG image included via the IMG tag. It turned out for me that Chrome didn't like there being a blank line directly at the top of the file.
I removed the blank line and my SVG immediately started rendering.
To reduce memory consumption and to speed up the search you may use -ReadCount option of Get-Content cmdlet (https://technet.microsoft.com/ru-ru/library/hh849787.aspx).
This may save hours when you working with large files.
Here is an example:
$n = 60699010
$src = 'hugefile.csv'
$batch = 100
$timer = [Diagnostics.Stopwatch]::StartNew()
$count = 0
Get-Content $src -ReadCount $batch -TotalCount $n | % {
$count += $_.Length
if ($count -ge $n ) {
$_[($n - $count + $_.Length - 1)]
}
}
$timer.Stop()
$timer.Elapsed
This prints $n'th line and elapsed time.
git rebase master
is the proper way to do this. Merging would mean a commit would be created for the merge, while rebasing would not.
There is an important point of arrays that is often not taught or missed in java classes. When arrays are passed to a function, then another pointer is created to the same array ( the same pointer is never passed ). You can manipulate the array using both the pointers, but once you assign the second pointer to a new array in the called method and return back by void to calling function, then the original pointer still remains unchanged.
You can directly run the code here : https://www.compilejava.net/
import java.util.Arrays;
public class HelloWorld
{
public static void main(String[] args)
{
int Main_Array[] = {20,19,18,4,16,15,14,4,12,11,9};
Demo1.Demo1(Main_Array);
// THE POINTER Main_Array IS NOT PASSED TO Demo1
// A DIFFERENT POINTER TO THE SAME LOCATION OF Main_Array IS PASSED TO Demo1
System.out.println("Main_Array = "+Arrays.toString(Main_Array));
// outputs : Main_Array = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
// Since Main_Array points to the original location,
// I cannot access the results of Demo1 , Demo2 when they are void.
// I can use array clone method in Demo1 to get the required result,
// but it would be faster if Demo1 returned the result to main
}
}
public class Demo1
{
public static void Demo1(int A[])
{
int B[] = new int[A.length];
System.out.println("B = "+Arrays.toString(B)); // output : B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Demo2.Demo2(A,B);
System.out.println("B = "+Arrays.toString(B)); // output : B = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
System.out.println("A = "+Arrays.toString(A)); // output : A = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
A = B;
// A was pointing to location of Main_Array, now it points to location of B
// Main_Array pointer still keeps pointing to the original location in void main
System.out.println("A = "+Arrays.toString(A)); // output : A = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// Hence to access this result from main, I have to return it to main
}
}
public class Demo2
{
public static void Demo2(int AAA[],int BBB[])
{
BBB[0] = 9999;
// BBB points to the same location as B in Demo1, so whatever I do
// with BBB, I am manipulating the location. Since B points to the
// same location, I can access the results from B
}
}
Based on Fedor Kazakov and others answers, I created a default config.
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="Widget.Design.TextInputLayout" parent="AppTheme">
<item name="hintTextAppearance">@style/AppTheme.TextFloatLabelAppearance</item>
<item name="errorTextAppearance">@style/AppTheme.TextErrorAppearance</item>
<item name="counterTextAppearance">@style/TextAppearance.Design.Counter</item>
<item name="counterOverflowTextAppearance">@style/TextAppearance.Design.Counter.Overflow</item>
</style>
<style name="AppTheme.TextFloatLabelAppearance" parent="TextAppearance.Design.Hint">
<!-- Floating label appearance here -->
<item name="android:textColor">@color/colorAccent</item>
<item name="android:textSize">20sp</item>
</style>
<style name="AppTheme.TextErrorAppearance" parent="TextAppearance.Design.Error">
<!-- Error message appearance here -->
<item name="android:textColor">#ff0000</item>
<item name="android:textSize">20sp</item>
</style>
</resources>
activity_layout.xml
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text hint here"
android:text="5,2" />
</android.support.design.widget.TextInputLayout>
Focused:
Without focus:
Error message:
I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000; /*Sets the text hover color on navbar*/
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}
.navbar-default {
background-color: #0f006f;
border-color: #030033;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #66CCFF; /*change color of links in drop down here*/
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: silver; /*Change rollover cell color here*/
}
.navbar-default .navbar-nav > li > a {
color: white; /*Change active text color here*/
}
You can use the .Clear method:
Sheets("Zeros").UsedRange.Clear
Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.
const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
It uses the built-in function Date.toISOString()
, chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123'
to '2019/01/05 09:01:07'
.
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
If you want to checkout all the files 'anywhere'
git checkout -- $(git rev-parse --show-toplevel)
virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install --user -r requirements.txt
My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.
Another way is to change properties "AutoSize" (set to True) and "AutosizeMode" (set to GrowAndShrink).
This has the effect of the form autosizing to the elements on it and never allowing the user to change its size.
Do you mean programatically, or just while you're developing and debugging? If the latter, you can see that info from the DDMS perspective in Eclipse. When your emulator (possibly even physical phone that is plugged in) is running, it will list the active processes in a window on the left. You can select it and there's an option to track the heap allocations.
Just use multiline selection in sublime to combine all of the files into a single line and add a space between each file name and then add rm
at the beginning of the list. This is mostly useful when there isn't a pattern in the filenames you want to delete.
[$]> rm abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28 abc.log.2012-03-29 abc.log.2012-03-30 abc.log.2012-04-02 abc.log.2012-04-04 abc.log.2012-04-05 abc.log.2012-04-09 abc.log.2012-04-10
I am not aware of any way you can change the transition animation publicly.
If the "back" button is not necessary you should use modal view controllers to have the "push from bottom" / "flip" / "fade" / (=3.2)"page curl" transitions.
On the private side, the method -pushViewController:animated:
calls the undocumented method -pushViewController:transition:forceImmediate:
, so e.g. if you want a flip-from-left-to-right transition, you can use
[navCtrler pushViewController:ctrler transition:10 forceImmediate:NO];
You can't change the "pop" transition this way, however.
github adds a reference to the commit if it contains #issuenbr (discovered this by chance).
sequenceName
is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize
which needs to be the same value that the DB sequence uses as its "auto increment".
Usage:
@GeneratedValue(generator="my_seq")
@SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1)
If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:
@GeneratedValue(strategy=GenerationType.SEQUENCE)
Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:
@GeneratedValue(strategy=GenerationType.AUTO)
Let me show you a little trick.
As Arkanciscan said, you can use CSS3 transitions. But his solution looks different from the original tag.
What you really need to do is this:
@keyframes blink {_x000D_
50% {_x000D_
opacity: 0.0;_x000D_
}_x000D_
}_x000D_
@-webkit-keyframes blink {_x000D_
50% {_x000D_
opacity: 0.0;_x000D_
}_x000D_
}_x000D_
.blink {_x000D_
animation: blink 1s step-start 0s infinite;_x000D_
-webkit-animation: blink 1s step-start 0s infinite;_x000D_
}
_x000D_
<span class="blink">Blink</span>
_x000D_
All the above answers are fine but a bit to complex to my liking. The simplest way to do it is to put some code in the cellForRowAtIndexPath
. That way you never have to worry about changing the color when the cell is deselected.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
/* this is where the magic happens, create a UIView and set its
backgroundColor to what ever color you like then set the cell's
selectedBackgroundView to your created View */
let backgroundView = UIView()
backgroundView.backgroundColor = YOUR_COLOR_HERE
cell.selectedBackgroundView = backgroundView
return cell
}
For a correct implementation, you need to change a series of things.
Database (immediately after the connection):
mysql_query("SET NAMES utf8");
// Meta tag HTML (probably it's already set):
meta charset="utf-8"
header php (before any output of the HTML):
header('Content-Type: text/html; charset=utf-8')
table-rows-charset (for each row):
utf8_unicode_ci
My issue was Mysql connector net 6.4.4, Nuget, xamarin, VSPackage, EditorPackage and etc.. package did not load correctly.
My solution is below for vs2015
forex. If you have Nuget package did not load correctly error - Remove Nuget folder in Local and Roaming directories.
that's it and it worked for me!...
You might need to register this DLL using the 32 bit version of regsvr32.exe
:
c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll
window.open(skey, "_blank", "toolbar=1, scrollbars=1, resizable=1, width=" + 1015 + ", height=" + 800);
if (itemdescription != null && itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38)));
} else {
pstmt2.setString(3, "_");
}
This occurred when trying to connect to the WCF Service using only host name e.g. https://host/MyService.svc while using a certificate tied to a name e.g. host.mysite.com.
Switching to the https://host.mysite.com/MyService.svc and this resolved it.
To determine if there are any results you can do any of the following:
if ($mentor->first()) { }
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }
Notes / References
->first()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first
isEmpty()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_isEmpty
->count()
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count
count($mentors)
works because the Collection implements Countable and an internal count() method:
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count
isNotEmpty()
https://laravel.com/docs/5.7/collections#method-isnotempty
So what you can do is :
if (!$mentors->intern->employee->isEmpty()) { }
I'm not sure how necessary this is, and it adds a call to getElementById
, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:
<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>
And then in your JavaScript:
var size_of_widget = document.getElementById("metadata-size-of-widget").title;
The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u
means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u
in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.
You can create a Unicode string multiple ways:
>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'
But the real reason is to represent something like this (translation here):
>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????
For the most part, Unicode and non-Unicode strings are interoperable on Python 2.
There are other symbols you will see, such as the "raw" symbol r
for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.
>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'
Unicode and non-Unicode strings can be equal on Python 2:
>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True
but not on Python 3:
>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False
=COUNTIF(C:C, C1) > 1
Explanation: The C1
here doesn't refer to the first row in C. Because this formula is evaluated by a conditional format rule, instead, when the formula is checked to see if it applies, the C1
effectively refers to whichever row is currently being evaluated to see if the highlight should be applied. (So it's more like INDIRECT(C &ROW())
, if that means anything to you!). Essentially, when evaluating a conditional format formula, anything which refers to row 1 is evaluated against the row that the formula is being run against. (And yes, if you use C2 then you asking the rule to check the status of the row immediately below the one currently being evaluated.)
So this says, count up occurences of whatever is in C1
(the current cell being evaluated) that are in the whole of column C
and if there is more than 1 of them (i.e. the value has duplicates) then: apply the highlight (because the formula, overall, evaluates to TRUE
).
=AND(COUNTIF(C:C, C1) > 1, COUNTIF(C$1:C1, C1) = 1)
Explanation: This only highlights if both of the COUNTIF
s are TRUE
(they appear inside an AND()
).
The first term to be evaluated (the COUNTIF(C:C, C1) > 1
) is the exact same as in the first example; it's TRUE
only if whatever is in C1
has a duplicate. (Remember that C1
effectively refers to the current row being checked to see if it should be highlighted).
The second term (COUNTIF(C$1:C1, C1) = 1
) looks similar but it has three crucial differences:
It doesn't search the whole of column C
(like the first one does: C:C
) but instead it starts the search from the first row: C$1
(the $
forces it to look literally at row 1
, not at whichever row is being evaluated).
And then it stops the search at the current row being evaluated C1
.
Finally it says = 1
.
So, it will only be TRUE
if there are no duplicates above the row currently being evaluated (meaning it must be the first of the duplicates).
Combined with that first term (which will only be TRUE
if this row has duplicates) this means only the first occurrence will be highlighted.
=AND(COUNTIF(C:C, C1) > 1, NOT(COUNTIF(C$1:C1, C1) = 1), COUNTIF(C1:C, C1) >= 1)
Explanation: The first expression is the same as always (TRUE
if the currently evaluated row is a duplicate at all).
The second term is exactly the same as the last one except it's negated: It has a NOT()
around it. So it ignores the first occurence.
Finally the third term picks up duplicates 2, 3 etc. COUNTIF(C1:C, C1) >= 1
starts the search range at the currently evaluated row (the C1
in the C1:C
). Then it only evaluates to TRUE
(apply highlight) if there is one or more duplicates below this one (and including this one): >= 1
(it must be >=
not just >
otherwise the last duplicate is ignored).
For OSX, run the following command from the terminal:
open -na Google\ Chrome --args --disable-web-security --user-data-dir=$HOME/profile-folder-name
This will start a new instance of Google Chrome with a warning on top.
this worked for me with minimal code
$(my_list).remove('li');
First of all, you would have to allocate memory:
char * S = new char[R.length() + 1];
then you can use strcpy
with S
and R.c_str()
:
std::strcpy(S,R.c_str());
You can also use R.c_str()
if the string doesn't get changed or the c string is only used once. However, if S
is going to be modified, you should copy the string, as writing to R.c_str()
results in undefined behavior.
Note: Instead of strcpy
you can also use str::copy
.
If you want to bind custom logic to resize event, nowadays you may start using ResizeObserver browser API for the bounding box of an SVGElement.
This will also handle the case when container is resized because of the nearby elements size change.
There is a polyfill for broader browser support.
This is how it may work in UI component:
function redrawGraph(container, { width, height }) {_x000D_
d3_x000D_
.select(container)_x000D_
.select('svg')_x000D_
.attr('height', height)_x000D_
.attr('width', width)_x000D_
.select('rect')_x000D_
.attr('height', height)_x000D_
.attr('width', width);_x000D_
}_x000D_
_x000D_
// Setup observer in constructor_x000D_
const resizeObserver = new ResizeObserver((entries, observer) => {_x000D_
for (const entry of entries) {_x000D_
// on resize logic specific to this component_x000D_
redrawGraph(entry.target, entry.contentRect);_x000D_
}_x000D_
})_x000D_
_x000D_
// Observe the container_x000D_
const container = document.querySelector('.graph-container');_x000D_
resizeObserver.observe(container)
_x000D_
.graph-container {_x000D_
height: 75vh;_x000D_
width: 75vw;_x000D_
}_x000D_
_x000D_
.graph-container svg rect {_x000D_
fill: gold;_x000D_
stroke: steelblue;_x000D_
stroke-width: 3px;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/ResizeObserver.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>_x000D_
_x000D_
<figure class="graph-container">_x000D_
<svg width="100" height="100">_x000D_
<rect x="0" y="0" width="100" height="100" />_x000D_
</svg>_x000D_
</figure>
_x000D_
// unobserve in component destroy method
this.resizeObserver.disconnect()
Couldn't you just add it as an environment variable in Jenkins settings:
Manage Jenkins -> Global properties > Environment variables: And then click "Add" to add a property PATH and its value to what you need.
You can reset settings for eclipse by deleting .metadata folder from your current workspace.
This will however remove all projects from your project explorer NOT workspace. So dont worry your projects have not gone anywhere.
You can import projects from your workspace like this : just make sure that you uncheck "Copy project into workspace".
There's also the Event.eventPhase
property which can tell you if the event is at target or comes from somewhere else, and it is fully supported by browsers.
Expanding on the already great snippet from the accepted answer, this is the output using the eventPhase
property
var logElement = document.getElementById('log');
function log(msg) {
if (logElement.innerHTML == "<p>No logs</p>")
logElement.innerHTML = "";
logElement.innerHTML += ('<p>' + msg + '</p>');
}
function humanizeEvent(eventPhase){
switch(eventPhase){
case 1: //Event.CAPTURING_PHASE
return "Event is being propagated through the target's ancestor objects";
case 2: //Event.AT_TARGET
return "The event has arrived at the event's target";
case 3: //Event.BUBBLING_PHASE
return "The event is propagating back up through the target's ancestors in reverse order";
}
}
function capture(e) {
log('capture: ' + this.firstChild.nodeValue.trim() + "; " +
humanizeEvent(e.eventPhase));
}
function bubble(e) {
log('bubble: ' + this.firstChild.nodeValue.trim() + "; " +
humanizeEvent(e.eventPhase));
}
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', capture, true);
divs[i].addEventListener('click', bubble, false);
}
_x000D_
p {
line-height: 0;
}
div {
display:inline-block;
padding: 5px;
background: #fff;
border: 1px solid #aaa;
cursor: pointer;
}
div:hover {
border: 1px solid #faa;
background: #fdd;
}
_x000D_
<div>1
<div>2
<div>3
<div>4
<div>5</div>
</div>
</div>
</div>
</div>
<button onclick="document.getElementById('log').innerHTML = '<p>No logs</p>';">Clear logs</button>
<section id="log"></section>
_x000D_
There are several ways to do that. But do not just update to the earlier revision as suggested here.
The easiest way to revert the changes from a single revision, or from a range of revisions, is to use the revision log dialog. This is also the method to use of you want to discard recent changes and make an earlier revision the new HEAD.
Show All
or Next 100
to show the revision(s) you are interested in.Context Menu
? Revert
changes from this revision.Context Menu
? Revert to this revision
. This will discard all changes after the selected revision. You have reverted the changes within your working copy. Check the results, then commit the changes.
All solutions are explained in the "How Do I..." part of the TortoiseSVN docs.
Use pd.concat
to merge a list of DataFrame into a single big DataFrame.
appended_data = []
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
# store DataFrame in list
appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet
appended_data.to_excel('appended.xlsx')
Works fine for me in 5.0.27
I just get a warning (not an error) that the table exists;
The following can be used in the eBook space:
application/vnd.ms-opentype
I would imagine that it is the same for the web.
window.location.href
returns the location of the current page.
top.location.href
(which is an alias of window.top.location.href
) returns the location of the topmost window in the window hierarchy. If a window has no parent, top
is a reference to itself (in other words, window
=== window.top
).
top
is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html
with the following script:
var newWin=window.open('about:blank','test','width=100,height=100');
newWin.document.write('<script>alert(top.location.href);</script>');
The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href
would return.
To answer your question about redirecting, go with window.location.assign(url);
I use this:
function fnIsAppleMobile()
{
if (navigator && navigator.userAgent && navigator.userAgent != null)
{
var strUserAgent = navigator.userAgent.toLowerCase();
var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
if (arrMatches != null)
return true;
} // End if (navigator && navigator.userAgent)
return false;
} // End Function fnIsAppleMobile
var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove
You can create a constructor using parameter Context of class A then you can use this context.
Context c;
A(Context context){ this.c=context }
From B activity you create a object of class A using this constructor and passing getApplicationContext().
Well, there are many solutions already given above. If there are none of them works, maybe you should just try to reset your password again to 'root' as described here, and then reopen http://localhost/phpMyAdmin/
in other browser. At least this solution works for me.
Another way to do it that hasn't been mentioned yet is the tolist method:
myseries.tolist().index(7)
should return the correct index, assuming the value exists in the Series.
No that is wrong. Arrays are special objects in Java. So it is like passing other objects where you pass the value of the reference, but not the reference itself. Meaning, changing the reference of an array in the called routine will not be reflected in the calling routine.
You can try to use:
$('*').live('click', function() {
console.log(this.id);
return false;
});
this will work definately !!!
$v = Validator::make($request->all(),[
'name' => ['Required','alpha']
]);
if($v->passes()){
print_r($request->name);
}
else{
//this will return the errors & to check put "dd($errors);" in your blade(view)
return back()->withErrors($v)->withInput();
}
ALTER TABLE `foo` MODIFY COLUMN `bar_id` INT NOT NULL AUTO_INCREMENT;
or
ALTER TABLE `foo` CHANGE `bar_id` `bar_id` INT UNSIGNED NOT NULL AUTO_INCREMENT;
But none of these will work if your bar_id
is a foreign key in another table: you'll be getting
an error 1068: Multiple primary key defined
To solve this, temporary disable foreign key constraint checks by
set foreign_key_checks = 0;
and after running the statements above, enable them back again.
set foreign_key_checks = 1;
At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:
IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END
Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.
If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.
IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE clockDate = '08/10/2012' AND userName = 'test'
END
As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.
I usually do this in my CSV files parsing routines. Assume that 'line' variable is one line within a CSV file and all of the columns' values are enclosed in double quotes. After the below two lines execute, you will get CSV columns in the 'values' collection.
// The below two lines will split the columns as well as trim the DBOULE QUOTES around values but NOT within them
string trimmedLine = line.Trim(new char[] { '\"' });
List<string> values = trimmedLine.Split(new string[] { "\",\"" }, StringSplitOptions.None).ToList();
Python code snippet to download a file from an url and save with its name
import requests
url = 'http://google.com/favicon.ico'
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)
In a LAN (Local Area Network) we have a server computer, here named xhost running Windows 10, IIS is activated as WebServer. We must access this computer via Browser like Google Chrome not only from localhost through https://localhost/ from server itsself, but also from other hosts in the LAN with URL https://xhost/ :
https://localhost/
https://xhost/
https://xhost.local/
...
With this manner of accessing, we have not a fully-qualified domain name, but only local computer name xhost here.
Or from WAN:
https://dev.example.org/
...
You shall replace xhost by your real local computer name.
None of above solutions may satisfy us. After days of try, we have adopted the solution openssl.exe. We use 2 certificates - a CA (self certified Authority certificate) RootCA.crt and xhost.crt certified by the former. We use PowerShell.
cd C:\users\so\crt
openssl req -x509 -nodes -new -sha256 -days 10240 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=ZA/CN=RootCA-CA"
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt
C: Country
ST: State
L: locality (city)
O: Organization Name
Organization Unit
CN: Common Name
openssl req -new -nodes -newkey rsa:2048 -keyout xhost.key -out xhost.csr -subj "/C=ZA/ST=FREE STATE/L=Golden Gate Highlands National Park/O=WWF4ME/OU=xhost.home/CN=xhost.local"
openssl x509 -req -sha256 -days 1024 -in xhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out xhost.crt
with extfile domains.ext file defining many secured ways of accessing the server website:
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = xhost
DNS.3 = xhost.local
DNS.4 = dev.example.org
DNS.5 = 192.168.1.2
combinig both private xhost.key and certificate xhost.crt, permitting to import into iis. This step asks for password, please let it empty by pressing [RETURN] key (without password):
openssl pkcs12 -export -out xhost.pfx -inkey xhost.key -in xhost.crt
installed in xhost computer (here localhost). and Restart IIS service.
IIS10 Gestionnaire des services Internet (IIS) (%windir%\system32\inetsrv\InetMgr.exe)
Restart IIS Service.
via Google Chrome in any computer that will access the website https://xhost/.
\Google Chrome/…/Settings /[Advanced]/Privacy and Security/Security/Manage certificates
Import RootCA.crt
The browser will show this valid certificate tree:
RootCA-CA
|_____ xhost.local
No Certificate Error will appear through LAN, even through WAN by https://dev.example.org.
Here is the whole Powershell Script socrt.ps1 file to generate all required certificate files from the naught:
#
# Generate:
# RootCA.pem, RootCA.key RootCA.crt
#
# xhost.key xhost.csr xhost.crt
# xhost.pfx
#
# created 15-EEC-2020
# modified 15-DEC-2020
#
#
# change to a safe directory:
#
cd C:\users\so\crt
#
# Generate RootCA.pem, RootCA.key & RootCA.crt as Certification Authority:
#
openssl req -x509 -nodes -new -sha256 -days 10240 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=ZA/CN=RootCA-CA"
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt
#
# get RootCA.pfx: permitting to import into iis10: not required.
#
#openssl pkcs12 -export -out RootCA.pfx -inkey RootCA.key -in RootCA.crt
#
# get xhost.key xhost.csr:
# C: Country
# ST: State
# L: locality (city)
# O: Organization Name
# OU: Organization Unit
# CN: Common Name
#
openssl req -new -nodes -newkey rsa:2048 -keyout xhost.key -out xhost.csr -subj "/C=ZA/ST=FREE STATE/L=Golden Gate Highlands National Park/O=WWF4ME/OU=xhost.home/CN=xhost.local"
#
# get xhost.crt certified by RootCA.pem:
# to show content:
# openssl x509 -in xhost.crt -noout -text
#
openssl x509 -req -sha256 -days 1024 -in xhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out xhost.crt
#
# get xhost.pfx, permitting to import into iis:
#
openssl pkcs12 -export -out xhost.pfx -inkey xhost.key -in xhost.crt
#
# import xhost.pfx in iis10 installed in xhost computer (here localhost).
#
To install openSSL for Windows, please visit https://slproweb.com/products/Win32OpenSSL.html
Empty
refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty
then it would return true.
IsEmpty
refers to no value being initialized.
In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty
. If you want to see if something is currently in its default value then use Empty
.
Probably the fastest way is:
myString.All(c => char.IsDigit(c))
Note: it will return True in case your string is empty which is incorrect (if you not considering empty as valid number/digit )
Jul 2015 update - boot2docker now supports direct mounting. You can use -v /var/logs/on/host:/var/logs/in/container
directly from your Mac prompt, without double mounting
To really update just one package install NCU and then run it just for that package. This will bump to the real latest.
npm install -g npm-check-updates
ncu -f your-intended-package-name -u
when you want to use your data existing in your data frame as y value, you must add stat = "identity" in mapping parameter. Function geom_bar have default y value. For example,
ggplot(data_country)+
geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")
If you're talking about an HTTP request, you can find the request host in:
request.headers.host
But that relies on an incoming request.
More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest
If you're looking for machine/native information, try the process object.
Rather Cast It to an Object Array.
Object obj2 = from some source . . ;
Object[] objects=(Object[])obj2;
The problem is how 100% height is being calculated. Two ways to deal with this.
Add 20px to the body padding-bottom
body {
padding-bottom: 20px;
}
or add a transparent border to body
body {
border: 1px solid transparent;
}
Both worked for me in firebug
Below are some comments regarding the correctness of my answer to this question. These kinds of discussions are exactly why stackoverflow is so great. Many different people have different opinions on how best to solve the problem. I've learned some incredible coding style that I would not have thought of myself. And I've been told that readers have learned something from my style from time to time. Social coding has really encouraged me to be a better programmer.
Social coding can, at times, be disturbing. I hate it when I spend 30 minutes flushing out an answer with a jsfiddle and detailed explanation only to submit and find 10 other answers all saying the same thing in less detail. And the author accepts someone else's answer. How frustrating! I think that this has happend to my fellow contributors–in particular thirtydot.
Thirtydot's answer is completely legit. The p
around the script
is the culprit in this problem. Remove it and the space goes away. It also is a good answer to this question.
But why? Shouldn't the p
tag's height, padding and margin be calculated into the height of the body?
And it is! If you remove the padding-bottom style that I've suggested and then set the body's background to black, you will see that the body's height includes this extra p
space accurately (you see the strip at the bottom turn to black). But the gradient fails to include it when finding where to start. This is the real problem.
The two solutions that I've offered are ways to tell the browser to calculate the gradient properly. In fact, the padding-bottom could just be 1px. The value isn't important, but the setting is. It makes the browser take a look at where the body ends. Setting the border will have the same effect.
In my opinion, a padding setting of 20px looks the best for this page and that is why I answered it this way. It is addressing the problem of where the gradient starts.
Now, if I were building this page. I would have avoided wrapping the script in a p tag. But I must assume that author of the page either can't change it or has a good reason for putting it in there. I don't know what that script does. Will it write something that needs a p tag? Again, I would avoid this practice and it is fine to question its presence, but also I accept that there are cases where it must be there.
My hope in writing this "defense" is that the people who marked down this answer might consider that decision. My answer is thought out, purposeful, and relevant. The author thought so. However, in this social environment, I respect that you disagree and have a right to degrade my answer. I just hope that your choice is motivated by disagreement with my answer and not that author chose mine over yours.
Let me introduce you to my friend "dotglob". It turns on and off whether or not "*" includes hidden files.
$ mkdir test
$ cd test
$ touch a b c .hidden .hi .den
$ ls -a
. .. .den .hi .hidden a b c
$ shopt -u dotglob
$ ls *
a b c
$ for i in * ; do echo I found: $i ; done
I found: a
I found: b
I found: c
$ shopt -s dotglob
$ ls *
.den .hi .hidden a b c
$ for i in * ; do echo I found: $i ; done
I found: .den
I found: .hi
I found: .hidden
I found: a
I found: b
I found: c
It defaults to "off".
$ shopt dotglob
dotglob off
It is best to turn it back on when you are done otherwise you will confuse things that assume it will be off.
An old thread, but...Answer of Konerak works, but why would you even set size of a container by default. What I prefer is to use code wherever no matter of hog big page size is. So this my code:
<style>
#container {
position: relative;
height: 100%;
}
#footer {
position: absolute;
bottom: 0;
}
</style>
</HEAD>
<BODY>
<div id="container">
<h1>Some heading</h1>
<p>Some text you have</p>
<br>
<br>
<div id="footer"><p>Rights reserved</p></div>
</div>
</BODY>
</HTML>
The trick is in <br>
where you break new line. So, when page is small you'll see footer at bottom of page, as you want.
BUT, when a page is big SO THAT YOU MUST SCROLL IT DOWN, then your footer is going to be 2 new lines under the whole content above. And If you will then make page bigger, your footer is allways going to go DOWN. I hope somebody will find this useful.
Easily! (because someone else already did the work for us...)
After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:
Install the package, can be done or from the NuGet package manager or from the package manager console like:
Install-Package InputSimulator
Use this 2 lines of code:
inputSimulator = new InputSimulator()
inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)
And that's it!
-------EDIT--------
The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.
In Visual Studio 2019- Tools > Command Line > Developer Command Prompt.enter image description here
For me i wanted to implement a 2-way handshake, meaning:
- the parent window will load faster then the iframe
- the iframe should talk to the parent window as soon as its ready
- the parent is ready to receive the iframe message and replay
this code is used to set white label in the iframe using [CSS custom property]
code:
iframe
$(function() {
window.onload = function() {
// create listener
function receiveMessage(e) {
document.documentElement.style.setProperty('--header_bg', e.data.wl.header_bg);
document.documentElement.style.setProperty('--header_text', e.data.wl.header_text);
document.documentElement.style.setProperty('--button_bg', e.data.wl.button_bg);
//alert(e.data.data.header_bg);
}
window.addEventListener('message', receiveMessage);
// call parent
parent.postMessage("GetWhiteLabel","*");
}
});
parent
$(function() {
// create listener
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
// replay to child (iframe)
document.getElementById('wrapper-iframe').contentWindow.postMessage(
{
event_id: 'white_label_message',
wl: {
header_bg: $('#Header').css('background-color'),
header_text: $('#Header .HoverMenu a').css('color'),
button_bg: $('#Header .HoverMenu a').css('background-color')
}
},
'*'
);
}, false);
});
naturally you can limit the origins and the text, this is easy-to-work-with code
i found this examlpe to be helpful:
[Cross-Domain Messaging With postMessage]
I use buffers like tabs, using the BufExplorer plugin and a few macros:
" CTRL+b opens the buffer list
map <C-b> <esc>:BufExplorer<cr>
" gz in command mode closes the current buffer
map gz :bdelete<cr>
" g[bB] in command mode switch to the next/prev. buffer
map gb :bnext<cr>
map gB :bprev<cr>
With BufExplorer you don't have a tab bar at the top, but on the other hand it saves space on your screen, plus you can have an infinite number of files/buffers open and the buffer list is searchable...
The closest thing I've seen would be to set border-spacing: 0 30px;
to the container div. However, this just leaves me with space on the upper edge of the table, which defeats the purpose, since you wanted margin-bottom.
See this Link
HTML
<div id="products"></div>
JS
var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
};
var name = $("<div/>",{"text":someone.name,"class":"name"
});
var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);
ROWID is a hidden column on Oracle tables, so, for SQL Server, build your own. Add a column called ROWID with a default value of NEWID()
.
How to do that: Add column, with default value, to existing table in SQL Server