using the Reflections library, it's easy as:
Reflections reflections = new Reflections("my.pkg", new SubTypesScanner(false));
That would scan all classes in the url/s that contains my.pkg package.
So, getting all classes is effectively getting all subtypes of Object, transitively:
Set<String> allClasses =
reflections.getStore().getSubTypesOf(Object.class.getName());
(The ordinary way reflections.getSubTypesOf(Object.class)
would cause loading all classes into PermGen and would probably throw OutOfMemoryError. you don't want to do it...)
If you want to get all direct subtypes of Object (or any other type), without getting its transitive subtypes all in once, use this:
Collection<String> directSubtypes =
reflections.getStore().get(SubTypesScanner.class).get(Object.class.getName());
Run this
for (Method m : sex.class.getDeclaredMethods()) {
System.out.println(m);
}
you will see
public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()
These are all public methods that "sex" class has. They are not in the source code, javac.exe added them
Notes:
never use sex as a class name, it's difficult to read your code, we use Sex in Java
when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class
you could use fopen() function.
some example:
$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
$newfname = $destination_folder .'myfile.mp4'; //set your file ext
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "a"); // to overwrite existing file
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp
. A few resources include:
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
How to store Java Date to Mysql datetime...?
EDIT:
As others have indicated, the suggestion of using strings may lead to issues.
This one has been answered already here: Python memory profiler
Basically you do something like that (cited from Guppy-PE):
>>> from guppy import hpy; h=hpy()
>>> h.heap()
Partition of a set of 48477 objects. Total size = 3265516 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 25773 53 1612820 49 1612820 49 str
1 11699 24 483960 15 2096780 64 tuple
2 174 0 241584 7 2338364 72 dict of module
3 3478 7 222592 7 2560956 78 types.CodeType
4 3296 7 184576 6 2745532 84 function
5 401 1 175112 5 2920644 89 dict of class
6 108 0 81888 3 3002532 92 dict (no owner)
7 114 0 79632 2 3082164 94 dict of type
8 117 0 51336 2 3133500 96 type
9 667 1 24012 1 3157512 97 __builtin__.wrapper_descriptor
<76 more rows. Type e.g. '_.more' to view.>
>>> h.iso(1,[],{})
Partition of a set of 3 objects. Total size = 176 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 33 136 77 136 77 dict (no owner)
1 1 33 28 16 164 93 list
2 1 33 12 7 176 100 int
>>> x=[]
>>> h.iso(x).sp
0: h.Root.i0_modules['__main__'].__dict__['x']
>>>
You can import one of them using import. For all other similar class , you need to specify Fully qualified class names. Otherwise you will get compilation error.
Eg:
import java.util.Date;
class Test{
public static void main(String [] args){
// your own date
my.own.Date myOwndate ;
// util.Date
Date utilDate;
}
}
Don't delete them!!! Until..........
Find a version on your git, svn or copy folder that works.
Delete them and then recover all .pyc.
That's work for me.
See LINQ: How to get the latest/last record with a group by clause
var firstItemsInGroup = from b in mainButtons
group b by b.category into g
select g.First();
I assume that mainButtons are already sorted correctly.
If you need to specify custom sort order, use OrderBy override with Comparer.
var firstsByCompareInGroups = from p in rows
group p by p.ID into grp
select grp.OrderBy(a => a, new CompareRows()).First();
See an example in my post "Select First Row In Group using Custom Comparer"
Create a zip folder in PHP.
public function zip_creation($source, $destination){
$dir = opendir($source);
$result = ($dir === false ? false : true);
if ($result !== false) {
$rootPath = realpath($source);
// Initialize archive object
$zip = new ZipArchive();
$zipfilename = $destination.".zip";
$zip->open($zipfilename, ZipArchive::CREATE | ZipArchive::OVERWRITE );
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
return TRUE;
} else {
return FALSE;
}
}
$source = $source_directory;
$destination = $destination_directory;
$zipcreation = $this->zip_creation($source, $destination);
In the examples below the client is the browser and the server is the webserver hosting the website.
Before you can understand these technologies, you have to understand classic HTTP web traffic first.
The server sends an event to the client when there's new information available.
The server and the client can now send each other messages when new data (on either side) is available.
Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.
Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?
You can use PHP with WebSockets, check out Ratchet.
The Gantt charts given by Hifzan and Raja are for FCFS algorithms.
With an SJF algorithm, processes can be interrupted. That is, every process doesn't necessarily execute straight through their given burst time.
P3|P2|P4|P3|P5|P1|P5
1|2|3|5|7|8|11|14
P3 arrives at 1ms, then is interrupted by P2 and P4 since they both have smaller burst times, and then P3 resumes. P5 starts executing next, then is interrupted by P1 since P1's burst time is smaller than P5's. You must note the arrival times and be careful. These problems can be trickier than how they appear at-first-glance.
EDIT: This applies only to Preemptive SJF algorithms. A plain SJF algorithm is non-preemptive, meaning it does not interrupt a process.
var myArray = [];
var arrayMax = 40;
var limit = arrayMax + 1;
for (var i = 0; i < arrayMax; i++) {
myArray.push(Math.floor(Math.random()*limit));
}
This above is the traditional way of doing it but I second @Pointy and @Phrogz if you want to avoid duplicates in your array without having to do expensive computation
The compiler can't figure out what type to make the Dictionary, because it's not homogenous. You have values of different types. The only way to get around this is to make it a [String: Any]
, which will make everything clunky as all hell.
return [
"title": title,
"is_draft": isDraft,
"difficulty": difficulty,
"duration": duration,
"cost": cost,
"user_id": userId,
"description": description,
"to_sell": toSell,
"images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
] as [String: Any]
This is a job for a struct. It'll vastly simplify working with this data structure.
I have the same problem, i read the url with an properties file:
String configFile = System.getenv("system.Environment");
if (configFile == null || "".equalsIgnoreCase(configFile.trim())) {
configFile = "dev.properties";
}
// Load properties
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/" + configFile));
//read url from file
apiUrl = properties.getProperty("url").trim();
URL url = new URL(apiUrl);
//throw exception here
URLConnection conn = url.openConnection();
dev.properties
url = "https://myDevServer.com/dev/api/gate"
it should be
dev.properties
url = https://myDevServer.com/dev/api/gate
without "" and my problem is solved.
According to oracle documentation
- Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
So it means it is not parsed inside the string.
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);
While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.
Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:
auth-server-whitelist
command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz"
. Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.AuthServerWhitelist
/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist
policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:
Start > Run > gpedit.msc
Local Computer Policy > Computer Configuration > Administrative Templates
Administrative Templates
, and select Add/Remove Templates
windows\adm\en-US\chrome.adm
template via the dialogComputer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication
enable and configure Authentication server whitelist
chrome://policy
to view active policiesWhile setting the paste mode with paste/nopaste/pastetoggle
is perfectly fine, you still have to manually enable paste mode before pasting and disable paste mode after pasting. Being the lazy person that I am, below is the best solution that I've found so far, which automatically toggles the paste mode when you paste.
Here's a little trick that uses terminal's bracketed paste mode to automatically set/unset Vim's paste mode when you paste. Put following in your .vimrc:
let &t_SI .= "\<Esc>[?2004h" let &t_EI .= "\<Esc>[?2004l" inoremap <special> <expr> <Esc>[200~ XTermPasteBegin() function! XTermPasteBegin() set pastetoggle=<Esc>[201~ set paste return "" endfunction
Now you can paste without explicitly turning paste mode on/off - it is handled automatically for you.
Source: Coderwall
Note: This solution doesn't work in WSL (Windows 10 Subsystem for Linux). If anyone has a solution for WSL, please update this answer or add it in the comments.
Tmux If using tmux, then the declarations need to be double escaped. The code for this is also in Coderwall
maybe you want to take a look java.util.Stack
class.
it has push, pop methods. and implemented List interface.
for shift/unshift, you can reference @Jon's answer.
however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.
A few ways to extend String.prototype
, or use ES2015 template literals.
var result = document.querySelector('#result');_x000D_
// -----------------------------------------------------------------------------------_x000D_
// Classic_x000D_
String.prototype.format = String.prototype.format ||_x000D_
function () {_x000D_
var args = Array.prototype.slice.call(arguments);_x000D_
var replacer = function (a){return args[a.substr(1)-1];};_x000D_
return this.replace(/(\$\d+)/gm, replacer)_x000D_
};_x000D_
result.textContent = _x000D_
'hello $1, $2'.format('[world]', '[how are you?]');_x000D_
_x000D_
// ES2015#1_x000D_
'use strict'_x000D_
String.prototype.format2 = String.prototype.format2 ||_x000D_
function(...merge) { return this.replace(/\$\d+/g, r => merge[r.slice(1)-1]); };_x000D_
result.textContent += '\nHi there $1, $2'.format2('[sir]', '[I\'m fine, thnx]');_x000D_
_x000D_
// ES2015#2: template literal_x000D_
var merge = ['[good]', '[know]'];_x000D_
result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`;
_x000D_
<pre id="result"></pre>
_x000D_
If anybody is looking for an option which handles nested variables, there are several such options in this github issue.
In short, you need to use "default" filter for every level of nested vars. For a variable "a.nested.var" it would look like:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ((a | default({})).nested | default({}) ).var | default('bar') }}"
or you could set default values of empty dicts for each level of vars, maybe using "combine" filter. Or use "json_query" filter. But the option I chose seems simpler to me if you have only one level of nesting.
TL;DR:
The ActionListener
s (there can be multiple) execute in the order they were registered BEFORE the action
Long Answer:
A business action
typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view
if that is not what you are doing an actionListener
is more appropriate i.e. for when the user interacts with the components, such as h:commandButton
or h:link
they can be handled by passing the name of the managed bean method in actionListener
attribute of a UI Component or to implement an ActionListener
interface and pass the implementation class name to actionListener
attribute of a UI Component.
Here's a function that finds the dictionary's index position if it exists.
dicts = [{'id':'1234','name':'Jason'},
{'id':'2345','name':'Tom'},
{'id':'3456','name':'Art'}]
def find_index(dicts, key, value):
class Null: pass
for i, d in enumerate(dicts):
if d.get(key, Null) == value:
return i
else:
raise ValueError('no dict with the key and value combination found')
print find_index(dicts, 'name', 'Tom')
# 1
find_index(dicts, 'name', 'Ensnare')
# ValueError: no dict with the key and value combination found
Also you can use
<select ng-change="updateValue(user, oldValue)"
ng-init="oldValue=0"
ng-focus="oldValue=user.id"
ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>
That's a half-open interval.
[a,b]
includes the end points.(a,b)
excludes them.In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".
Half-open intervals are useful in programming because they correspond to the common idiom for looping:
for (int i = 0; i < n; ++i) { ... }
Here i is in the range [0, n).
I use the MAVEN_OPTS option, and find it useful to set suspend to "suspend=y" as my exec:java programs tend to be small generators which are finished before I have manage to attach a debugger.... :) With suspend on it will wait for a debugger to attach before proceding.
Tab is [HT], or character number 9, in the unicode library.
After struggling much with the npm link
command (suggested solution for developing local modules without publishing them to a registry or maintaining a separate copy in the node_modules folder), I built a small npm module to help with this issue.
The fix requires two easy steps.
First:
npm install lib-manager --save-dev
Second, add this to your package.json
:
{
"name": "yourModuleName",
// ...
"scripts": {
"postinstall": "./node_modules/.bin/local-link"
}
}
More details at https://www.npmjs.com/package/lib-manager. Hope it helps someone.
SIMPLE method may not be the best for all cases
<%
if (Session["Utype"].ToString() == "1")
{
%>
<li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>
<li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
<%
}
else
{
%>
<li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
<%
}
%>
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
The recursive function approach has a problem. It builds up a call stack of size O(n), which makes our total memory cost O(n). This makes it vulnerable to a stack overflow error, where the call stack gets too big and runs out of space.
Tail call optimization (TCO) scheme. Where it can optimize recursive functions to avoid building up a tall call stack and hence saves the memory cost.
There are many languages who are doing TCO like (JavaScript, Ruby and few C) whereas Python and Java do not do TCO.
JavaScript language has confirmed using :) http://2ality.com/2015/06/tail-call-optimization.html
use this query in your local DB.
select * from schema_version delete from schema_version where checksum Column = -1729781252;
Note: -1729781252 is the "Resolved locally" value.
Build and start the server.
With <button>
, you can use img tags, etc. where text is
<button type='submit'> text -- can be img etc. </button>
with <input>
type, you are limited to text
Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.
Command-line help for "at":
C:\>at /? The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]] AT [\\computername] time [/INTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command" \\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted. id Is an identification number assigned to a scheduled command. /delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled. /yes Used with cancel all jobs command when no further confirmation is desired. time Specifies the time when command is to run. /interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs. /every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed. /next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed. "command" Is the Windows NT command, or batch program to be run.
For those on Azure, follow these modified instructions from Virus:
Slightly abbreviated could be...
echo date("Y-m-d H:i:s", strtotime($mysqltime));
You have to add the reference to the project.
In Assemblies, there is a System.Web.Extensions Add that.
Once that is done put:
using System.Web;
using System.Web.Script;
using System.Web.Script.Serialization;
That worked for me.
Disclaimer: This modified XML parser was inspired by Adam Clark The original XML parser works for most of simple cases. However, it didn't work for some complicated XML files. I debugged the code line by line and finally fixed some issues. If you find some bugs, please let me know. I am glad to fix it.
class XmlDictConfig(dict):
'''
Note: need to add a root into if no exising
Example usage:
>>> tree = ElementTree.parse('your_file.xml')
>>> root = tree.getroot()
>>> xmldict = XmlDictConfig(root)
Or, if you want to use an XML string:
>>> root = ElementTree.XML(xml_string)
>>> xmldict = XmlDictConfig(root)
And then use xmldict for what it is... a dict.
'''
def __init__(self, parent_element):
if parent_element.items():
self.updateShim( dict(parent_element.items()) )
for element in parent_element:
if len(element):
aDict = XmlDictConfig(element)
# if element.items():
# aDict.updateShim(dict(element.items()))
self.updateShim({element.tag: aDict})
elif element.items(): # items() is specialy for attribtes
elementattrib= element.items()
if element.text:
elementattrib.append((element.tag,element.text )) # add tag:text if there exist
self.updateShim({element.tag: dict(elementattrib)})
else:
self.updateShim({element.tag: element.text})
def updateShim (self, aDict ):
for key in aDict.keys(): # keys() includes tag and attributes
if key in self:
value = self.pop(key)
if type(value) is not list:
listOfDicts = []
listOfDicts.append(value)
listOfDicts.append(aDict[key])
self.update({key: listOfDicts})
else:
value.append(aDict[key])
self.update({key: value})
else:
self.update({key:aDict[key]}) # it was self.update(aDict)
One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).
You'll want to use the WHERE EXISTS syntax instead.
SELECT *
FROM table1
WHERE EXISTS (SELECT *
FROM table2
WHERE Lead_Key = @Lead_Key
AND table1.CM_PLAN_ID = table2.CM_PLAN_ID
AND table1.Individual_ID = table2.Individual_ID)
This also does seem to work, although W3C specifies it is not intended "for an external (typically non-HTML) application or interactive content"
<embed src="http://www.somesite.com" width=200 height=200 />
More info: http://www.w3.org/wiki/HTML/Elements/embed http://www.w3schools.com/tags/tag_embed.asp
Here is a clearer solution.
def freeze(o):
if isinstance(o,dict):
return frozenset({ k:freeze(v) for k,v in o.items()}.items())
if isinstance(o,list):
return tuple([freeze(v) for v in o])
return o
def make_hash(o):
"""
makes a hash out of anything that contains only list,dict and hashable types including string and numeric types
"""
return hash(freeze(o))
Use extension methods. Replace NameOfContext with the name of your object context.
public static class Extensions{
public static IQueryable<Company> CompleteCompanies(this NameOfContext context){
return context.Companies
.Include("Employee.Employee_Car")
.Include("Employee.Employee_Country") ;
}
public static Company CompanyById(this NameOfContext context, int companyID){
return context.Companies
.Include("Employee.Employee_Car")
.Include("Employee.Employee_Country")
.FirstOrDefault(c => c.Id == companyID) ;
}
}
Then your code becomes
Company company =
context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);
//or if you want even more
Company company =
context.CompanyById(companyID);
String.Join() is implemented quite fast, and as you already have a collection of the strings in question, is probably the best choice. Above all, it shouts "I'm joining a list of strings!" Always nice.
Because you need parentheses around the value your looking for.
So here : document.querySelector('a[data-a="1"]')
If you don't know in advance the value but is looking for it via variable you can use template literals :
Say we have divs with data-price
<div data-price="99">My okay price</div>
<div data-price="100">My too expensive price</div>
We want to find an element but with the number that someone chose (so we don't know it):
// User chose 99
let chosenNumber = 99
document.querySelector(`[data-price="${chosenNumber}"`]
Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.
var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.5472,12.282715),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
jQuery UI extends the jQuery native toggleClass
to take a second optional parameter: duration
toggleClass( class, [duration] )
There are many answers which explain more detailed on the differences, but here is my very brief explanation.
One important difference is that VMs use a separate kernel to run the OS. That's the reason it is heavy and takes time to boot, consuming more system resources.
In Docker, the containers share the kernel with the host; hence it is lightweight and can start and stop quickly.
In Virtualization, the resources are allocated in the beginning of set up and hence the resources are not fully utilized when the virtual machine is idle during many of the times. In Docker, the containers are not allocated with fixed amount of hardware resources and is free to use the resources depending on the requirements and hence it is highly scalable.
Docker uses UNION File system .. Docker uses a copy-on-write technology to reduce the memory space consumed by containers. Read more here
You can use the Status Sidekick of TFS Sidekicks tool and unlock the files which are checked out by other users. To do this you should be a part of Administrator group of that particular Team Project (or) your group should have the permissions to undo and unlock the other user changes which by default Administrator group has.
You can get the tool here: http://www.attrice.info/cm/tfs/
Yes you can, set the position: relative
for the container and position: absolute
for the help_panel
Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.
tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
exit 0
Find out two pieces of information
$> telnet <hostname or ip> <port>
Assuming the daemon is up and running and listening on that port it should etablish a telnet session. Likely causes:
You add your ActionListener
twice to button
. So correct your code for button2
to
JButton button2 = new JButton("hello agin2");
panel.add(button2);
button2.addActionListener (new Action2());//note the button2 here instead of button
Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater
This thread was quite helpful. The jQuery selector need to be told which of the selected elements the following code applies to. The easiest way is to append a
[0]
such as
$(".test")[0].play();
JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern
// filename: MyComponent.js
function MyComponent() {
return <div />;
}
as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here
The simple solution would be to use a ItemListener
. When the state changes, you would simply check the currently selected item and set the text accordingly
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestComboBox06 {
public static void main(String[] args) {
new TestComboBox06();
}
public TestComboBox06() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JComboBox cb;
private JTextField field;
public TestPane() {
cb = new JComboBox(new String[]{"Item 1", "Item 2"});
field = new JTextField(12);
add(cb);
add(field);
cb.setSelectedItem(null);
cb.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
Object item = cb.getSelectedItem();
if ("Item 1".equals(item)) {
field.setText("20");
} else if ("Item 2".equals(item)) {
field.setText("30");
}
}
});
}
}
}
A better solution would be to create a custom object that represents the value to be displayed and the value associated with it...
Updated
Now I no longer have a 10 month chewing on my ankles, I updated the example to use a ListCellRenderer
which is a more correct approach then been lazy and overriding toString
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestComboBox06 {
public static void main(String[] args) {
new TestComboBox06();
}
public TestComboBox06() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JComboBox cb;
private JTextField field;
public TestPane() {
cb = new JComboBox(new Item[]{
new Item("Item 1", "20"),
new Item("Item 2", "30")});
cb.setRenderer(new ItemCelLRenderer());
field = new JTextField(12);
add(cb);
add(field);
cb.setSelectedItem(null);
cb.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
Item item = (Item)cb.getSelectedItem();
field.setText(item.getValue());
}
});
}
}
public class Item {
private String value;
private String text;
public Item(String text, String value) {
this.text = text;
this.value = value;
}
public String getText() {
return text;
}
public String getValue() {
return value;
}
}
public class ItemCelLRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
if (value instanceof Item) {
setText(((Item)value).getText());
}
return this;
}
}
}
I would suggest using conda. Conda is an anconda specific package manager. If you want to know more about conda, read the conda docs.
Using conda in the command line, the command below would install scipy 0.17.
conda install scipy=0.17.0
I contest that choice B is closer to the test string, as it's only 4 characters(and 2 deletes) from being the original string. Whereas you see C as closer because it includes both brown and red. It would, however, have a greater edit distance.
There is an algorithm called Levenshtein Distance which measures the edit distance between two inputs.
Here is a tool for that algorithm.
EDIT: Sorry, I keep mixing strings in the levenshtein tool. Updated to correct answers.
The variable '$$' contains the PID.
Pattern satisfy, these below criteria
^(?!.*([A-Za-z0-9]))(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$
You have a lot of type-mismatches in your code such as trying to put an int
value where BigDecimal
is required. The corrected version of your code:
public class Payment
{
BigDecimal itemCost = BigDecimal.ZERO;
BigDecimal totalCost = BigDecimal.ZERO;
public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
{
itemCost = itemPrice.multiply(new BigDecimal(itemQuantity));
totalCost = totalCost.add(itemCost);
return totalCost;
}
}
You need to enclose multiple conditions in braces due to operator precedence and use the bitwise and (&
) and or (|
) operators:
foo = df[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]
If you use and
or or
, then pandas is likely to moan that the comparison is ambiguous. In that case, it is unclear whether we are comparing every value in a series in the condition, and what does it mean if only 1 or all but 1 match the condition. That is why you should use the bitwise operators or the numpy np.all
or np.any
to specify the matching criteria.
There is also the query method: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.query.html
but there are some limitations mainly to do with issues where there could be ambiguity between column names and index values.
You've got the ternary syntax x if x else ''
- is that what you're after?
Check if below are enabled
bz, mbstring, intl, ioncube_loader and Json extension.
This is way I did it:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)
You can define your own sizes.
The problem is that PhpMyAdmin control user (usually: pma) password does not match the mysql user: pma (same user) password.
To fix it, 1. Set the password you want for user pma here:
"C:\xampp\phpMyAdmin\config.inc.php"
$cfg['Servers'][$i]['controlpass'] = 'your_new_phpmyadmin_pass';
(should be like on line 32)
Then go to mysql, login as root, go to: (I used phpmyadmin to go here)
Database: mysql »Table: user
Edit the user: pma
Select "Password" from the function list (left column) and set "your_new_phpmyadmin_pass" on the right column and hit go.
Restart mysql server.
Now the message should disappear.
pure css solution
input::-webkit-input-placeholder {
opacity: 1;
-webkit-transition: opacity 0s;
transition: opacity 0s;
text-align: right;
}
/* Chrome <=56, Safari < 10 */
input:-moz-placeholder {
opacity: 1;
-moz-transition: opacity 0s;
transition: opacity 0s;
text-align: right;
}
/* FF 4-18 */
input::-moz-placeholder {
opacity: 1;
-moz-transition: opacity 0s;
transition: opacity 0s;
text-align: right;
}
/* FF 19-51 */
input:-ms-input-placeholder {
opacity: 1;
-ms-transition: opacity 0s;
transition: opacity 0s;
text-align: right;
}
/* IE 10+ */
input::placeholder {
opacity: 1;
transition: opacity 0s;
text-align: right;
}
/* Modern Browsers */
*:focus::-webkit-input-placeholder {
opacity: 0;
text-align: left;
}
/* Chrome <=56, Safari < 10 */
*:focus:-moz-placeholder {
opacity: 0;
text-align: left;
}
/* FF 4-18 */
*:focus::-moz-placeholder {
opacity: 0;
text-align: left;
}
/* FF 19-50 */
*:focus:-ms-input-placeholder {
opacity: 0;
text-align: left;
}
/* IE 10+ */
*:focus::placeholder {
opacity: 0;
text-align: left;
}
/* Modern Browsers */
input:focus {
text-align: left;
}
How about sys.exit()
from the module sys
.
If sys.exit()
is executed from within a thread it will close that thread only.
This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
In case you are running it on Fedora or CentOS, this is what worked for me (PostgreSQL 9.6):
In terminal:
$ sudo visudo -f /etc/sudoers
modify the following text from:
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
to
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/pgsql-9.6/bin
exit, then:
$ printenv PATH
$ sudo su postgres
$ psql
To exit postgreSQL terminal, you need to digit:
$ \q
Source: https://serverfault.com/questions/541847/why-doesnt-sudo-know-where-psql-is#comment623883_541880
app.use()
handles all the middleware functions.
What is middleware?
Middlewares are the functions which work like a door between two all the routes.
For instance:
app.use((req, res, next) => {
console.log("middleware ran");
next();
});
app.get("/", (req, res) => {
console.log("Home route");
});
When you visit /
route in your console the two message will be printed. The first message will be from middleware function. If there is no next()
function passed then only middleware function runs and other routes are blocked.
$('#myform input:checkbox').click(
function(e){
alert($(this).is(':checked'))
}
)
After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?
Look for lines that start with LoadModule php
...
There probably are configuration files/directories named mods
or something like that, start from there.
You could also check output from php -r 'phpinfo();' | grep php
and compare lines to phpinfo();
from web server.
php
interactively:(so you can paste/write code in the console)
php -a
php -f file.php
php -f file.php > results.html
To run only small part, one line or like, you can use:
php -r '$x = "Hello World"; echo "$x\n";'
If you are running linux then do man php
at console.
if you need/want to run php through fpm, use cli fcgi
SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"
where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.
I think you're missing something.
<ul>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:black;">
</div>
</li>
</ul>
<ul>
<li style="height:100px;">
<div style="height:500px; background-color:red;">
</div>
</li>
</ul>
In FF4, this displays a 100px black bar, followed by a 500px red block.
A little bit different example:
<ul>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:black;">
</div>
</li>
</ul>
<ul>
<li style="height:100px;">
<div style="height:500px; background-color:red;">
</div>
</li>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:blue;">
</div>
</li>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:green;">
</div>
</li>
</ul>
In case of lubuntu 14.04 use
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
P.S-no need to restart the system.
Even easier...
ASP.NET
<asp:RadioButtonList runat="server" ID="MyRadioButtonList" RepeatDirection="Horizontal" CssClass="FormatRadioButtonList"> ...
CSS
.FormatRadioButtonList label
{
margin-right: 15px;
}
Try this
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
//your code here that talks with the UI level widgets/ try to access the UI
//elements from this block because this piece of snippet will run in the UI/MainThread.
}
});
I found the fix you were looking for:
context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");
For some reason Android makes a bad cache of the url which it keeps returning by accident instead of the new data you need. Sure, you could just delete the entries from the DB but in my case I am only trying to access one URL so blowing away the whole DB is easier.
And don't worry, these DBs are just associated with your app so you aren't clearing the cache of the whole phone.
I had to run the following on AWS EC2 Linux instance (PHP Version 7.3):
sudo yum install php73-php-pdo php73-php-mysqlnd
In iOS 6, the
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
is deprecated.
Use following code instead
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}
For iOS 6~8, the above method is still necessary, but you have to handle authorization.
_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
//[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
) {
// Will open an confirm dialog to get user's approval
[_locationManager requestWhenInUseAuthorization];
//[_locationManager requestAlwaysAuthorization];
} else {
[_locationManager startUpdatingLocation]; //Will update location immediately
}
This is the delegate method which handle user's authorization
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined: {
NSLog(@"User still thinking..");
} break;
case kCLAuthorizationStatusDenied: {
NSLog(@"User hates you");
} break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways: {
[_locationManager startUpdatingLocation]; //Will update location immediately
} break;
default:
break;
}
}
Insert a column, for instance a new A column. Then use this function;
="k"&B1
and copy it down.
Then you can hide the new column A if you need too.
It seems that Luiggi Mendoza
and joey rohan
both already answered this, but I think it can be clarified a little.
You can write it as a single if
statement:
if (inventory.contains("bread") && !inventory.contains("water")) {
// do something
}
This is an informational message only. It means nothing if your test scripts and chromedriver are on the same machine then it is possible to add the "whitelisted-ips" option .your test will run fine.However if you use chromedriver in a grid setup, this message will not appear
If you want to do multiple $ne
then do
db.users.find({name : {$nin : ["mary", "dick", "jane"]}})
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install yarn
brew install node
brew install watchman
brew tap AdoptOpenJDK/openjdk
brew cask install adoptopenjdk8
npm install -g react-native-cli
On CentOS Linux release 7.5.1804, we were able to make this work by editing /etc/selinux/config and changing the setting of SELINUX like so:
SELINUX=disabled
From slide 21 of http://www.slideshare.net/hadley/plyr-one-data-analytic-strategy:
(Hopefully it's clear that apply
corresponds to @Hadley's aaply
and aggregate
corresponds to @Hadley's ddply
etc. Slide 20 of the same slideshare will clarify if you don't get it from this image.)
(on the left is input, on the top is output)
you can use this module -> https://github.com/jiahut/ng.lodash
this is for lodash
so does underscore
You can acheive this using window.open()
method, passing _blank
as one of the parameter. You can refer the below links which has more information on this.
http://www.w3schools.com/jsref/met_win_open.asp
http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx
Hope this will help you.
You can use String.Join
. If you have a List<string>
then you can call ToArray
first:
List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());
In .NET 4 you don't need the ToArray
anymore, since there is an overload of String.Join
that takes an IEnumerable<string>
.
Results:
John, Anna, Monica
ActionBar actionBar = getSupportActionBar();
TextView tv = new TextView(getApplicationContext());
Typeface typeface = ResourcesCompat.getFont(this, R.font.monotype_corsiva);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView
tv.setLayoutParams(lp);
tv.setText("Your Text"); // ActionBar title text
tv.setTextSize(25);
tv.setTextColor(Color.WHITE);
tv.setTypeface(typeface, typeface.ITALIC);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(tv);
THIS IS A VERY SIMPLE PROBLEM
Here is the best method for solve this problem.
Step 1 : Login to your cPanel (http://website.com/cpanel OR http://cpanel.website.com).
Step 2 : SOFTWARE -> Select PHP Version
Step 3 : Change Your Current PHP version : 5.6
Step 3 : HIT 'Set as current' [ ENJOY ]
Tomcat is primarily an application server, which serves requests to custom-built Java servlets or JSP files on your server. It is usually used in conjunction with the Apache HTTP server (at least in my experience). Use it to manually process incoming requests.
The HTTP server, by itself, is best for serving up static content... html files, images, etc.
I just encountered the same problem myself.
... = reader["myYear"] as int?;
works and is clean.
It works with any type without an issue. If the result is DBNull, it returns null as the conversion fails.
For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.
Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4
columns_to_overwrite = ["column_1", "column_3"]
First delete the columns that you intend to replace...
original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)
... then re-insert the columns, but using the values that you intended to overwrite
original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]
If it returns nothing, then they match:
cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
ssh -i $HOME/.ssh/id_rsa localhost
I just want to update with another easy method.
You can also use forEach method.
var Cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"];
var result = [];
Cars.forEach((car, index) => car === 'Nano' ? result.push(index) : null)
The greps can be chained. For example:
tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"
My own tests conclusively show that br
tags do not like to be targeted for css.
But if you can add style then you can probably also add a scrip tag to the header of the page?
Link to an external .js
that does something like this:
function replaceLineBreaksWithHorizontalRulesInElement( element )
{
elems = element.getElementsByTagName( 'br' );
for ( var i = 0; i < elems.length; i ++ )
{
br = elems.item( i );
hr = document.createElement( 'hr' );
br.parentNode.replaceChild( hr, br );
}
}
So in short, it's not optimal, but here is my solution.
Here is simple way using HTML5 and jQuery:
1) include two JS file
<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>
2) include CSS to have cool buttons
<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />
3) create DIV or SPAN
<div class="demo" > </div>
4) write this code in your HTML page
$('.demo').ajaxupload({
url:'upload.php'
});
5) create you upload.php file to have PHP code to upload data.
You can download required JS file from here Here is Example
Its too cool and too fast And easy too! :)
You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.
Use a function to get rid off some limitation in the ~z
operator. It is especially useful with a for
loop:
@echo off
set size=0
call :filesize "C:\backup\20120714-0035\error.log"
echo file size is %size%
goto :eof
:: Set filesize of first argument in %size% variable, and return
:filesize
set size=%~z1
exit /b 0
In VSCode for Mac (0.10.6) I opened "Preferences -> User Settings" and placed the following code in the settings.json file
"editor.referenceInfos": false
The packages you installed introduced dependencies to version 5.2.3.0 dll's as user Bracher showed above. Microsoft.AspNet.WebApi.Cors is an example package. The path I take is to update the MVC project proir to any package installs:
Install-Package Microsoft.AspNet.Mvc -Version 5.2.3
@anothershrubery answer worked for me. I've made an enhancement using StringEntensions Class so I can easily convert any string at all in my program.
Method:
public static class StringExtensions
{
public static string ToUTF8(this string text)
{
return Encoding.UTF8.GetString(Encoding.Default.GetBytes(text));
}
}
Usage:
string myString = "Acción";
string strConverted = myString.ToUTF8();
Or simply:
string strConverted = "Acción".ToUTF8();
res_list = [x[0] for x in rows]
c.f. http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
For a discussion on why to prefer comprehensions over higher-order functions such as map
, go to http://www.artima.com/weblogs/viewpost.jsp?thread=98196.
@Html.Partial("nameOfPartial", Model)
Update
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter()) {
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
You can use this
var fs = require('fs');
var myCss = {
style : fs.readFileSync('./style.css','utf8');
};
app.get('/', function(req, res){
res.render('index.ejs', {
title: 'My Site',
myCss: myCss
});
});
put this on template
<%- myCss.style %>
just build style.css
<style>
body {
background-color: #D8D8D8;
color: #444;
}
</style>
I try this for some custom css. It works for me
I use AlertifyJS to style my dialogues.
alertify.alert('Ready!');_x000D_
alertify.YoutubeDialog || alertify.dialog('YoutubeDialog',function(){_x000D_
var iframe;_x000D_
return {_x000D_
// dialog constructor function, this will be called when the user calls alertify.YoutubeDialog(videoId)_x000D_
main:function(videoId){_x000D_
//set the videoId setting and return current instance for chaining._x000D_
return this.set({ _x000D_
'videoId': videoId_x000D_
});_x000D_
},_x000D_
// we only want to override two options (padding and overflow)._x000D_
setup:function(){_x000D_
return {_x000D_
options:{_x000D_
//disable both padding and overflow control._x000D_
padding : !1,_x000D_
overflow: !1,_x000D_
}_x000D_
};_x000D_
},_x000D_
// This will be called once the DOM is ready and will never be invoked again._x000D_
// Here we create the iframe to embed the video._x000D_
build:function(){ _x000D_
// create the iframe element_x000D_
iframe = document.createElement('iframe');_x000D_
iframe.frameBorder = "no";_x000D_
iframe.width = "100%";_x000D_
iframe.height = "100%";_x000D_
// add it to the dialog_x000D_
this.elements.content.appendChild(iframe);_x000D_
_x000D_
//give the dialog initial height (half the screen height)._x000D_
this.elements.body.style.minHeight = screen.height * .5 + 'px';_x000D_
},_x000D_
// dialog custom settings_x000D_
settings:{_x000D_
videoId:undefined_x000D_
},_x000D_
// listen and respond to changes in dialog settings._x000D_
settingUpdated:function(key, oldValue, newValue){_x000D_
switch(key){_x000D_
case 'videoId':_x000D_
iframe.src = "https://www.youtube.com/embed/" + newValue + "?enablejsapi=1";_x000D_
break; _x000D_
}_x000D_
},_x000D_
// listen to internal dialog events._x000D_
hooks:{_x000D_
// triggered when the dialog is closed, this is seperate from user defined onclose_x000D_
onclose: function(){_x000D_
iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');_x000D_
},_x000D_
// triggered when a dialog option gets update._x000D_
// warning! this will not be triggered for settings updates._x000D_
onupdate: function(option,oldValue, newValue){_x000D_
switch(option){_x000D_
case 'resizable':_x000D_
if(newValue){_x000D_
this.elements.content.removeAttribute('style');_x000D_
iframe && iframe.removeAttribute('style');_x000D_
}else{_x000D_
this.elements.content.style.minHeight = 'inherit';_x000D_
iframe && (iframe.style.minHeight = 'inherit');_x000D_
}_x000D_
break; _x000D_
} _x000D_
}_x000D_
}_x000D_
};_x000D_
});_x000D_
//show the dialog_x000D_
alertify.YoutubeDialog('GODhPuM5cEE').set({frameless:true});
_x000D_
<!-- JavaScript -->_x000D_
<script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>_x000D_
<!-- CSS -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css"/>_x000D_
<!-- Default theme -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css"/>_x000D_
<!-- Default theme -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.rtl.min.css"/>
_x000D_
I reproduced your issue on my Windows 8.1 system :
I got the same message you did. Thinking that it might be the environment variable, I did the following :
It came up successfully !
try this
in the php.ini file uncomment this
extension_dir = "./"
"remove semicolon"
You can make a new file under [.git\refs\remotes\origin] with name "HEAD" and put content "ref: refs/remotes/origin/master" to it. This should solve your problem.
It seems that clone from an empty repos will lead to this. Maybe the empty repos do not have HEAD because no commit object exist.
You can use the
git log --remotes --branches --oneline --decorate
to see the difference between each repository, while the "problem" one do not have "origin/HEAD"
Edit: Give a way using command line
You can also use git command line to do this, they have the same result
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master
clock() has a often a pretty lousy resolution. If you want to measure time at the millisecond level, one alternative is to use clock_gettime(), as explained in this question.
(Remember that you need to link with -lrt on Linux).
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
Hope this tip will save someone else's life. In my case the problem was that I ran out of memory, but only slightly, was hard to think about it. Wasted 3hrs on that. I recommend running:
sudo htop
or
sudo free -m
...along with running problematic requests on the server to see if your memory doesn't run out. And if it does like in my case, you need to create swap file (unless you already have one).
I have followed this tutorial to create swap file on Ubuntu Server 14.04 and it worked just fine: http://www.cyberciti.biz/faq/ubuntu-linux-create-add-swap-file/
require 'uri'
class Hash
def to_query_hash(key)
reduce({}) do |h, (k, v)|
new_key = key.nil? ? k : "#{key}[#{k}]"
v = Hash[v.each_with_index.to_a.map(&:reverse)] if v.is_a?(Array)
if v.is_a?(Hash)
h.merge!(v.to_query_hash(new_key))
else
h[new_key] = v
end
h
end
end
def to_query(key = nil)
URI.encode_www_form(to_query_hash(key))
end
end
2.4.2 :019 > {:a => "a", :b => "b"}.to_query_hash(nil)
=> {:a=>"a", :b=>"b"}
2.4.2 :020 > {:a => "a", :b => "b"}.to_query
=> "a=a&b=b"
2.4.2 :021 > {:a => "a", :b => ["c", "d", "e"]}.to_query_hash(nil)
=> {:a=>"a", "b[0]"=>"c", "b[1]"=>"d", "b[2]"=>"e"}
2.4.2 :022 > {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B0%5D=c&b%5B1%5D=d&b%5B2%5D=e"
Windows Firewall was creating this error for me. SMTP was trying to post to GMAIL at port 587. Adding port 587 to the Outbound rule [Outbound HTTP/SMTP/RDP] resolved the issue.
More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (
.keyCode
and.which
) are Deprecated.
node.addEventListener('keydown', function(event) {
const key = event.key; // "a", "1", "Shift", etc.
});
If you want to make sure only single characters are entered, check key.length === 1
, or that it is one of the characters you expect.
ENGINE=MEMORY
is not supported when table contains BLOB
/TEXT
columns
Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.
Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.
In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
End If
Next iCol
Next iRow
End Sub
To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:
Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need
From the Java API:
Document result = mongoDatabase.runCommand(new Document("buildInfo", 1));
String version = (String) result.get("version");
List<Integer> versionArray = (List<Integer>) result.get("versionArray");
I found the answer.
You can configure IE8 to display application/json in the browser window by updating the registry. There's no need for an external tool. I haven't tested this broadly, but it works with IE8 on Vista.
To use this, remember, all the usual caveats about updating the registry apply. Stop IE. Then, cut and paste the following into a file, by the name of json-ie.reg
.
Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00
Then double-click the .reg file. Restart IE. The new behavior you get when tickling a URL that returns a doc with Content-Type: application/json
or Content-Type: text/json
is like this:
What it does, why it works:
The 25336920-03F9-11cf-8FD0-00AA00686F13
is the CLSID for the "Browse in place" action. Basically this registry entry is telling IE that for docs that have a mime type of application/json, just view it in place. This won't affect any application/json documents downloaded via <script>
tags, or via XHR, and so on.
The CLSID and Encoding keys get the same values used for image/gif
, image/jpeg
, and text/html
.
This hint came from this site, and from Microsoft's article Handling MIME Types in Internet Explorer .
In FF, you don't need an external add-on either. You can just use the view-source:
pseudo-protocol. Enter a URL like this into the address bar:
view-source:http://myserver/MyUrl/That/emits/Application/json
This pseudo-protocol used to be supported in IE, also, until WinXP-sp2, when Microsoft disabled it for security reasons.
I've found a solution worked for me:
const handleDownload = async () => {
const req = await axios({
method: "get",
url: `/companies/${company.id}/data`,
responseType: "blob",
});
var blob = new Blob([req.data], {
type: req.headers["content-type"],
});
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = `report_${new Date().getTime()}.xlsx`;
link.click();
};
I just point a responseType: "blob"
This uses the function and waits for it to complete.
http://jsfiddle.net/SN2t6/118/
function getMeta(url){
var r = $.Deferred();
$('<img/>').attr('src', url).load(function(){
var s = {w:this.width, h:this.height};
r.resolve(s)
});
return r;
}
getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
alert(test.w + ' ' + test.h);
});
Based on First answer here is the complete image selection options:
Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
|PNG|*.PNG;*.png
|JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
|Bitmap(.BMP,.bmp)|*.BMP;*.bmp
|GIF|*.GIF;*.gif
|TIF|*.tif;*.tiff
|ICO|*.ico;*.ICO";
Program Debug Database file (pdb) is a file format by Microsoft for storing debugging information.
When you build a project using Visual Studio or command prompt the compiler creates these symbol files.
Check Microsoft Docs
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
This technique is now deprecated.
This used to tell Google how to index the page.
https://developers.google.com/webmasters/ajax-crawling/
This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value
, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value
to fetch a non-AJAX version of the contents.
You can provide a new testContext.xml in which the @Autowired
bean you define is of the type you need for your test.
In my mind I have to consider that the foo
folder is a stand-alone library. I might want to consider moving it to the Lib\site-packages
folder within a python installation. I might want to consider adding a foo.pth
file there.
I know it's a library since the ./programs/my_python_program.py
contains the following line:
from foo.tasks import my_function
So it doesn't matter that ./programs
is a sibling folder to ./foo
. It's the fact that my_python_program.py
is run as a script like this:
python ./programs/my_python_program.py
I used this and it worked !
mContext.getWindow().getDecorView().isShown() //boolean
1st Step: Add this content in pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2nd Step : Execute this command line by line.
cd /go/to/myApp
mvn clean
mvn compile
mvn package
java -cp target/myApp-0.0.1-SNAPSHOT.jar go.to.myApp.select.file.to.execute
.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))
UPDATE:
when I need sleep in async function I throw in
await new Promise(resolve => setTimeout(resolve, 1000))
Boost has something to help: the Boost.Iterator library.
More precisely this page: boost::iterator_adaptor.
What's very interesting is the Tutorial Example which shows a complete implementation, from scratch, for a custom type.
template <class Value> class node_iter : public boost::iterator_adaptor< node_iter<Value> // Derived , Value* // Base , boost::use_default // Value , boost::forward_traversal_tag // CategoryOrTraversal > { private: struct enabler {}; // a private type avoids misuse public: node_iter() : node_iter::iterator_adaptor_(0) {} explicit node_iter(Value* p) : node_iter::iterator_adaptor_(p) {} // iterator convertible to const_iterator, not vice-versa template <class OtherValue> node_iter( node_iter<OtherValue> const& other , typename boost::enable_if< boost::is_convertible<OtherValue*,Value*> , enabler >::type = enabler() ) : node_iter::iterator_adaptor_(other.base()) {} private: friend class boost::iterator_core_access; void increment() { this->base_reference() = this->base()->next(); } };
The main point, as has been cited already, is to use a single template implementation and typedef
it.
Indeed, the compiler doesn't know how to convert this anonymous type (the new { x.ServerName, x.ProcessID, x.Username }
part) to a PInfo object.
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new { x.ServerName, x.ProcessID, x.Username }).ToList();
This gives you a list of objects (of anonymous type) you can use afterwards, but you can't return that or pass that to another method.
If your PInfo object has the right properties, it can be like this :
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new PInfo
{
ServerName = x.ServerName,
ProcessID = x.ProcessID,
UserName = x.Username
}).ToList();
Assuming that PInfo has at least those three properties.
Both query allow you to fetch only the wanted columns, but using an existing type (like in the second query) allows you to send this data to other parts of your app.
In this case,
sb.setLength(sb.length() - 1);
is preferable as it just assign the last value to '\0'
whereas deleting last character does System.arraycopy
I have added line
$this->_productCollection->addAttributeToSelect('releasedate');
in
app/code/core/Mage/Catalog/Block/Product/List.php on line 95
in function _getProductCollection()
and then call it in
app/design/frontend/default/hellopress/template/catalog/product/list.phtml
By writing code
<div><?php echo $this->__('Release Date: %s', $this->dateFormat($_product->getReleasedate())) ?>
</div>
Now it is working in Magento 1.4.x
Limiting output to two lines of text is possible with CSS, if you set the line-height
and height
of the element, and set overflow:hidden;
:
#someDiv {
line-height: 1.5em;
height: 3em; /* height is 2x line-height, so two lines will display */
overflow: hidden; /* prevents extra lines from being visible */
}
Alternatively, you can use the CSS text-overflow
and white-space
properties to add ellipses, but this only appears to work for a single line.
#someDiv {
line-height: 1.5em;
height: 3em;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
width: 100%;
}
And a demo:
Achieving both multiple lines of text and ellipses appears to be the realm of javascript.
Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).
Either way works, I like to put that logic in the query so the report has to do less.
Not sure what your asking!
However
SELECT GETDATE()
Will get you the current date and time
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Will get you just the date with time set to 00:00:00
If you are still intrested in why this didn't work for you at first:
The reason you don't see changes you've made to the cell's style is because you do these changes before the form was shown, and so they are disregarded.
Changing cell styles in the events suggested here will do the job, but they are called multiple times causing your style changes to happen more times than you wish, and so aren't very efficient.
To solve this, either change the style after the point in your code in which the form is shown, or subscribe to the Shown event, and place your changes there (this is event is called significantly less than the other events suggested).
(function(con) {
var oDate = new Date();
var nHrs = oDate.getHours();
var nMin = oDate.getMinutes();
var nDate = oDate.getDate();
var nMnth = oDate.getMonth();
var nYear = oDate.getFullYear();
con.log(nDate + ' - ' + nMnth + ' - ' + nYear);
con.log(nHrs + ' : ' + nMin);
})(console);
This produces an output like:
30 - 8 - 2013
21 : 30
Perhaps you may refer documentation on Date object at MDN for more information
If you have start-stop-daemon
start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:
registered(X, Y) :-
X = ct101; X = ct102; X = ct103.
For a fuller explanation:
Actually I would advocate .profile
if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc
is fine, though.
The following bash script returns the Name of your current ec2 instance (the value of the "Name" tag). Modify TAG_NAME to your specific case.
TAG_NAME="Name"
INSTANCE_ID="`wget -qO- http://instance-data/latest/meta-data/instance-id`"
REGION="`wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
TAG_VALUE="`aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=$TAG_NAME" --region $REGION --output=text | cut -f5`"
To install the aws cli
sudo apt-get install python-pip -y
sudo pip install awscli
In case you use IAM instead of explicit credentials, use these IAM permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "ec2:DescribeTags"],
"Resource": ["*"]
}
]
}
The -fpermissive
flag causes the compiler to report some things that are actually errors (but are permitted by some compilers) as warnings, to permit code to compile even if it doesn't conform to the language rules. You really should fix the underlying problem. Post the smallest, compilable code sample that demonstrates the problem.
-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using-fpermissive
will allow some nonconforming code to compile.
The following query replace each and every a
character with a b
character.
UPDATE
YourTable
SET
Column1 = REPLACE(Column1,'a','b')
WHERE
Column1 LIKE '%a%'
This will not work on SQL server 2003.
Json Convert To C# Class = https://json2csharp.com/json-to-csharp
after the schema comes out
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string myJSON = client.DownloadString("http://xxx/xx/xx.json");
var valueSet = JsonConvert.DeserializeObject<Root>(myJSON);
The biggest one of our mistakes is that we can't match the class structure with json.
This connection will do the process automatically. You will code it later ;) = https://json2csharp.com/json-to-csharp
that's it.
DISCLAIMER: Please read comments below carefully, and I assume you've already read the accepted answer. As I said nearly 5 years ago:
if anyone has any comments to add for situations when this is NOT an adequate or optimal solution then please comment below
Right click on the database name.
Select Tasks ? Shrink ? Database
Then click OK!
I usually open the Windows Explorer directory containing the database files, so I can immediately see the effect.
I was actually quite surprised this worked! Normally I've used DBCC before, but I just tried that and it didn't shrink anything, so I tried the GUI (2005) and it worked great - freeing up 17 GB in 10 seconds
In Full recovery mode this might not work, so you have to either back up the log first, or change to Simple recovery, then shrink the file. [thanks @onupdatecascade for this]
--
PS: I appreciate what some have commented regarding the dangers of this, but in my environment I didn't have any issues doing this myself especially since I always do a full backup first. So please take into consideration what your environment is, and how this affects your backup strategy and job security before continuing. All I was doing was pointing people to a feature provided by Microsoft!
I was having the same issue, and for me it worked by simply concatenating https:${image.getAttribute('src')}
To expand one what CheeseConQueso is saying, here are the entire steps to update a view using PHPMyAdmin:
SHOW CREATE VIEW your_view_name
CREATE VIEW
... syntax) to make sure it runs as you expect it to.CREATE VIEW...
syntax).I hope that helps somebody. Special thanks to CheesConQueso for his/her insightful answer.
I would prefer a datepicker (and a input box with documented format as a fall-back) for an international site.
Date formats vary and are sometimes hard to read if you are now used to them. Too bad many people aren't comfortable with ISO 8601. :-(
Check out Datejs. Their built in formatters can do this: http://code.google.com/p/datejs/wiki/APIDocumentation#toString
It's a really handy library, especially if you are planning on doing other things with date objects.
Change the line into this
angular.forEach(values, function(value, key){
console.log(key + ': ' + value);
});
angular.forEach(values, function(value, key){
console.log(key + ': ' + value.Name);
});
Yeah, it's typically because it starts out as 'where 1 = 0', to force the statement to fail.
It's a more naive way of wrapping it up in a transaction and not committing it at the end, to test your query. (This is the preferred method).
It's a method on Exception
instances that prints the stack trace of the instance to System.err
.
It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.
Here's an example of how it might be used in practice:
try {
// ...
} catch (SomeException e) {
e.printStackTrace();
}
If you are using Kotlin
leftPanel.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
leftPanel.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
else {
leftPanel.viewTreeObserver.removeGlobalOnLayoutListener(this)
}
// Here you can get the size :)
leftThreshold = leftPanel.width
}
})
When you convert your string to a date you need to match the date mask to the format in the string. This includes a time element, which you need to remove with truncation:
select
p1.PA_VALUE as StartDate,
p2.PA_VALUE as EndDate
from WP_Work p
LEFT JOIN PARAMETER p1 on p1.WP_ID=p.WP_ID AND p1.NAME = 'StartDate'
LEFT JOIN PARAMETER p2 on p2.WP_ID=p.WP_ID AND p2.NAME = 'Date_To'
WHERE p.TYPE = 'EventManagement2'
AND trunc(TO_DATE(p1.PA_VALUE, 'DD-MM-YYYY HH24:MI')) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')
AND trunc(TO_DATE(p2.PA_VALUE, 'DD-MM-YYYY HH24:MI')) <= TO_DATE('26/10/2012', 'DD/MM/YYYY')
// .blur is triggered when element loses focus
$('#target').blur(function() {
alert($(this).val());
});
// To trigger manually use:
$('#target').blur();
You did not activate the virtual environment before using pip.
Try it with:
$(your venv path) . bin/activate
And then use pip -r requirements.txt on your main folder
When I was faced with a similar solution, I backtracked and found that the business request was actually for creating some form of rotation of the inventory being presented. In that case, there are much better options, which have answers from search engines like Solr, not data stores like MongoDB.
In short, with the requirement to "intelligently rotate" content, what we should do instead of a random number across all of the documents is to include a personal q score modifier. To implement this yourself, assuming a small population of users, you can store a document per user that has the productId, impression count, click-through count, last seen date, and whatever other factors the business finds as being meaningful to compute a q score modifier. When retrieving the set to display, typically you request more documents from the data store than requested by the end user, then apply the q score modifier, take the number of records requested by the end user, then randomize the page of results, a tiny set, so simply sort the documents in the application layer (in memory).
If the universe of users is too large, you can categorize users into behavior groups and index by behavior group rather than user.
If the universe of products is small enough, you can create an index per user.
I have found this technique to be much more efficient, but more importantly more effective in creating a relevant, worthwhile experience of using the software solution.
I see readytocloud.com is hosted on Apache 2.2.
There is a much simpler and more efficient way to redirect the non-www site to the www site in Apache.
Add the following rewrite rules to the Apache configs (either inside the virtual host or outside. It doesn't matter):
RewriteCond %{HTTP_HOST} ^readytocloud.com [NC]
RewriteRule ^/$ http://www.readytocloud.com/ [R=301,L]
Or, the following rewrite rules if you want a 1-to-1 mapping of URLs from the non-www site to the www site:
RewriteCond %{HTTP_HOST} ^readytocloud.com [NC]
RewriteRule (.*) http://www.readytocloud.com$1 [R=301,L]
Note, the mod_rewrite module needs to be loaded for this to work. Luckily readytocloud.com is runing on a CentOS box, which by default loads mod_rewrite.
We have a client server running Apache 2.2 with just under 3,000 domains and nearly 4,000 redirects, however, the load on the server hover around 0.10 - 0.20.
You could use a simple regular expression to assert that the id only contains allowed characters, like so:
if(id.match(/^[0-9a-zA-Z]{1,16}$/)){
//The id is fine
}
else{
//The id is illegal
}
My example allows only alphanumerical characters, and strings of length 1 to 16, you should change it to match the type of ids that you use.
By the way, at line 6, the value property is missing a pair of quotes, an easy mistake to make when you quote on two levels.
I can't see your actual data flow, depending on context this check may not at all be needed, or it may not be enough. In order to make a proper security review we would need more information.
In general, about built in escape or sanitize functions, don't trust them blindly. You need to know exactly what they do, and you need to establish that that is actually what you need. If it is not what you need, the code your own, most of the time a simple whitelisting regex like the one I gave you works just fine.
use OutputStream instead of FileWriter to set encoding type
// file is your File object where you want to write you data
OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(json); // json is your data
outputStreamWriter.flush();
outputStreamWriter.close();
To get more specific version number information with major and minor versions separated:
NSString* versionString = [UIDevice currentDevice].systemVersion;
NSArray* vN = [versionString componentsSeparatedByString:@"."];
The array vN
will contain the major and minor versions as strings, but if you want to do comparisons, version numbers should be stored as numbers (ints). You can add this code to store them in the C-array* versionNumbers
:
int versionNumbers[vN.count];
for (int i = 0; i < sizeof(versionNumbers)/sizeof(versionNumbers[0]); i++)
versionNumbers[i] = [[vN objectAtIndex:i] integerValue];
* C-arrays used here for more concise syntax.
We can resolve this warning by adding this code below in Strings.xml and activity_main.xml
<string name="imgDescription">Background Picture</string>
you image will be like that:
<ImageView
android:id="@+id/imageView2"
android:lay`enter code hereout_width="0dp"
android:layout_height="wrap_content"
android:contentDescription="@string/imgDescription"
app:layout_editor_absoluteX="0dp"
app:layout_editor_absoluteY="0dp"
app:srcCompat="@drawable/background1"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
android:contentDescription="@string/imgDescription"
Strings.xml
<resources>
<string name="app_name">Saini_Browser</string>
<string name="SainiBrowser">textView2</string>
<string name="imgDescription">BackGround Picture</string>
</resources>
To add to the other answers in Android, Ems size, can, by default, vary in each language and input.
It means that if you want to set a minimum width to a text field, defined by number of chars, you have to calculate the Ems properly and set it, according to your typeface and font size with the Ems attribute.
To those of you struggle with this, you can calculate the hint size yourself to avoid messing with Ems:
val tf = TextField()
val layout = TextInputLayout()
val hint = "Hint"
val measureText = tf.paint.measureText(hint).toInt()
tf.width = tf.paddingLeft + tf.paddingRight + measureText.toInt()
layout.hint = hint
In general don't expose List<T>
publicly, and don't provide setters for collection properties. Also, you may want to copy the elements of the passed list (as shown below). Otherwise changes to the original list will affect the Human instance.
public class Human
{
public Human()
{
}
public Human(IEnumerable<ContactNumber> contactNumbers)
{
if (contactNumbers == null)
{
throw new ArgumentNullException("contactNumbers");
}
_contactNumbers.AddRange(contactNumbers);
}
public IEnumerable<ContactNumber> ContactNumbers
{
get { return _contactNumbers; }
}
private readonly List<ContactNumber> _contactNumbers = new List<ContactNumber>();
}
Another option is to use the list constructor that takes a collection and remove the field initializer.
There are static libraries (LIB) and dynamic libraries (DLL) - but note that .LIB files can be either static libraries (containing object files) or import libraries (containing symbols to allow the linker to link to a DLL).
Libraries are used because you may have code that you want to use in many programs. For example if you write a function that counts the number of characters in a string, that function will be useful in lots of programs. Once you get that function working correctly you don't want to have to recompile the code every time you use it, so you put the executable code for that function in a library, and the linker can extract and insert the compiled code into your program. Static libraries are sometimes called 'archives' for this reason.
Dynamic libraries take this one step further. It seems wasteful to have multiple copies of the library functions taking up space in each of the programs. Why can't they all share one copy of the function? This is what dynamic libraries are for. Rather than building the library code into your program when it is compiled, it can be run by mapping it into your program as it is loaded into memory. Multiple programs running at the same time that use the same functions can all share one copy, saving memory. In fact, you can load dynamic libraries only as needed, depending on the path through your code. No point in having the printer routines taking up memory if you aren't doing any printing. On the other hand, this means you have to have a copy of the dynamic library installed on every machine your program runs on. This creates its own set of problems.
As an example, almost every program written in 'C' will need functions from a library called the 'C runtime library, though few programs will need all of the functions. The C runtime comes in both static and dynamic versions, so you can determine which version your program uses depending on particular needs.
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention.
Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
.
So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.
But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like
SELECT [columns] FROM table WHERE yearmonth = '200801'
instead of
SELECT [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')
Press Back when you get the notification and then Next. This time it will find the JDK
.
I tend to prefer passing a URL to psql:
psql "postgresql://$DB_USER:$DB_PWD@$DB_SERVER/$DB_NAME"
This gives me the freedom to name my environment variables as I wish and avoids creating unnecessary files.
This requires libpq
. The documentation can be found here.
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
You can simply get the text in editText by applying below code:
EditText editText=(EditText)findViewById(R.id.vnosZadeve);
String text=editText.getText().toString();
then you can toast string text!
Happy coding!
If you wanna find just the word like 'are' in "How are you?" and not like 'are' in 'hare'
$word=" are ";
$str="How are you?";
if(strpos($word,$str) !== false){
echo 1;
}
Starting with Sql Server 2012: string concatenation function CONCAT
converts to string implicitly. Therefore, another option is
SELECT Id AS 'PatientId',
CONCAT(ParentId,'') AS 'ParentId'
FROM Patients
CONCAT
converts null
values to empty strings.
Some will consider this hacky, because it merely exploits a side effect of a function while the function itself isn't required for the task in hand.
SELECT COUNT( * )
FROM agents
HAVING COUNT(*)>3;
See more below link:
I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.
<div class="form-group">
<div class="col-sm-12">
<label for="user_login">Username</label>
<input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
</div>
</div>
Check out this demo.
Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.
<form action="#" method="post" class="form-horizontal">
Check out this demo.
When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.
While currently not possible with CSS, there is a proposal to enable this functionality called Cascading Attribute Sheets.
String split[], docStr = null;
Document textAreaDoc = (Document)e.getDocument();
try {
docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
split = docStr.split("\n");
In my case it was an improperly named XML file that caused my R file not to rebuild. This did not show up in the package explorer, but it was shown in the LogCat. Look out for any warnings there about your res files. No matter how many times you clean your project, the R file will not rebuild until those errors are taken care of.
It depends on the jQuery selector that you use. Since id
should be unique within the DOM, the first one would be simple:
$('#Comanda').hide();
The second one might require something more, depending on the other elements and how to uniquely identify it. If the name
of that particular input
is unique, then this would work:
$('input[name="Vizualizeaza"]').hide();
Via which interface? Using the REST interface, you just send a delete:
DELETE /ObjectName HTTP/1.1
Host: BucketName.s3.amazonaws.com
Date: date
Content-Length: length
Authorization: signatureValue
Via the SOAP interface:
<DeleteObject xmlns="http://doc.s3.amazonaws.com/2006-03-01">
<Bucket>quotes</Bucket>
<Key>Nelson</Key>
<AWSAccessKeyId> 1D9FVRAYCP1VJEXAMPLE=</AWSAccessKeyId>
<Timestamp>2006-03-01T12:00:00.183Z</Timestamp>
<Signature>Iuyz3d3P0aTou39dzbqaEXAMPLE=</Signature>
</DeleteObject>
If you're using a Python library like boto, it should expose a "delete" feature, like delete_key()
.
There are several reasons you could have problems loading from lib - see here for details - http://www.williambharding.com/blog/technology/rails-3-autoload-modules-and-classes-in-production/
Session.Clear();
Reset your email to the config globally:
git config --global user.email [email protected]
Now reset the author of your commit without edit required:
git commit --amend --reset-author --no-edit
In the end I had had to make changes to the content of the page behind the modal screen to ensure that it never got long enough to scroll the page.
Once I did that, the problems I encountered when applying position: absolute
to the dialog were resolved as the user could no longer scroll down the page.
I think the confusing aspect of this is the fact that BootStrap 3 is a mobile first responsive system and fails to explain how this affects the col-xx-n hierarchy in that part of the Bootstrap documentation. This makes you wonder what happens on smaller devices if you choose a value for larger devices and makes you wonder if there is a need to specify multiple values. (You don't)
I would attempt to clarify this by stating that... Lower grain types (xs, sm) attempt retain layout appearance on smaller screens and larger types (md,lg) will display correctly only on larger screens but will wrap columns on smaller devices. The values quoted in previous examples refer to the threshold as which bootstrap degrades the appearance to fit the available screen estate.
What this means in practice is that if you make the columns col-xs-n then they will retain correct appearance even on very small screens, until the window drops to a size that is so restrictive that the page cannot be displayed correctly. This should mean that devices that have a width of 768px or less should show your table as you designed it rather than in degraded (single or wrapped column form). Obviously this still depends on the content of the columns and that's the whole point. If the page attempts to display multiple columns of large data, side by side on a small screen then the columns will naturally wrap in a horrible way if you did not account for it. Therefore, depending on the data within the columns you can decide the point at which the layout is sacificed to display the content adequately.
e.g. If your page contains three col-sm-n columns bootstrap would wrap the columns into rows when the page width drops below 992px. This means that the data is still visible but will require vertical scrolling to view it. If you do not want your layout to degrade, choose xs (as long as your data can be adequately displayed on a lower resolution device in three columns)
If the horizontal position of the data is important then you should try to choose lower granularity values to retain the visual nature. If the position is less important but the page must be visible on all devices then a higher value should be used.
If you choose col-lg-n then the columns will display correctly until the screen width drops below the xs threshold of 1200px.
@Michael Lockwood - you don't need to use the keyword "CALL" anywhere. You just need to mention the procedure call directly.
That is
Begin
proc1(input1, input2);
end;
/
instead of
Begin
call proc1(input1, input2);
end;
/
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
Since your server already includes the sites-enabled
folder ( notice the include /etc/nginx/sites-enabled/*
line ), then you better use that.
Create a file inside /etc/nginx/sites-available
and call it whatever you want, I'll call it django
since it's a djanog server
sudo touch /etc/nginx/sites-available/django
Then create a symlink that points to it
sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
Then edit that file with whatever file editor you use, vim
or nano
or whatever and create the server inside it
server {
# hostname or ip or multiple separated by spaces
server_name localhost example.com 192.168.1.1; #change to your setting
location / {
root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
}
}
Restart or reload nginx settings
sudo service nginx reload
Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server
To set parameters to your HttpPostRequest
you can use BasicNameValuePair
, something like this :
HttpClient httpclient;
HttpPost httpPost;
ArrayList<NameValuePair> postParameters;
httpclient = new DefaultHttpClient();
httpPost = new HttpPost("your login link");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
I did a test finding a case-insensitive match of a string. I have a Vector of 150,000 objects all with a String as one field and wanted to find the subset which matched a string. I tried three methods:
Convert all to lower case
for (SongInformation song: songs) {
if (song.artist.toLowerCase().indexOf(pattern.toLowercase() > -1) {
...
}
}
Use the String matches() method
for (SongInformation song: songs) {
if (song.artist.matches("(?i).*" + pattern + ".*")) {
...
}
}
Use regular expressions
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("");
for (SongInformation song: songs) {
m.reset(song.artist);
if (m.find()) {
...
}
}
Timing results are:
No attempted match: 20 msecs
To lower match: 182 msecs
String matches: 278 msecs
Regular expression: 65 msecs
The regular expression looks to be the fastest for this use case.
I have created a simple program for this and your question helped me complete the solution... I added one more feature and few configurations. In case you want to add a specific character/ string after every few lines (configurable). Please go through the notes. I have added the code files : https://github.com/mohitsharma779/FileSplit