If you installed visual studio with Xamarin/mobile development support, you'll have a java install here C:\Program Files\Android\jdk\microsoft_dist_openjdk_{version}\bin\
, as was my case.
If you are completely sure HEAD is the good state:
git branch -f master HEAD
git checkout master
You probably can't push to origin, since your master has diverged from origin. If you are sure no one else is using the repo, you can force-push:
git push -f
Most useful if you are on a feature branch no one else is using.
what's the problem with:
field like "*AA*" and field not like "*BB*"
it should be working.
Could you post some example of your data?
Should you want to add a new column (say 'count_column') containing the groups' counts into the dataframe:
df.count_column=df.groupby(['col5','col2']).col5.transform('count')
(I picked 'col5' as it contains no nan)
It is not good practice to save the value that is returned from JSON.stringify(userData)
to a cookie; it can lead to a bug in some browsers.
Before using it, you should convert it to base64 (using btoa
), and when reading it, convert from base64 (using atob
).
val = JSON.stringify(userData)
val = btoa(val)
write_cookie(val)
In python this work for me
self.set_your_value = "your value"
def your_method_name(self):
self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`
my solution:
MOVE:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
COPY:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.
This answer is for docker-compose version 2 and it also works on version 3
You can still access the data when you use depends_on.
If you look at docker docs Docker Compose and Django, you still can access the database like this:
version: '2'
services:
db:
image: postgres
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
depends_on:
- db
What is the difference between links and depends_on?
links:
When you create a container for a database, for example:
docker run -d --name=test-mysql --env="MYSQL_ROOT_PASSWORD=mypassword" -P mysql
docker inspect d54cf8a0fb98 |grep HostPort
And you may find
"HostPort": "32777"
This means you can connect the database from your localhost port 32777 (3306 in container) but this port will change every time you restart or remove the container. So you can use links to make sure you will always connect to the database and don't have to know which port it is.
web:
links:
- db
depends_on:
I found a nice blog from Giorgio Ferraris Docker-compose.yml: from V1 to V2
When docker-compose executes V2 files, it will automatically build a network between all of the containers defined in the file, and every container will be immediately able to refer to the others just using the names defined in the docker-compose.yml file.
And
So we don’t need links anymore; links were used to start a network communication between our db container and our web-server container, but this is already done by docker-compose
Express dependency between services, which has two effects:
docker-compose up
will start services in dependency order. In the following example, db and redis will be started before web.docker-compose up SERVICE
will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.Simple example:
version: '2'
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
Note: depends_on will not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.
//For proper line spacing
NSString *text1 = @"Hello";
NSString *text2 = @"\nWorld";
UIFont *text1Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:10];
NSMutableAttributedString *attributedString1 =
[[NSMutableAttributedString alloc] initWithString:text1 attributes:@{ NSFontAttributeName : text1Font }];
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setAlignment:NSTextAlignmentCenter];
[paragraphStyle1 setLineSpacing:4];
[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [attributedString1 length])];
UIFont *text2Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:16];
NSMutableAttributedString *attributedString2 =
[[NSMutableAttributedString alloc] initWithString:text2 attributes:@{NSFontAttributeName : text2Font }];
NSMutableParagraphStyle *paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle2 setLineSpacing:4];
[paragraphStyle2 setAlignment:NSTextAlignmentCenter];
[attributedString2 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle2 range:NSMakeRange(0, [attributedString2 length])];
[attributedString1 appendAttributedString:attributedString2];
If you want to do this in jQuery instead of CSS, you basically follow the same process.
Assuming you have some <div id="target"></div>
, you can use the following code:
$("#target").hover(function() {
$(this).css('cursor','pointer');
}, function() {
$(this).css('cursor','auto');
});
and that should do it.
.queue()
and .dequeue()
Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using jQuery.data()
. They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue()
, and you remove (by calling) the functions using .dequeue()
.
To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .delay()
:
$.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
};
fx
The default queue in jQuery is fx
. The default queue has some special properties that are not shared with other queues.
$(elem).queue(function(){});
the fx
queue will automatically dequeue
the next function and run it if the queue hasn't started. dequeue()
a function from the fx
queue, it will unshift()
(push into the first location of the array) the string "inprogress"
- which flags that the queue is currently being run.fx
queue is used by .animate()
and all functions that call it by default.NOTE: If you are using a custom queue, you must manually .dequeue()
the functions, they will not auto start!
You can retrieve a reference to a jQuery queue by calling .queue()
without a function argument. You can use the method if you want to see how many items are in the queue. You can use push
, pop
, unshift
, shift
to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue()
function.
Quick Examples:
// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop();
// insert it at the beginning:
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3));
fx
) queue example:$(function() {
// lets do something with google maps:
var $map = $("#map_canvas");
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map($map[0], myOptions);
var resized = function() {
// simple animation callback - let maps know we resized
google.maps.event.trigger(map, 'resize');
};
// wait 2 seconds
$map.delay(2000);
// resize the div:
$map.animate({
width: 250,
height: 250,
marginLeft: 250,
marginTop:250
}, resized);
// geocode something
$map.queue(function(next) {
// find stackoverflow's whois address:
geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);
function handleResponse(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
map.setZoom(13);
map.setCenter(location);
new google.maps.Marker({ map: map, position: location });
}
// geocoder result returned, continue with animations:
next();
}
});
// after we find stack overflow, wait 3 more seconds
$map.delay(3000);
// and resize the map again
$map.animate({
width: 500,
height: 500,
marginLeft:0,
marginTop: 0
}, resized);
});
var theQueue = $({}); // jQuery on an empty object - a perfect queue holder
$.each([1,2,3],function(i, num) {
// lets add some really simple functions to a queue:
theQueue.queue('alerts', function(next) {
// show something, and if they hit "yes", run the next function.
if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
next();
}
});
});
// create a button to run the queue:
$("<button>", {
text: 'Run Queue',
click: function() {
theQueue.dequeue('alerts');
}
}).appendTo('body');
// create a button to show the length:
$("<button>", {
text: 'Show Length',
click: function() {
alert(theQueue.queue('alerts').length);
}
}).appendTo('body');
I developed an $.ajaxQueue()
plugin that uses the $.Deferred
, .queue()
, and $.ajax()
to also pass back a promise that is resolved when the request completes. Another version of $.ajaxQueue
that still works in 1.4 is posted on my answer to Sequencing Ajax Requests
/*
* jQuery.ajaxQueue - A queue for ajax requests
*
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/
(function($) {
// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});
$.ajaxQueue = function( ajaxOpts ) {
var jqXHR,
dfd = $.Deferred(),
promise = dfd.promise();
// queue our ajax request
ajaxQueue.queue( doRequest );
// add the abort method
promise.abort = function( statusText ) {
// proxy abort to the jqXHR if it is active
if ( jqXHR ) {
return jqXHR.abort( statusText );
}
// if there wasn't already a jqXHR we need to remove from queue
var queue = ajaxQueue.queue(),
index = $.inArray( doRequest, queue );
if ( index > -1 ) {
queue.splice( index, 1 );
}
// and then reject the deferred
dfd.rejectWith( ajaxOpts.context || ajaxOpts,
[ promise, statusText, "" ] );
return promise;
};
// run the actual query
function doRequest( next ) {
jqXHR = $.ajax( ajaxOpts )
.done( dfd.resolve )
.fail( dfd.reject )
.then( next, next );
}
return promise;
};
})(jQuery);
I have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.
A today extension would be the most fitting solution.
Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.
Please be aware that although tables are discouraged as a primary means of page layout, they still have their place. Tables can and should be used when and where appropriate and until some of the more popular browsers (ahem, IE, ahem) become more standards compliant, tables are sometimes the best route to a solution.
private String convertFrom(String lines, String from, String to) {
ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
CharBuffer cb = Charset.forName(to).decode(bb);
return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};
The following code can help you to understand some real world use of predicates (Combined with named iterators).
namespace Predicate
{
class Person
{
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
foreach (Person person in OlderThan(18))
{
Console.WriteLine(person.Age);
}
}
static IEnumerable<Person> OlderThan(int age)
{
Predicate<Person> isOld = x => x.Age > age;
Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };
foreach (Person person in persons)
if (isOld(person)) yield return person;
}
}
}
Use the git commit
command without any flags. The configured editor will open (Vim in this case):
To start typing press the INSERT key on your keyboard, then in insert mode create a better commit with description how do you want. For example:
Once you have written all that you need, to returns to git, first you should exit insert mode, for that press ESC. Now close the Vim editor with save changes by typing on the keyboard :wq
(w - write, q - quit):
and press ENTER.
On GitHub this commit will looks like this:
As a commit editor you can use VS Code:
git config --global core.editor "code --wait"
From VS Code docs website: VS Code as Git editor
This is a solution that uses gawk. It's something I find I need to use often so I created a function for it
function regex1 { gawk 'match($0,/'$1'/, ary) {print ary['${2:-'1'}']}'; }
to use just do
$ echo 'hello world' | regex1 'hello\s(.*)'
world
Try this
public ActionResult CreatePerson(string Enc)
window.location = '@Url.Action("CreatePerson", "Person", new { Enc = "id", actionType = "Disable" })'.replace("id", id).replace("&", "&");
you will get the id inside the Enc string.
use this code
Data Source=.;Initial Catalog=master;Integrated Security=True
grep
will print any lines matching the pattern you provide. If you only want to print the part of the line that matches the pattern, you can pass the -o option:
-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Like this:
echo 'Here is a line mentioning 99% somewhere' | grep -o '[0-9]+'
The issue has been resolved while installation of the maven settings is provided as External in Eclipse. The navigation settings are Window --> Preferences --> Installations. Select the External as installation Type, provide the Installation home and name and click on Finish. Finally select this as default installations.
Default value doesn't mean default value of data type .Here default value mean value defined at the time of defining function. we have to declare default value of variable while defining variable in function.
Look into creating Applets if you want to make a website with Java. You most likely wont need to use anything but regular Java, unless you want something more specialized.
.sort()
, in pymongo, takes key
and direction
as parameters.
So if you want to sort by, let's say, id
then you should .sort("_id", 1)
For multiple fields:
.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])
You can declare the array in C++ in these type of ways.
If you know the array size then you should declare the array for:
integer: int myArray[array_size];
Double: double myArray[array_size];
Char and string : char myStringArray[array_size];
The difference between char and string is as follows
char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";
If you don't know the size of array then you should leave the array blank like following.
integer: int myArray[array_size];
Double: double myArray[array_size];
Example:
How to transfer putty configuration and session configuration from one user account to another e.g. when created a new account and want to use the putty sessions/configurations from the old account
Process:
- Export registry key from old account into a file
- Import registry key from file into new account
Export reg key: (from OLD account)
Import reg key: (into NEW account)
Login into NEW account e.g. tom
Open normal 'command prompt' (NOT admin !)
Type 'regedit'
Select 'Import' from the menu
Select the registry file to import e.g. 'puttyconfig.reg'
Done
Note:
Do not use an 'admin command prompt' as settings are located under '[HKEY_CURRENT_USER...] 'and regedit would run as admin and show that section for the admin-user rather then for the user to transfer from and/or to.
Based on @seb's solution, I created a subclass of RecyclerView.Adapter that supports an arbitrary number of headers and footers.
https://gist.github.com/mheras/0908873267def75dc746
Although it seems to be a solution, I also think this thing should be managed by the LayoutManager. Unfortunately, I need it now and I don't have time to implement a StaggeredGridLayoutManager from scratch (nor even extend from it).
I'm still testing it, but you can try it out if you want. Please let me know if you find any issues with it.
Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:
>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0
# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)
Note that different timezones have impact on results, e.g. my current TZ/DST returns:
>>> time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h
therefore one should consider normalizing to UTC by using UTC versions of the functions.
Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.
References:
You can also do it by toggling between display: block on hover and display:none without hover to produce the effect.
Initialize it first
MainActivity mActivity= new MainActivity();
Then you can continue
mActivity.startChronometer();
I think this syntax has not been mentionned yet (in the case you want a method without arguments) :
class Clazz {
static <T> T doIt() {
// shake that booty
}
}
And the call :
String str = Clazz.<String>doIt();
Hope this help someone.
As you're using Python 3, there is no urllib module anymore. It has been split into several modules.
This would be equivalent to urlretrieve:
import urllib.request
data = urllib.request.urlretrieve("http://...")
urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.
Basically:
urlretrieve
saves the file to a temporary file and returns a tuple (filename, headers)
urlopen
returns a Request
object whose read
method returns a bytestring containing the file contentsConverting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.
Try this.
<Directory "/home/userx/Downloads">
Options +Indexes
AllowOverride all
Order allow,deny
Allow from all
Require all granted
</Directory>
If that doesn't work, you probably have 'deny indexes' somewhere that's overriding your config.
This worked for me on my MAC - 2020
Go to directory containing adb:
cd ~/Library/Android/sdk/platform-tools/
Run adb command to list all services
./adb shell dumpsys activity services
In Raspbian, there is even no need to mention python2.7
. Indeed this is best way to install pip if python version in less then 2.7.9.
curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python
Thanks to @tal-weiss
This is what I cooked. It returns a tuple of a map and a list. List is for input, like input file names. Map is for switches/options.
val args = "--sw1 1 input_1 --sw2 --sw3 2 input_2 --sw4".split(" ")
val (options, inputs) = OptParser.parse(args)
will return
options: Map[Symbol,Any] = Map('sw1 -> 1, 'sw2 -> true, 'sw3 -> 2, 'sw4 -> true)
inputs: List[Symbol] = List('input_1, 'input_2)
Switches can be "--t" which x will be set to true, or "--x 10" which x will be set to "10". Everything else will end up in list.
object OptParser {
val map: Map[Symbol, Any] = Map()
val list: List[Symbol] = List()
def parse(args: Array[String]): (Map[Symbol, Any], List[Symbol]) = _parse(map, list, args.toList)
private [this] def _parse(map: Map[Symbol, Any], list: List[Symbol], args: List[String]): (Map[Symbol, Any], List[Symbol]) = {
args match {
case Nil => (map, list)
case arg :: value :: tail if (arg.startsWith("--") && !value.startsWith("--")) => _parse(map ++ Map(Symbol(arg.substring(2)) -> value), list, tail)
case arg :: tail if (arg.startsWith("--")) => _parse(map ++ Map(Symbol(arg.substring(2)) -> true), list, tail)
case opt :: tail => _parse(map, list :+ Symbol(opt), tail)
}
}
}
If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded
data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data
then contains the json data is php array.
php://input
is a so called wrapper.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
Javascript's inheritance is prototype based, so you extend the prototypes of objects such as Date, Math, and even your own custom ones.
Date.prototype.lol = function() {
alert('hi');
};
( new Date ).lol() // alert message
In the snippet above, I define a method for all Date objects ( already existing ones and all new ones ).
extend
is usually a high level function that copies the prototype of a new subclass that you want to extend from the base class.
So you can do something like:
extend( Fighter, Human )
And the Fighter
constructor/object will inherit the prototype of Human
, so if you define methods such as live
and die
on Human
then Fighter
will also inherit those.
Updated Clarification:
"high level function" meaning .extend isn't built-in but often provided by a library such as jQuery or Prototype.
If you simply want a Uri for a method that has a route annotation, the following worked for me.
Noting the Route name of the target action, get the relative URL using the controller's URL property as follows:
var routeUrl = Url.RouteUrl("*Route Name Here*", new { *Route parameters here* });
var absUrl = string.Format("{0}://{1}{2}", Request.Scheme,
Request.Host, routeUrl);
var uri = new Uri(absUrl, UriKind.Absolute)
[Produces("application/json")]
[Route("api/Children")]
public class ChildrenController : Controller
{
private readonly ApplicationDbContext _context;
public ChildrenController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/Children
[HttpGet]
public IEnumerable<Child> GetChild()
{
return _context.Child;
}
[HttpGet("uris")]
public IEnumerable<Uri> GetChildUris()
{
return from c in _context.Child
select
new Uri(
$"{Request.Scheme}://{Request.Host}{Url.RouteUrl("GetChildRoute", new { id = c.ChildId })}",
UriKind.Absolute);
}
// GET: api/Children/5
[HttpGet("{id}", Name = "GetChildRoute")]
public IActionResult GetChild([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
Child child = _context.Child.Single(m => m.ChildId == id);
if (child == null)
{
return HttpNotFound();
}
return Ok(child);
}
}
I got the solution
download Xuggler 5.4 here
and some more jar to make it work...
commons-cli-1.1.jar
commons-lang-2.1.jar
logback-classic-1.0.0.jar
logback-core-1.0.0.jar
slf4j-api-1.6.4.jar
You can check which dependencies xuggler needs from here:
Add this jars and xuggle-xuggler-5.4.jar to your project's build path and it s ready.
**version numbers may change
Here is a read/write example. The with statements insure the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm
import sys
fIn = 'symbolsIn.csv'
fOut = 'symbolsOut.csv'
try:
with open(fIn, 'r') as f:
file_content = f.read()
print "read file " + fIn
if not file_content:
print "no data in file " + fIn
file_content = "name,phone,address\n"
with open(fOut, 'w') as dest:
dest.write(file_content)
print "wrote file " + fOut
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except: #handle other exceptions such as attribute errors
print "Unexpected error:", sys.exc_info()[0]
print "done"
In my case, some broken url found in layout.
You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.
Usually, you can login as the postgres user:
Open a Terminal and do sudo su postgres
.
Now, after entering your admin password, you are able to launch psql
and do
CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';
This creates a new admin user. If you want to list the existing users, you could also do
\du
to list all users and then
ALTER USER yourusername WITH PASSWORD 'yournewpass';
create table demo ( id int, ts timestamp )
insert into demo(id,ts) values (1, DEFAULT)
Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
From o In ords.DefaultIfEmpty _
Select New With {e.FirstName, e.LastName, .Order = o}
ObjectDumper.Write(q) End Sub
Try replacing your meta tag with this below:
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />
Or in addition to what you have, you should add http://*
to both style-src
and script-src
as seen above added after 'self'.
If your server is including the Content-Security-Policy
header, the header will override the meta.
Run the following command to remove the images with docker rmi
docker images --filter "dangling=true"
A StringBuffer
or its younger and faster brother StringBuilder
is preferred whenever you're going do to a lot of string concatenations in flavor of
string += newString;
or equivalently
string = string + newString;
because the above constructs implicitly creates new string everytime which will be a huge performance and drop. A StringBuffer
/ StringBuilder
is under the hoods best to be compared with a dynamically expansible List<Character>
.
you can use this too
.parent:hover * {
/* ... */
}
_x000D_
While this question is old, the answers aren't proper. Context menus have their own events on DataGridView. There is an event for row context menu and cell context menu.
The reason for which these answers aren't proper is they do not account for different operation schemes. Accessibility options, remote connections, or Metro/Mono/Web/WPF porting might not work and keyboard shortcuts will down right fail (Shift+F10 or Context Menu key).
Cell selection on right mouse click has to be handled manually. Showing the context menu does not need to be handled as this is handled by the UI.
This completely mimics the approach used by Microsoft Excel. If a cell is part of a selected range, the cell selection doesn't change and neither does CurrentCell
. If it isn't, the old range is cleared and the cell is selected and becomes CurrentCell
.
If you are unclear on this, CurrentCell
is where the keyboard has focus when you press the arrow keys. Selected
is whether it is part of SelectedCells
. The context menu will show on right click as handled by the UI.
private void dgvAccount_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex != -1 && e.RowIndex != -1 && e.Button == System.Windows.Forms.MouseButtons.Right)
{
DataGridViewCell c = (sender as DataGridView)[e.ColumnIndex, e.RowIndex];
if (!c.Selected)
{
c.DataGridView.ClearSelection();
c.DataGridView.CurrentCell = c;
c.Selected = true;
}
}
}
Keyboard shortcuts do not show the context menu by default, so we have to add them in.
private void dgvAccount_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.F10 && e.Shift) || e.KeyCode == Keys.Apps)
{
e.SuppressKeyPress = true;
DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
if (currentCell != null)
{
ContextMenuStrip cms = currentCell.ContextMenuStrip;
if (cms != null)
{
Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
Point p = new Point(r.X + r.Width, r.Y + r.Height);
cms.Show(currentCell.DataGridView, p);
}
}
}
}
I've reworked this code to work statically, so you can copy and paste them into any event.
The key is to use CellContextMenuStripNeeded
since this will give you the context menu.
Here's an example using CellContextMenuStripNeeded
where you can specify which context menu to show if you want to have different ones per row.
In this context MultiSelect
is True
and SelectionMode
is FullRowSelect
. This is just for the example and not a limitation.
private void dgvAccount_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.RowIndex == -1 || e.ColumnIndex == -1)
return;
bool isPayment = true;
bool isCharge = true;
foreach (DataGridViewRow row in dgv.SelectedRows)
{
if ((string)row.Cells["P/C"].Value == "C")
isPayment = false;
else if ((string)row.Cells["P/C"].Value == "P")
isCharge = false;
}
if (isPayment)
e.ContextMenuStrip = cmsAccountPayment;
else if (isCharge)
e.ContextMenuStrip = cmsAccountCharge;
}
private void cmsAccountPayment_Opening(object sender, CancelEventArgs e)
{
int itemCount = dgvAccount.SelectedRows.Count;
string voidPaymentText = "&Void Payment"; // to be localized
if (itemCount > 1)
voidPaymentText = "&Void Payments"; // to be localized
if (tsmiVoidPayment.Text != voidPaymentText) // avoid possible flicker
tsmiVoidPayment.Text = voidPaymentText;
}
private void cmsAccountCharge_Opening(object sender, CancelEventArgs e)
{
int itemCount = dgvAccount.SelectedRows.Count;
string deleteChargeText = "&Delete Charge"; //to be localized
if (itemCount > 1)
deleteChargeText = "&Delete Charge"; //to be localized
if (tsmiDeleteCharge.Text != deleteChargeText) // avoid possible flicker
tsmiDeleteCharge.Text = deleteChargeText;
}
private void tsmiVoidPayment_Click(object sender, EventArgs e)
{
int paymentCount = dgvAccount.SelectedRows.Count;
if (paymentCount == 0)
return;
bool voidPayments = false;
string confirmText = "Are you sure you would like to void this payment?"; // to be localized
if (paymentCount > 1)
confirmText = "Are you sure you would like to void these payments?"; // to be localized
voidPayments = (MessageBox.Show(
confirmText,
"Confirm", // to be localized
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button2
) == DialogResult.Yes);
if (voidPayments)
{
// SQLTransaction Start
foreach (DataGridViewRow row in dgvAccount.SelectedRows)
{
//do Work
}
}
}
private void tsmiDeleteCharge_Click(object sender, EventArgs e)
{
int chargeCount = dgvAccount.SelectedRows.Count;
if (chargeCount == 0)
return;
bool deleteCharges = false;
string confirmText = "Are you sure you would like to delete this charge?"; // to be localized
if (chargeCount > 1)
confirmText = "Are you sure you would like to delete these charges?"; // to be localized
deleteCharges = (MessageBox.Show(
confirmText,
"Confirm", // to be localized
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button2
) == DialogResult.Yes);
if (deleteCharges)
{
// SQLTransaction Start
foreach (DataGridViewRow row in dgvAccount.SelectedRows)
{
//do Work
}
}
}
With eclipse or any other IDE, just right click on your main spring boot application and click "debug as java application"
If you use Spring Boot 2.x and want to pass the context path property in the command line, you should put double // like this:
--server.servlet.context-path=//your-path
That worked for me running in windows.
If you are working in a browser that doesn't support tabindex="-1"
, you may be able to get away with just giving the things that need to be skipped a really high tab index. For example tabindex="500"
basically moves the object's tab order to the end of the page.
I did this for a long data entry form with a button thrown in the middle of it. It's not a button people click very often so I didn't want them to accidentally tab to it and press enter. disabled
wouldn't work because it's a button.
What I believe you're looking for is a way to work with arrays as object values:
var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into
var data = {
sampleTime: '1450632410296',
data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
sampleTime: '1450632410296',
data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);
This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify
:
JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
python compile on the fly when you run it.
Run a .py file by(linux): python abc.py
I used Sorin Comanescu's solution, but hit a problem when trying to get the selected value. My combobox was a toolstrip combobox. I used the "combobox" property, which exposes a normal combobox.
I had a
Dictionary<Control, string> controls = new Dictionary<Control, string>();
Binding code (Sorin Comanescu's solution - worked like a charm):
controls.Add(pictureBox1, "Image");
controls.Add(dgvText, "Text");
cbFocusedControl.ComboBox.DataSource = new BindingSource(controls, null);
cbFocusedControl.ComboBox.ValueMember = "Key";
cbFocusedControl.ComboBox.DisplayMember = "Value";
The problem was that when I tried to get the selected value, I didn't realize how to retrieve it. After several attempts I got this:
var control = ((KeyValuePair<Control, string>) cbFocusedControl.ComboBox.SelectedItem).Key
Hope it helps someone else!
Specify maven.compiler.source and target versions.
1) Maven version which supports jdk you use. In my case JDK 11 and maven 3.6.0.
2) pom.xml
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
As an alternative, you can fully specify maven compiler plugin. See previous answers. It is shorter in my example :)
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
3) rebuild the project to avoid compile errors in your IDE.
4) If it still does not work. In Intellij Idea I prefer using terminal instead of using terminal from OS. Then in Idea go to file -> settings -> build tools -> maven. I work with maven I downloaded from apache (by default Idea uses bundled maven). Restart Idea then and run mvn clean install
again. Also make sure you have correct Path, MAVEN_HOME, JAVA_HOME environment variables.
I also saw this one-liner, but it does not work.
<maven.compiler.release>11</maven.compiler.release>
I made some quick starter projects, which I re-use in other my projects, feel free to check:
A generic way that can be applied to any class without specific formatting could be done as follows:
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)
And then,
elem = Element('my_name', 'some_symbol', 3)
print(elem)
produces
__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}
None of the solutions above worked for me straight away. So I followed these steps:
pom.xml:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Go to Project Properties
> Java Build Path
, then remove the JRE
System Library pointing to JRE1.5
.
Force updated the project.
If using integers as targets, makes sure they aren't symmetrical at 0.
I.e., don't use classes -1, 0, 1. Use instead 0, 1, 2.
above answers In simple words,
you have to register under @NgModule
's
declarations: [
AppComponent, YourNewComponentHere
]
of app.module.ts
do not forget to import
that component.
You are describing exactly how and why signing is used in public key cryptography. Note that it's very dangerous to sign (or encrypt) aritrary messages supplied by others - this allows attacks on the algorithms that could compromise your keys.
Have a look at Styled Button it will surely help you. There are lots examples please search on INTERNET.
eg:style
<style name="Widget.Button" parent="android:Widget">
<item name="android:background">@drawable/red_dot</item>
</style>
you can use your selector instead of red_dot
red_dot:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#f00"/>
<size android:width="55dip"
android:height="55dip"/>
</shape>
Button:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp"
style="@style/Widget.Button"
android:text="Button" />
I have found following way to fix this issue... I hope this can help you.
json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
android:fitsSystemWindows="true"
add property on main layout of layout file and
android:windowSoftInputMode="adjustResize"
add line in your Manifest.xml file on your Activty
its perfect work for me.
MySQL uses CONCAT() to concatenate strings
SELECT * FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)
public static void main(String[] args) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Accept", MediaType.APPLICATION_JSON_VALUE);
final String url = "https://host:port/contract/{code}";
Map<String, String> params = new HashMap<String, String>();
params.put("code", "123456");
HttpEntity<?> httpEntity = new HttpEntity<>(httpHeaders);
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange(url, HttpMethod.GET, httpEntity,String.class, params);
}
When I am in a situation like that I propose the solution below.
And as a consuming class you could have
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyApp.Dictionaries
{
class Greek
{
public static readonly string Alpha = "Alpha";
public static readonly string Beta = "Beta";
public static readonly string Gamma = "Gamma";
public static readonly string Delta = "Delta";
private static readonly BiDictionary<int, string> Dictionary = new BiDictionary<int, string>();
static Greek() {
Dictionary.Add(1, Alpha);
Dictionary.Add(2, Beta);
Dictionary.Add(3, Gamma);
Dictionary.Add(4, Delta);
}
public static string getById(int id){
return Dictionary.GetByFirst(id);
}
public static int getByValue(string value)
{
return Dictionary.GetBySecond(value);
}
}
}
And using a bidirectional dictionary: Based on this (https://stackoverflow.com/a/255638/986160) assuming that the keys will be associated with single values in the dictionary and similar to (https://stackoverflow.com/a/255630/986160) but a bit more elegant. This dictionary is also enumerable and you can go back and forth from ints to strings. Also you don't have to have any string in your codebase with the exception of this class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace MyApp.Dictionaries
{
class BiDictionary<TFirst, TSecond> : IEnumerable
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
public void Add(TFirst first, TSecond second)
{
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
public TSecond this[TFirst first]
{
get { return GetByFirst(first); }
}
public TFirst this[TSecond second]
{
get { return GetBySecond(second); }
}
public TSecond GetByFirst(TFirst first)
{
return firstToSecond[first];
}
public TFirst GetBySecond(TSecond second)
{
return secondToFirst[second];
}
public IEnumerator GetEnumerator()
{
return GetFirstEnumerator();
}
public IEnumerator GetFirstEnumerator()
{
return firstToSecond.GetEnumerator();
}
public IEnumerator GetSecondEnumerator()
{
return secondToFirst.GetEnumerator();
}
}
}
Package Explorer / View Menu / Package Presentation... / Hierarchical
The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
I was looking forward this for a long time, and found no simple working example, but based on these answers I created the downloadAndUnzip()
function.
The usage is quite simple:
downloadAndUnzip('http://your-domain.com/archive.zip', 'yourfile.xml')
.then(function (data) {
console.log(data); // unzipped content of yourfile.xml in root of archive.zip
})
.catch(function (err) {
console.error(err);
});
And here is the declaration:
var AdmZip = require('adm-zip');
var request = require('request');
var downloadAndUnzip = function (url, fileName) {
/**
* Download a file
*
* @param url
*/
var download = function (url) {
return new Promise(function (resolve, reject) {
request({
url: url,
method: 'GET',
encoding: null
}, function (err, response, body) {
if (err) {
return reject(err);
}
resolve(body);
});
});
};
/**
* Unzip a Buffer
*
* @param buffer
* @returns {Promise}
*/
var unzip = function (buffer) {
return new Promise(function (resolve, reject) {
var resolved = false;
var zip = new AdmZip(buffer);
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function (zipEntry) {
if (zipEntry.entryName == fileName) {
resolved = true;
resolve(zipEntry.getData().toString('utf8'));
}
});
if (!resolved) {
reject(new Error('No file found in archive: ' + fileName));
}
});
};
return download(url)
.then(unzip);
};
It's simple-
SELECT empname,
empid,
(SELECT COUNT (profileid)
FROM profile
WHERE profile.empid = employee.empid)
AS number_of_profiles
FROM employee;
It is even simpler when you use a table join like this:
SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;
Explanation for the subquery:
Essentially, a subquery in a select
gets a scalar value and passes it to the main query. A subquery in select
is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count
to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null
to the main query. Moreover, a subquery can access columns from the from
clause of the main query, as shown in my query where employee.empid
is passed from the outer query to the inner query.
Edit:
When you use a subquery in a select
clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.
Explanation for the left join
A left join is very handy, especially when you want to replace the select
subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN
keyword.
For more information read Oracle Docs on subqueries and left join or left outer join.
Another solution would be as below where the list is placed under a drop-down button.
<button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
>Markets<span class="caret"></span></button>
<ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
{{ form.markets }}
</ul>
Use String.matches(), like:
String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));
That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.
>>> from datetime import date
>>> date.today().month
2
>>> date.today().year
2020
>>> date.today().day
13
Just decrease the width and height by double of border-width
Just right click on that column and select properties and write getdate()
in Default value or binding
.like image:
If you want do it in CodeFirst
in EF
you should add this attributes befor of your column definition:
[Databasegenerated(Databaseoption.computed)]
this attributes can found in System.ComponentModel.Dataannotion.Schema
.
In my opinion first one is better:))
I think you ought to use a regex:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
String neg = "-123abc";
String pos = "123abc";
String non = "abc123";
/* I'm not sure if this regex is too verbose, but it should be
* clear. It checks that the string starts with either a series
* of one or more digits... OR a negative sign followed by 1 or
* more digits. Anything can follow the digits. Update as you need
* for things that should not follow the digits or for floating
* point numbers.
*/
Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
Matcher matcher = pattern.matcher(neg);
if(matcher.matches()) {
System.out.println("matches negative number");
}
matcher = pattern.matcher(pos);
if (matcher.matches()) {
System.out.println("positive matches");
}
matcher = pattern.matcher(non);
if (!matcher.matches()) {
System.out.println("letters don't match :-)!!!");
}
}
}
You may want to adjust this to accept floating point numbers, but this will work for negatives. Other answers won't work for negatives because they only check the first character! Be more specific about your needs and I can help you adjust this approach.
The postfix increment ++
does not increase the value of its operand until after it has been evaluated. The value of i++
is i
.
The prefix decrement increases the value of its operand before it has been evaluated. The value of --i
is i - 1
.
Prefix increment/decrement change the value before the expression is evaluated. Postfix increment/decrement change the value after.
So, in your case, fun(10)
returns 10, and printing --i
prints i - 1
, which is 9.
moment().format(); // "2019-08-12T17:52:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, August 12th 2019, 5:52:00 pm"
moment().format("ddd, hA"); // "Mon, 5PM"
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
You can also use a variant array as the return result to return a sequence of arbitrary values:
Function f(i As Integer, s As String) As Variant()
f = Array(i + 1, "ate my " + s, Array(1#, 2#, 3#))
End Function
Sub test()
result = f(2, "hat")
i1 = result(0)
s1 = result(1)
a1 = result(2)
End Sub
Ugly and bug prone because your caller needs to know what's being returned to use the result, but occasionally useful nonetheless.
Take a look at this solution using Linq. His example is similar in that he needed different markup for every 3rd item.
foreach( var myItem in Model.Members.Select(x,i) => new {Member = x, Index = i){
...
}
You should try the currentRegion property, if you know from where you are to find the range. This will give you the boundaries of your used range.
www.bitvise.com - sftpc is a good command line client also.
This message means that there are certain possible method calls which may fail at run-time. Suppose you have
class A { public function foo($a = 1) {;}}
class B extends A { public function foo($a) {;}}
function bar(A $a) {$a->foo();}
The compiler only checks the call $a->foo() against the requirements of A::foo() which requires no parameters. $a may however be an object of class B which requires a parameter and so the call would fail at runtime.
This however can never fail and does not trigger the error
class A { public function foo($a) {;}}
class B extends A { public function foo($a = 1) {;}}
function bar(A $a) {$a->foo();}
So no method may have more required parameters than its parent method.
The same message is also generated when type hints do not match, but in this case PHP is even more restrictive. This gives an error:
class A { public function foo(StdClass $a) {;}}
class B extends A { public function foo($a) {;}}
as does this:
class A { public function foo($a) {;}}
class B extends A { public function foo(StdClass $a) {;}}
That seems more restrictive than it needs to be and I assume is due to internals.
Visibility differences cause a different error, but for the same basic reason. No method can be less visible than its parent method.
Or File::Find
use File::Find;
finddepth(\&wanted, '/some/path/to/dir');
sub wanted { print };
It'll go through subdirectories if they exist.
You can catch that exception and return whatever you want from there.
open(target, 'a').close()
scores = {};
try:
with open(target, "rb") as file:
unpickler = pickle.Unpickler(file);
scores = unpickler.load();
if not isinstance(scores, dict):
scores = {};
except EOFError:
return {}
I have a local install of tensorflow 1.15.0 (with tensorboard obviously included) on MacOS.
For me, the path to the relevant file within my user directory is Library/Python/3.7/lib/python/site-packages/tensorboard/main.py. So, which
does not work for me, but you have to look for the file named main.py, which is weird since it apparently is named something else for other users.
you can specify which column to sort by, with following steps:
steps: * top * shift + F * select a column from the list e.g. n means sort by memory, * press enter * ok
Use an associative array, with command names as keys.
# Requires bash 4, though
declare -A magic_variable=()
function grep_search() {
magic_variable[$1]=$( ls | tail -1 )
echo ${magic_variable[$1]}
}
If you can't use associative arrays (e.g., you must support bash
3), you can use declare
to create dynamic variable names:
declare "magic_variable_$1=$(ls | tail -1)"
and use indirect parameter expansion to access the value.
var="magic_variable_$1"
echo "${!var}"
See BashFAQ: Indirection - Evaluating indirect/reference variables.
one-liner and preserve order
list(OrderedDict.fromkeys([2,1,1,3]))
although you'll need
from collections import OrderedDict
I believe there is a maximum number of concurrent http requests that browsers will make to the same domain, which is in the order of 4-8 requests depending on the user's settings and browser.
You could set up your requests to go to different domains, which may or may not be feasible. The Yahoo guys did a lot of research in this area, which you can read about (here). Remember that every new domain you add also requires a DNS lookup. The YSlow guys recommend between 2 and 4 domains to achieve a good compromise between parallel requests and DNS lookups, although this is focusing on the page's loading time, not subsequent AJAX requests.
Can I ask why you want to make so many requests? There is good reasons for the browsers limiting the number of requests to the same domain. You will be better off bundling requests if possible.
import os
import cv2
rootdir = "directory path"
for subdir, dirs, files in os.walk(rootdir):
for file in files:
frame = cv2.imread(os.path.join(subdir, file))
If you type the executable name and a /?
switch at the command line, there is typically help information available. Doing so with taskkill /?
provides the following, for instance:
TASKKILL [/S system [/U username [/P [password]]]]
{ [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]
Description:
This tool is used to terminate tasks by process id (PID) or image name.
Parameter List:
/S system Specifies the remote system to connect to.
/U [domain\]user Specifies the user context under which the
command should execute.
/P [password] Specifies the password for the given user
context. Prompts for input if omitted.
/FI filter Applies a filter to select a set of tasks.
Allows "*" to be used. ex. imagename eq acme*
/PID processid Specifies the PID of the process to be terminated.
Use TaskList to get the PID.
/IM imagename Specifies the image name of the process
to be terminated. Wildcard '*' can be used
to specify all tasks or image names.
/T Terminates the specified process and any
child processes which were started by it.
/F Specifies to forcefully terminate the process(es).
/? Displays this help message.
Filters:
Filter Name Valid Operators Valid Value(s)
----------- --------------- -------------------------
STATUS eq, ne RUNNING |
NOT RESPONDING | UNKNOWN
IMAGENAME eq, ne Image name
PID eq, ne, gt, lt, ge, le PID value
SESSION eq, ne, gt, lt, ge, le Session number.
CPUTIME eq, ne, gt, lt, ge, le CPU time in the format
of hh:mm:ss.
hh - hours,
mm - minutes, ss - seconds
MEMUSAGE eq, ne, gt, lt, ge, le Memory usage in KB
USERNAME eq, ne User name in [domain\]user
format
MODULES eq, ne DLL name
SERVICES eq, ne Service name
WINDOWTITLE eq, ne Window title
NOTE
----
1) Wildcard '*' for /IM switch is accepted only when a filter is applied.
2) Termination of remote processes will always be done forcefully (/F).
3) "WINDOWTITLE" and "STATUS" filters are not considered when a remote
machine is specified.
Examples:
TASKKILL /IM notepad.exe
TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
TASKKILL /F /IM cmd.exe /T
TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"
You can also find this information, as well as documentation for most of the other command-line utilities, in the Microsoft TechNet Command-Line Reference
You only need []
to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.
The same thing applies at the first level in your loop. It is merely an array and []
is a new empty array - job done.
As for the second level, if Thing
is a class then new Thing()
will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.
class Something {
private things: Thing[][];
constructor() {
this.things = [];
for(var i: number = 0; i < 10; i++) {
this.things[i] = [];
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing();
}
}
}
}
Tuples cannot efficiently be appended like a list.
So a tuple comprehension would need to use a list internally and then convert to a tuple.
That would be the same as what you do now : tuple( [ comprehension ] )
Minor changes required for Kafka 0.10 and the new consumer compared to laughing_man's answer:
message.max.bytes
and replica.fetch.max.bytes
. message.max.bytes
has to be equal or smaller(*) than replica.fetch.max.bytes
.max.request.size
to send the larger message.max.partition.fetch.bytes
to receive larger messages.(*) Read the comments to learn more about message.max.bytes
<=replica.fetch.max.bytes
They both return the same thing, as noted in the documentation you linked; an HttpSession object.
You can also look at a concrete implementation (e.g. Tomcat) and see what it's actually doing: Request.java class. In this case, basically they both call:
Session session = doGetSession(true);
Please refer to this link. You can have any button you want just use javascript to submit the form
My issue was also caused by missing https binding in IIS: Selected default website > On the far right pane selected Bindings > add > https
Choose 'IIS Express Development Certificate' and set port to 443
On Windows 10 Pro, the batch file can be registered; the workaround of registering cmd.exe and specifying the bat file as a param isn't needed. I just did this, registering both a shutdown script and a startup (boot) script, and it worked.
Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors
Not sure what you are trying to accomplish on your first few lines but you can try this:
$(document).ready(function()
{
$("#ms_num").attr('maxlength','6');
});
In general, I/O means Input or Output. Those methods throw the IOException
whenever an input or output operation is failed or interpreted. Note that this won't be thrown for reading or writing to memory as Java will be handling it automatically.
Here are some cases which result in IOException
.
I'm assuming you're talking about com.google.common.base.Predicate<T>
from Guava.
From the API:
Determines a
true
orfalse
value for a given input. For example, aRegexPredicate
might implementPredicate<String>
, and return true for any string that matches its given regular expression.
This is essentially an OOP abstraction for a boolean
test.
For example, you may have a helper method like this:
static boolean isEven(int num) {
return (num % 2) == 0; // simple
}
Now, given a List<Integer>
, you can process only the even numbers like this:
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
for (int number : numbers) {
if (isEven(number)) {
process(number);
}
}
With Predicate
, the if
test is abstracted out as a type. This allows it to interoperate with the rest of the API, such as Iterables
, which have many utility methods that takes Predicate
.
Thus, you can now write something like this:
Predicate<Integer> isEven = new Predicate<Integer>() {
@Override public boolean apply(Integer number) {
return (number % 2) == 0;
}
};
Iterable<Integer> evenNumbers = Iterables.filter(numbers, isEven);
for (int number : evenNumbers) {
process(number);
}
Note that now the for-each loop is much simpler without the if
test. We've reached a higher level of abtraction by defining Iterable<Integer> evenNumbers
, by filter
-ing using a Predicate
.
Iterables.filter
Predicate
allows Iterables.filter
to serve as what is called a higher-order function. On its own, this offers many advantages. Take the List<Integer> numbers
example above. Suppose we want to test if all numbers are positive. We can write something like this:
static boolean isAllPositive(Iterable<Integer> numbers) {
for (Integer number : numbers) {
if (number < 0) {
return false;
}
}
return true;
}
//...
if (isAllPositive(numbers)) {
System.out.println("Yep!");
}
With a Predicate
, and interoperating with the rest of the libraries, we can instead write this:
Predicate<Integer> isPositive = new Predicate<Integer>() {
@Override public boolean apply(Integer number) {
return number > 0;
}
};
//...
if (Iterables.all(numbers, isPositive)) {
System.out.println("Yep!");
}
Hopefully you can now see the value in higher abstractions for routines like "filter all elements by the given predicate", "check if all elements satisfy the given predicate", etc make for better code.
Unfortunately Java doesn't have first-class methods: you can't pass methods around to Iterables.filter
and Iterables.all
. You can, of course, pass around objects in Java. Thus, the Predicate
type is defined, and you pass objects implementing this interface instead.
This's a jQuery free solution that can work with SPA inside the iframe
document.getElementById('iframe-id').addEventListener('load', function () {
let that = this;
setTimeout(function () {
that.style.height = that.contentWindow.document.body.offsetHeight + 'px';
}, 2000) // if you're having SPA framework (angularjs for example) inside the iframe, some delay is needed for the content to populate
});
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
This error means that file was not found. Either path is wrong or file is not present where you want it to be. Try to access it by entering source address in your browser to check if it really is there. Browse the directories on server to ensure the path is correct. You may even copy and paste the relative path to be certain it is alright.
In Python 2 dict.keys() return a list, whereas in Python 3 it returns a generator.
You could only iterate over it's values else you may have to explicitly convert it to a list i.e. pass it to a list function.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
<style>
/* Basics */
html, body {
width: 100%;
height: 100%;
font-family: "Helvetica Neue", Helvetica, sans-serif;
color: #444;
-webkit-font-smoothing: antialiased;
background: #f0f0f0;
}
#container {
position: fixed;
width: 340px;
height: 280px;
top: 50%;
left: 50%;
margin-top: -140px;
margin-left: -170px;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
}
form {
margin: 0 auto;
margin-top: 20px;
}
label {
color: #555;
display: inline-block;
margin-left: 18px;
padding-top: 10px;
font-size: 14px;
}
p a {
font-size: 11px;
color: #aaa;
float: right;
margin-top: -13px;
margin-right: 20px;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
p a:hover {
color: #555;
}
input {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
outline: none;
}
input[type=text],
input[type=password] ,input[type=time]{
color: #777;
padding-left: 10px;
margin: 10px;
margin-top: 12px;
margin-left: 18px;
width: 290px;
height: 35px;
border: 1px solid #c7d0d2;
border-radius: 2px;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
input[type=text]:hover,
input[type=password]:hover,input[type=time]:hover {
border: 1px solid #b6bfc0;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
}
input[type=text]:focus,
input[type=password]:focus,input[type=time]:focus {
border: 1px solid #a8c9e4;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
}
#lower {
background: #ecf2f5;
width: 100%;
height: 69px;
margin-top: 20px;
box-shadow: inset 0 1px 1px #fff;
border-top: 1px solid #ccc;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
input[type=checkbox] {
margin-left: 20px;
margin-top: 30px;
}
.check {
margin-left: 3px;
font-size: 11px;
color: #444;
text-shadow: 0 1px 0 #fff;
}
input[type=submit] {
float: right;
margin-right: 20px;
margin-top: 20px;
width: 80px;
height: 30px;
font-size: 14px;
font-weight: bold;
color: #fff;
background-color: #acd6ef; /*IE fallback*/
background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
border-radius: 30px;
border: 1px solid #66add6;
box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
cursor: pointer;
}
input[type=submit]:hover {
background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
}
input[type=submit]:active {
background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
}
</style>
</head>
<body>
<!-- Begin Page Content -->
<div id="container">
<form action="login_process.php" method="post">
<label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php echo @$_GET['msg'];?></label>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div>
<!--/ lower-->
</form>
</div>
<!--/ container-->
<!-- End Page Content -->
</body>
</html>
You're misinformed about fcntl()
not always being reliable. It's untrue.
To mark a socket as non-blocking the code is as simple as:
// where socketfd is the socket you want to make non-blocking
int status = fcntl(socketfd, F_SETFL, fcntl(socketfd, F_GETFL, 0) | O_NONBLOCK);
if (status == -1){
perror("calling fcntl");
// handle the error. By the way, I've never seen fcntl fail in this way
}
Under Linux, on kernels > 2.6.27 you can also create sockets non-blocking from the outset using socket()
and accept4()
.
e.g.
// client side
int socketfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
// server side - see man page for accept4 under linux
int socketfd = accept4( ... , SOCK_NONBLOCK);
It saves a little bit of work, but is less portable so I tend to set it with fcntl()
.
For Java:
X, exactly n times: X{n}
X, at least n times: X{n,}
X, at least n but not more than m times: X{n,m}
We have similar situation right now and as of this answer, I am using laravel 5.6 release.
I will not use your example in the question but mine, because it's related though.
I have route like this:
Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');
Then in your controller method, make sure you include
use Illuminate\Http\Request;
and this should be above your controller, most likely a default, if generated using php artisan
, now to get variable from the url it should look like this:
public function someMethod(Request $request)
{
$foo = $request->input("start");
$bar = $request->input("limit");
// some codes here
}
Regardless of the HTTP verb, the input() method may be used to retrieve user input.
https://laravel.com/docs/5.6/requests#retrieving-input
Hope this help.
This should work ...
var tst = "12345\n\n\r\n\r\r";
var res = tst.TrimEnd( '\r', '\n' );
Every form of the query string retrievable from flask request object as described in O'Reilly Flask Web Devleopment:
From O'Reilly Flask Web Development, and as stated by Manan Gouhari earlier, first you need to import request:
from flask import request
request
is an object exposed by Flask as a context variable named (you guessed it) request
. As its name suggests, it contains all the information that the client included in the HTTP request. This object has many attributes and methods that you can retrieve and call, respectively.
You have quite a few request
attributes which contain the query string from which to choose. Here I will list every attribute that contains in any way the query string, as well as a description from the O'Reilly book of that attribute.
First there is args
which is "a dictionary with all the arguments passed in the query string of the URL." So if you want the query string parsed into a dictionary, you'd do something like this:
from flask import request
@app.route('/'):
queryStringDict = request.args
(As others have pointed out, you can also use .get('<arg_name>')
to get a specific value from the dictionary)
Then, there is the form
attribute, which does not contain the query string, but which is included in part of another attribute that does include the query string which I will list momentarily. First, though, form
is "A dictionary with all the form fields submitted with the request." I say that to say this: there is another dictionary attribute available in the flask request object called values
. values
is "A dictionary that combines the values in form
and args
." Retrieving that would look something like this:
from flask import request
@app.route('/'):
formFieldsAndQueryStringDict = request.values
(Again, use .get('<arg_name>')
to get a specific item out of the dictionary)
Another option is query_string
which is "The query string portion of the URL, as a raw binary value." Example of that:
from flask import request
@app.route('/'):
queryStringRaw = request.query_string
Then as an added bonus there is full_path
which is "The path and query string portions of the URL." Por ejemplo:
from flask import request
@app.route('/'):
pathWithQueryString = request.full_path
And finally, url
, "The complete URL requested by the client" (which includes the query string):
from flask import request
@app.route('/'):
pathWithQueryString = request.url
Happy hacking :)
Regarding the suggestion So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
From the answers for the question System.Net.WebClient unreasonably slow
Try setting Proxy = null;
WebClient wc = new WebClient(); wc.Proxy = null;
Credit to Alex Burtsev
$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
(the w3schools example, it works perfect)
Please use an inner query inside of the in
-clause:
select col1, col2, col3... from table1
where id in (select id from table2 where conditions...)
What you can do is in your .config for the app is create the resolve object for the route and in the function pass in $q (promise object) and the name of the service you're depending on, and resolve the promise in the callback function for the $http in the service like so:
ROUTE CONFIG
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'home.html',
controller: 'homeCtrl',
resolve:function($q,MyService) {
//create the defer variable and pass it to our service
var defer = $q.defer();
MyService.fetchData(defer);
//this will only return when the promise
//has been resolved. MyService is going to
//do that for us
return defer.promise;
}
})
}
Angular won't render the template or make the controller available until defer.resolve() has been called. We can do that in our service:
SERVICE
app.service('MyService',function($http){
var MyService = {};
//our service accepts a promise object which
//it will resolve on behalf of the calling function
MyService.fetchData = function(q) {
$http({method:'GET',url:'data.php'}).success(function(data){
MyService.data = data;
//when the following is called it will
//release the calling function. in this
//case it's the resolve function in our
//route config
q.resolve();
}
}
return MyService;
});
Now that MyService has the data assigned to it's data property, and the promise in the route resolve object has been resolved, our controller for the route kicks into life, and we can assign the data from the service to our controller object.
CONTROLLER
app.controller('homeCtrl',function($scope,MyService){
$scope.servicedata = MyService.data;
});
Now all our binding in the scope of the controller will be able to use the data which originated from MyService.
For individual element the code below could be used:
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
for (int second = 0;; second++) {
if (second >= 60){
fail("timeout");
}
try {
if (isElementPresent(By.id("someid"))){
break;
}
}
catch (Exception e) {
}
Thread.sleep(1000);
}
There is already a solution provided which allows building a dictionary, (or nested dictionary for more complex data), but if you wish to build an object, then perhaps try 'ObjDict'. This gives much more control over the json to be created, for example retaining order, and allows building as an object which may be a preferred representation of your concept.
pip install objdict first.
from objdict import ObjDict
data = ObjDict()
data.key = 'value'
json_data = data.dumps()
Why not checking if the file exists?
string fileName;
do
{
fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
} while (System.IO.File.Exists(fileName));
You can use any one these [starting from the fastest]
$("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")
See the docs FAQ: "How can I see the raw SQL queries Django is running?"
django.db.connection.queries
contains a list of the SQL queries:
from django.db import connection
print(connection.queries)
Querysets also have a query
attribute containing the query to be executed:
print(MyModel.objects.filter(name="my name").query)
Note that the output of the query is not valid SQL, because:
"Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations."
From Django bug report #17741.
Because of that, you should not send query output directly to a database.
-Confirm
is a switch in most PowerShell cmdlets that forces the cmdlet to ask for user confirmation. What you're actually looking for is the Read-Host
cmdlet:
$confirmation = Read-Host "Are you Sure You Want To Proceed:"
if ($confirmation -eq 'y') {
# proceed
}
or the PromptForChoice()
method of the host user interface:
$title = 'something'
$question = 'Are you sure you want to proceed?'
$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}
Edit:
As M-pixel pointed out in the comments the code could be simplified further, because the choices can be passed as a simple string array.
$title = 'something'
$question = 'Are you sure you want to proceed?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}
One liner with .apply()
method is following:
df['color'] = df['Set'].apply(lambda set_: 'green' if set_=='Z' else 'red')
After that, df
data frame looks like this:
>>> print(df)
Type Set color
0 A Z green
1 B Z green
2 B X red
3 C Y red
You can use visual studio 2015. Go to Tools => SQL server => New Data comparison
Select source and target Database.
from Swift 3 and above, Date is Comparable so we can directly compare dates like
let date1 = Date()
let date2 = Date().addingTimeInterval(50)
let isGreater = date1 > date2
print(isGreater)
let isSmaller = date1 < date2
print(isSmaller)
let isEqual = date1 == date2
print(isEqual)
Alternatively We can create extension on Date
extension Date {
func isEqualTo(_ date: Date) -> Bool {
return self == date
}
func isGreaterThan(_ date: Date) -> Bool {
return self > date
}
func isSmallerThan(_ date: Date) -> Bool {
return self < date
}
}
Use: let isEqual = date1.isEqualTo(date2)
If using MinGW, add an option, -Wl,subsystem,console
or -mconsole
.
This query uses the Group By
and and Having
clauses to allow you to select (locate and list out) for each duplicate record. The As
clause is a convenience to refer to Quantity
in the select
and Order By
clauses, but is not really part of getting you the duplicate rows.
Select
Title,
Count( Title ) As [Quantity]
From
Training
Group By
Title
Having
Count( Title ) > 1
Order By
Quantity desc
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
You need to keep an array of the google.maps.Marker
objects to hide (or remove or run other operations on them).
In the global scope:
var gmarkers = [];
Then push the markers on that array as you create them:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
title: locations[i].title,
icon: icon,
map:map
});
// Push your newly created marker into the array:
gmarkers.push(marker);
Then to remove them:
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
working example (toggles the markers)
code snippet:
var gmarkers = [];_x000D_
var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);_x000D_
var styles = [{_x000D_
stylers: [{_x000D_
hue: "black"_x000D_
}, {_x000D_
saturation: -90_x000D_
}]_x000D_
}, {_x000D_
featureType: "road",_x000D_
elementType: "geometry",_x000D_
stylers: [{_x000D_
lightness: 100_x000D_
}, {_x000D_
visibility: "simplified"_x000D_
}]_x000D_
}, {_x000D_
featureType: "road",_x000D_
elementType: "labels",_x000D_
stylers: [{_x000D_
visibility: "on"_x000D_
}]_x000D_
}];_x000D_
_x000D_
var styledMap = new google.maps.StyledMapType(styles, {_x000D_
name: "Campus"_x000D_
});_x000D_
var mapOptions = {_x000D_
center: RoseHulman,_x000D_
zoom: 15,_x000D_
mapTypeControl: true,_x000D_
zoomControl: true,_x000D_
zoomControlOptions: {_x000D_
style: google.maps.ZoomControlStyle.SMALL_x000D_
},_x000D_
mapTypeControlOptions: {_x000D_
mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID],_x000D_
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU_x000D_
},_x000D_
scrollwheel: false,_x000D_
streetViewControl: true,_x000D_
_x000D_
};_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map'), mapOptions);_x000D_
map.mapTypes.set('map_style', styledMap);_x000D_
map.setMapTypeId('map_style');_x000D_
_x000D_
var infowindow = new google.maps.InfoWindow({_x000D_
maxWidth: 300,_x000D_
infoBoxClearance: new google.maps.Size(1, 1),_x000D_
disableAutoPan: false_x000D_
});_x000D_
_x000D_
var marker, i, icon, image;_x000D_
_x000D_
var locations = [{_x000D_
"id": "1",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Alpha Tau Omega Fraternity",_x000D_
"description": "<p>Alpha Tau Omega house</p>",_x000D_
"longitude": "-87.321133",_x000D_
"latitude": "39.484092"_x000D_
}, {_x000D_
"id": "2",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment Commons",_x000D_
"description": "<p>The commons area of the apartment-style residential complex</p>",_x000D_
"longitude": "-87.329282",_x000D_
"latitude": "39.483599"_x000D_
}, {_x000D_
"id": "3",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment East",_x000D_
"description": "<p>Apartment East</p>",_x000D_
"longitude": "-87.328809",_x000D_
"latitude": "39.483748"_x000D_
}, {_x000D_
"id": "4",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment West",_x000D_
"description": "<p>Apartment West</p>",_x000D_
"longitude": "-87.329732",_x000D_
"latitude": "39.483429"_x000D_
}, {_x000D_
"id": "5",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Baur-Sames-Bogart (BSB) Hall",_x000D_
"description": "<p>Baur-Sames-Bogart Hall</p>",_x000D_
"longitude": "-87.325714",_x000D_
"latitude": "39.482382"_x000D_
}, {_x000D_
"id": "6",_x000D_
"category": "6",_x000D_
"campus_location": "D3",_x000D_
"title": "Blumberg Hall",_x000D_
"description": "<p>Blumberg Hall</p>",_x000D_
"longitude": "-87.328321",_x000D_
"latitude": "39.483388"_x000D_
}, {_x000D_
"id": "7",_x000D_
"category": "1",_x000D_
"campus_location": "E1",_x000D_
"title": "The Branam Innovation Center",_x000D_
"description": "<p>The Branam Innovation Center</p>",_x000D_
"longitude": "-87.322614",_x000D_
"latitude": "39.48494"_x000D_
}, {_x000D_
"id": "8",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Chi Omega Sorority",_x000D_
"description": "<p>Chi Omega house</p>",_x000D_
"longitude": "-87.319905",_x000D_
"latitude": "39.482071"_x000D_
}, {_x000D_
"id": "9",_x000D_
"category": "3",_x000D_
"campus_location": "D1",_x000D_
"title": "Cook Stadium/Phil Brown Field",_x000D_
"description": "<p>Cook Stadium at Phil Brown Field</p>",_x000D_
"longitude": "-87.325258",_x000D_
"latitude": "39.485007"_x000D_
}, {_x000D_
"id": "10",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Crapo Hall",_x000D_
"description": "<p>Crapo Hall</p>",_x000D_
"longitude": "-87.324368",_x000D_
"latitude": "39.483709"_x000D_
}, {_x000D_
"id": "11",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Delta Delta Delta Sorority",_x000D_
"description": "<p>Delta Delta Delta</p>",_x000D_
"longitude": "-87.317477",_x000D_
"latitude": "39.482951"_x000D_
}, {_x000D_
"id": "12",_x000D_
"category": "6",_x000D_
"campus_location": "D2",_x000D_
"title": "Deming Hall",_x000D_
"description": "<p>Deming Hall</p>",_x000D_
"longitude": "-87.325822",_x000D_
"latitude": "39.483421"_x000D_
}, {_x000D_
"id": "13",_x000D_
"category": "5",_x000D_
"campus_location": "F1",_x000D_
"title": "Facilities Operations",_x000D_
"description": "<p>Facilities Operations</p>",_x000D_
"longitude": "-87.321782",_x000D_
"latitude": "39.484916"_x000D_
}, {_x000D_
"id": "14",_x000D_
"category": "2",_x000D_
"campus_location": "E3",_x000D_
"title": "Flame of the Millennium",_x000D_
"description": "<p>Flame of Millennium sculpture</p>",_x000D_
"longitude": "-87.323306",_x000D_
"latitude": "39.481978"_x000D_
}, {_x000D_
"id": "15",_x000D_
"category": "5",_x000D_
"campus_location": "E2",_x000D_
"title": "Hadley Hall",_x000D_
"description": "<p>Hadley Hall</p>",_x000D_
"longitude": "-87.324046",_x000D_
"latitude": "39.482887"_x000D_
}, {_x000D_
"id": "16",_x000D_
"category": "2",_x000D_
"campus_location": "F2",_x000D_
"title": "Hatfield Hall",_x000D_
"description": "<p>Hatfield Hall</p>",_x000D_
"longitude": "-87.322340",_x000D_
"latitude": "39.482146"_x000D_
}, {_x000D_
"id": "17",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Hulman Memorial Union",_x000D_
"description": "<p>Hulman Memorial Union</p>",_x000D_
"longitude": "-87.32698",_x000D_
"latitude": "39.483574"_x000D_
}, {_x000D_
"id": "18",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "John T. Myers Center for Technological Research with Industry",_x000D_
"description": "<p>John T. Myers Center for Technological Research With Industry</p>",_x000D_
"longitude": "-87.322984",_x000D_
"latitude": "39.484063"_x000D_
}, {_x000D_
"id": "19",_x000D_
"category": "6",_x000D_
"campus_location": "A2",_x000D_
"title": "Lakeside Hall",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.330612",_x000D_
"latitude": "39.482804"_x000D_
}, {_x000D_
"id": "20",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Lambda Chi Alpha Fraternity",_x000D_
"description": "<p>Lambda Chi Alpha</p>",_x000D_
"longitude": "-87.320999",_x000D_
"latitude": "39.48305"_x000D_
}, {_x000D_
"id": "21",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Logan Library",_x000D_
"description": "<p>Logan Library</p>",_x000D_
"longitude": "-87.324851",_x000D_
"latitude": "39.483408"_x000D_
}, {_x000D_
"id": "22",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Mees Hall",_x000D_
"description": "<p>Mees Hall</p>",_x000D_
"longitude": "-87.32778",_x000D_
"latitude": "39.483533"_x000D_
}, {_x000D_
"id": "23",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "Moench Hall",_x000D_
"description": "<p>Moench Hall</p>",_x000D_
"longitude": "-87.323695",_x000D_
"latitude": "39.483471"_x000D_
}, {_x000D_
"id": "24",_x000D_
"category": "1",_x000D_
"campus_location": "G4",_x000D_
"title": "Oakley Observatory",_x000D_
"description": "<p>Oakley Observatory</p>",_x000D_
"longitude": "-87.31616",_x000D_
"latitude": "39.483789"_x000D_
}, {_x000D_
"id": "25",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Olin Hall and Olin Advanced Learning Center",_x000D_
"description": "<p>Olin Hall</p>",_x000D_
"longitude": "-87.324550",_x000D_
"latitude": "39.482796"_x000D_
}, {_x000D_
"id": "26",_x000D_
"category": "6",_x000D_
"campus_location": "C3",_x000D_
"title": "Percopo Hall",_x000D_
"description": "<p>Percopo Hall</p>",_x000D_
"longitude": "-87.328182",_x000D_
"latitude": "39.482121"_x000D_
}, {_x000D_
"id": "27",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Public Safety Office",_x000D_
"description": "<p>The Office of Public Safety</p>",_x000D_
"longitude": "-87.320377",_x000D_
"latitude": "39.48191"_x000D_
}, {_x000D_
"id": "28",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "Rotz Mechanical Engineering Lab",_x000D_
"description": "<p>Rotz Lab</p>",_x000D_
"longitude": "-87.323247",_x000D_
"latitude": "39.483711"_x000D_
}, {_x000D_
"id": "28",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Scharpenberg Hall",_x000D_
"description": "<p>Scharpenberg Hall</p>",_x000D_
"longitude": "-87.328139",_x000D_
"latitude": "39.483582"_x000D_
}, {_x000D_
"id": "29",_x000D_
"category": "6",_x000D_
"campus_location": "G2",_x000D_
"title": "Sigma Nu Fraternity",_x000D_
"description": "<p>The Sigma Nu house</p>",_x000D_
"longitude": "-87.31999",_x000D_
"latitude": "39.48374"_x000D_
}, {_x000D_
"id": "30",_x000D_
"category": "6",_x000D_
"campus_location": "E4",_x000D_
"title": "South Campus / Rose-Hulman Ventures",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.330623",_x000D_
"latitude": "39.417646"_x000D_
}, {_x000D_
"id": "31",_x000D_
"category": "6",_x000D_
"campus_location": "C3",_x000D_
"title": "Speed Hall",_x000D_
"description": "<p>Speed Hall</p>",_x000D_
"longitude": "-87.326632",_x000D_
"latitude": "39.482121"_x000D_
}, {_x000D_
"id": "32",_x000D_
"category": "3",_x000D_
"campus_location": "C1",_x000D_
"title": "Sports and Recreation Center",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.3272",_x000D_
"latitude": "39.484874"_x000D_
}, {_x000D_
"id": "33",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Triangle Fraternity",_x000D_
"description": "<p>Triangle fraternity</p>",_x000D_
"longitude": "-87.32113",_x000D_
"latitude": "39.483659"_x000D_
}, {_x000D_
"id": "34",_x000D_
"category": "6",_x000D_
"campus_location": "B3",_x000D_
"title": "White Chapel",_x000D_
"description": "<p>The White Chapel</p>",_x000D_
"longitude": "-87.329367",_x000D_
"latitude": "39.482481"_x000D_
}, {_x000D_
"id": "35",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Women's Fraternity Housing",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320753",_x000D_
"latitude": "39.482401"_x000D_
}, {_x000D_
"id": "36",_x000D_
"category": "3",_x000D_
"campus_location": "E1",_x000D_
"title": "Intramural Fields",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.321267",_x000D_
"latitude": "39.485934"_x000D_
}, {_x000D_
"id": "37",_x000D_
"category": "3",_x000D_
"campus_location": "A3",_x000D_
"title": "James Rendel Soccer Field",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.332135",_x000D_
"latitude": "39.480933"_x000D_
}, {_x000D_
"id": "38",_x000D_
"category": "3",_x000D_
"campus_location": "B2",_x000D_
"title": "Art Nehf Field",_x000D_
"description": "<p>Art Nehf Field</p>",_x000D_
"longitude": "-87.330923",_x000D_
"latitude": "39.48022"_x000D_
}, {_x000D_
"id": "39",_x000D_
"category": "3",_x000D_
"campus_location": "B2",_x000D_
"title": "Women's Softball Field",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.329904",_x000D_
"latitude": "39.480278"_x000D_
}, {_x000D_
"id": "40",_x000D_
"category": "3",_x000D_
"campus_location": "D1",_x000D_
"title": "Joy Hulbert Tennis Courts",_x000D_
"description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>",_x000D_
"longitude": "-87.323767",_x000D_
"latitude": "39.485595"_x000D_
}, {_x000D_
"id": "41",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Speed Lake",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.328134",_x000D_
"latitude": "39.482779"_x000D_
}, {_x000D_
"id": "42",_x000D_
"category": "5",_x000D_
"campus_location": "F1",_x000D_
"title": "Recycling Center",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320098",_x000D_
"latitude": "39.484593"_x000D_
}, {_x000D_
"id": "43",_x000D_
"category": "1",_x000D_
"campus_location": "F3",_x000D_
"title": "Army ROTC",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.321342",_x000D_
"latitude": "39.481992"_x000D_
}, {_x000D_
"id": "44",_x000D_
"category": "2",_x000D_
"campus_location": " ",_x000D_
"title": "Self Made Man",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.326272",_x000D_
"latitude": "39.484481"_x000D_
}, {_x000D_
"id": "P1",_x000D_
"category": "4",_x000D_
"title": "Percopo Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.328756",_x000D_
"latitude": "39.481587"_x000D_
}, {_x000D_
"id": "P2",_x000D_
"category": "4",_x000D_
"title": "Speed Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.327361",_x000D_
"latitude": "39.481694"_x000D_
}, {_x000D_
"id": "P3",_x000D_
"category": "4",_x000D_
"title": "Main Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.326245",_x000D_
"latitude": "39.481446"_x000D_
}, {_x000D_
"id": "P4",_x000D_
"category": "4",_x000D_
"title": "Lakeside Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.330848",_x000D_
"latitude": "39.483284"_x000D_
}, {_x000D_
"id": "P5",_x000D_
"category": "4",_x000D_
"title": "Hatfield Hall Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.321417",_x000D_
"latitude": "39.482398"_x000D_
}, {_x000D_
"id": "P6",_x000D_
"category": "4",_x000D_
"title": "Women's Fraternity Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320977",_x000D_
"latitude": "39.482315"_x000D_
}, {_x000D_
"id": "P7",_x000D_
"category": "4",_x000D_
"title": "Myers and Facilities Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.322243",_x000D_
"latitude": "39.48417"_x000D_
}, {_x000D_
"id": "P8",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.323241",_x000D_
"latitude": "39.484758"_x000D_
}, {_x000D_
"id": "P9",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.323617",_x000D_
"latitude": "39.484311"_x000D_
}, {_x000D_
"id": "P10",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.325714",_x000D_
"latitude": "39.484584"_x000D_
}, {_x000D_
"id": "P11",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.32778",_x000D_
"latitude": "39.484145"_x000D_
}, {_x000D_
"id": "P12",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.329035",_x000D_
"latitude": "39.4848"_x000D_
}];_x000D_
_x000D_
for (i = 0; i < locations.length; i++) {_x000D_
_x000D_
var marker = new google.maps.Marker({_x000D_
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),_x000D_
title: locations[i].title,_x000D_
map: map_x000D_
});_x000D_
gmarkers.push(marker);_x000D_
google.maps.event.addListener(marker, 'click', (function(marker, i) {_x000D_
return function() {_x000D_
if (locations[i].description !== "" || locations[i].title !== "") {_x000D_
infowindow.setContent('<div class="content" id="content-' + locations[i].id +_x000D_
'" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' +_x000D_
'<hr class="grey" />' +_x000D_
hasImage(locations[i]) +_x000D_
locations[i].description) + '</div>';_x000D_
infowindow.open(map, marker);_x000D_
}_x000D_
}_x000D_
})(marker, i));_x000D_
}_x000D_
_x000D_
function toggleMarkers() {_x000D_
for (i = 0; i < gmarkers.length; i++) {_x000D_
if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);_x000D_
else gmarkers[i].setMap(map);_x000D_
}_x000D_
}_x000D_
_x000D_
function hasImage(location) {_x000D_
return '';_x000D_
}
_x000D_
html,_x000D_
body,_x000D_
#map {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>_x000D_
<div id="controls">_x000D_
<input type="button" value="Toggle All Markers" onClick="toggleMarkers()" />_x000D_
</div>_x000D_
<div id="map"></div>
_x000D_
You can still use map
if you can afford to create a makeshift array:
{
new Array(this.props.level).fill(0).map((_, index) => (
<span className='indent' key={index}></span>
))
}
This works because new Array(n).fill(x)
creates an array of size n
filled with x
, which can then aid map
.
You can do that with the following:
Form3 formshow = new Form3();
formshow.ShowDialog();
In mvc3 with razor @Html.Raw(Json.Encode(object))
seems to do the trick.
try
window.frameElement.ownerDocument.domain
USB 5v power is always on (even when the computer is turned off, on some computers and on some ports.) You will probably need to program an Arduino with some sort of switch, and control it via Serial library from USB plugged in to the computer.
In other words, a combination of this switch tutorial and this tutorial on communicating via Serial libary to Arduino plugged in via USB.
Adding to the popular answer to include this error:
"ERROR 1200 (HY000): The server is not configured as slave; fix in config file or with CHANGE MASTER TO",
Replication from slave in one shot:
In one terminal window:
mysql -h <Master_IP_Address> -uroot -p
After connecting,
RESET MASTER;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
The status appears as below: Note that position number varies!
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 | 98 | your_DB | |
+------------------+----------+--------------+------------------+
Export the dump similar to how he described "using another terminal"!
Exit and connect to your own DB(which is the slave):
mysql -u root -p
The type the below commands:
STOP SLAVE;
Import the Dump as mentioned (in another terminal, of course!) and type the below commands:
RESET SLAVE;
CHANGE MASTER TO
MASTER_HOST = 'Master_IP_Address',
MASTER_USER = 'your_Master_user', // usually the "root" user
MASTER_PASSWORD = 'Your_MasterDB_Password',
MASTER_PORT = 3306,
MASTER_LOG_FILE = 'mysql-bin.000001',
MASTER_LOG_POS = 98; // In this case
Once logged, set the server_id parameter (usually, for new / non-replicated DBs, this is not set by default),
set global server_id=4000;
Now, start the slave.
START SLAVE;
SHOW SLAVE STATUS\G;
The output should be the same as he described.
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Note: Once replicated, the master and slave share the same password!
All have to use bellow code:
$nday = time() + ( 24 * 60 * 60);
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Day: '. date('Y-m-d', $nday) ."\n";
Java converts Integer to int and back automatically (unless you are still with Java 1.4).
The shortcut command for --upgrade
:
pip install Django --upgrade
Is:
pip install Django -U
Just think of Database Index as Index of a book.
If you have a book about dogs and you want to find an information about let's say, German Shepherds, you could of course flip through all the pages of the book and find what you are looking for - but this of course is time consuming and not very fast.
Another option is that, you could just go to the Index section of the book and then find what you are looking for by using the Name of the entity you are looking ( in this instance, German Shepherds) and also looking at the page number to quickly find what you are looking for.
In Database, the page number is referred to as a pointer which directs the database to the address on the disk where entity is located. Using the same German Shepherd analogy, we could have something like this (“German Shepherd”, 0x77129) where 0x77129
is the address on the disk where the row data for German Shepherd is stored.
In short, an index is a data structure that stores the values for a specific column in a table so as to speed up query search.
If all you need to do is wait for the html on the page to become stable before trying to interact with elements, you can poll the DOM periodically and compare the results, if the DOMs are the same within the given poll time, you're golden. Something like this where you pass in the maximum wait time and the time between page polls before comparing. Simple and effective.
public void waitForJavascript(int maxWaitMillis, int pollDelimiter) {
double startTime = System.currentTimeMillis();
while (System.currentTimeMillis() < startTime + maxWaitMillis) {
String prevState = webDriver.getPageSource();
Thread.sleep(pollDelimiter); // <-- would need to wrap in a try catch
if (prevState.equals(webDriver.getPageSource())) {
return;
}
}
}
How about this
for (int i = 0; i < str.length(); i++) {
System.out.println(str.substring(i, i + 1));
}
There's a very interesting discussion of this type of issue here: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/
I think with absolutely no assumptions about the table that your O(n lg n) solution is the best. Though actually with a good optimizer or a slightly different technique the query you list may be a bit better, O(m*n) where m is the number of random rows desired, as it wouldn't necesssarily have to sort the whole large array, it could just search for the smallest m times. But for the sort of numbers you posted, m is bigger than lg n anyway.
Three asumptions we might try out:
there is a unique, indexed, primary key in the table
the number of random rows you want to select (m) is much smaller than the number of rows in the table (n)
the unique primary key is an integer that ranges from 1 to n with no gaps
With only assumptions 1 and 2 I think this can be done in O(n), though you'll need to write a whole index to the table to match assumption 3, so it's not necesarily a fast O(n). If we can ADDITIONALLY assume something else nice about the table, we can do the task in O(m log m). Assumption 3 would be an easy nice additional property to work with. With a nice random number generator that guaranteed no duplicates when generating m numbers in a row, an O(m) solution would be possible.
Given the three assumptions, the basic idea is to generate m unique random numbers between 1 and n, and then select the rows with those keys from the table. I don't have mysql or anything in front of me right now, so in slightly pseudocode this would look something like:
create table RandomKeys (RandomKey int)
create table RandomKeysAttempt (RandomKey int)
-- generate m random keys between 1 and n
for i = 1 to m
insert RandomKeysAttempt select rand()*n + 1
-- eliminate duplicates
insert RandomKeys select distinct RandomKey from RandomKeysAttempt
-- as long as we don't have enough, keep generating new keys,
-- with luck (and m much less than n), this won't be necessary
while count(RandomKeys) < m
NextAttempt = rand()*n + 1
if not exists (select * from RandomKeys where RandomKey = NextAttempt)
insert RandomKeys select NextAttempt
-- get our random rows
select *
from RandomKeys r
join table t ON r.RandomKey = t.UniqueKey
If you were really concerned about efficiency, you might consider doing the random key generation in some sort of procedural language and inserting the results in the database, as almost anything other than SQL would probably be better at the sort of looping and random number generation required.
The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:
FileSystemWatcher watcher;
private void watch()
{
watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
//Copies file to another directory.
}
ng-init
is a directive that can be placed inside div
's, span
's, whatever, whereas onload
is an attribute specific to the ng-include
directive that functions as an ng-init
. To see what I mean try something like:
<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>
You'll see that only the second one shows up.
An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.
(For completeness)
You could also query the (SQL-standard) information schema:
SELECT
table_schema || '.' || table_name
FROM
information_schema.tables
WHERE
table_type = 'BASE TABLE'
AND
table_schema NOT IN ('pg_catalog', 'information_schema');
Copying file to host:
scp SourceFile remoteuser@remotehost:/directory/TargetFile
Copying file from host:
scp user@host:/directory/SourceFile TargetFile
Copying directory recursively from host:
scp -r user@host:/directory/SourceFolder TargetFolder
NOTE: If the host is using a port other than port 22, you can specify it with the -P option:
scp -P 2222 user@host:/directory/SourceFile TargetFile
I assume due diligence here that you confirmed the CPU is actually consumed by SQL process (perfmon Process category counters would confirm this). Normally for such cases you take a sample of the relevant performance counters and you compare them with a baseline that you established in normal load operating conditions. Once you resolve this problem I recommend you do establish such a baseline for future comparisons.
You can find exactly where is SQL spending every single CPU cycle. But knowing where to look takes a lot of know how and experience. Is is SQL 2005/2008 or 2000 ? Fortunately for 2005 and newer there are a couple of off the shelf solutions. You already got a couple good pointer here with John Samson's answer. I'd like to add a recommendation to download and install the SQL Server Performance Dashboard Reports. Some of those reports include top queries by time or by I/O, most used data files and so on and you can quickly get a feel where the problem is. The output is both numerical and graphical so it is more usefull for a beginner.
I would also recommend using Adam's Who is Active script, although that is a bit more advanced.
And last but not least I recommend you download and read the MS SQL Customer Advisory Team white paper on performance analysis: SQL 2005 Waits and Queues.
My recommendation is also to look at I/O. If you added a load to the server that trashes the buffer pool (ie. it needs so much data that it evicts the cached data pages from memory) the result would be a significant increase in CPU (sounds surprising, but is true). The culprit is usually a new query that scans a big table end-to-end.
try [h!] first but else you can do it the ugly way.
LateX is a bit hard in placing images with such constraints as it manages placing itself. What I usually do if I want a figure right in that spot is do something like|:
text in front of image here
\newpage
\figure1
\figure2
text after images here
I know it may not be the correct way to do it but it works like a charm :).
//edit
You can do the same if you want a little text at top of the page but then just use /clearpage. Of course you can also scale them a bit smaller so it does not happen anymore. Maybe the non-seen whitespace is a bit larger than you suspect, I always try to scale down my image until they do appear on the same page, just to know for sure there is not like 1% overlap only making all of this not needed.
As other users have pointed out, we use expression()
. I'd like to answer the original question which involves a comma in the subscript:
How can I write v 1,2 with 1,2 as subscripts?
plot(1:10, 11:20 , main=expression(v["1,2"]))
Also, I'd like to add the reference for those looking to find the full expression
syntax in R
plotting: For more information see the ?plotmath
help page. Running demo(plotmath)
will showcase many expressions and relevant syntax.
Remember to use *
to join different types of text within an expression.
Here is some of the sample output from demo(plotmath)
:
Use net time
net time \\timesrv /set /yes
after your comment try this one in evelated prompt :
w32tm /config /update /manualpeerlist:yourtimerserver
If you can have your quote delimiter be double quotes, then this is a duplicate of Example JavaScript code to parse CSV data.
You can either translate all single-quotes to double-quotes first:
string = string.replace( /'/g, '"' );
...or you can edit the regex in that question to recognize single-quotes instead of double-quotes:
// Quoted fields.
"(?:'([^']*(?:''[^']*)*)'|" +
However, this assumes certain markup that is not clear from your question. Please clarify what all the various possibilities of markup can be, per my comment on your question.
In the project into the folder Libraries-->right click --> Add Library --> Mysqlconnector 5.1
So do you want them to get the IE password-challenge box, or should they be directed to your login page and enter their information there? If it's the second option, then you should at least enable Anonymous access to your login page, since the site won't know who they are yet.
If you want the first option, then the login page they're getting forwarded to will need to read the currently logged-in user and act based on that, since they would have had to correctly authenticate to get this far.
Here's a somewhat cleaner way of implementing this. This makes the following changes:
.src
attributes instead of DOM elements to make it work properly.Code:
function imageCache(base, firstNum, lastNum) {
this.cache = [];
var img;
for (var i = firstNum; i <= lastnum; i++) {
img = new Image();
img.src = base + i + ".jpg";
this.cache.push(img);
}
}
imageCache.prototype.nextImage(id) {
var element = document.getElementById(id);
var targetSrc = element.src;
var cache = this.cache;
for (var i = 0; i < cache.length; i++) {
if (cache[i].src) === targetSrc) {
i++;
if (i >= cache.length) {
i = 0;
}
element.src = cache[i].src;
return;
}
}
}
// sample usage
var myCache = new imageCache('images/img/Splash_image', 1, 6);
myCache.nextImage("foo");
Some advantages of this more object oriented and DRYed approach:
P.S. If you don't know what DRY stands for, it's "Don't Repeat Yourself" and basically means that you should never have many copies of similar looking code. Anytime you have that, it should be reduced somehow to a loop or function or something that removes the need for lots of similarly looking copies of code. The end result will be smaller, usually easier to maintain and often more reusable.
This is for the total beginner... like me:
HTML:
<ul>
<li>
<a href="#"> Home </a>
</li>
<li>
<a href="#Info"> Info </a>
</li>
</ul>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-view>
</div>
</div>
Angular:
//Create App
var app = angular.module("myApp", ["ngRoute"]);
//Configure routes
app.config(function ($routeProvider) {
$routeProvider
.otherwise({ template: "<p>Coming soon</p>" })
.when("/", {
template: "<p>Home information</p>"
})
.when("/Info", {
template: "<p>Basic information</p>"
//templateUrl: "/content/views/Info.html"
});
});
//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
$scope.location = $location.path();
$rootScope.$on('$routeChangeStart', function () {
console.log("routeChangeStart");
//Place code here:....
});
});
Hope this helps a total beginner like me. Here is the full working sample:
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#"> Home </a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#Info"> Info </a>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MainCtrl">_x000D_
<div ng-view>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
<script>_x000D_
//Create App_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
_x000D_
//Configure routes_x000D_
app.config(function ($routeProvider) {_x000D_
$routeProvider_x000D_
.otherwise({ template: "<p>Coming soon</p>" })_x000D_
.when("/", {_x000D_
template: "<p>Home information</p>"_x000D_
})_x000D_
.when("/Info", {_x000D_
template: "<p>Basic information</p>"_x000D_
//templateUrl: "/content/views/Info.html"_x000D_
});_x000D_
});_x000D_
_x000D_
//Controller_x000D_
app.controller('MainCtrl', function ($scope, $rootScope, $location) {_x000D_
$scope.location = $location.path();_x000D_
$rootScope.$on('$routeChangeStart', function () {_x000D_
console.log("routeChangeStart");_x000D_
//Place code here:...._x000D_
});_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Reading your requirements the simplest way would be to display a mode-less form and use a standard System.Windows.Forms timer to update the progress on the mode-less form. No threads, no possible memory leaks.
As this only uses the one UI thread, you would also need to call Application.DoEvents() at certain points during your main processing to guarantee the progress bar is updated visually.
Try to uncheck the CheckBox “Use Managed Compatibility Mode” in
Tools => Options => Debugging => General
It worked for me.
Why are they using
<i>
tag to display icons ?
Because it is:
Is it not a bad practice ?
Awful practice. It is a triumph of performance over semantics.
git branch --set-upstream-to origin/solaris
The answer to the question you asked—which I'll rephrase a bit as "do I have to set an upstream"—is: no, you don't have to set an upstream at all.
If you do not have upstream for the current branch, however, Git changes its behavior on git push
, and on other commands as well.
The complete push story here is long and boring and goes back in history to before Git version 1.5. To shorten it a whole lot, git push
was implemented poorly.1 As of Git version 2.0, Git now has a configuration knob spelled push.default
which now defaults to simple
. For several versions of Git before and after 2.0, every time you ran git push
, Git would spew lots of noise trying to convince you to set push.default
just to get git push
to shut up.
You do not mention which version of Git you are running, nor whether you have configured push.default
, so we must guess. My guess is that you are using Git version 2-point-something, and that you have set push.default
to simple
to get it to shut up. Precisely which version of Git you have, and what if anything you have push.default
set to, does matter, due to that long and boring history, but in the end, the fact that you're getting yet another complaint from Git indicates that your Git is configured to avoid one of the mistakes from the past.
An upstream is simply another branch name, usually a remote-tracking branch, associated with a (regular, local) branch.
Every branch has the option of having one (1) upstream set. That is, every branch either has an upstream, or does not have an upstream. No branch can have more than one upstream.
The upstream should, but does not have to be, a valid branch (whether remote-tracking like origin/B
or local like master
). That is, if the current branch B has upstream U, git rev-parse U
should work. If it does not work—if it complains that U does not exist—then most of Git acts as though the upstream is not set at all. A few commands, like git branch -vv
, will show the upstream setting but mark it as "gone".
If your push.default
is set to simple
or upstream
, the upstream setting will make git push
, used with no additional arguments, just work.
That's it—that's all it does for git push
. But that's fairly significant, since git push
is one of the places where a simple typo causes major headaches.
If your push.default
is set to nothing
, matching
, or current
, setting an upstream does nothing at all for git push
.
(All of this assumes your Git version is at least 2.0.)
git fetch
If you run git fetch
with no additional arguments, Git figures out which remote to fetch from by consulting the current branch's upstream. If the upstream is a remote-tracking branch, Git fetches from that remote. (If the upstream is not set or is a local branch, Git tries fetching origin
.)
git merge
and git rebase
tooIf you run git merge
or git rebase
with no additional arguments, Git uses the current branch's upstream. So it shortens the use of these two commands.
git pull
You should never2 use git pull
anyway, but if you do, git pull
uses the upstream setting to figure out which remote to fetch from, and then which branch to merge or rebase with. That is, git pull
does the same thing as git fetch
—because it actually runs git fetch
—and then does the same thing as git merge
or git rebase
, because it actually runs git merge
or git rebase
.
(You should usually just do these two steps manually, at least until you know Git well enough that when either step fails, which they will eventually, you recognize what went wrong and know what to do about it.)
git status
This may actually be the most important. Once you have an upstream set, git status
can report the difference between your current branch and its upstream, in terms of commits.
If, as is the normal case, you are on branch B
with its upstream set to origin/B
, and you run git status
, you will immediately see whether you have commits you can push, and/or commits you can merge or rebase onto.
This is because git status
runs:
git rev-list --count @{u}..HEAD
: how many commits do you have on B
that are not on origin/B
?git rev-list --count HEAD..@{u}
: how many commits do you have on origin/B
that are not on B
?Setting an upstream gives you all of these things.
master
already has an upstream set?When you first clone from some remote, using:
$ git clone git://some.host/path/to/repo.git
or similar, the last step Git does is, essentially, git checkout master
. This checks out your local branch master
—only you don't have a local branch master
.
On the other hand, you do have a remote-tracking branch named origin/master
, because you just cloned it.
Git guesses that you must have meant: "make me a new local master
that points to the same commit as remote-tracking origin/master
, and, while you're at it, set the upstream for master
to origin/master
."
This happens for every branch you git checkout
that you do not already have. Git creates the branch and makes it "track" (have as an upstream) the corresponding remote-tracking branch.
If you create a new branch:
$ git checkout -b solaris
there is, as yet, no origin/solaris
. Your local solaris
cannot track remote-tracking branch origin/solaris
because it does not exist.
When you first push the new branch:
$ git push origin solaris
that creates solaris
on origin
, and hence also creates origin/solaris
in your own Git repository. But it's too late: you already have a local solaris
that has no upstream.3
Probably. See "implemented poorly" and footnote 1. It's hard to change now: There are millions4 of scripts that use Git and some may well depend on its current behavior. Changing the behavior requires a new major release, nag-ware to force you to set some configuration field, and so on. In short, Git is a victim of its own success: whatever mistakes it has in it, today, can only be fixed if the change is either mostly invisible, clearly-much-better, or done slowly over time.
The fact is, it doesn't today, unless you use --set-upstream
or -u
during the git push
. That's what the message is telling you.
You don't have to do it like that. Well, as we noted above, you don't have to do it at all, but let's say you want an upstream. You have already created branch solaris
on origin
, through an earlier push, and as your git branch
output shows, you already have origin/solaris
in your local repository.
You just don't have it set as the upstream for solaris
.
To set it now, rather than during the first push, use git branch --set-upstream-to
. The --set-upstream-to
sub-command takes the name of any existing branch, such as origin/solaris
, and sets the current branch's upstream to that other branch.
That's it—that's all it does—but it has all those implications noted above. It means you can just run git fetch
, then look around, then run git merge
or git rebase
as appropriate, then make new commits and run git push
, without a bunch of additional fussing-around.
1To be fair, it was not clear back then that the initial implementation was error-prone. That only became clear when every new user made the same mistakes every time. It's now "less poor", which is not to say "great".
2"Never" is a bit strong, but I find that Git newbies understand things a lot better when I separate out the steps, especially when I can show them what git fetch
actually did, and they can then see what git merge
or git rebase
will do next.
3If you run your first git push
as git push -u origin solaris
—i.e., if you add the -u
flag—Git will set origin/solaris
as the upstream for your current branch if (and only if) the push succeeds. So you should supply -u
on the first push. In fact, you can supply it on any later push, and it will set or change the upstream at that point. But I think git branch --set-upstream-to
is easier, if you forgot.
4Measured by the Austin Powers / Dr Evil method of simply saying "one MILLLL-YUN", anyway.
This may be off topic, but for those who are struggling on how to exactly change also the font of the button text (that was my case and Skatephone's answer helped me) here's how I did it (if you made buttons ind design mode):
First we need to have the button's string name "converted" (it's a foul way to explain, but straightforward) into java from the xml, and so we paste the aforementioned code into our MainActivity.java
IMPORTANT! place the code under the OnCreate method!
import android.widget.RemoteViews;
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");
Keep in mind:
my_layout
has to be substituted with the xml file where your buttons are
Counter
has to be substituted with the id name of your button ("@+id/ButtonName"
)
if you want to change the button text just insert the text in place of "Set button text here"
here comes the part where you change the font:
Now that you "converted" from xml to java, you can set a Typeface method for TextView. Paste the following code exactly under the previous one just described above
TextView txt = (TextView) findViewById(R.id.text_your_text_view_id);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MyFontName.ttf");
txt.setTypeface(font);
where in place of text_your_text_view_id
you put your button's id name (like as previous code) and in place of MyFontName.ttf
you put your desired font
WARNING! This assumes you already put your desired font into the assets/font folder. e.g. assets/fonts/MyFontName.ttf
If you want to refer to calculated column on the "same query level" then you could use CROSS APPLY
(Oracle 12c):
--Sample data:
CREATE TABLE tab(ColumnA NUMBER(10,2),ColumnB NUMBER(10,2),ColumnC NUMBER(10,2));
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2);
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (3, 15, 6);
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (7, 14, 3);
COMMIT;
Query:
SELECT
ColumnA,
ColumnB,
sub.calccolumn1,
sub.calccolumn1 / ColumnC AS calccolumn2
FROM tab t
CROSS APPLY (SELECT t.ColumnA + t.ColumnB AS calccolumn1 FROM dual) sub;
Please note that expression from CROSS APPLY/OUTER APPLY
is available in other clauses too:
SELECT
ColumnA,
ColumnB,
sub.calccolumn1,
sub.calccolumn1 / ColumnC AS calccolumn2
FROM tab t
CROSS APPLY (SELECT t.ColumnA + t.ColumnB AS calccolumn1 FROM dual) sub
WHERE sub.calccolumn1 = 12;
-- GROUP BY ...
-- ORDER BY ...;
This approach allows to avoid wrapping entire query with outerquery or copy/paste same expression in multiple places(with complex one it could be hard to maintain).
Related article: The SQL Language’s Most Missing Feature
From what I see, people use package.json scripts when they would like to run script in simpler way. For example, to use nodemon
that installed in local node_modules, we can't call nodemon
directly from the cli, but we can call it by using ./node_modules/nodemon/nodemon.js
. So, to simplify this long typing, we can put this...
... scripts: { 'start': 'nodemon app.js' } ...
... then call npm start
to use 'nodemon' which has app.js as the first argument.
What I'm trying to say, if you just want to start your server with the node
command, I don't think you need to use scripts
. Typing npm start
or node app.js
has the same effort.
But if you do want to use nodemon
, and want to pass a dynamic argument, don't use script
either. Try to use symlink instead.
For example using migration with sequelize
. I create a symlink...
ln -s node_modules/sequelize/bin/sequelize sequelize
... And I can pass any arguement when I call it ...
./sequlize -h /* show help */
./sequelize -m /* upgrade migration */
./sequelize -m -u /* downgrade migration */
etc...
At this point, using symlink is the best way I could figure out, but I don't really think it's the best practice.
I also hope for your opinion to my answer.
try to change your method if you need to loop!
within the parent stored procedure, create a #temp table that contains the data that you need to process. Call the child stored procedure, the #temp table will be visible and you can process it, hopefully working with the entire set of data and without a cursor or loop.
this really depends on what this child stored procedure is doing. If you are UPDATE-ing, you can "update from" joining in the #temp table and do all the work in one statement without a loop. The same can be done for INSERT and DELETEs. If you need to do multiple updates with IFs you can convert those to multiple UPDATE FROM
with the #temp table and use CASE statements or WHERE conditions.
When working in a database try to lose the mindset of looping, it is a real performance drain, will cause locking/blocking and slow down the processing. If you loop everywhere, your system will not scale very well, and will be very hard to speed up when users start complaining about slow refreshes.
Post the content of this procedure you want call in a loop, and I'll bet 9 out of 10 times, you could write it to work on a set of rows.
In case you want to do it programmatically,
checkBoxOrRadioButton.setButtonDrawable(null);
checkBoxOrRadioButton.setBackgroundResource(R.drawable.resource_name);
Why not use insertAdjacentHTML
for example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here
Don't use tellg
to determine the exact size of the file. The length determined by tellg
will be larger than the number of characters can be read from the file.
From stackoverflow question tellg() function give wrong size of file? tellg
does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It's not even guaranteed that you can convert the type to an integral type.). For Windows (and most non-Unix systems), in text mode, there is no direct and immediate mapping between what tellg returns and the number of bytes you must read to get to that position.
If it is important to know exactly how many bytes you can read, the only way of reliably doing so is by reading. You should be able to do this with something like:
#include <fstream>
#include <limits>
ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear(); // Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );
You may want to comment out the DL is deprecated, please use Fiddle
warning at
C:\Ruby200\lib\ruby\2.0.0\dl.rb
since it’s annoying and you are not the irb/pry or some other gems code owner
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
=============== and for post
$.ajax({ type: 'post',
must be met with
app.post('/', function(req, res) {
There's a very nice extension to VS2010, which does exactly this: Solution Explorer Tools.
This extension adds a button which selects the current file in the solution explorer, as well as convenient buttons for collapsing and expanding projects.
The dialog needs to be started only after the window states of the Activity are initialized This happens only after onresume.
So call
runOnUIthread(new Runnable(){
showInfoMessageDialog("Please check your network connection","Network Alert");
});
in your OnResume function. Do not create dialogs in OnCreate
Edit:
use this
Handler h = new Handler();
h.postDelayed(new Runnable(){
showInfoMessageDialog("Please check your network connection","Network Alert");
},500);
in your Onresume instead of showonuithread
Since <input>
element displays only value of value attribute, we have to manipulate only it:
<input type="submit" class="btn fa-input" value=" Input">
I'm using 
entity here, which corresponds to the U+F043, the Font Awesome's 'tint' symbol.
Then we have to style it to use the font:
.fa-input {
font-family: FontAwesome, 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
Which will give us the tint symbol in Font Awesome and the other text in the appropriate font.
However, this control will not be pixel-perfect, so you might have to tweak it by yourself.
You can use :nth-last-child()
; in fact, besides :nth-last-of-type()
I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.
ul li:nth-last-child(2)
Another C++ one. Optimized for speed and size.
bool is_palindrome(const std::string& candidate) {
for(std::string::const_iterator left = candidate.begin(), right = candidate.end(); left < --right ; ++left)
if (*left != *right)
return false;
return true;
}
An example I found somewhere here in the past. Might be of some help:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class Form1 : Form
{
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
//Mouse actions
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
public Form1()
{
}
public void DoMouseClick()
{
//Call the imported function with the cursor's current position
uint X = (uint)Cursor.Position.X;
uint Y = (uint)Cursor.Position.Y;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
}
//...other code needed for the application
}
I'm asked this question very frequently, if it's smart to use "Share project..." if a eclipse project has been disconnected from it SVN counterpart in the repository. So, I append my answer to this thread.
The SVN-Team option "Share project ..." is totally fine for projects that exist in SVN and in your Eclipse workspace, even if the Eclipse project is missing the hidden .svn configuration. You can still connect them. Eclipse SVN-implementation (Subclipse/Subversive) will verify if the provided SVN http(s) source is populated. If yes, all existing files will be copied and linked (checked out in SVN terms) to your very personal Eclipse workspace.
Word of caution:
regards, Feder
If you want to make sure that the library is loaded if and only if the program lunar-calendar-gtk
is launched, you can apply this:
You set the environment variable per command by prefixing the command with it:
$ LD_PRELOAD="liblunar-calendar-preload.so" printenv "LD_PRELOAD"
liblunar-calendar-preload.so
$ printenv "LD_PRELOAD"
$
You can then choose to put this in a shell script and make lunar-calendar-gtk
a symlink to this shell script, replaceing the original referencee. This effectively makes sure that the library is loaded everytime the original application is executed.
You will have to rename the original lunar-calendar-gtk
to something else, which might not be too intriguing as it possibly may cause issues with uninstallation and upgrading. However, I found it useful with a former version of Skype.
I use inf/-inf as initial values to find minimum/maximum value of a measurement. Lets say that you measure temperature with a sensor and you want to keep track of minimum/maximum temperature. The sensor might provide a valid temperature or might be broken. Pseudocode:
# initial value of the temperature
t = float('nan')
# initial value of minimum temperature, so any measured temp. will be smaller
t_min = float('inf')
# initial value of maximum temperature, so any measured temp. will be bigger
t_max = float('-inf')
while True:
# measure temperature, if sensor is broken t is not changed
t = measure()
# find new minimum temperature
t_min = min(t_min, t)
# find new maximum temperature
t_max = max(t_max, t)
The above code works because inf/-inf/nan are valid for min/max operation, so there is no need to deal with exceptions.
Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that
package main
import (
"fmt"
"reflect"
)
type person struct {
firsName string
lastName string
iceCream []string
}
func main() {
u := struct {
myMap map[int]int
mySlice []string
myPerson person
}{
myMap: map[int]int{1: 10, 2: 20},
mySlice: []string{"red", "green"},
myPerson: person{
firsName: "Esmaeil",
lastName: "Abedi",
iceCream: []string{"Vanilla", "chocolate"},
},
}
v := reflect.ValueOf(u)
for i := 0; i < v.NumField(); i++ {
fmt.Println(v.Type().Field(i).Name)
fmt.Println("\t", v.Field(i))
}
}
and there is no *panic* for v.Field(i)
I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly/project. I came up with the following thanks to the source code of the DynamicJson project:
public XmlDocument JsonToXML(string json)
{
XmlDocument doc = new XmlDocument();
using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
{
XElement xml = XElement.Load(reader);
doc.LoadXml(xml.ToString());
}
return doc;
}
Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from JSON to XML, there are various ways to do the opposite.
scp -r C:/site user@server_ip:path
path
is the place, where site
will be copied into the remote server
EDIT: As I said in my comment, try pscp
, as you want to use scp
using PuTTY
.
The other option is WinSCP
Try this
For red color,
<string name="hello_worldRed"><![CDATA[<b><font color=#FF0000>Hello world!</font></b>]]></string>
For blue,
<string name="hello_worldBlue"><![CDATA[<b><font color=#0000FF>Hello world!</font></b>]]></string>
In java code,
//red color text
TextView redColorTextView = (TextView)findViewById(R.id.redText);
String redString = getResources().getString(R.string.hello_worldRed)
redColorTextView.setText(Html.fromHtml(redString));
//Blue color text
TextView blueColorTextView = (TextView)findViewById(R.id.blueText);
String blueString = getResources().getString(R.string.hello_worldBlue)
blueColorTextView.setText(Html.fromHtml(blueString));
Try this:
def word(string, num)
string = 'Smith'
string[0..(num-1)]
end
Simply in JavaScript, you can redirect to a specific page by using the following:
window.location.replace("http://www.test.com");
Or
location.replace("http://www.test.com");
Or
window.location.href = "http://www.test.com";
Using jQuery:
$(window).attr("location","http://www.test.com");
Harish has the answer here - except you need to request manage_pages
permission when authenticating and then using the page-id
instead of me
when posting....
$result = $facebook->api('page-id/feed/','post',$attachment);
Take a look at CBFG and the Android port of the loading/rendering code. You should be able to drop the code into your project and use it straight away.
CBFG - http://www.codehead.co.uk/cbfg
Android loader - http://www.codehead.co.uk/cbfg/TexFont.java
You can also use this:
.dropdown {
height: 0px;
width: 0px;
opacity: .0;
color: white;
}
.dropdown:hover {
height: 20px;
width: 50px;
opacity: 1;
transition: opacity 200ms;
/* Safari */
-webkit-transition: opacity 200ms;
}
Install Flysystem:
composer require league/flysystem-sftp
Then:
use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;
$filesystem = new Filesystem(new SftpAdapter([
'host' => 'example.com',
'port' => 22,
'username' => 'username',
'password' => 'password',
'privateKey' => 'path/to/or/contents/of/privatekey',
'root' => '/path/to/root',
'timeout' => 10,
]));
$filesystem->listFiles($path); // get file lists
$filesystem->read($path_to_file); // grab file
$filesystem->put($path); // upload file
....
Read:
It could be even caused by your ad blocker.
Try to disable it or adding an exception for the domain from which the images come from.