I have experienced that it is not safe (VS2010) to delete[] NULL (i.e. array syntax). I'm not sure whether this is according to the C++ standard.
It is safe to delete NULL (scalar syntax).
I have version 2.0.7 installed on Ubuntu and it defaulted to /var/lib/mongodb/
and that is also what was placed into my /etc/mongodb.conf
file.
Suppress Warnings for XML comments
(not my work, but I found it useful so I've included the article & link)
http://bernhardelbl.wordpress.com/2009/02/23/suppress-warnings-for-xml-comments/
Here i will show you, how you can suppress warnings for XML comments after a Visual Studio build.
Background
If you have checked the "XML documentation file" mark in the Visual Studio project settings, a XML file containing all XML comments is created. Additionally you will get a lot of warnings also in designer generated files, because of the missing or wrong XML comments. While sometimes warnings helps us to improve and stabilize our code, getting hundreds of XML comment warnings is just a pain.
Warnings
Missing XML comment for publicly visible type or member …
XML comment on … has a param tag for ‘…’, but there is no parameter by that name Parameter ‘…’ has no matching param tag in the XML comment for ‘…’ (but other parameters do)Solution
You can suppress every warning in Visual Studio.
Right-click the Visual Studio project / Properties / Build Tab
Insert the following warning numbers in the "Suppress warnings": 1591,1572,1571,1573,1587,1570
I use the following:
git grep ^ | wc -l
This searches all files versioned by git for the regex ^
, which represents the beginning of a line, so this command gives the total number of lines!
Problem statement – Getting java.awt.HeadlessException while trying to initialize java.awt.Component from the application as the tomcat environment does not have any head(terminal).
Issue – The linux virtual environment was setup without a virtual display terminal. Tried to install virtual display – Xvfb, but Xvfb has been taken off by the redhat community.
Solution – Installed ‘xorg-x11-drv-vmware.x86_64’ using yum install xorg-x11-drv-vmware.x86_64 and executed startx. Finally set the display to :0.0 using export DISPLAY=:0.0 and then executed xhost +
You can use a structure like the following:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
You could use a map function that allows multiple arguments, as does the fork of multiprocessing
found in pathos
.
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>>
>>> def add_and_subtract(x,y):
... return x+y, x-y
...
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
pathos
enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.
>>> from pathos.multiprocessing import ThreadingPool as TPool
>>>
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
Even more fun, is to build a nested function that we can pass into the Pool.
This is possible because pathos
uses dill
, which can serialize almost anything in python.
>>> def build_fun_things(f, g):
... def do_fun_things(x, y):
... return f(x,y), g(x,y)
... return do_fun_things
...
>>> def add(x,y):
... return x+y
...
>>> def sub(x,y):
... return x-y
...
>>> neato = build_fun_things(add, sub)
>>>
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap
as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)
Get pathos
here: https://github.com/uqfoundation
If you have "something" and need 'something', use replace(col, "\"", "\'")
and viceversa.
I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".
To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P
So maybe:
def super_cool_logic():
# execute common code here
@app.route("/foo")
def do_foo():
# do some logic here
super_cool_logic()
return render_template("foo.html")
@app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
super_cool_logic()
return render_template("foo.html", messages={"main":"Condition failed on page baz"})
I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)
This will help:
from bs4 import BeautifulSoup
data = '''<div class="image">
<a href="http://www.example.com/eg1">Content1<img
src="http://image.example.com/img1.jpg" /></a>
</div>
<div class="image">
<a href="http://www.example.com/eg2">Content2<img
src="http://image.example.com/img2.jpg" /> </a>
</div>'''
soup = BeautifulSoup(data)
for div in soup.findAll('div', attrs={'class':'image'}):
print(div.find('a')['href'])
print(div.find('a').contents[0])
print(div.find('img')['src'])
If you are looking into Amazon products then you should be using the official API. There is at least one Python package that will ease your scraping issues and keep your activity within the terms of use.
Please see what the update-alternatives command does (it has a nice man...).
Shortly - what happens when you have java-sun-1.4 and java-opensouce-1.0 ... which one takes "java"? It debian "/usr/bin/java" is symbolic link and "/usr/bin/java-sun-1.4" is an alternative to "/usr/bin/java"
Edit:
As Richard said, update-alternatives
is not enough. You actually need to use update-java-alternatives
. More info at:
After copying from A to B open file A again to write mode and then write empty string in it
Navigate to /tomcat-root/conf folder. Within you will find the server.xml file.
Open the server.xml in your preferred editor. Search the below similar statement (not exactly same as below will differ)
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Going to give the port number to 9090
<Connector port="9090" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Save the file and restart the server. Now the tomcat will listen at port 9090
Try this code:
@echo off
color 02
set num1=0
set num2=1
set terminator=5
:loop
set /a num1= %num1% + %num2%
if %num1%==%terminator% goto close
goto open
:close
echo %num1%
pause
exit
:open
echo %num1%
goto loop
num1
is the number to be incremented and num2
is the value added to num1
and terminator is the value where the num1
will end. You can indicate different value for terminator in this statement (if %num1%==%terminator% goto close
). This is the boolean expression goto close is the process if the boolean is true and goto open is the process if the boolean is false.
As loganfsmyth already stated in his answer, you need to purge git history because the files continue to exist there even after deleting them from the repo. Official GitHub docs recommend BFG which I find easier to use than filter-branch
:
Download BFG from their website. Make sure you have java installed, then create a mirror clone and purge history. Make sure to replace YOUR_FILE_NAME
with the name of the file you'd like to delete:
git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --delete-files YOUR_FILE_NAME some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push
Same as above but use --delete-folders
java -jar bfg.jar --delete-folders YOUR_FOLDER_NAME some-big-repo.git
BFG also allows for even fancier options (see docs) like these:
Remove all files bigger than 100M from history:
java -jar bfg.jar --strip-blobs-bigger-than 100M some-big-repo.git
When running BFG, be careful that both YOUR_FILE_NAME
and YOUR_FOLDER_NAME
are indeed just file/folder names. They're not paths, so something like foo/bar.jpg
will not work! Instead all files/folders with the specified name will be removed from repo history, no matter which path or branch they existed.
Here is a solution if you need to hook up some methods to @User for use in your views. No solution for any serious membership customization, but if the original question was needed for views alone then this perhaps would be enough. The below was used for checking a variable returned from a authorizefilter, used to verify if some links wehere to be presented or not(not for any kind of authorization logic or access granting).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
namespace SomeSite.Web.Helpers
{
public static class UserHelpers
{
public static bool IsEditor(this IPrincipal user)
{
return null; //Do some stuff
}
}
}
Then just add a reference in the areas web.config, and call it like below in the view.
@User.IsEditor()
I did this in my local environment. Wasn't difficult but obviously it was done in "unsupported" way.
To do the downgrade you need just to download php 5.3 from http://php.net/releases/ (zip archive), than go to xampp folder and copy subfolder "php" to e.g. php5.5 (just for backup). Than remove content of the folder php and unzip content of zip archive downloaded from php.net. The next step is to adjust configuration (php.ini) - you can refer to your backed-up version from php 5.5. After that just run xampp control utility - everything should work (at least worked in my local environment). I didn't found any problem with such installation, although I didn't tested this too intensively.
To elaborate on Sami's answer:
From the docs:
class Payload(object):
def __init__(self, action, method, data):
self.action = action
self.method = method
self.data = data
import json
def as_payload(dct):
return Payload(dct['action'], dct['method'], dct['data'])
payload = json.loads(message, object_hook = as_payload)
My objection to the
.__dict__
solution is that while it does the job and is concise, the Payload class becomes totally generic - it doesn't document its fields.
For example, if the Payload message had an unexpected format, instead of throwing a key not found error when the Payload was created, no error would be generated until the payload was used.
As @Zyzle mentioned, and @Günter mentioned in a comment (https://github.com/angular/angular/issues/7315), this is not supported.
With
<ul *ngIf="show">
<li *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</li>
</ul>
there are no empty <li>
elements when the list is empty. Even the <ul>
element does not exist (as expected).
When the list is populated, there are no redundant container elements.
The github discussion (4792) that @Zyzle mentioned in his comment also presents another solution using <template>
(below I'm using your original markup ‐ using <div>
s):
<template [ngIf]="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</template>
This solution also does not introduce any extra/redundant container elements.
The Light,
You can configure the process acting as the client to use fiddler as a proxy.
Fiddler sets itself up as a proxy conveniently on 127.0.0.1:8888, and by default overrides the system settings under Internet Options in the Control Panel (if you've configured any) such that all traffic from the common protocols (http, https, and ftp) goes to 127.0.0.1:8888 before leaving your machine.
Now these protocols are often from common processes such as browsers, and so are easily picked up by fiddler. However, in your case, the process initiating the requests is probably not a browser, but one for a programming language like php.exe, or java.exe, or whatever language you are using.
If, say, you're using php, you can leverage curl. Ensure that the curl module is enabled, and then right before your code that invokes the request, include:
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
Hope this helps. You can also always lookup stuff like so from the fiddler documentation for a basis for you to build upon e.g. http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigurePHPcURL
The following command worked for me using the command prompt (As an Administrator) in Windows:
mysqlcheck -u root -p -A --auto-repair
Run mysqlcheck with the root user, prompt for a password, check all databases, and auto-repair any corrupted tables.
Something that sometimes crops up you may/maynot be aware of
Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE
As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?
If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?
With ldd
you can get the libraries that tools use. To rank the usage of libraries for a set of tool you can use something like the following command.
ldd /bin/* /usr/bin/* ... | sed -e '/^[^\t]/ d; s/^\t\(.* => \)\?\([^ ]*\) (.*/\2/g' | sort | uniq -c
(Here sed
strips all lines that do not start with a tab and the filters out only the actual libraries. With sort | uniq -c
you get each library with a count indicating the number of times it occurred.)
You might want to add sort -g
at the end to get the libraries in order of usage.
Note that you probably get lines two non-library lines with the above command. One of static executables ("not a dynamic executable") and one without any library. The latter is the result of linux-gate.so.1
which is not a library in your file system but one "supplied" by the kernel.
Please use -t
to see which command is actually being ran
I just tweaked Virender answer to do same:
git ls-files --deleted -z | xargs -t -0 git rm
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
I think you're mixed up between PATH and PYTHONPATH. All you have to do to run a 'script' is have it's parental directory appended to your PATH variable. You can test this by running
which myscript.py
Also, if myscripy.py
depends on custom modules, their parental directories must also be added to the PYTHONPATH variable. Unfortunately, because the designers of python were clearly on drugs, testing your imports in the repl with the following will not guarantee that your PYTHONPATH is set properly for use in a script. This part of python programming is magic and can't be answered appropriately on stackoverflow.
$python
Python 2.7.8 blahblahblah
...
>from mymodule.submodule import ClassName
>test = ClassName()
>^D
$myscript_that_needs_mymodule.submodule.py
Traceback (most recent call last):
File "myscript_that_needs_mymodule.submodule.py", line 5, in <module>
from mymodule.submodule import ClassName
File "/path/to/myscript_that_needs_mymodule.submodule.py", line 5, in <module>
from mymodule.submodule import ClassName
ImportError: No module named submodule
Use button.layer.cornerRadius
, button.layer.borderColor
and button.layer.borderWidth
.
Note that borderColor
requires a CGColor
, so you could say (Swift 3/4):
button.backgroundColor = .clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
Swift 3
This is doable in a safe way by presenting the splash controller for what ever time you specify then remove it and display your normal rootViewController.
In AppDelegate you can create these 2 methods:
private func extendSplashScreenPresentation(){
// Get a refernce to LaunchScreen.storyboard
let launchStoryBoard = UIStoryboard.init(name: "LaunchScreen", bundle: nil)
// Get the splash screen controller
let splashController = launchStoryBoard.instantiateViewController(withIdentifier: "splashController")
// Assign it to rootViewController
self.window?.rootViewController = splashController
self.window?.makeKeyAndVisible()
// Setup a timer to remove it after n seconds
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(dismissSplashController), userInfo: nil, repeats: false)
}
2.
@objc private func dismissSplashController() {
// Get a refernce to Main.storyboard
let mainStoryBoard = UIStoryboard.init(name: "Main", bundle: nil)
// Get initial viewController
let initController = mainStoryBoard.instantiateViewController(withIdentifier: "initController")
// Assign it to rootViewController
self.window?.rootViewController = initController
self.window?.makeKeyAndVisible()
}
Now you call
self.extendSplashScreenPresentation()
in didFinishLaunchingWithOptions.
You are set to go...
Use the quotemeta
function:
$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";
print "wee" if ($text_to_search =~ /$search_string/);
I know I'm late, but I've only ever had this error if my Response.Redirect
is in a Try...Catch
block.
Never put a Response.Redirect into a Try...Catch block. It's bad practice
As an alternative to putting the Response.Redirect into the Try...Catch block, I'd break up the method/function into two steps.
inside the Try...Catch block performs the requested actions and sets a "result" value to indicate success or failure of the actions.
outside of the Try...Catch block does the redirect (or doesn't) depending on what the "result" value is.
This code is far from perfect and probably should not be copied since I haven't tested it.
public void btnLogin_Click(UserLoginViewModel model)
{
bool ValidLogin = false; // this is our "result value"
try
{
using (Context Db = new Context)
{
User User = new User();
if (String.IsNullOrEmpty(model.EmailAddress))
ValidLogin = false; // no email address was entered
else
User = Db.FirstOrDefault(x => x.EmailAddress == model.EmailAddress);
if (User != null && User.PasswordHash == Hashing.CreateHash(model.Password))
ValidLogin = true; // login succeeded
}
}
catch (Exception ex)
{
throw ex; // something went wrong so throw an error
}
if (ValidLogin)
{
GenerateCookie(User);
Response.Redirect("~/Members/Default.aspx");
}
else
{
// do something to indicate that the login failed.
}
}
pwd
can be used to find the current working directory, and dirname
to find the directory of a particular file (command that was run, is $0
, so dirname $0
should give you the directory of the current script).
However, dirname
gives precisely the directory portion of the filename, which more likely than not is going to be relative to the current working directory. If your script needs to change directory for some reason, then the output from dirname
becomes meaningless.
I suggest the following:
#!/bin/bash
reldir=`dirname $0`
cd $reldir
directory=`pwd`
echo "Directory is $directory"
This way, you get an absolute, rather than a relative directory.
Since the script will be run in a separate Bash instance, there isn't any need to restore the working directory afterwards, but if you do want to change back in your script for some reason, you can easily assign the value of pwd
to a variable before you change directory, for future use.
Although just
cd `dirname $0`
solves the specific scenario in the question, I find having the absolute path to more more useful generally.
C#
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
...
[ValidateModel]
public HttpResponseMessage Post([FromBody]AnyModel model)
{
Javascript
$.ajax({
type: "POST",
url: "/api/xxxxx",
async: 'false',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (xhr, status, err) {
if (xhr.status == 400) {
DisplayModelStateErrors(xhr.responseJSON.ModelState);
}
},
....
function DisplayModelStateErrors(modelState) {
var message = "";
var propStrings = Object.keys(modelState);
$.each(propStrings, function (i, propString) {
var propErrors = modelState[propString];
$.each(propErrors, function (j, propError) {
message += propError;
});
message += "\n";
});
alert(message);
};
I researched a bit into SVG webfonts and font creation, in my eyes if you want to "add" fonts to font-awesome already existing font you need to do the following:
go to inkscape and create a glyph, save it as SVG so you could read the code, make sure to assign it a unicode character which is not currently used so it will not conflict with any of the existing glyphs in the font. this could be hard so i think a better simpler approad would be replacing an existing glyph with your own (just choose one you dont use, copy the first part:
Save the svg then convert it to web-font using any online converter so your webfont would work in all browsers.
once this is done, you should have either an SVG with one of the glyphs replaced in which case youre done. if not you need to create the CSS for your new glyph, in this case try and reuse FAs existing CSS, and only add
>##CSS##
>.FA.NEW-GLYPH:after {
>content:'WHATEVER AVAILABLE UNICODE CHARACTER YOU FOUND'
>(other conditions should be copied from other fonts)
>}
Hi I'm late to the party.. just wanted to point out that the instructions from http://davidtsadler.com/archives/2012/06/03/how-to-install-magento-on-ubuntu/ were really useful.
I had Ubuntu server installed with Apache, MySql and Php so I thought I could jump to the heading Creating the directory from which Magento will be served from and I reached the same problem as the OP, i.e. I had 'index.php' needed in all the URLs (or I would get 404 not found). I then went back to Installing and configuring the Apache HTTP server and after restarting apache it works perfectly.
For reference, I was missing:
sudo bash -c "cat >> /etc/apache2/conf.d/servername.conf <<EOF
ServerName localhost
EOF"
... and
sudo a2enmod rewrite
sudo service apache2 restart
Hope this helps
Beside above solutions, there is a more "COMMON" way - directly delete the largest space consumer from Linux machine. You can follow the below steps:
Using ls -lart to list out hidden folder also, normally jenkin installation is placed in .jenkins/ folder
[xxxxx ~]$ ls -lart drwxrwxr-x 12 xxxx 4096 Feb 8 02:08 .jenkins/
Use df -h
to show Disk space in high level
du -sh ./*/
to list out total memory for each subfolder in current path.
du -a /etc/ | sort -n -r | head -n 10
will list top 10 directories eating disk space in /etc/
Normally ./job/ folder or ./workspace/ folder can be the largest folder. Please go inside and delete base on you need (DO NOT delete entire folder).
rm -rf theFolderToDelete
Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.
http://developer.android.com/reference/android/webkit/WebView.html
I think that you can enable javascript if you need it.
1. Create a class
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s[] = {"app","amm","abb","akk","all"};
doForAllTabs(s);
}
public static void doForAllTabs(String[] tablist){
for(int i = 0; i<tablist.length;i++){
System.out.println(tablist[i]);
}
}
}
2. Right click on left side of System.out.println(tablist[i]); in Eclipse --> select Toggle Breakpoint
3. Right click on toggle point --> select Breakpoint properties
4. Check the Conditional Check Box --> write tablist[i].equalsIgnoreCase("amm") in text field --> Click on OK
5. Right click on class --> Debug As --> Java Application
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
Fixed this issue by concatenating my certificates to generate a valid certificate chain (using GoDaddy Standard SSL + Nginx).
http://nginx.org/en/docs/http/configuring_https_servers.html#chains
To generate the chain:
cat 123456789.crt gd_bundle-g2-g1.crt > my.domain.com.chained.crt
Then:
ssl_certificate /etc/nginx/ssl/my.domain.com.chained.crt;
ssl_certificate_key /etc/nginx/ssl/my.domain.com.key;
Hope it helps!
$http
service returns a promise
which has two callback methods as shown below.
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'filename.csv'
})[0].click();
}).
error(function(data, status, headers, config) {
// handle error
});
answer = True
myvar = "the answer is " + str(answer)
or
myvar = "the answer is %s" % answer
Like this:
people = []
begin
info = gets.chomp
people += [Person.new(info)] if not info.empty?
end while not info.empty?
Reference: Ruby's Hidden do {} while () Loop
Have you tried using the layout_weight value? If you set one it to a value greater than 0, it will stretch that view into the remaining space available.
If you had multiple views that needed to be stretched, then the value will become a weight between them.
So if you had two views both set to a layout_weight value of 1, then they would both stretch to fill in the space but they would both stretch to an equal amount of space. If you set one of them to the value of 2, then it would stretch twice as much as the other view.
By default, when a flutter app gets installed, the app name on the launcher is your Flutter project name. To change that to your desired application name on Android or iOS both, you need to change AndroidManifest.xml
and Info.plist
respectively. here is a two way to achieve this
1 By plugin
You can use a flutter rename plugin. It helps you to change your flutter project's AppName and BundleId for different platforms, currently only available for iOS, Android and macOS
You can change the bundleId and appName in the following steps
Default Usage if you dont pass -t or --target parameter it will try to rename all available platform project folders inside flutter project.
Run this command inside your flutter project root.
pub global run rename --bundleId com.onatcipli.networkUpp
pub global run rename --appname "Test App Name"
Custom Usage if you want to run commands directly (without using pub global run) ensure you add system catche bin directory to your path
rename --appname yourappname -t ios
or
pub global run rename --appname yourappname --target macOS
To target a specific platform use the "--target" option. e.g.
pub global run rename --bundleId com.example.android.app --target android
2 By manual
For Android
App Name is reflected under Android>src>main>Androidmanifest.xml The label name in the Android manifest is responsible for giving the App Name for Android Application
Go to AndroidManifest.xml
, find <application> tag
. Change its android:label
property with your desired app name.
Navigate to the : android/app/src/main/AndroidManifest.xml
The Androidmanifest.xml can now be modified. Choose the
<application
android:name="io.flutter.app.FlutterApplication"
android:label="YourAppName"
android:icon="@mipmap/ic_launcher">
For Package Name
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">
This portion represents the actual Android file naming system. Important information like Launcher Icon and App name can be controlled here. Modify the android:label
to change the App Name only.
For iOS
For iOS, open info.plist
. Change CFBundleName (Bundle Name).
Go to the Xcode project folder and open Info.plist
for edit (in Xcode you can choose Open As > Source Code in the file context menu). All we need is to edit the value for key CFBundleName
. It’s a user-visible short name for the bundle.
Navigate to the: project/ios/Runner/Info.plist
Find the CFBundleName <key>
. This denotes the Key that holds the app name. The app name now can be changed by modifying the <String> </String>
below that.
<key>CFBundleName</key>
<string>YouAppName</string>
That’s it. By having these changes, That’s achieved, an updated application name in the launcher when an app gets installed on a device. your new app name will be displayed on your phone now.
If you are not on the same network you could use this third party tool called localtunnel
It basically routes your content through another server and you access that.
IN db2warehouse I found that "owner" doesn't exist, so I describe table syscat.systables and try using CREATOR instead and it works.
db2 "select NAME from sysibm.systables where CREATOR = '[SCHEMANAME]'and type = 'T'"
TLDR: ssh-add ~/.ssh/yourkey
I've just worked through this problem.
And none of the other answers helped.
I did have a ./ssh/config with all the right stuff, also an earlier repository working fine (same bitbucket account, same key). Then I generated a deploy_key, and after that created a new repository.
After that could not clone the new repo.
I wish I knew how/why ssh agent was messing this up, but adding the key solved it. I mean adding the key in my local Ubuntu, not in bitbucket admin. The command is just
~/.ssh$ ssh-add myregualrkey
Hope this helps someone.
You can't access the overflow flag from C/C++.
I don't agree with this. You could write some inline assembly language and use a jo
(jump overflow) instruction assuming you are on x86 to trap the overflow. Of course, your code would no longer be portable to other architectures.
Look at info as
and info gcc
.
You must have an empty line in your file.
You may want to wrap your parseInt calls in a "try" block:
try {
tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
continue;
}
Or simply check for empty strings before parsing:
if (s.length() == 0)
continue;
Note that by initializing your index variable i
inside the loop, it is always 0. You should move the declaration before the while
loop. (Or make it part of a for
loop.)
Just my 2 cents. The following command fails if called from batch file (Windows 7) placed on pendrive:
xcopy /s /e /i %cd%Ala C:\KS\Ala
But this does the job:
xcopy /s /e /i %~dp0Ala C:\KS\Ala
I like to stick to the "overflow: hidden" method and just add padding-right that's equal to the scrollbar width.
Get scrollbar width function, by lostsource.
function getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
When showing the overlay, add "noscroll" class to html and add padding-right to body:
$(html).addClass("noscroll");
$(body).css("paddingRight", getScrollbarWidth() + "px");
When hiding, remove the class and padding:
$(html).removeClass("noscroll");
$(body).css("paddingRight", 0);
The noscroll style is just this:
.noscroll { overflow: hidden; }
Note that if you have any elements with position:fixed you need to add the padding to those elements too.
For CUDA 6.5 (and apparently 7.0 and 7.5), I've created a version of the gcc 4.8.5 RPM package (under Fedora Core 30) that allows that version of gcc to be install alongside your system's current GCC.
You can find all of that information here.
This solution fixed my problem while replacing br tag to '\n' .
alert(content.replace(/<br\/\>/g,'\n'));
If you just want to compare only one row with $lactureName then use following
function checkLectureStatus($lectureName)
{
$con = connectvar();
mysql_select_db("mydatabase", $con);
$result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName'");
if(mysql_num_rows($result) > 0)
{
mysql_close($con);
return "Assigned";
}
else
{
mysql_close($con);
return "Available";
}
}
You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.
Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
My fail was to use
zoomLevel
as an option, rather than the correct option
zoom
This sounds like NTFS permissions. It usually means your SQL Server service account has read only access to the file (note that SQL Server uses the same service account to access database files regardless of how you log in). Are you sure you didn't change the folder permissions in between logging in as yourself and logging in as sa? If you detach and try again, does it still have the same problem?
I've tested this, it all works. So this method processInput will just ask the user to type something in. it will return a string that has no extra spaces internally, nor extra spaces at the begining or the end. Hope this helps. (also put a heap of commenting in to make it simple to understand).
you can see how to implement it in the main() at the bottom
#include <string>
#include <iostream>
string processInput() {
char inputChar[256];
string output = "";
int outputLength = 0;
bool space = false;
// user inputs a string.. well a char array
cin.getline(inputChar,256);
output = inputChar;
string outputToLower = "";
// put characters to lower and reduce spaces
for(int i = 0; i < output.length(); i++){
// if it's caps put it to lowercase
output[i] = tolower(output[i]);
// make sure we do not include tabs or line returns or weird symbol for null entry array thingy
if (output[i] != '\t' && output[i] != '\n' && output[i] != 'Ì') {
if (space) {
// if the previous space was a space but this one is not, then space now is false and add char
if (output[i] != ' ') {
space = false;
// add the char
outputToLower+=output[i];
}
} else {
// if space is false, make it true if the char is a space
if (output[i] == ' ') {
space = true;
}
// add the char
outputToLower+=output[i];
}
}
}
// trim leading and tailing space
string trimmedOutput = "";
for(int i = 0; i < outputToLower.length(); i++){
// if it's the last character and it's not a space, then add it
// if it's the first character and it's not a space, then add it
// if it's not the first or the last then add it
if (i == outputToLower.length() - 1 && outputToLower[i] != ' ' ||
i == 0 && outputToLower[i] != ' ' ||
i > 0 && i < outputToLower.length() - 1) {
trimmedOutput += outputToLower[i];
}
}
// return
output = trimmedOutput;
return output;
}
int main() {
cout << "Username: ";
string userName = processInput();
cout << "\nModified Input = " << userName << endl;
}
I had this same problem, however mine was because I hadn't set the Server authentication to "SQL Server and Windows Authentication mode" (which you had) I just wanted to mention it here in case someone missed it in your question.
You can access this by
Change
$array=array_map('intval', explode(',', $string));
To:
$array= implode(',', array_map('intval', explode(',', $string)));
array_map returns an array, not a string. You need to convert the array to a comma separated string in order to use in the WHERE clause.
Use:
git checkout -b serverfix origin/serverfix
This is a common enough operation that Git provides the --track
shorthand:
git checkout --track origin/serverfix
In fact, this is so common that there’s even a shortcut for that shortcut. If the branch name you’re trying to checkout (a) doesn’t exist and (b) exactly matches a name on only one remote, Git will create a tracking branch for you:
git checkout serverfix
To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:
git checkout -b sf origin/serverfix
Now, your local branch sf
will automatically pull from origin/serverfix
.
Source: Pro Git, 2nd Edition, written by Scott Chacon and Ben Straub (cut for readability)
you need to place the opening brace after main
, not before it
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
The following approach worked well for me. Modified from here.
function callback(theVar) {_x000D_
return function() {_x000D_
theVar();_x000D_
}_x000D_
}_x000D_
_x000D_
function some_other_function() {_x000D_
document.body.innerHTML += "made it.";_x000D_
}_x000D_
_x000D_
var someVar = some_other_function;_x000D_
document.getElementById('button').addEventListener('click', callback(someVar));
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<button type="button" id="button">Click Me!</button>_x000D_
</body>_x000D_
</html>
_x000D_
For all Solution index.php remove form url and woff file allowed. for write below code in .htaccess file and and make this alternation to your application/config/config.php file: $config['index_page'] = '';
For only Linux hosting server. .htaccess file details
AddType font/ttf .ttf
AddType font/eot .eot
AddType font/otf .otf
AddType font/woff .woff
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
If you have a List of type string that you want in a drop down list I do the following:
EDIT: Clarified, making it a fuller example.
public class ShipDirectory
{
public string ShipDirectoryName { get; set; }
public List<string> ShipNames { get; set; }
}
ShipDirectory myShipDirectory = new ShipDirectory()
{
ShipDirectoryName = "Incomming Vessels",
ShipNames = new List<string>(){"A", "A B"},
}
myShipDirectory.ShipNames.Add("Aunt Bessy");
@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })
Which gives a drop down list like so:
<select id="ShipNames" name="ShipNames" style="width:500px">
<option value="">Select a Ship...</option>
<option>A</option>
<option>A B</option>
<option>Aunt Bessy</option>
</select>
To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):
public ActionResult MyActionName(MyViewModel model)
Access the ShipNames value like so: model.ShipNames
If you just want to access the drop down list on post then the signature becomes:
public ActionResult MyActionName(string ShipNames)
EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.
Yep, hitting on the --subdirectory-filter
of filter-branch
was key. The fact that you used it essentially proves there's no easier way - you had no choice but to rewrite history, since you wanted to end up with only a (renamed) subset of the files, and this by definition changes the hashes. Since none of the standard commands (e.g. pull
) rewrite history, there's no way you could use them to accomplish this.
You could refine the details, of course - some of your cloning and branching wasn't strictly necessary - but the overall approach is good! It's a shame it's complicated, but of course, the point of git isn't to make it easy to rewrite history.
If you don't mind logging the message also to syslog, the not_so_ugly way is:
logger -s $msg
The -s option means: "Output the message to standard error as well as to the system log."
Sample code block for strong password:
(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?=\\S+$).{6,18}
A small note on try
/finally
: The finally will always execute unless
System.exit()
is called.try{}
block never ends (e.g. endless loop).>>> import re
>>> string = "Kl13@£$%[};'\""
>>> pattern = re.compile('\W')
>>> string = re.sub(pattern, '', string)
>>> print string
Kl13
If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.
#include <cstring>
#include <iostream>
int main()
{
char array1[] ="The dog jumps ";
char array2[] = "over the log";
char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
std::strcpy(newArray,array1);
std::strcat(newArray,array2);
std::cout << newArray << std::endl;
delete [] newArray;
return 0;
}
This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE
. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.
Edit, a safe version with the "enough buffer space" assumption:
#include <cstring>
#include <iostream>
int main()
{
const unsigned BUFFER_SIZE = 50;
char array1[BUFFER_SIZE];
std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
char array2[] = "over the log";
std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
std::cout << array1 << std::endl;
return 0;
}
Let's say we have a number "a", which is not prime [not prime/composite number means - a number which can be divided evenly by numbers other than 1 or itself. For example, 6 can be divided evenly by 2, or by 3, as well as by 1 or 6].
6 = 1 × 6 or 6 = 2 × 3
So now if "a" is not prime then it can be divided by two other numbers and let's say those numbers are "b" and "c". Which means
a=b*c.
Now if "b" or "c" , any of them is greater than square root of "a "than multiplication of "b" & "c" will be greater than "a".
So, "b" or "c" is always <= square root of "a" to prove the equation "a=b*c".
Because of the above reason, when we test if a number is prime or not, we only check until square root of that number.
I ran into situations where I actually wanted a SortedSet with access via index (I concur with other posters that accessing an unsorted Set with an index makes no sense). An example would be a tree where I wanted the children to be sorted and duplicate children were not allowed.
I needed the access via index to display them and the set attributes came in handy to efficiently eliminate duplicates.
Finding no suitable collection in java.util or google collections, I found it straightforward to implement it myself. The basic idea is to wrap a SortedSet and create a List when access via index is required (and forget the list when the SortedSet is changed). This does of course only work efficiently when changing the wrapped SortedSet and accessing the list is separated in the lifetime of the Collection. Otherwise it behaves like a list which is sorted often, i.e. too slow.
With large numbers of children, this improved performance a lot over a list I kept sorted via Collections.sort.
For tomcat you can increase the permGem space by using
-XX:MaxPermSize=128m
For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it
export JAVA_OPTS="-XX:MaxPermSize=128m"
Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat
No, you can not have a generic "eval" in Java (or any compiled language). Unless you're willing to write a Java compiler AND a JVM to be executed inside of your Java program.
Yes, you can have some library to evaluate numeric algebraic expressions like the one above - see this thread for discussion.
I got the error because of Allow-Control-Allow-Origin: * browser extension.
One way if you already know the package top level path is to use OpenPojo
final List<PojoClass> pojoClasses = PojoClassFactory.getPojoClassesRecursively("my.package.path", null);
Then you can go over the list and perform any functionality you desire.
You can do in this way:
int[] numbers= {1,3,4,9,2};
List<int> lst_numbers = new List<int>(numbers);
int required_number = 4;
int i = 0;
foreach (int number in lst_numbers)
{
if(number == required_number)
{
break;
}
i++;
}
lst_numbers.RemoveAt(i);
numbers = lst_numbers.ToArray();
If you do truly want the IP assigned to your emulator:
adb shell
ifconfig eth0
Which will give you something like:
eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]
Or you can use this javascript
$(function () {
$("#projectKey").change(function () {
alert($('#projectKey option:selected').text());
});
});
Try using the TimeRange object in C# to complete your goal.
TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");
bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);
Go to build.gradle
(project: xyz)
buildscript {
repositories {
jcenter()
google()
}
allprojects {
repositories {
jcenter()
google()
}
// Just place 'google()' to the top of 'jcenter()'
buildscript {
repositories {
google()
jcenter()
}
allprojects {
repositories {
google()
jcenter()
// enter code here
}
}
It works perfectly for me.
All the different answers on this topic are very confusing, so I’m hoping to give a bit more clarity with this overview of the different bindings of libmagic. Previously mammadori gave a short answer listing the available option.
magic
When determining a files mime-type, the tool of choice is simply called file
and its back-end is called libmagic
. (See the Project home page.) The project is developed in a private cvs-repository, but there is a read-only git mirror on github.
Now this tool, which you will need if you want to use any of the libmagic bindings with python, already comes with its own python bindings called file-magic
. There is not much dedicated documentation for them, but you can always have a look at the man page of the c-library: man libmagic
. The basic usage is described in the readme file:
import magic
detected = magic.detect_from_filename('magic.py')
print 'Detected MIME type: {}'.format(detected.mime_type)
print 'Detected encoding: {}'.format(detected.encoding)
print 'Detected file type name: {}'.format(detected.name)
Apart from this, you can also use the library by creating a Magic
object using magic.open(flags)
as shown in the example file.
Both toivotuo and ewr2san use these file-magic
bindings included in the file
tool. They mistakenly assume, they are using the python-magic
package. This seems to indicate, that if both file
and python-magic
are installed, the python module magic
refers to the former one.
magic
This is the library that Simon Zimmermann talks about in his answer and which is also employed by Claude COULOMBE as well as Gringo Suave.
magic
Note: This project was last updated in 2013!
Due to being based on the same c-api, this library has some similarity with file-magic
included in libmagic
. It is only mentioned by mammadori and no other answer employs it.
Personally I don't like to use TempData, but I prefer to pass a strongly typed object as explained in Passing Information Between Controllers in ASP.Net-MVC.
You should always find a way to make it explicit and expected.
from the Chrome Rest client make a GET request or
curl -XGET 'http://localhost:9200'
in console
rest client: http://localhost:9200
{
"name": "node",
"cluster_name": "elasticsearch-cluster",
"version": {
"number": "2.3.4",
"build_hash": "dcxbgvzdfbbhfxbhx",
"build_timestamp": "2016-06-30T11:24:31Z",
"build_snapshot": false,
"lucene_version": "5.5.0"
},
"tagline": "You Know, for Search"
}
where number field denotes the elasticsearch
version. Here elasticsearch
version is 2.3.4
It's a nightmare since each browser/device handles it differently.
Favicon generator helps me a lot for those applications where we need to cover the most possible scenarios.
https://realfavicongenerator.net/
You just need a png image 260px x 260px (at least) and from there the generator will create all references you need within your web page.
You just need to add this references and images to your application.
You need to write a native query, refer this.
@Query(value =
"SELECT * FROM user_metric UM WHERE UM.user_id = :userId AND UM.metric_id = :metricId LIMIT :limit", nativeQuery = true)
List<UserMetricValue> findTopNByUserIdAndMetricId(
@Param("userId") String userId, @Param("metricId") Long metricId,
@Param("limit") int limit);
In Kotlin language you can do it in this way:
val values = arrayOf(
"cat",
"dog",
"chicken"
)
ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
values
).also {
it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = it
}
If you do not need a particular order of concatenated values, and the separator can be a comma, you can do:
select col1, stragg(distinct col2)
from table
group by col1
We overflowed an integer primary key once (which is ~2.4 billion rows) on a table. If there's a row limit, you're not likely to ever hit it at a mere 36 million rows per year.
The closest I have come is by trying to create it, and seeing if it succeeds.
I had this issue occurring with mailto:
and tel:
links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.
Adding target="_blank"
, as suggested by this discussion of the issue fixed the problem for me.
For some reason, the accepted answer worked for me only if being used once on the page, but in my case I was trying to save data on many elements on the page and the data was somehow lost on all except the first element.
As an alternative, I ended up writing the data out to the dom and parsing it back in when needed. Perhaps it's less efficient, but worked well for my purpose because I'm really prototyping data and not writing this for production.
To save the data I used:
$('#myElement').attr('data-key', JSON.stringify(jsonObject));
To then read the data back is the same as the accepted answer, namely:
var getBackMyJSON = $('#myElement').data('key');
Doing it this way also made the data appear in the dom if I were to inspect the element with Chrome's debugger.
If it's working from Postman, try new Spring version, becouse the 'org.springframework.boot' 2.2.2.RELEASE version can throw "Required request body content is missing" exception.
Try 2.2.6.RELEASE version.
I got the same issue. My solution was a foreach of radio buttons, with the image at the right of it. Since you can only choose a single option at radio, it works (like) a select.
Worket well for me. Hope it can help someone else.
It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):
public enum Language {
ENGLISH("eng", "en", "en_GB", "en_US"),
GERMAN("de", "ge"),
CROATIAN("hr", "cro"),
RUSSIAN("ru"),
BELGIAN("be",";-)");
static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>();
static {
for (Language l:Language.values()) {
// ignoring the case by normalizing to uppercase
ALIAS_MAP.put(l.name().toUpperCase(),l);
for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l);
}
}
static public boolean has(String value) {
// ignoring the case by normalizing to uppercase
return ALIAS_MAP.containsKey(value.toUpper());
}
static public Language fromString(String value) {
if (value == null) throw new NullPointerException("alias null");
Language l = ALIAS_MAP.get(value);
if (l == null) throw new IllegalArgumentException("Not an alias: "+value);
return l;
}
private List<String> aliases;
private Language(String... aliases) {
this.aliases = Arrays.asList(aliases);
}
}
Here the initializer is used to maintain an index (ALIAS_MAP
), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum
itself.
As you can see, the static initializer accesses even the private
field aliases
. It is important to understand that the static
block already has access to the Enum
value instances (e.g. ENGLISH
). This is because the order of initialization and execution in the case of Enum
types, just as if the static private
fields have been initialized with instances before the static
blocks have been called:
Enum
constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.static
block and initialization of static fields in the order of occurrence.This out-of-order initialization (constructor before static
block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):
public class Foo {
static { System.out.println("Static Block 1"); }
public static final Foo FOO = new Foo();
static { System.out.println("Static Block 2"); }
public Foo() { System.out.println("Constructor"); }
static public void main(String p[]) {
System.out.println("In Main");
new Foo();
}
}
What we see is the following output:
Static Block 1
Constructor
Static Block 2
In Main
Constructor
Clear is that the static initialization actually can happen before the constructor, and even after:
Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.
For more info on this see the book "Effective Java".
Since Oracle inserted some md5hash in their download links, one cannot automatically assemble a download link for command line.
So I tinkered some nasty bash command line to get the latest jdk download link, download it and directly install via rpm. For all who are interested:
wget -q http://www.oracle.com/technetwork/java/javase/downloads/index.html -O ./index.html && grep -Eoi ']+>' index.html | grep -Eoi '/technetwork/java/javase/downloads/jdk8-downloads-[0-9]+.html' | (head -n 1) | awk '{print "http://www.oracle.com"$1}' | xargs wget --no-cookies --header "Cookie: gpw_e24=xxx; oraclelicense=accept-securebackup-cookie;" -O index.html -q && grep -Eoi '"filepath":"[^"]+jdk-8u[0-9]+-linux-x64.rpm"' index.html | grep -Eoi 'http:[^"]+' | xargs wget --no-cookies --header "Cookie: gpw_e24=xxx; oraclelicense=accept-securebackup-cookie;" -q -O ./jdk8.rpm && sudo rpm -i ./jdk8.rpm
The bold part should be replaced by the package of your liking.
One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?
Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...
<div id="checkboxes">
<input type="checkbox" /> Some label<br />
<input type="checkbox" /> Some other label<br />
</div>
<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>
Based on this markup your jquery could bind to the click
event of the button and manipulate the DOM.
$('#addCheckbox').click(function() {
var text = $('#newCheckText').val();
$('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});
You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:
var config=document.getElementsByName('configselect').value;
because you have declared only the name
attribute in your <select>
tag. So you should get this element by name.
After correcting this, it will run without any JavaScript error
You say you don't want to use the system("pause")
hack. Why not?
If it's because you don't want the program to prompt when it's not being debugged, there's a way around that. This works for me:
void pause () {
system ("pause");
}
int main (int argc, char ** argv) {
// If "launched", then don't let the console close at the end until
// the user has seen the report.
// (See the MSDN ConGUI sample code)
//
do {
HANDLE hConsoleOutput = ::GetStdHandle (STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE == hConsoleOutput)
break;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (0 == ::GetConsoleScreenBufferInfo (hConsoleOutput, &csbi))
break;
if (0 != csbi.dwCursorPosition.X)
break;
if (0 != csbi.dwCursorPosition.Y)
break;
if (csbi.dwSize.X <= 0)
break;
if (csbi.dwSize.Y <= 0)
break;
atexit (pause);
} while (0);
I just paste this code into each new console application I'm writing. If the program is being run from a command window, the cursor position won't be <0,0>, and it won't call atexit()
. If it has been launched from you debugger (any debugger) the console cursor position will be <0,0> and the atexit()
call will be executed.
I got the idea from a sample program that used to be in the MSDN library, but I think it's been deleted.
NOTE: The Microsoft Visual Studio implementation of the system() routine requires the COMSPEC environment variable to identify the command line interpreter. If this environment variable gets messed up -- for example, if you've got a problem in the Visual Studio project's debugging properties so that the environment variables aren't properly passed down when the program is launched -- then it will just fail silently.
I think you have to write some extra code. For example:
if 'MICHAEL89' in map(lambda name: name.upper(), USERNAMES):
...
In this case we are forming a new list with all entries in USERNAMES
converted to upper case and then comparing against this new list.
Update
As @viraptor says, it is even better to use a generator instead of map
. See @Nathon's answer.
I had to make a jar file from my test classes and add it to my class path. Previously I added my test class file to class path and then I got above error. So I created a jar and added to classpath.
e.g
java -cp "my_jars/*" org.testng.TestNG testing.xml
What about this solution? Modules and Controllers in Files (at the end of the page) It works with multiple controllers, directives and so on:
app.js
var app = angular.module("myApp", ['deps']);
myCtrl.js
app.controller("myCtrl", function($scope) { ..});
html
<script src="app.js"></script>
<script src="myCtrl.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Google has also a Best Practice Recommendations for Angular App Structure I really like to group by context. Not all the html in one folder, but for example all files for login (html, css, app.js,controller.js and so on). So if I work on a module, all the directives are easier to find.
you can also use this format and use comparison operators like '==' '<='
if (( $total == 0 )); then
echo "No results for ${1}"
return
fi
All the languages you've mentioned are Turing Complete, so in theory there is nothing one can do and another can't. In practice of course, there are differences, especially in productivity and efficiency. Compared to C, C++ and Java, which are static typed, Python is a dynamic language and can help you write the same code in significantly fewer lines. Python has a moto "batteries included", which means that the standard library offers all the things needed to build a complex application. Other languages would need external libraries for this. On top of this, since Python is an old and mature language (older than Java), many external libraries (for game development and scientific calculations just to mention a few) have been evolved. So Python can be used to program desktop applications and in fact in some cases more efficiently than other traditional languages.
Python is also a scripting language. This means that you can easily and quickly write scripts and simple tests with it.
More recently python is also used for web frameworks. Since there is a big code base and many python programmers, this was a logical thing to do. These web frameworks follow the practice mainly introduced by Ruby on Rails.
Rather than rolling your own, the most reliable way to tell if an in-built type is numeric is probably to reference Microsoft.VisualBasic
and call Information.IsNumeric(object value)
. The implementation handles a number of subtle cases such as char[]
and HEX and OCT strings.
The reason why Neil's suggestion results in a fullscreen DatePicker
is the choice of parent theme:
<!-- Theme.AppCompat.Light is not a dialog theme -->
<style name="DialogTheme" parent="**Theme.AppCompat.Light**">
<item name="colorAccent">@color/blue_500</item>
</style>
Moreover, if you go this route, you have to specify the theme while creating the DatePickerDialog
:
// R.style.DialogTheme
new DatePickerDialog(MainActivity.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//DO SOMETHING
}
}, 2015, 02, 26).show();
This, in my opinion, is not good. One should try to keep the styling out of java and inside styles.xml/themes.xml.
I do agree that Neil's suggestion, with a bit of change (changing the parent theme to say, Theme.Material.Light.Dialog
) will get you the desired result. But, here's the other way:
On first inspection, we come across datePickerStyle
which defines things such as: headerBackground
(what you are trying to change), dayOfWeekBackground
, and a few other text-colors and text-styles.
Overriding this attribute in your app's theme will not work. DatePickerDialog
uses a separate theme assignable by the attribute datePickerDialogTheme
. So, for our changes to take affect, we must override datePickerStyle
inside an overriden datePickerDialogTheme
.
Here we go:
Override datePickerDialogTheme
inside your app's base theme:
<style name="AppBaseTheme" parent="android:Theme.Material.Light">
....
<item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>
Define MyDatePickerDialogTheme
. The choice of parent theme will depend on what your app's base theme is: it could be either Theme.Material.Dialog
or Theme.Material.Light.Dialog
:
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>
We have overridden datePickerStyle
with the style MyDatePickerStyle
. The choice of parent will once again depend on what your app's base theme is: either Widget.Material.DatePicker
or Widget.Material.Light.DatePicker
. Define it as per your requirements:
<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">@color/chosen_header_bg_color</item>
</style>
Currently, we are only overriding headerBackground
which by default is set to ?attr/colorAccent
(this is also why Neil suggestion works in changing the background). But there's quite a lot of customization possible:
dayOfWeekBackground
dayOfWeekTextAppearance
headerMonthTextAppearance
headerDayOfMonthTextAppearance
headerYearTextAppearance
headerSelectedTextColor
yearListItemTextAppearance
yearListSelectorColor
calendarTextColor
calendarSelectedTextColor
If you don't want this much control (customization), you don't need to override datePickerStyle
. colorAccent
controls most of the DatePicker's
colors. So, overriding just colorAccent
inside MyDatePickerDialogTheme
should work:
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:colorAccent">@color/date_picker_accent</item>
<!-- No need to override 'datePickerStyle' -->
<!-- <item name="android:datePickerStyle">@style/MyDatePickerStyle</item> -->
</style>
Overriding colorAccent
gives you the added benefit of changing OK
& CANCEL
text colors as well. Not bad.
This way you don't have to provide any styling information to DatePickerDialog's
constructor. Everything has been wired properly:
DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
}, 2015, 5, 22);
dpd.show();
The PHP function array_key_exists()
determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset()
can tell you that (and that the value is not null
). array_key_exists()
cannot return information about the value of a key/index.
You could inspect the available apache2 modules:
$ ls /usr/lib/apache2/modules/
Or try to enable the php module, if you have the appropriate access:
$ a2enmod
Which module would you like to enable?
Your choices are: actions alias asis ...
... php5 proxy_ajp proxy_balancer proxy_connect ..
By their mathematical definition, OR and AND are binary operators; they verify the LHS and RHS conditions regardless, similarly to | and &.
|| and && alter the properties of the OR and AND operators by stopping them when the LHS condition isn't fulfilled.
Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.
For example, you can validate the content negotiation like this.
This Accept
header prefers plain text so returns in that format:-
$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain
Whereas this one prefers JSON and so returns in that format:-
$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
"Accept": "application/json,text/*;q=0.99"
}
Short answer:
$ git remote show -n origin
or, an alternative for pure quick scripts:
$ git config --get remote.origin.url
Some info:
$ git remote -v
will print all remotes (not what you want). You want origin right?$ git remote show origin
much better, shows only origin
but takes too long (tested on git version 1.8.1.msysgit.1).I ended up with: $ git remote show -n origin
, which seems to be fastest. With -n
it will not fetch remote heads (AKA branches). You don't need that type of info, right?
http://www.kernel.org/pub//software/scm/git/docs/git-remote.html
You can apply | grep -i fetch
to all three versions to show only the fetch URL.
If you require pure speed, then use:
$ git config --get remote.origin.url
Thanks to @Jefromi for pointing that out.
What’s New In Python 3.4
...
pip should always be available
...
By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.
https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453
so if you have python 3.4 installed, you can just: sudo pip3 install xxx
Use the options
command, e.g. options(max.print=1000000)
.
See ?options
:
‘max.print’: integer, defaulting to ‘99999’. ‘print’ or ‘show’
methods can make use of this option, to limit the amount of
information that is printed, to something in the order of
(and typically slightly less than) ‘max.print’ _entries_.
Repository.addorupdate(entity, entity.id);
Repository.savechanges();
Var id = entity.id;
This will work.
HigLabo.Mail is easy to use. Here is a sample usage:
using (Pop3Client cl = new Pop3Client())
{
cl.UserName = "MyUserName";
cl.Password = "MyPassword";
cl.ServerName = "MyServer";
cl.AuthenticateMode = Pop3AuthenticateMode.Pop;
cl.Ssl = false;
cl.Authenticate();
///Get first mail of my mailbox
Pop3Message mg = cl.GetMessage(1);
String MyText = mg.BodyText;
///If the message have one attachment
Pop3Content ct = mg.Contents[0];
///you can save it to local disk
ct.DecodeData("your file path");
}
you can get it from https://github.com/higty/higlabo or Nuget [HigLabo]
Another option: Do not float your right column; just give it a left margin to move it beyond the float. You'll need a hack or two to fix IE6, but that's the basic idea.
If Perl 5.10+ is not an option, here is a quick and dirty approximation. It's not exactly the same, since say has some magic when its first arg is a handle, but for printing to STDOUT:
sub say {print @_, "\n"}
say 'hello';
Although purely from engineering perspective, indexed views sound like something everybody could use to improve performance but the real life scenario is very different. I have been unsuccessful is using indexed views where I most need them because of too many restrictions on what can be indexed and what cannot.
If you have outer joins in the views, they cannot be used. Also, common table expressions are not allowed... In fact if you have any ordering in subselects or derived tables (such as with partition by clause), you are out of luck too.
That leaves only very simple scenarios to be utilizing indexed views, something in my opinion can be optimized by creating proper indexes on underlying tables anyway.
I will be thrilled to hear some real life scenarios where people have actually used indexed views to their benefit and could not have done without them
I'm particularly fond of this date picker built for Mootools: http://electricprism.com/aeron/calendar/
It's lovely right out of the box.
all answers are wrong. "Opera" and "Chrome" are same in all cases.
(edited part)
here is the right answer
if (window.chrome && window.chrome.webstore) {
// this is Chrome
}
Because the dot is inside character class (square brackets []
).
Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):
Any character except ^-]\ add that character to the possible matches for the character class.
You need two columns of the same type, one on each table, to JOIN on. Whether they're primary and foreign keys or not doesn't matter.
you can do diff a on b and diff b on a, then merge both results
let a = [_x000D_
{ value: "0", display: "Jamsheer" },_x000D_
{ value: "1", display: "Muhammed" },_x000D_
{ value: "2", display: "Ravi" },_x000D_
{ value: "3", display: "Ajmal" },_x000D_
{ value: "4", display: "Ryan" }_x000D_
]_x000D_
_x000D_
let b = [_x000D_
{ value: "0", display: "Jamsheer" },_x000D_
{ value: "1", display: "Muhammed" },_x000D_
{ value: "2", display: "Ravi" },_x000D_
{ value: "3", display: "Ajmal" }_x000D_
]_x000D_
_x000D_
// b diff a_x000D_
let resultA = b.filter(elm => !a.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));_x000D_
_x000D_
// a diff b_x000D_
let resultB = a.filter(elm => !b.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm))); _x000D_
_x000D_
// show merge _x000D_
console.log([...resultA, ...resultB]);
_x000D_
The main factors are that it's a statically-typed language and that's compiled to machine code. Also, since it's a low-level language, it generally doesn't do anything you don't tell it to.
These are some other factors that come to mind.
Most static-typed languages could be compiled just as fast or faster than C though, especially if they can make assumptions that C can't because of pointer aliasing, etc.
This only works after you save a bookmark to the app to the home screen. Not if you just browse to the site normally.
Got it :D
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
alert(getContextPath());
Important note: Does only work for the "root" context path. Does not work with "subfolders", or if context path has a slash ("/") in it.
Detect Enter key pressed on whole document:
$(document).keypress(function (e) {
if (e.which == 13) {
alert('enter key is pressed');
}
});
Use list, it will solve problem
Step1:
result=YOUR_MODELE_NAME.objects.values('PROP1','PROP2').all();
Step2:
result=list(result) #after getting data from model convert result to list
Step3:
return HttpResponse(json.dumps(result), content_type = "application/json")
Solution for me.
Step: 1
<a onclick="exportAsExcel()">Export to excel</a>
Step: 2
I'm using file-saver lib.
Read more: https://www.npmjs.com/package/file-saver
npm i file-saver
Step: 3
let FileSaver = require('file-saver'); // path to file-saver
function exportAsExcel() {
let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
this.downloadFile(dataBlob);
}
function downloadFile(blobContent){
let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
FileSaver.saveAs(blob, 'report.xlsx');
}
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
let sliceSize = 1024;
let byteCharacters = atob(base64Data);
let bytesLength = byteCharacters.length;
let slicesCount = Math.ceil(bytesLength / sliceSize);
let byteArrays = new Array(slicesCount);
for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
let begin = sliceIndex * sliceSize;
let end = Math.min(begin + sliceSize, bytesLength);
let bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Work for me. ^^
I didn't find it easy to understand what is required even after reading all the answers until I executed this. TensofFlow is new to me too.
def printtest():
x = tf.constant([1.0, 3.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
sess.run(init)
print(sess.run(b))
sess.close()
But still you may need the value returned by executing the session.
def printtest():
x = tf.constant([100.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
sess.run(init)
c = sess.run(b)
print(c)
sess.close()
You could prove to yourself that there is no other difference by trying to define a function in a struct. I remember even my college professor who was teaching about structs and classes in C++ was surprised to learn this (after being corrected by a student). I believe it, though. It was kind of amusing. The professor kept saying what the differences were and the student kept saying "actually you can do that in a struct too". Finally the prof. asked "OK, what is the difference" and the student informed him that the only difference was the default accessibility of members.
A quick Google search suggests that POD stands for "Plain Old Data".
Plain and simple:
plt.plot(x, y, 'r-', alpha=0.7)
(I know I add nothing new, but the straightforward answer should be visible).
Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);
The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.
You can use CountIf
. Put the following code in B1 and drag down the whole column
=COUNTIF(A:A,A1)
It will look like this:
Using Focus method
Private Sub frmTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
yourControl.Focus()
End Sub
Using EntityManager em;
public User getUserById(Long id) {
return em.getReference(User.class, id);
}
I tried many scripts but they didn't work for all objects. You can't move clustered objects from one tablespace to another. For that you will have to use expdp, so I will suggest expdp is the best option to move all objects to a different tablespace.
Below is the command:
nohup expdp \"/ as sysdba\" DIRECTORY=test_dir DUMPFILE=users.dmp LOGFILE=users.log TABLESPACES=USERS &
You can check this link for details.
Here's a simple way
for (i in 1:10) {
skip_to_next <- FALSE
# Note that print(b) fails since b doesn't exist
tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b)
with any code you want. You can also wrap many lines of code in {
and }
if you have more than one line of code inside the tryCatch
You can specify the orientation of an activity in the manifest. See here.
<activity android:allowTaskReparenting=["true" | "false"]
...
android:screenOrientation=["unspecified" | "user" | "behind" |
"landscape" | "portrait" |
"sensor" | "nosensor"]
...
"adjustResize", "adjustPan"] >
If you are connecting to multiple servers you should add a 'GO' before switching servers, or your sql statements will run against the wrong server.
e.g.
:CONNECT SERVER1
Select * from Table
GO
enter code here
:CONNECT SERVER1
Select * from Table
GO
If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.
php artisan cache:clear
php artisan route:cache
It should work.
Any int other than zero is true; false is zero. That way code like this continues to work as expected:
int done = 0; // `int` could be `bool` just as well
while (!done)
{
// ...
done = OS_SUCCESS_CODE == some_system_call ();
}
IMO, bool
is an overrated type, perhaps a carry over from other languages. int
works just fine as a boolean type.
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
int
variables can't be null
If a null
is to be converted to int
, then it is the converter which decides whether to set 0
, throw exception, or set another value (like Integer.MIN_VALUE
). Try to plug your own converter.
Take a look at DATEDIFF, this should be what you're looking for. It takes the two dates you're comparing, and the date unit you want the difference in (days, months, seconds...)
Adding to Dmitri Chebotarev's answer, as for Laravel 5+.
After requiring the doctrine/dbal package:
composer require doctrine/dbal
You can then make a migration with nullable columns, like so:
public function up()
{
Schema::table('users', function (Blueprint $table) {
// change() tells the Schema builder that we are altering a table
$table->integer('user_id')->unsigned()->nullable()->change();
});
}
To revert the operation, do:
public function down()
{
/* turn off foreign key checks for a moment */
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
/* set null values to 0 first */
DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
/* alter table */
DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
/* finally turn foreign key checks back on */
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
function trimNumber(num, len) {
const modulu_one = 1;
const start_numbers_float=2;
var int_part = Math.trunc(num);
var float_part = String(num % modulu_one);
float_part = float_part.slice(start_numbers_float, start_numbers_float+len);
return int_part+'.'+float_part;
}
slide to right
viewPager.arrowScroll(View.FOCUS_RIGHT);
slide to left
viewPager.arrowScroll(View.FOCUS_LEFT);
You can use below function for relative path as absolute path is not a good idea to add in script
Import
import sys, os
Use code as below :
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'Screenshots'+ os.sep)
driver.get_screenshot_as_file(screenshotpath+"testPngFunction.png")
make sure you create the folder where the .py file is present.
os.path.join
also prevent you to run your script in cross-platform like: UNIX and windows. It will generate path separator as per OS at runtime. os.sep
is similar like File.separtor
in java
For a larger set of environment variables or when you want to reuse them you can use env-cmd
.
./.env
file:
# This is a comment
ENV1=THANKS
ENV2=FOR ALL
ENV3=THE FISH
./package.json
:
{
"scripts": {
"test": "env-cmd mocha -R spec"
}
}
my solution: first step like most other answer:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python2.7 get-pip.py --force-reinstall
second, add soft link
sudo ln -s /usr/local/bin/pip /usr/bin/pip
As mentioned above, put gem: --no-document
in your gem file. However, the system-wide gemrc will not always necessarily go into /etc/gemrc
. If you are using RVM, or you have Ruby installed under /usr/local/bin
, it needs to go in a different location. You can find this location by running irb
and typing...
require 'rubygems'
Gem::ConfigFile::SYSTEM_WIDE_CONFIG_FILE
See the original post on this over here.
In the case of a dialog, it has a property called draggable, set it to false.
$("#yourDialog").dialog({
draggable: false
});
Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.
Try this - You have to import java.util.regex.*;
Pattern pattern = Pattern.compile("\\s+");
Matcher matcher = pattern.matcher(string);
boolean check = matcher.find();
String str = matcher.replaceAll(" ");
Where string
is your string on which you need to remove duplicate white spaces
IIRC, it involves garbage collection strategies. The theory is that a client and server will be different in terms of short-lived objects, which is important for modern GC algorithms.
Here is a link on server mode. Alas, they don't mention client mode.
Here is a very thorough link on GC in general; this is a more basic article. Not sure if either address -server vs -client but this is relevant material.
At No Fluff Just Stuff, both Ken Sipe and Glenn Vandenburg do great talks on this kind of thing.
Not jQuery
, as the question asks for, but natively (i.e., no libraries required) I think the better tool for the job is querySelector
to get a single instance of a selector:
let el = document.querySelector('img');
console.log(el);
For all matching instances, use document.querySelectorAll()
, or for those within another element you can chain as follows:
// Get some wrapper, with class="parentClassName"
let parentEl = document.querySelector('.parentClassName');
// Get all img tags within the parent element by parentEl variable
let childrenEls = parentEl.querySelectorAll('img');
Note the above is equivalent to:
let childrenEls = document.querySelector('.parentClassName').querySelectorAll('img');
There is another way of doing so:
<span style="width: 10px"></span>
You can adjust the amount of space using the width property.
Your code would be:
<div style="text-align: center">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
<span style="width: 10px"></span>
<asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>
Since you are using $.ajax
, and not $.getJSON
, your return type is plain text. you need to now convert data
into a JSON object.
you can either do this by changing your $.ajax
to $.getJSON
(which is a shorthand for $.ajax
, only preconfigured to fetch json).
Or you can parse the data
string into JSON after you receive it, like so:
success: function (data) {
var obj = $.parseJSON(data);
console.log(obj);
},
I had this problem and all I had to do is return true
from touchend and the warning went away.
You could try using MultiMap instead of HashMap
Initialising it will require fewer lines of codes. Adding and retrieving the values will also make it shorter.
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
would become:
Multimap<String, Integer> multiMap = ArrayListMultimap.create();
You can check this link: http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and
just you pass this things in your select query. using CASE
CASE WHEN gender=0 then 'Female' WHEN gender=1 then 'Male' END as Genderdisp
you might want to try microsoft script debugger it's pretty old but it's quite useful in the sense if you stumble on any javascript error, the debugger will popup to show you which line is messing up. it could get irrating sometimes when you do normal surfing, but you can turn if off.
here's a good startup on how to use this tool too. HOW-TO: Debug JavaScript in Internet Explorer
var string = 'test- _ 0Test';
string.match(/^[-_ a-zA-Z0-9]+$/)
1.-In XAMPP press button Shell
2.-place command:
mysqladmin -u root password
New password: aqui colocar password ejemplo ´09876´
3.-go on the local disk c: xampp \ phpMyAdmin open config.inic.php with notepad ++
5.- add the password and in AllowNoPassword change to false
/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '09876';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['Lang'] = '';
6.- save changes, clear browser cache and restart xampp
I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)
Thanks!
When you use Task.Run to run a method, Task gets a thread from threadpool to run that method. So from the UI thread's perspective, it is "asynchronous" as it doesn't block UI thread.This is fine for desktop application as you usually don't need many threads to take care of user interactions.
However, for web application each request is serviced by a thread-pool thread and thus the number of active requests can be increased by saving such threads. Frequently using threadpool threads to simulate async operation is not scalable for web applications.
True Async doesn't necessarily involving using a thread for I/O operations, such as file / DB access etc. You can read this to understand why I/O operation doesn't need threads. http://blog.stephencleary.com/2013/11/there-is-no-thread.html
In your simple example,it is a pure CPU-bound calculation, so using Task.Run is fine.
I'd rather use static widths and if you'd like your page to resize depending on screen size, you can have a look at media queries.
Or, you can set a min-width on elements like header, navigation, content etc.
Quick tip: !obj.blank? == obj.present?
Can be handy/easier on the eyes in some expressions
You 'can' have a static class in C++, as mentioned before, a static class is one that does not have any objects of it instantiated it. In C++, this can be obtained by declaring the constructor/destructor as private. End result is the same.
INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));
Anyone looking for a quick Vue file component, here you go:
// WindowUrl.vue
<template>
<a :href="url" :class="classes" @click="open">
<slot></slot>
</a>
</template>
<script>
export default {
props: {
url: String,
width: String,
height: String,
classes: String,
},
methods: {
open(e) {
// Prevent the link from opening on the parent page.
e.preventDefault();
window.open(
this.url,
'targetWindow',
`toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=${this.width},height=${this.height}`
);
}
}
}
</script>
Usage:
<window-url url="/print/shipping" class="btn btn-primary" height="250" width="250">
Print Shipping Label
</window-url>
Just in case someone is interest only in what kind of process created the shared moeries, call
ls -l /dev/shm
It lists the names that are associated with the shared memories - at least on Ubuntu. Usually the names are quite telling.
You can have return
in a void method, you just can't return any value (as in return 5;
), that's why they call it a void method. Some people always explicitly end void methods with a return statement, but it's not mandatory. It can be used to leave a function early, though:
void someFunct(int arg)
{
if (arg == 0)
{
//Leave because this is a bad value
return;
}
//Otherwise, do something
}
Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.
Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.
Javascript:
$("#startTransition").on("click", function()
{
if( $(".boxOne").is(":visible"))
{
$(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
$(".boxTwo").css({ x: '100%' });
$(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
return;
}
$(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
$(".boxOne").css({ x: '100%' });
$(".boxOne").show().transition({ x: '0%', opacity: 1.0 });
});
Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.
I just added inline style .
<div id="map_canvas" style="width:750px;height:484px;"></div>
And it worked for me .
I choose to write in C because I enjoy working with a small, tight language. I like having access to a standard which can be read in a reasonable amount of time (for me -- I'm a very slow reader). Moreover, I use it to write software for embedded systems for which few desirable C++ compilers exist (like some PIC micro-controllers).
I got the same error (TypeError: 'int' object is not callable)
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
return xl
... ... ... ...
>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable
after reading this post I realized that I forgot a multiplication sign * so
def xlim(i,k,s1,s2):
x=i/(2*k)
xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
return xl
xlim(1.0,100.0,0.0,0.0)
0.005
tanks
One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)
gui_en.properties:
title.text=<html>Text color: <font color='red'>red</font></html>
gui_fr.properties:
title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>
gui_ru.properties:
title.text=<html>???? ??????: <font color='red'>???????</font></html>
I created the following extension:
extension String {
func substring(from from:Int, to:Int) -> String? {
if from<to && from>=0 && to<self.characters.count {
let rng = self.startIndex.advancedBy(from)..<self.startIndex.advancedBy(to)
return self.substringWithRange(rng)
} else {
return nil
}
}
}
example of use:
print("abcde".substring(from: 1, to: 10)) //nil
print("abcde".substring(from: 2, to: 4)) //Optional("cd")
print("abcde".substring(from: 1, to: 0)) //nil
print("abcde".substring(from: 1, to: 1)) //nil
print("abcde".substring(from: -1, to: 1)) //nil
In my case, I add file as Link from another project and then rename file in source project that cause problem in destination project. I delete linked file in destination and add again with new name.
you can simply disable maximize inside form constructor.
public Form1(){
InitializeComponent();
MaximizeBox = false;
}
to minimize when closing.
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
e.Cancel = true;
WindowState = FormWindowState.Minimized;
}
TL;DR:
sudo apt-get install nodejs-legacy
First of all let me clarify the situation a bit. In summer 2012 Debian maintainers decided to rename Node.js executable to prevent some kind of namespace collision with another package. It was very hard decision for Debian Technical Committee, because it breaks backward compatibility.
The following is a quote from Committee resolution draft, published in Debian mailing list:
The nodejs package shall be changed to provide /usr/bin/nodejs, not /usr/bin/node. The package should declare a Breaks: relationship with any packages in Debian that reference /usr/bin/node.
The nodejs source package shall also provide a nodejs-legacy binary package at Priority: extra that contains /usr/bin/node as a symlink to /usr/bin/nodejs. No package in the archive may depend on or recommend the nodejs-legacy package, which is provided solely for upstream
compatibility. This package declares shall also declare a Conflicts: relationship with the node package.<...>
Paragraph 2 is the actual solution for OP's issue. OP should try to install this package instead of doing symlink by hand. Here is a link to this package in Debian package index website.
It can be installed using sudo apt-get install nodejs-legacy
.
I have not found any information about adopting the whole thing by NPM developers, but I think npm
package will be fixed on some point and nodejs-legacy
become really legacy.
The ALL_CAPS is taken from the C and C++ way of working I believe. This article here explains how the style differences came about.
In the new IDE's such as Visual Studio it is easy to identify the types, scope and if they are constant so it is not strictly necessary.
The FxCop and Microsoft StyleCop software will help give you guidelines and check your code so everyone works the same way.
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>();
foreach (JToken attribute in attributes)
{
JProperty jProperty = attribute.ToObject<JProperty>();
string propertyName = jProperty.Name;
}
I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
From Wikipedia (you can read which is correct for your OS at that article):
Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A).
Here are the ways to assign parent object in child object of Bi-directional relations ?
Suppose you have a relation say One-To-Many,then for each parent object,a set of child object exists. In bi-directional relations,each child object will have reference to its parent.
eg : Each Department will have list of Employees and each Employee is part of some department.This is called Bi directional relations.
To achieve this, one way is to assign parent in child object while persisting parent object
Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);
List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChilds(children);
session.save(parent);
Other way is, you can do using hibernate Intercepter,this way helps you not to write above code for all models.
Hibernate interceptor provide apis to do your own work before perform any DB operation.Likewise onSave of object, we can assign parent object in child objects using reflection.
public class CustomEntityInterceptor extends EmptyInterceptor {
@Override
public boolean onSave(
final Object entity, final Serializable id, final Object[] state, final String[] propertyNames,
final Type[] types) {
if (types != null) {
for (int i = 0; i < types.length; i++) {
if (types[i].isCollectionType()) {
String propertyName = propertyNames[i];
propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
try {
Method method = entity.getClass().getMethod("get" + propertyName);
List<Object> objectList = (List<Object>) method.invoke(entity);
if (objectList != null) {
for (Object object : objectList) {
String entityName = entity.getClass().getSimpleName();
Method eachMethod = object.getClass().getMethod("set" + entityName, entity.getClass());
eachMethod.invoke(object, entity);
}
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
return true;
}
}
And you can register Intercepter to configuration as
new Configuration().setInterceptor( new CustomEntityInterceptor() );
I have the same issue when processing a file generated from Linux. It turns out it was related with files containing question marks..
I got my script to work by editing /etc/rc.local
then issuing the following 3 commands.
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Now the script works at boot.
git add
puts pending files to the so called git 'index' which is local.
After that you use git commit
to commit (apply) things in the index.
Then use git push [remotename] [localbranch][:remotebranch]
to actually push them to a remote repository.
Set data to this:
data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
the term "smart pointer" includes shared pointers, auto pointers, locking pointers and others. you meant to say auto pointer (more ambiguously known as "owning pointer"), not smart pointer.
Dumb pointers (T*) are never the best solution. They make you do explicit memory management, which is verbose, error prone, and sometimes nigh impossible. But more importantly, they don't signal your intent.
Auto pointers delete the pointee at destruction. For arrays, prefer encapsulations like vector and deque. For other objects, there's very rarely a need to store them on the heap - just use locals and object composition. Still the need for auto pointers arises with functions that return heap pointers -- such as factories and polymorphic returns.
Shared pointers delete the pointee when the last shared pointer to it is destroyed. This is useful when you want a no-brainer, open-ended storage scheme where expected lifetime and ownership can vary widely depending on the situation. Due to the need to keep an (atomic) counter, they're a bit slower than auto pointers. Some say half in jest that shared pointers are for people who can't design systems -- judge for yourself.
For an essential counterpart to shared pointers, look up weak pointers too.