I assume your game has a main loop, and all your sprites are in a list called sprites
.
In your main loop, get all events, and check for the MOUSEBUTTONDOWN
or MOUSEBUTTONUP
event.
while ... # your main loop
# get all events
ev = pygame.event.get()
# proceed events
for event in ev:
# handle MOUSEBUTTONUP
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
# get a list of all sprites that are under the mouse cursor
clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
# do something with the clicked sprites...
So basically you have to check for a click on a sprite yourself every iteration of the mainloop. You'll want to use mouse.get_pos() and rect.collidepoint().
Pygame does not offer event driven programming, as e.g. cocos2d does.
Another way would be to check the position of the mouse cursor and the state of the pressed buttons, but this approach has some issues.
if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()):
print ("You have opened a chest!")
You'll have to introduce some kind of flag if you handled this case, since otherwise this code will print "You have opened a chest!" every iteration of the main loop.
handled = False
while ... // your loop
if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()) and not handled:
print ("You have opened a chest!")
handled = pygame.mouse.get_pressed()[0]
Of course you can subclass Sprite
and add a method called is_clicked
like this:
class MySprite(Sprite):
...
def is_clicked(self):
return pygame.mouse.get_pressed()[0] and self.rect.collidepoint(pygame.mouse.get_pos())
So, it's better to use the first approach IMHO.
In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.
To get detail out of each value in a multidimensional array is quite straightforward once you have your array in place. So this is the array:
$example_array = array(
array('1','John','Smith'),
array('2','Dave','Jones'),
array('3','Bob','Williams')
);
Then use a foreach loop and have the array ran through like this:
foreach ($example_array as $value) {
echo $value[0]; //this will echo 1 on first cycle, 2 on second etc....
echo $value[1]; //this will echo John on first cycle, Dave on second etc....
echo $value[2]; //this will echo Smith on first cycle, Jones on second etc....
}
You can echo whatever you like around it to, so to echo into a table:
echo "<table>"
foreach ($example_array as $value) {
echo "<tr><td>" . $value[0] . "</td>";
echo "<td>" . $value[1] . "</td>";
echo "<td>" . $value[2] . "</td></tr>";
}
echo "</table>";
Should give you a table like this:
|1|John|Smith |
|2|Dave|Jones |
|3|Bob |Williams|
As far as I know, by using only Docker this is not possible. You need some DNS to map container ip:s to hostnames.
If you want out of the box solution. One solution is to use for example Kontena. It comes with network overlay technology from Weave and this technology is used to create virtual private LAN networks for each service and every service can be reached by service_name.kontena.local-address
.
Here is simple example of Wordpress application's YAML file where Wordpress service connects to MySQL server with wordpress-mysql.kontena.local address:
wordpress:
image: wordpress:4.1
stateful: true
ports:
- 80:80
links:
- mysql:wordpress-mysql
environment:
- WORDPRESS_DB_HOST=wordpress-mysql.kontena.local
- WORDPRESS_DB_PASSWORD=secret
mysql:
image: mariadb:5.5
stateful: true
environment:
- MYSQL_ROOT_PASSWORD=secret
There are a couple of things to be aware of:
src/main/resources/public
will be served from the root of your application.
For example src/main/resources/public/hello.jpg
would be served from http://localhost:8080/hello.jpg
This is why your current matcher configuration hasn't permitted access to the static resources. For /resources/**
to work, you would have to place the resources in src/main/resources/public/resources
and access them at http://localhost:8080/resources/your-resource
.
As you're using Spring Boot, you may want to consider using its defaults rather than adding extra configuration. Spring Boot will, by default, permit access to /css/**
, /js/**
, /images/**
, and /**/favicon.ico
. You could, for example, have a file named src/main/resources/public/images/hello.jpg
and, without adding any extra configuration, it would be accessible at http://localhost:8080/images/hello.jpg
without having to log in. You can see this in action in the web method security smoke test where access is permitted to the Bootstrap CSS file without any special configuration.
Install cors dependency in your project:
npm i --save cors
Add to your server configuration file the following:
var cors = require('cors');
app.use(cors());
It works for me with 2.8.4 cors version.
^
for start of the string pattern,
?
for allowing 0 or 1 time repeat. ie., s?
s can exist 1 time or no need to exist at all.
/
is a special character in regex so it needs to be escaped by a backslash \/
/^https?:\/\//.test('https://www.bbc.co.uk/sport/cricket'); // true
/^https?:\/\//.test('http://www.bbc.co.uk/sport/cricket'); // true
/^https?:\/\//.test('ftp://www.bbc.co.uk/sport/cricket'); // false
You can use
<mat-checkbox [attr.checked] = "myCondition ? 'checked' : null">
if the checked attribute is set to null, it gets removed from the html tag
or you can use Vega's anwser which should work too (mine is a completion that can be usefull if you don't want to link it with ngModel)
Apparently this would be possible in settings.gradle
with something like this.
rootProject.name = 'someName'
gradle.rootProject {
it.sourceCompatibility = '1.7'
}
I recently received advice that a project property can be set by using a closure which will be called later when the Project is available.
If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &
-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:
void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference
You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)
), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.
Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.
I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:
void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }
int main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foo1(arr);
foo2(arr);
foo3(arr);
foo4(arr);
}
Adding to @gojomo you could use :after
pseudo element for the additional element. The only caveat is that you'll need to define your innerText
in a data-text
attribute since CSS has limited content
functions.
s {_x000D_
color: red;_x000D_
text-align: -1000em;_x000D_
overflow: hidden;_x000D_
}_x000D_
s:after {_x000D_
color: black;_x000D_
content: attr(data-text);_x000D_
}
_x000D_
<s data-text="Strikethrough">Strikethrough</s>
_x000D_
Instead of a size divisor of 1024 * 1024
you could use the <<
bitwise shifting operator, i.e. 1<<20
to get megabytes, 1<<30
to get gigabytes, etc.
In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20)
which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR
.
Megabytes are usually all that you need, or otherwise something like this can be used:
# bytes pretty-printing
UNITS_MAPPING = [
(1<<50, ' PB'),
(1<<40, ' TB'),
(1<<30, ' GB'),
(1<<20, ' MB'),
(1<<10, ' KB'),
(1, (' byte', ' bytes')),
]
def pretty_size(bytes, units=UNITS_MAPPING):
"""Get human-readable file sizes.
simplified version of https://pypi.python.org/pypi/hurry.filesize/
"""
for factor, suffix in units:
if bytes >= factor:
break
amount = int(bytes / factor)
if isinstance(suffix, tuple):
singular, multiple = suffix
if amount == 1:
suffix = singular
else:
suffix = multiple
return str(amount) + suffix
print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))
## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB
You have also the possibility to write a custom filter for your date, that display it in UTC format. Note that I used toUTCString()
.
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('dateCtrl', function($scope) {_x000D_
$scope.today = new Date();_x000D_
});_x000D_
_x000D_
app.filter('utcDate', function() {_x000D_
return function(input) {_x000D_
return input.toUTCString();_x000D_
};_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> _x000D_
_x000D_
<div ng-app="myApp" ng-controller="dateCtrl"> _x000D_
Today is {{today | utcDate}} _x000D_
</div>
_x000D_
How about this:
$(this).css('background-color', '#FFFFFF');
Related post: Add background color and border to table row on hover using jquery
Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.
Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:
As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the
CreateThread
function will not setup the stack correctly for the C runtime library. You should use_beginthreadex
instead, which is (almost) completely compatible withCreateThread
.
Very simple.... Try these steps:
Step 1: Add the SystemConfiguration
framework into your project.
Step 2: Import the following code into your header
file.
#import <SystemConfiguration/SystemConfiguration.h>
Step 3: Use the following method
Type 1:
- (BOOL) currentNetworkStatus {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
BOOL connected;
BOOL isConnected;
const char *host = "www.apple.com";
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host);
SCNetworkReachabilityFlags flags;
connected = SCNetworkReachabilityGetFlags(reachability, &flags);
isConnected = NO;
isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(reachability);
return isConnected;
}
Type 2:
Import header : #import "Reachability.h"
- (BOOL)currentNetworkStatus
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}
Step 4: How to use:
- (void)CheckInternet
{
BOOL network = [self currentNetworkStatus];
if (network)
{
NSLog(@"Network Available");
}
else
{
NSLog(@"No Network Available");
}
}
This is usually caused by duplicates in the query specified in USING clause. This probably means that TABLE_A is a parent table and the same ROWID is returned several times.
You could quickly solve the problem by using a DISTINCT in your query (in fact, if 'Y' is a constant value you don't even need to put it in the query).
Assuming your query is correct (don't know your tables) you could do something like this:
MERGE INTO table_1 a
USING
(SELECT distinct ta.ROWID row_id
FROM table_1 a ,table_2 b ,table_3 c
WHERE a.mbr = c.mbr
AND b.head = c.head
AND b.type_of_action <> '6') src
ON ( a.ROWID = src.row_id )
WHEN MATCHED THEN UPDATE SET in_correct = 'Y';
When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like
public interface Thunk { void apply(); }
somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.
In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.
Try out df.apply() if you've a small/medium dataframe,
df['c2'] = df.apply(lambda x: 10 if x['c1'] == 'Value' else x['c1'], axis = 1)
Else, follow the slicing techniques mentioned in the above comments if you've got a big dataframe.
Not sure what the author of that code wanted to achieve. Definining a function inside another function does NOT mean that the inner function is only visible inside the outer function. After calling x() the first time, the y() function will be in global scope as well.
$wpdb->get_results("SELECT ...", ARRAY_A);
ARRAY_A is a "output_type" argument. It can be one of four pre-defined constants (defaults to OBJECT):
OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first columns values as keys (duplicates will be discarded).
ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys.
ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:
set rowcount @top
select * from sometable
set rowcount 0
Hope this helps
Oisin.
(edited to replace @@rowcount with rowcount - thanks augustlights)
I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:
Make sure ESLint is not run with the --no-inline-config
flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):
/* eslint-env browser */
This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.
There are plenty of environments, and you can declare more than one at the same time, for example, in-line:
/* eslint-env browser, node */
If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.
From their docs:
An environment defines global variables that are predefined. The available environments are:
browser
- browser global variables.node
- Node.js global variables and Node.js scoping.commonjs
- CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).shared-node-browser
- Globals common to both Node and Browser.[...]
Besides environments, you can make it ignore anything you want. If it warns you about using console.log()
but you don't want to be warned about it, just inline:
/* eslint-disable no-console */
You can see the list of all rules, including recommended rules to have for best coding practices.
remove the ios::binary
from your modes in your ofstream and use studentPassword.c_str()
instead of (char *)&studentPassword
in your write.write()
Based on @Fletcher Johns answer I came up with:
open class AddressView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {
protected lateinit var countryInputLayout: TextInputLayout
protected lateinit var countryAutoCompleteTextView: CountryAutoCompleteTextView
protected lateinit var cityInputLayout: TextInputLayout
protected lateinit var cityEditText: CityEditText
protected lateinit var postCodeInputLayout: TextInputLayout
protected lateinit var postCodeEditText: PostCodeEditText
protected lateinit var streetInputLayout: TextInputLayout
protected lateinit var streetEditText: StreetEditText
init {
initView()
}
private fun initView() {
val view = inflate(context, R.layout.view_address, this)
orientation = VERTICAL
countryInputLayout = view.findViewById(R.id.countryInputLayout)
countryAutoCompleteTextView = view.findViewById(R.id.countryAutoCompleteTextView)
streetInputLayout = view.findViewById(R.id.streetInputLayout)
streetEditText = view.findViewById(R.id.streetEditText)
cityInputLayout = view.findViewById(R.id.cityInputLayout)
cityEditText = view.findViewById(R.id.cityEditText)
postCodeInputLayout = view.findViewById(R.id.postCodeInputLayout)
postCodeEditText = view.findViewById(R.id.postCodeEditText)
}
// Declare your direct and indirect child views that need to be saved
private val childrenToSave get() = mapOf<String, View>(
"coutryIL" to countryInputLayout,
"countryACTV" to countryAutoCompleteTextView,
"streetIL" to streetInputLayout,
"streetET" to streetEditText,
"cityIL" to cityInputLayout,
"cityET" to cityEditText,
"postCodeIL" to postCodeInputLayout,
"postCodeET" to postCodeEditText,
)
private var viewIds: HashMap<String, Int>? = null
override fun onSaveInstanceState(): Parcelable? {
// Create a bundle to put super parcelable in
val bundle = Bundle()
bundle.putParcelable(SUPER_INSTANCE_STATE, super.onSaveInstanceState())
// Store viewIds in the bundle - initialize if necessary.
if (viewIds == null) {
childrenToSave.values.forEach { view -> view.id = generateViewId() }
viewIds = HashMap<String, Int>(childrenToSave.mapValues { (key, view) -> view.id })
}
bundle.putSerializable(STATE_VIEW_IDS, viewIds)
return bundle
}
override fun onRestoreInstanceState(state: Parcelable?) {
// We know state is a Bundle:
val bundle = state as Bundle
// Get mViewIds out of the bundle
viewIds = bundle.getSerializable(STATE_VIEW_IDS) as HashMap<String, Int>
// For each id, assign to the view of same index
if (viewIds != null) {
viewIds!!.forEach { (key, id) -> childrenToSave[key]!!.id = id }
}
super.onRestoreInstanceState(bundle.getParcelable(SUPER_INSTANCE_STATE))
}
companion object {
private const val SUPER_INSTANCE_STATE = "saved_instance_state_parcelable"
private const val STATE_VIEW_IDS = "state_view_ids"
}
}
You can use the is function
if( $('#cartContent').is(':empty') ) { }
or use the length
if( $('#cartContent:empty').length ) { }
check for this by calling the library jquery after the noconflict.js or that this calling more than once jquery library after the noconflict.js
You can use Union or Concat, the former removes duplicates, the later doesn't
foreach (var item in List1.Union(List1))
{
//TODO: Real code goes here
}
foreach (var item in List1.Concat(List1))
{
//TODO: Real code goes here
}
This is somewhat ago but it still might be useful.
My experience shows that resizing the image in-memory before passing it to tesseract sometimes helps.
Try different modes of interpolation. The post https://stackoverflow.com/a/4756906/146003 helped me a lot.
1- Register the notification in the viewWillAppear
method:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
2- Method to be called:
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
print(keyboardHeight)
}
}
I am elaborating a bit on o.k.w.'s answer.
You can use the browser's DOM functions for that.
var utils = {
dummy: document.createElement('div'),
escapeHTML: function(s) {
this.dummy.textContent = s
return this.dummy.innerHTML
}
}
utils.escapeHTML('<escapeThis>&')
This returns <escapeThis>&
It uses the standard function createElement
to create an invisible element, then uses the function textContent
to set any string as its content and then innerHTML
to get the content in its HTML representation.
The MVCFutures for ASP.NET MVC decided to do both. In fact if you provide 'alt' it will automatically create a 'title' with the same value for you.
I don't have the source code to hand but a quick google search turned up a test case for it!
[TestMethod]
public void ImageWithAltValueInObjectDictionaryRendersImageWithAltAndTitleTag() {
HtmlHelper html = TestHelper.GetHtmlHelper(new ViewDataDictionary());
string imageResult = html.Image("/system/web/mvc.jpg", new { alt = "this is an alt value" });
Assert.AreEqual("<img alt=\"this is an alt value\" src=\"/system/web/mvc.jpg\" title=\"this is an alt value\" />", imageResult);
}
Interesting blog post here:
http://geekswithblogs.net/cskardon/archive/2008/06/23/dispose-of-a-wpf-usercontrol-ish.aspx
It mentions subscribing to Dispatcher.ShutdownStarted to dispose of your resources.
Pass by value sends a COPY of the data stored in the variable you specify, pass by reference sends a direct link to the variable itself. So if you pass a variable by reference and then change the variable inside the block you passed it into, the original variable will be changed. If you simply pass by value, the original variable will not be able to be changed by the block you passed it into but you will get a copy of whatever it contained at the time of the call.
You can use the regular expression /(?!$)/
:
"overpopulation".split(/(?!$)/)
The negative look-ahead assertion (?!$)
will match right in front of every character.
hi,that maybe the project's problem,
chose the project and setting you eclipse:
project -> clean...
There are many suggestions here. The bitwise OR seems to be the simplest by far. Here is another short solution which works with negative numbers as well using the modulo operator. It is probably easier to understand than the bitwise OR:
intval = floatval - floatval%1;
This method also works with high value numbers where neither '|0' nor '~~' nor '>>0' work correctly:
> n=4294967295;
> n|0
-1
> ~~n
-1
> n>>0
-1
> n-n%1
4294967295
Thanks. I used this to create this simple bash script that can be used to watch a process and its memory usage:
$ watch watchmypid.sh
#!/bin/bash
#
PROCESSNAME=changethistoyourprocessname
MYPID=`pidof $PROCESSNAME`
echo "=======";
echo PID:$MYPID
echo "--------"
Rss=`echo 0 $(cat /proc/$MYPID/smaps | grep Rss | awk '{print $2}' | sed 's#^#+#') | bc;`
Shared=`echo 0 $(cat /proc/$MYPID/smaps | grep Shared | awk '{print $2}' | sed 's#^#+#') | bc;`
Private=`echo 0 $(cat /proc/$MYPID/smaps | grep Private | awk '{print $2}' | sed 's#^#+#') | bc;`
Swap=`echo 0 $(cat /proc/$MYPID/smaps | grep Swap | awk '{print $2}' | sed 's#^#+#') | bc;`
Pss=`echo 0 $(cat /proc/$MYPID/smaps | grep Pss | awk '{print $2}' | sed 's#^#+#') | bc;`
Mem=`echo "$Rss + $Shared + $Private + $Swap + $Pss"|bc -l`
echo "Rss " $Rss
echo "Shared " $Shared
echo "Private " $Private
echo "Swap " $Swap
echo "Pss " $Pss
echo "=================";
echo "Mem " $Mem
echo "=================";
That simply means using Linux, Apache, MySQL and PHP as your operating system, web server, database, and programming language, respectively.
Currently it only works for the .dropdown-menu
:
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
If you want it for other use, in your own css, following the bootstrap.css create another one:
.divider {
height: 1px;
width:100%;
display:block; /* for use on default inline elements like span */
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
@rvighne solution works well, but as identified in the comments ParentElement
and ClassList
both have compatibility issues. To make it more compatible, I have used:
function findAncestor (el, cls) {
while ((el = el.parentNode) && el.className.indexOf(cls) < 0);
return el;
}
parentNode
property instead of the parentElement
propertyindexOf
method on the className
property instead of the contains
method on the classList
property.Of course, indexOf is simply looking for the presence of that string, it does not care if it is the whole string or not. So if you had another element with class 'ancestor-type' it would still return as having found 'ancestor', if this is a problem for you, perhaps you can use regexp to find an exact match.
Assuming your ints are 0, 375, 668,5 and 6:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [
0,
375,
668,
5,
6
]
}
I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/
just add in your backend API new property's into response body. from example .net core:
[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
var users = await _repo.GetUsers(userParams);
var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);
// create new object and add into it total count param etc
var UsersListResult = new
{
usersToReturn,
currentPage = users.CurrentPage,
pageSize = users.PageSize,
totalCount = users.TotalCount,
totalPages = users.TotalPages
};
return Ok(UsersListResult);
}
In body response it look like this
{
"usersToReturn": [
{
"userId": 1,
"username": "[email protected]",
"firstName": "Joann",
"lastName": "Wilson",
"city": "Armstrong",
"phoneNumber": "+1 (893) 515-2172"
},
{
"userId": 2,
"username": "[email protected]",
"firstName": "Booth",
"lastName": "Drake",
"city": "Franks",
"phoneNumber": "+1 (800) 493-2168"
}
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44
}
Alternative iterative solution:
def myprint(d):
stack = d.items()
while stack:
k, v = stack.pop()
if isinstance(v, dict):
stack.extend(v.iteritems())
else:
print("%s: %s" % (k, v))
Try using this attribute, for example for password min length:
[StringLength(100, ErrorMessage = "???????????? ????? ?????? 20 ????????", MinimumLength = User.PasswordMinLength)]
Check file permissions.
I had exactly the same error on a Linux machine with the wrong permissions set.
chmod 755 myfile.pl
solved the problem.
just configure your log4j property file path in beginning of main method: e.g.: PropertyConfigurator.configure("D:\files\log4j.properties");
Typically, you'll split your test set into small batches for the network to learn from, and make the training go step by step through your number of layers, applying gradient-descent all the way down. All these small steps can be called iterations.
An epoch corresponds to the entire training set going through the entire network once. It can be useful to limit this, e.g. to fight overfitting.
you can press gg to locate your curser to the start of the file,then press yG to copy all the content from the start to end(G located) to buffer.good luck!
It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.
First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).
Finding the cell that contains the number of aircraft was:
=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1
I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:
=INDIRECT(ADDRESS(StateRow,1))
This returns the name of the state from the dynamic value in row "StateRow", column 1
Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.
I also had same problem with Eclipse 3.7.2 (Indigo) and maven 3.0.4.
Eclipse wasn't picking up my maven settings, so this is what I did to fix the problem:
Window - Preferences - Maven - Installations
Maven > Update Project Configuration... on project (right click)
Shutdown Eclipse
Run mvn install
from the command line.
Open Eclipse
Those steps worked for me, but the problem isn't consistent. I've only had with issue on one computer.
What you want cannot be done, because plt.legend()
places a legend in the current axes, in your case in the last one.
If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()
Note that you pass to legend
not the axes, as in your example code, but the lines as returned by the plot
invocation.
Of course you can invoke legend
after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.
In my experience, using the 32-bit version is more trouble-free. Unless you are working on applications that make heavy use of memory (mostly scientific computing, that uses more than 2GB memory), you're better off with 32-bit versions because:
Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.
The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.
#!/bin/bash -vx
##config file with ip addresses like 10.10.10.1:80
file=config.txt
while read line ; do
##this line is not correct, should strip :port and store to ip var
ip=$( echo "$line" |cut -d\: -f1 )
ping $ip
done < ${file}
You could write your top line as
for line in $(cat $file) ; do ...
(but not recommended).
You needed command substitution $( ... )
to get the value assigned to $ip
reading lines from a file is usually considered more efficient with the while read line ... done < ${file}
pattern.
I hope this helps.
https://docs.angularjs.org/guide/$location#html-link-rewriting
In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.
Links that contain target element Example:
<a href="/ext/link?a=b" target="_self">link</a>
Absolute links that go to a different domain Example:
<a href="http://angularjs.org/">link</a>
Links starting with '/' that lead to a different base path when base is defined Example:
<a href="/not-my-base/link">link</a>
So in your case, you should add a target attribute like so...
<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
I like to avoid raising a new exception while handling an old one. It makes the error messages confusing to read.
For example, in my code, I originally wrote
try:
return tuple.__getitem__(self, i)(key)
except IndexError:
raise KeyError(key)
And I got this message.
>>> During handling of above exception, another exception occurred.
I wanted this:
try:
return tuple.__getitem__(self, i)(key)
except IndexError:
pass
raise KeyError(key)
It doesn't affect how exceptions are handled. In either block of code, a KeyError would have been caught. This is merely an issue of getting style points.
Create a footer view layout consisting of text that you want to set as footer and then try
View footerView = ((LayoutInflater) ActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
ListView.addFooterView(footerView);
Layout for footer could be something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="7dip"
android:paddingBottom="7dip"
android:orientation="horizontal"
android:gravity="center">
<LinearLayout
android:id="@+id/footer_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_gravity="center">
<TextView
android:text="@string/footer_text_1"
android:id="@+id/footer_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dip"
android:textStyle="bold"
android:layout_marginRight="5dip" />
</LinearLayout>
</LinearLayout>
The activity class could be:
public class MyListActivty extends ListActivity {
private Context context = null;
private ListView list = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = (ListView)findViewById(android.R.id.list);
//code to set adapter to populate list
View footerView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
list.addFooterView(footerView);
}
}
An alternative approach is resample
, which can handle duplicate dates in addition to missing dates. For example:
df.resample('D').mean()
resample
is a deferred operation like groupby
so you need to follow it with another operation. In this case mean
works well, but you can also use many other pandas methods like max
, sum
, etc.
Here is the original data, but with an extra entry for '2013-09-03':
val
date
2013-09-02 2
2013-09-03 10
2013-09-03 20 <- duplicate date added to OP's data
2013-09-06 5
2013-09-07 1
And here are the results:
val
date
2013-09-02 2.0
2013-09-03 15.0 <- mean of original values for 2013-09-03
2013-09-04 NaN <- NaN b/c date not present in orig
2013-09-05 NaN <- NaN b/c date not present in orig
2013-09-06 5.0
2013-09-07 1.0
I left the missing dates as NaNs to make it clear how this works, but you can add fillna(0)
to replace NaNs with zeroes as requested by the OP or alternatively use something like interpolate()
to fill with non-zero values based on the neighboring rows.
USE [TSQL2012]
GO
/****** Object: Table [dbo].[Table_1] Script Date: 11/22/2015 12:45:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table_1](
[seq] [bigint] IDENTITY(1,1) NOT NULL,
[ID] [int] NOT NULL,
[name] [nvarchar](50) NULL,
[cat] [nvarchar](50) NULL,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_Table_1] UNIQUE NONCLUSTERED
(
[name] ASC,
[cat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Here is my contribution, that deals with any URL using http or https, and use Promises.
const http = require('http')
const https = require('https')
const url = require('url')
function getHeaders(myURL) {
const parsedURL = url.parse(myURL)
const options = {
protocol: parsedURL.protocol,
hostname: parsedURL.hostname,
method: 'HEAD',
path: parsedURL.path
}
let protocolHandler = (parsedURL.protocol === 'https:' ? https : http)
return new Promise((resolve, reject) => {
let req = protocolHandler.request(options, (res) => {
resolve(res.headers)
})
req.on('error', (e) => {
reject(e)
})
req.end()
})
}
getHeaders(myURL).then((headers) => {
console.log(headers)
})
The simplest way to import a database in your MYSQL from the terminal is done by the below-mentioned process -
mysql -u root -p root database_name < path to your .sql file
What I'm doing above is:
root
& root
)<
and then path to your .sql file. For example, if my file is stored in Desktop, the path will be /home/Desktop/db.sql
That's it. Once you've done all this, press enter and wait for your .sql file to get uploaded to the respective database
You may want to use statement_timestamp(). This give the timestamp when the statement was executed. Whereas NOW()
and CURRENT_TIMESTAMP
give the timestamp when the transaction started.
More details in the manual
It would be something like this
function CustomInputBox([string] $title, [string] $message, [string] $defaultText)
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript"
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" )
$_userInput = $inputObject.eval("getInput")
return $_userInput
}
Then you can call the function similar to this.
$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null )
{
echo "Input was [$userInput]"
}
else
{
echo "User cancelled the form!"
}
This is the most simple way to do this that I can think of.
Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:
<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
<div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
<div class="uil-default-css">
<img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
</div>
<div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;"> </div>
</div>
<div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>
Finally, replace .loader-text element's
content on the fly on every navigation event and turn on the #resultloading
div, note that it is initially hidden.
var showLoader = function (text) {
$('#resultLoading').show();
$('#resultLoading').find('.loader-text').html(text);
};
jQuery(document).ready(function () {
jQuery(window).on("beforeunload ", function () {
showLoader('Loading, please wait...');
});
});
This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.
The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.
Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.
I was testing a function that had multiple UPDATE
statements within IF-ELSE
blocks.
I was testing all possible paths, so I reset the tables to their previous values with 'manual' UPDATE
statements each time before running the function again.
I noticed that the issue would happen just after those UPDATE
statements;
I added a COMMIT;
after the UPDATE
statement I used to reset the tables and that solved the problem.
So, caution, the problem was not the function itself...
Use case/esac
to test:
case "$var" in
"") echo "zero length";;
esac
How to get the last N rows of a pandas DataFrame?
If you are slicing by position, __getitem__
(i.e., slicing with[]
) works well, and is the most succinct solution I've found for this problem.
pd.__version__
# '0.24.2'
df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df
A B
0 a 1
1 a 2
2 a 3
3 b 4
4 b 5
5 b 6
6 b 7
7 c 8
df[-3:]
A B
5 b 6
6 b 7
7 c 8
This is the same as calling df.iloc[-3:]
, for instance (iloc
internally delegates to __getitem__
).
As an aside, if you want to find the last N rows for each group, use groupby
and GroupBy.tail
:
df.groupby('A').tail(2)
A B
1 a 2
2 a 3
5 b 6
6 b 7
7 c 8
Make sure Virtualization is enabled in your bios.
Calling /search/
should result in "you submitted nothing", but calling /search/?q=
on the other hand should result in "you submitted u''"
Browsers have to add the q=
even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:
if request.GET.get('q'):
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
I've used like this
function chatSearchCtrl($scope, $http,$sce) {
// some more my code
// take this
data['message'] = $sce.trustAsHtml(data['message']);
$scope.searchresults = data;
and in html I did
<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>
thats it I get my <br/>
tag rendered
Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:
^[a-zA-Z ._-]*$
If you use the case-insensitive modifier, you can shorten this to
^[a-z ._-]*$
Note that the space is significant (it is just a character like any other).
Microsoft's Visual C++ compiler ignores the register
keyword when global register-allocation optimization (the /Oe compiler flag) is enabled.
See register Keyword on MSDN.
Use std::stringstream
to convert integers into strings and its special manipulators to set the base. For example like that:
std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();
Try : http://localhost/phpmyadmin/
Use lowercase letters and try again
there is indeed an xpath contains function it should look something like:
<xsl:for-each select="item">
<xsl:variable name="hhref" select="link" />
<xsl:variable name="pdate" select="pubDate" />
<xsl:if test="not(contains(hhref,'1234'))">
<li>
<a href="{$hhref}" title="{$pdate}">
<xsl:value-of select="title"/>
</a>
</li>
</xsl:if>
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
May I expand on the question and ask if Git work well on MacOS?
Reply to Comments: Thanks for the news, I'd been looking forward to trying it out. I'll install it at home on my Mac.
Just to confirm: You are sure you are running MySQL 5.7, and not MySQL 5.6 or earlier version. And the plugin column contains "mysql_native_password". (Before MySQL 5.7, the password hash was stored in a column named password. Starting in MySQL 5.7, the password column is removed, and the password has is stored in the authentication_string column.) And you've also verified the contents of authentication string matches the return from PASSWORD('mysecret'). Also, is there a reason we are using DML against the mysql.user table instead of using the SET PASSWORD FOR syntax? – spencer7593
So Basically Just make sure that the Plugin Column contains "mysql_native_password".
Not my work but I read comments and noticed that this was stated as the answer but was not posted as a possible answer yet.
Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.
As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString()
.
values-es/strings.xml
<string name="get_started">SIGUIENTE</string>
Reference to resource
textView.setText(getString(R.string.get_started)
Logcat:
06-11 11:46:37.835 7007-7007/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
at android.content.res.Resources.getText(Resources.java:299)
at android.content.res.Resources.getString(Resources.java:385)
at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml
so that if the phone is in another language it will always have a resource to fall back to.
values/strings.xml
<string name="get_started">Get Started</string>
values-en/strings.xml
<string name="get_started">Get Started</string>
values-es/strings.xml
<string name="get_started">Siguiente</string>
values-de/strings.xml
<string name="get_started">Ioslegen</string>
I got this error Unexpected identifier
because of a missing semi-colon ;
at the end of a line. Anyone wandering here for other than above-mentioned solutions, This might also be the cause of this error.
I solved this error with clearing cache and restarting chrome. Hope they will fix it in ver 40.
In at least Postgres, you can use the alias name in the group by clause:
SELECT itemName as ItemName1, substring(itemName, 1,1) as FirstLetter, Count(itemName) FROM table1 GROUP BY ItemName1, FirstLetter;
I wouldn't recommend renaming an alias as a change in capitalization, that causes confusion.
runAllManagedModulesForAllRequests=true
is actually a real bad solution. This increased the load time of my application by 200%. The better solution is to manually remove and add the session object and to avoid the run all managed modules attribute all together.
Your request mapping is /save
, but your POST is to /save.html
. Changing the POST to /save
should fix it.
The simplest solution:
Just divide the navbar
into columns: for instance, if you have 24 columns over all, 12 are going to be empty and 12 are going to contrain the navbar:
<nav class="navbar navbar-default">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-12">
<ul class="nav navbar-nav" align="center">
<li><a href="#">Home</a></li>
<li><a href="#">First Link</a></li>
<li><a href="#">Second Link</a></li>
<li><a href="#">Third Link</a></li>
<li><a href="#">Fourth Link</a></li>
</ul>
</div>
</div>
</nav>
You can create something like c using CSS multiple-backgrounds.
div {
background: linear-gradient(red, red),
linear-gradient(blue, blue),
linear-gradient(green, green);
background-size: 30% 50%,
30% 60%,
40% 80%;
background-position: 0% top,
calc(30% * 100 / (100 - 30)) top,
calc(60% * 100 / (100 - 40)) top;
background-repeat: no-repeat;
}
Note, you still have to use linear-gradients for background types, because CSS will not allow you to control the background-size of a single color layer. So here we just make a single-color gradient. Then you can control the size/position of each of those blocks of color independently. You also have to make sure they don't repeat, or they'll just expand and cover the whole image.
The trickiest part here is background-position. A background-position of 0% puts your element's left edge at the left. 100% puts its right edge at the right. 50% centers is middle.
For a fun bit of math to solve that, you can guess the transform is probably linear, and just solve two little slope-intercept equations.
// (at 0%, the div's left edge is 0% from the left)
0 = m * 0 + b
// (at 100%, the div's right edge is 100% - width% from the left)
100 = m * (100 - width) + b
b = 0, m = 100 / (100 - width)
so to position our 40% wide div 60% from the left, we put it at 60% * 100 / (100 - 40) (or use css-calc).
With VS 2015 and up, Use the Smart Command Line Arguments extension. This plug-in adds a window that allows you to turn arguments on and off:
The extension additionally stores the arguments in a JSON file, allowing you to commit them to source control. In addition to ensuring you don't have to type in all the arguments every single time, this serves as a useful supplement to your documentation for other developers to discover the available options.
On a fresh ubuntu docker image, run
apt-get update
apt-get install net-tools
These can be executed by logging into the docker container or add this to your dockerfile to build an image with the same.
Try this:
select *
from xxx
where dates >= '2012-10-26 00:00:00.000' and dates <= '2012-10-27 23:59:59.997'
Use HTML Form "elements" attribute:
$.each($("form").elements, function(){
console.log($(this));
});
Now it's not necessary to provide such names as "input, textarea, select ..." etc.
All the methods above do not handle deep cloning of objects where it is nested to n levels. I did not check its performance over others but it is short and simple.
The first example below shows object cloning using Object.assign
which clones just till first level.
var person = {_x000D_
name:'saksham',_x000D_
age:22,_x000D_
skills: {_x000D_
lang:'javascript',_x000D_
experience:5_x000D_
}_x000D_
}_x000D_
_x000D_
newPerson = Object.assign({},person);_x000D_
newPerson.skills.lang = 'angular';_x000D_
console.log(newPerson.skills.lang); //logs Angular
_x000D_
Using the below approach deep clones object
var person = {_x000D_
name:'saksham',_x000D_
age:22,_x000D_
skills: {_x000D_
lang:'javascript',_x000D_
experience:5_x000D_
}_x000D_
}_x000D_
_x000D_
anotherNewPerson = JSON.parse(JSON.stringify(person));_x000D_
anotherNewPerson.skills.lang = 'angular';_x000D_
console.log(person.skills.lang); //logs javascript
_x000D_
Regular expression for simple address validation
^[#.0-9a-zA-Z\s,-]+$
E.g. for Address match case
#1, North Street, Chennai - 11
E.g. for Address not match case
$1, North Street, Chennai @ 11
You can't float or set the width of an inline element. Remove display: inline;
from both classes and your markup should present fine.
EDIT: You can set the width, but it will cause the element to be rendered as a block.
ok I reached to this solution by the help of two people who answered above, Mosh Feu and Suragch First open settings (ctrl+alt+s), second go to Editor->General->Fonts->Size.
Although I've tried all the previous answers, only the following one worked out:
1 - Open Powershell (as Admin)
2 - Run:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
3 - Run:
Install-PackageProvider -Name NuGet
The author is Niels Weistra: Microsoft Forum
(gdb) maintenance info sections
Exec file:
`/path/to/app.out', file type elf32-littlearm.
0x0000->0x0360 at 0x00008000: .intvecs ALLOC LOAD READONLY DATA HAS_CONTENTS
This is from comment by phihag above, deserves a separate answer. This works but info proc
does not on the arm-none-eabi-gdb v7.4.1.20130913-cvs from the gcc-arm-none-eabi Ubuntu package.
If you want to add a dynamic class to your host element, you may combine your HostBinding
with a getter as
@HostBinding('class') get class() {
return aComponentVariable
}
Stackblitz demo at https://stackblitz.com/edit/angular-dynamic-hostbinding
You must use Color.FromArgb method to create new color structure
var newColor = Color.FromArgb(0xCC,0xBB,0xAA);
You may also want to check whether the double is higher than the max Int value before trying to convert the value to an Int.
let number = Double.infinity
if number >= Double(integerLiteral: Int64.max) {
let rounded = Int.max
} else {
let rounded = Int(number.rounded())
}
Take some base date which is the 31st of some month e.g. '20011231'. Then use the
following procedure (I have given 3 identical examples below, only the @dt value differs).
declare @dt datetime;
set @dt = '20140312'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
set @dt = '20140208'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
set @dt = '20140405'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
One thing that to be remembered while solving such problems is that in JSON file, a {
indicates a JSONObject
and a [
indicates JSONArray
. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.
The Gson JsonReader documentation explains how to handle parsing of JsonObjects
and JsonArrays
:
- Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
- Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().
There is already a good solution to the problem you are having. Everyone has been forgetting the CSS property font-size
: the last but not least solution. One can decrease the font size by 2 to 3 pixels. It may still be visible to the user and for somewhat you can decrease the width of the table. This worked for me. My table has 5 columns with 4 showing perfectly, but the fifth column went out of the viewport. To fix the problem, I decreased the font size and all five columns were fitted onto the screen.
table th td {
font-size: 14px;
}
For your information, if your table has too many columns and you are not able to decrease, then make the font size small. It will get rid of the horizontal scroll. There are two advantages: your style for mobile web will remain the same (good without horizontal scroll) and when user sees small sizes, most users will zoom into the table to their comfort level.
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
Sometimes it's easier to think in terms of which fields to exclude.
If the number of fields not being cut (not being retained in the output) is small, it may be easier to use the --complement
flag, e.g. to include all fields 1-20 except not 3, 7, and 12 -- do this:
cut -d, --complement -f3,7,12 <inputfile
Rather than
cut -d, -f-2,4-6,8-11,13-
SAMPLE.CSV
a, 1, +
b, 2, -
c, 3, *
d, 4, /
column_names = ["Letter", "Number", "Symbol"]
df = pd.read_csv("sample.csv", names=column_names)
print(df)
OUTPUT
Letter Number Symbol
0 a 1 +
1 b 2 -
2 c 3 *
3 d 4 /
letters = df.Letter.to_list()
print(letters)
OUTPUT
['a', 'b', 'c', 'd']
You could use the built-in serialization tools in the framework and serialize to a MemoryStream. This may be the most straightforward option, but might produce a larger byte[] than may be strictly necessary for your scenario.
If that is the case, you could utilize reflection to iterate over the fields and/or properties in the object to be serialized and manually write them to the MemoryStream, calling the serialization recursively if needed to serialize non-trivial types. This method is more complex and will take more time to implement, but allows you much more control over the serialized stream.
Slightly related, I was looking for the unique combinations and I came up with this method:
def unique_columns(df,columns):
result = pd.Series(index = df.index)
groups = meta_data_csv.groupby(by = columns)
for name,group in groups:
is_unique = len(group) == 1
result.loc[group.index] = is_unique
assert not result.isnull().any()
return result
And if you only want to assert that all combinations are unique:
df1.set_index(['A','B']).index.is_unique
In the case of CROSS ORIGIN request read this:
I faced this situation and at first I chose to use the Authorization
Header and later removed it after facing the following issue.
Authorization
Header is considered a custom header. So if a cross-domain request is made with the Autorization
Header set, the browser first sends a preflight request. A preflight request is an HTTP request by the OPTIONS method, this request strips all the parameters from the request. Your server needs to respond with Access-Control-Allow-Headers
Header having the value of your custom header (Authorization
header).
So for each request the client (browser) sends, an additional HTTP request(OPTIONS) was being sent by the browser. This deteriorated the performance of my API. You should check if adding this degrades your performance. As a workaround I am sending tokens in http parameters, which I know is not the best way of doing it but I couldn't compromise with the performance.
I usually combine CSS and JavaScript approaches, so that it works without JavaScript in all browsers but IE6/7, and in IE6/7 with JavaScript on (but not off), since they does not support the :last-child
pseudo-class.
$("li:last-child").addClass("last-child");
li:last-child,li.last-child{ /* ... */ }
If table does not have relation, just copy all in new table with row number and remove old and rename new one with old one.
Select RowNum = ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) , * INTO cdm.dbo.SALES2018 from
(
select * from SALE2018) as SalesSource
In SWIFT 3.0
if let url = URL(string: "https://www.google.com") {
UIApplication.shared.open(url, options: [:])
}
In addition to the accepted answer, you can also achieve what you originally wanted (creating a deployment using the run
command) with the following command:
kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989 --generator=run-pod/v1
I found the information about the generator on the Kubernetes-dev forum:
If you're using
kubectl run
, it generates a manifest for you that happens to haveimagePullPolicy
set toAlways
by default. You can use this command to get animagePullPolicy
ofIfNotPresent
, which will work forminikube
:
kubectl run --image=<container> --generator=run-pod/v1
Dan Lorenc
https://groups.google.com/forum/#!topic/kubernetes-dev/YfvWuFr_XOM
EDIT: Probably not the right way to do it, see comments
You could use sklearn.feature_selection.f_regression.
None is a singleton object (meaning there is only one None), used in many places in the language and library to represent the absence of some other value.
For example:
if d
is a dictionary, d.get(k)
will return d[k]
if it exists, but None
if d
has no key k
.
Read this info from a great blog: http://python-history.blogspot.in/
in swift
NavigationController and pushController you can replace for
present(vc, animated:true , completion: nil)
This is based on thread2 -- killable threads (Python recipe)
You need to call PyThreadState_SetasyncExc(), which is only available through ctypes.
This has only been tested on Python 2.7.3, but it is likely to work with other recent 2.x releases.
import ctypes
def terminate_thread(thread):
"""Terminates a python thread from another thread.
:param thread: a threading.Thread instance
"""
if not thread.isAlive():
return
exc = ctypes.py_object(SystemExit)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(thread.ident), exc)
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
IDP Initiated SSO
From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html
In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.
Processing Steps:
SP Initiated SSO
From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST
In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.
Processing Steps:
Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)
The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.
(Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.
If you want to get the content without the html tags from the web page (HTML document) , then use this code inside the UIWebViewDidfinishLoading
delegate method.
NSString *myText = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
This is old, but I thought I'd put this out anyway since I couldn't find a query that would give me ALL the SQL code from EVERY view I had out there. So here it is:
SELECT SM.definition
FROM sys.sql_modules SM
INNER JOIN sys.Objects SO ON SM.Object_id = SO.Object_id
WHERE SO.type = 'v'
What does the percentage sign mean?
It's an operator in Python that can mean several things depending on the context. A lot of what follows was already mentioned (or hinted at) in the other answers but I thought it could be helpful to provide a more extensive summary.
%
for Numbers: Modulo operation / Remainder / RestThe percentage sign is an operator in Python. It's described as:
x % y remainder of x / y
So it gives you the remainder/rest that remains if you "floor divide" x by y. Generally (at least in Python) given a number x
and a divisor y
:
x == y * (x // y) + (x % y)
For example if you divide 5 by 2:
>>> 5 // 2
2
>>> 5 % 2
1
>>> 2 * (5 // 2) + (5 % 2)
5
In general you use the modulo operation to test if a number divides evenly by another number, that's because multiples of a number modulo that number returns 0:
>>> 15 % 5 # 15 is 3 * 5
0
>>> 81 % 9 # 81 is 9 * 9
0
That's how it's used in your example, it cannot be a prime if it's a multiple of another number (except for itself and one), that's what this does:
if n % x == 0:
break
If you feel that n % x == 0
isn't very descriptive you could put it in another function with a more descriptive name:
def is_multiple(number, divisor):
return number % divisor == 0
...
if is_multiple(n, x):
break
Instead of is_multiple
it could also be named evenly_divides
or something similar. That's what is tested here.
Similar to that it's often used to determine if a number is "odd" or "even":
def is_odd(number):
return number % 2 == 1
def is_even(number):
return number % 2 == 0
And in some cases it's also used for array/list indexing when wrap-around (cycling) behavior is wanted, then you just modulo the "index" by the "length of the array" to achieve that:
>>> l = [0, 1, 2]
>>> length = len(l)
>>> for index in range(10):
... print(l[index % length])
0
1
2
0
1
2
0
1
2
0
Note that there is also a function for this operator in the standard library operator.mod
(and the alias operator.__mod__
):
>>> import operator
>>> operator.mod(5, 2) # equivalent to 5 % 2
1
But there is also the augmented assignment %=
which assigns the result back to the variable:
>>> a = 5
>>> a %= 2 # identical to: a = a % 2
>>> a
1
%
for strings: printf
-style String FormattingFor strings the meaning is completely different, there it's one way (in my opinion the most limited and ugly) for doing string formatting:
>>> "%s is %s." % ("this", "good")
'this is good'
Here the %
in the string represents a placeholder followed by a formatting specification. In this case I used %s
which means that it expects a string. Then the string is followed by a %
which indicates that the string on the left hand side will be formatted by the right hand side. In this case the first %s
is replaced by the first argument this
and the second %s
is replaced by the second argument (good
).
Note that there are much better (probably opinion-based) ways to format strings:
>>> "{} is {}.".format("this", "good")
'this is good.'
%
in Jupyter/IPython: magic commandsTo quote the docs:
To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the
%
syntax element for magics as%
is not a valid unary operator in Python. While, the syntax element has meaning in other languages.
This is regularly used in Jupyter notebooks and similar:
In [1]: a = 10
b = 20
%timeit a + b # one % -> line-magic
54.6 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [2]: %%timeit # two %% -> cell magic
a ** b
362 ns ± 8.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%
operator on arrays (in the NumPy / Pandas ecosystem)The %
operator is still the modulo operator when applied to these arrays, but it returns an array containing the remainder of each element in the array:
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a % 2
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
%
operator for your own classesOf course you can customize how your own classes work when the %
operator is applied to them. Generally you should only use it to implement modulo operations! But that's a guideline, not a hard rule.
Just to provide a simple example that shows how it works:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
This example isn't really useful, it just prints and then delegates the operator to the stored value, but it shows that __mod__
is called when %
is applied to an instance:
>>> a = MyNumber(10)
>>> a % 2
__mod__ called on 'MyNumber(10)'
0
Note that it also works for %=
without explicitly needing to implement __imod__
:
>>> a = MyNumber(10)
>>> a %= 2
__mod__ called on 'MyNumber(10)'
>>> a
0
However you could also implement __imod__
explicitly to overwrite the augmented assignment:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __imod__(self, other):
print("__imod__ called on '{!r}'".format(self))
self.value %= other
return self
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
Now %=
is explicitly overwritten to work in-place:
>>> a = MyNumber(10)
>>> a %= 2
__imod__ called on 'MyNumber(10)'
>>> a
MyNumber(0)
All the posted answers rightfully discuss this from a strictly maven perspective. My issues was in doing this install for maven using Netbeans as my primary IDE. I found the below article helpful.
Credit to the following netbeans forum article: http://forums.netbeans.org/topic22907.html
How can I go from this
A - B - C - D - E
|
master
to this?
A - B - C - D - E
| |
master newbranch
With two commands
giving
A - B - C - D - E
|
newbranch
and
giving
A - B - C - D - E
| |
master newbranch
There's no guarantee that SQL Server won't attempt to perform the CONVERT
to numeric(20,0)
before it runs the filter in the WHERE
clause.
And, even if it did, ISNUMERIC
isn't adequate, since it recognises £
and 1d4
as being numeric, neither of which can be converted to numeric(20,0)
.(*)
Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)
For your filter, probably use account_code not like '%[^0-9]%'
instead of ISNUMERIC
.
(*) ISNUMERIC
answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x
is a specific target datatype.
You have to set setOnItemLongClickListener() in the ListView:
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos: " + pos);
return true;
}
});
The XML for each item in the list (should you use a custom XML) must have android:longClickable="true"
as well (or you can use the convenience method lv.setLongClickable(true);
). This way you can have a list with only some items responding to longclick.
Hope this will help you.
You can make your code more concise and (sometimes) to run faster using numpy
. For example, in two-classes case your function can be rewritten as (see mply.acc()
):
def accuracy(actual, predicted):
"""accuracy = (tp + tn) / ts
, where:
ts - Total Samples
tp - True Positives
tn - True Negatives
"""
return (actual == predicted).sum() / float(len(actual))
, where:
actual = (numpy.array(input_arr) == 2)
predicted = (numpy.array(prob_arr) < 0.5)
Just add
xAxis: {
...
lineWidth: 0,
minorGridLineWidth: 0,
lineColor: 'transparent',
...
labels: {
enabled: false
},
minorTickLength: 0,
tickLength: 0
}
to the xAxis definition.
Since Version 4.1.9 you can simply use the axis attribute visible
:
xAxis: {
visible: false,
}
I was a bit puzzled that norm.fit
apparently only worked with the expanded list of sampled values. I tried giving it two lists of numbers, or lists of tuples, but it only appeared to flatten everything and threat the input as individual samples. Since I already have a histogram based on millions of samples, I didn't want to expand this if I didn't have to. Thankfully, the normal distribution is trivial to calculate, so...
# histogram is [(val,count)]
from math import sqrt
def normfit(hist):
n,s,ss = univar(hist)
mu = s/n
var = ss/n-mu*mu
return (mu, sqrt(var))
def univar(hist):
n = 0
s = 0
ss = 0
for v,c in hist:
n += c
s += c*v
ss += c*v*v
return n, s, ss
I'm sure this must be provided by the libraries, but as I couldn't find it anywhere, I'm posting this here instead. Feel free to point to the correct way to do it and downvote me :-)
res
is an HttpResponse object which extends from OutgoingMessage. res.send
calls res.end
which is implemented by OutgoingMessage to send HTTP response and close connection. We see code here
You might want to put the absolutely aligned div in a relatively aligned container - this way it will still be contained into the container rather than the browser window.
<div style="position: relative;background-color: blue; width: 600px; height: 800px;">
<div style="position: absolute; bottom: 5px; background-color: green">
TEST (C) 2010
</div>
</div>
Quite simply: echo str_replace('\'', '\\\'', $myString);
However, I'd suggest use of JSON and json_encode()
function as it will be more reliable (quotes new lines for instance):
<?php $data = array('myString' => '...'); ?>
<script>
var phpData = <?php echo json_encode($data) ?>;
alert(phpData.myString);
</script>
Use following JQuery. Demo
$(function() {
$('#row_dim').hide();
$('#type').change(function(){
if($('#type').val() == 'parcel') {
$('#row_dim').show();
} else {
$('#row_dim').hide();
}
});
});
I solved it by switching tohttp
protocol from the file
protocol.
live-server [dirPath]
In Hibernate 4.2.2
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Test {
public static void main(String[] args) throws Exception
{
Configuration configuration = new Configuration()
.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Users users = new Users();
... ...
session.save(users);
transaction.commit();
session.close();
sessionFactory.close();
}
}
I implemented in this form in webview using fragment- inside oncreate:
webView.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView viewx, String urlx)
{
if(Uri.parse(urlx).getHost().endsWith("facebook.com")) {
{
goToFacebook();
}
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlx));
viewx.getContext().startActivity(intent);
return true;
}
});
and outside onCreateView :
private void goToFacebook() {
try {
String facebookUrl = getFacebookPageURL();
Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
//facebook url load
private String getFacebookPageURL() {
String FACEBOOK_URL = "https://www.facebook.com/pg/XXpagenameXX/";
String facebookurl = null;
try {
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager != null) {
Intent activated = packageManager.getLaunchIntentForPackage("com.facebook.katana");
if (activated != null) {
int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
if (versionCode >= 3002850) {
facebookurl = "fb://page/XXXXXXpage_id";
}
} else {
facebookurl = FACEBOOK_URL;
}
} else {
facebookurl = FACEBOOK_URL;
}
} catch (Exception e) {
facebookurl = FACEBOOK_URL;
}
return facebookurl;
}
arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);
If you don't have control of the server, you can simply add this argument to your Chrome launcher: --disable-web-security
.
Note that I wouldn't use this for normal "web surfing". For reference, see this post: Disable same origin policy in Chrome.
One you use Phonegap to actually build the application and load it onto the device, this won't be an issue.
Reading the code of guys who do it for a living will get you a LONG WAY.
Check out how guys from MySQL did it. The source is VERY WELL COMMENTED and will teach you much more than hacked up solutions found all over the place.
MySQL's implementation of int2str
I provide the mentioned implementation here; the link is here for reference and should be used to read the full implementation.
char *
int2str(long int val, char *dst, int radix,
int upcase)
{
char buffer[65];
char *p;
long int new_val;
char *dig_vec= upcase ? _dig_vec_upper : _dig_vec_lower;
ulong uval= (ulong) val;
if (radix < 0)
{
if (radix < -36 || radix > -2)
return NullS;
if (val < 0)
{
*dst++ = '-';
/* Avoid integer overflow in (-val) for LLONG_MIN (BUG#31799). */
uval = (ulong)0 - uval;
}
radix = -radix;
}
else if (radix > 36 || radix < 2)
return NullS;
/*
The slightly contorted code which follows is due to the fact that
few machines directly support unsigned long / and %. Certainly
the VAX C compiler generates a subroutine call. In the interests
of efficiency (hollow laugh) I let this happen for the first digit
only; after that "val" will be in range so that signed integer
division will do. Sorry 'bout that. CHECK THE CODE PRODUCED BY
YOUR C COMPILER. The first % and / should be unsigned, the second
% and / signed, but C compilers tend to be extraordinarily
sensitive to minor details of style. This works on a VAX, that's
all I claim for it.
*/
p = &buffer[sizeof(buffer)-1];
*p = '\0';
new_val= uval / (ulong) radix;
*--p = dig_vec[(uchar) (uval- (ulong) new_val*(ulong) radix)];
val = new_val;
while (val != 0)
{
ldiv_t res;
res=ldiv(val,radix);
*--p = dig_vec[res.rem];
val= res.quot;
}
while ((*dst++ = *p++) != 0) ;
return dst-1;
}
I want to collaborate a little with the solution for the server side. So, the server is saying it does not support DSA, this is because the openssh client does not activate it by default:
OpenSSH 7.0 and greater similarly disable the ssh-dss (DSA) public key algorithm. It too is weak and we recommend against its use.
So, to fix this this in the server side I should activate other Key algorithms like RSA o ECDSA. I just had this problem with a server in a lan. I suggest the following:
Update the openssh:
yum update openssh-server
Merge new configurations in the sshd_config if there is a sshd_config.rpmnew.
Verify there are hosts keys at /etc/ssh/. If not generate new ones, see man ssh-keygen
.
$ ll /etc/ssh/
total 580
-rw-r--r--. 1 root root 553185 Mar 3 2017 moduli
-rw-r--r--. 1 root root 1874 Mar 3 2017 ssh_config
drwxr-xr-x. 2 root root 4096 Apr 17 17:56 ssh_config.d
-rw-------. 1 root root 3887 Mar 3 2017 sshd_config
-rw-r-----. 1 root ssh_keys 227 Aug 30 15:33 ssh_host_ecdsa_key
-rw-r--r--. 1 root root 162 Aug 30 15:33 ssh_host_ecdsa_key.pub
-rw-r-----. 1 root ssh_keys 387 Aug 30 15:33 ssh_host_ed25519_key
-rw-r--r--. 1 root root 82 Aug 30 15:33 ssh_host_ed25519_key.pub
-rw-r-----. 1 root ssh_keys 1675 Aug 30 15:33 ssh_host_rsa_key
-rw-r--r--. 1 root root 382 Aug 30 15:33 ssh_host_rsa_key.pub
Verify in the /etc/ssh/sshd_config the HostKey configuration. It should allow the configuration of RSA and ECDSA. (If all of them are commented by default it will allow too the RSA, see in man sshd_config
the part of HostKey).
# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
For the client side, create a key for ssh (not a DSA like in the question) by just doing this:
ssh-keygen
After this, because there are more options than ssh-dss(DSA) the client openssh (>=v7) should connect with RSA or better algorithm.
This is my first question answered, I welcome suggestions :D .
Just use div { padding: 20px; }
and substract 40px
from your original div
width.
Like Philip Wills pointed out, you can also use box-sizing
instead of substracting 40px
:
div {
padding: 20px;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
The -moz-box-sizing
is for Firefox.
You need to use the border property as seen here: jsFiddle
HTML:
<table width="770">
<tr>
<td class="border-left-bottom">picture (border only to the left and bottom ) </td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td class="border-left-bottom">picture (border only to the left and bottom) </td>
</tr>
</table>`
CSS:
td.border-left-bottom{
border-left: solid 1px #000;
border-bottom: solid 1px #000;
}
QLineEdit::setValidator()
, for example:
myLineEdit->setValidator( new QIntValidator(0, 100, this) );
or
myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );
See: QIntValidator, QDoubleValidator, QLineEdit::setValidator
Now there is a Native support in SQL Server (CTP3) for import, export, query and validate JSON inside T-SQL Refer to https://msdn.microsoft.com/en-us/library/dn921897.aspx
Commenting just so people can have a solution to the intended question.
You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.
In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.
The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.
Since this keeps coming up in search results for making git and github work with SSH on Windows (and because I didn't need anything from the guides above), I'm adding the following, simple solution.
(Microsoft says they are working on adding SSH to Visual Studio, and GitHub for Windows still doesn't support SSH...)
1. I installed "git for Windows" (which includes ssh and a bash shell)
https://git-scm.com/download/win
2. From the included bash shell (which, for me, was installed at: C:\Program Files\Git\git-bash.exe
)
cd
to the root level of where you want your repo saved (something like: C:\code\github\
), and
Type:
eval $(ssh-agent -s) && ssh-add "C:\Users\YOURNAMEHERE\.ssh\github_rsa"
3. Type: (the SSH link from the repo)
git clone [email protected]:RepoName/Project.git
You can use urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
Also you can use httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
or the requests library
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
Any data storage for application generally uses the database. It could be relational database or no sql databases which are currently trending.
Data warehouse is also database. We can call data warehouse database as specialized data storage for the analytical reporting purposes for the company. This data used for key business decision.
The organized data helps is reporting and taking business decision effectively.
One additional information I just one to add is that a PATCH request use less bandwidth compared to a PUT request since just a part of the data is sent not the whole entity. So just use a PATCH request for updates of specific records like (1-3 records) while PUT request for updating a larger amount of data. That is it, don't think too much or worry about it too much.
Where you already have a project in NetBeans and you wish to change the compiler (e.g. from 1.7 to 1.) then you would need to also change the Java source compiler for that project.
Right-click on the project and choose properties as outlined below:
Then check that the project has the necessary source circled below:
then check that the Java compiler is correct for the project:
Each element of the container is a map<K, V>::value_type
, which is a typedef
for std::pair<const K, V>
. Consequently, in C++17 or higher, you can write
for (auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}
or as
for (const auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}
if you don't plan on modifying the values.
In C++11 and C++14, you can use enhanced for
loops to extract out each pair on its own, then manually extract the keys and values:
for (const auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}
You could also consider marking the kv
variable const
if you want a read-only view of the values.
Starting from PHP 7.3, there is a new built in function called array_key_first()
which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info.
reset($array);
$first_key = key($array);
It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.
Just remember to call reset
, or you may get any of the keys in the array. You can also use end
instead of reset
to get the last key.
If you wanted the key to get the first value, reset
actually returns it:
$first_value = reset($array);
There is one special case to watch out for though (so check the length of the array first):
$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)
From the documentation:
requests
can also ignore verifying the SSL certificate if you setverify
to False.>>> requests.get('https://kennethreitz.com', verify=False) <Response [200]>
If you're using a third-party module and want to disable the checks, here's a context manager that monkey patches requests
and changes it so that verify=False
is the default and suppresses the warning.
import warnings
import contextlib
import requests
from urllib3.exceptions import InsecureRequestWarning
old_merge_environment_settings = requests.Session.merge_environment_settings
@contextlib.contextmanager
def no_ssl_verification():
opened_adapters = set()
def merge_environment_settings(self, url, proxies, stream, verify, cert):
# Verification happens only once per connection so we need to close
# all the opened adapters once we're done. Otherwise, the effects of
# verify=False persist beyond the end of this context manager.
opened_adapters.add(self.get_adapter(url))
settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)
settings['verify'] = False
return settings
requests.Session.merge_environment_settings = merge_environment_settings
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore', InsecureRequestWarning)
yield
finally:
requests.Session.merge_environment_settings = old_merge_environment_settings
for adapter in opened_adapters:
try:
adapter.close()
except:
pass
Here's how you use it:
with no_ssl_verification():
requests.get('https://wrong.host.badssl.com/')
print('It works')
requests.get('https://wrong.host.badssl.com/', verify=True)
print('Even if you try to force it to')
requests.get('https://wrong.host.badssl.com/', verify=False)
print('It resets back')
session = requests.Session()
session.verify = True
with no_ssl_verification():
session.get('https://wrong.host.badssl.com/', verify=True)
print('Works even here')
try:
requests.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
print('It breaks')
try:
session.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
print('It breaks here again')
Note that this code closes all open adapters that handled a patched request once you leave the context manager. This is because requests maintains a per-session connection pool and certificate validation happens only once per connection so unexpected things like this will happen:
>>> import requests
>>> session = requests.Session()
>>> session.get('https://wrong.host.badssl.com/', verify=False)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
<Response [200]>
>>> session.get('https://wrong.host.badssl.com/', verify=True)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
<Response [200]>
You have a scope problem indeed, because statement
is a local method variable defined here:
protected void createContents() {
...
Statement statement = null; // local variable
...
btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
@Override
public void mouseDown(MouseEvent e) {
...
try {
statement.executeUpdate(query); // local variable out of scope here
} catch (SQLException e1) {
e1.printStackTrace();
}
...
});
}
When you try to access this variable inside mouseDown()
method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final
(which given your code is not possible) or declared as a class member so the inner class can access this statement
variable.
Sources:
Make statement
a class member instead of a local variable:
public class A1 { // Note Java Code Convention, also class name should be meaningful
private Statement statement;
...
}
Define another final variable and use this one instead, as suggested by @HotLicks:
protected void createContents() {
...
Statement statement = null;
try {
statement = connect.createStatement();
final Statement innerStatement = statement;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
...
}
Reconsider your approach. If statement
variable won't be used until btnInsert
button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:
btnInsert.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
try (Connection connect = DriverManager.getConnection(...);
Statement statement = connect.createStatement()) {
// execute the statement here
} catch (SQLException ex) {
ex.printStackTrace();
}
} catch (ClassNotFoundException ex) {
e.printStackTrace();
}
});
Ok, I fixed it:
When I changed manifest to target 1.5 version, million errors appeared and only one wasn't related to inexistance of R class - in manifest file attributes "targetSdkVersion" and "maxSdkVersion" did not exist in sdk 1.5
Because of this R class was not able to generate.
Extra Tips:
Multiple "nots", input that is NOT hidden and NOT disabled:
:not([type="hidden"]):not([disabled])
Also did you know you can do this:
node.parentNode.querySelectorAll('div');
This is equivelent to jQuery's:
$(node).parent().find('div');
Which will effectively find all divs in "node" and below recursively, HOT DAMN!
A simple database example to insert Todo List of day today life in DB and get list of all todo list.
public class MyDatabaseHelper extends SQLiteOpenHelper {
// Logcat tag
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "SQLiteDemoDB";
// Table Names
private static final String TABLE_TODO = "todos";
// column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TODO = "todoDescr";
// *********************************************************************************************
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TODO);
}
// Upgrading database **************************************************************************
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
// Create tables again
onCreate(db);
}
// Creating Table TABLE_TEAM
String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_TODO + "("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_TODO + " text, "
+ KEY_CREATED_AT + " text" + ")";
// insert values of todo
public boolean InsertTodoDetails(String todo, String createdAt) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_TODO, todo);
contentValues.put(KEY_CREATED_AT, createdAt);
long rowInserted = db.insert(TABLE_TODO, null, contentValues);
db.close();
return true;
}
// Select values of todo
public Cursor GetAllTodoDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_TODO;
Cursor mcursor = db.rawQuery(query, null);
if (mcursor != null) {
mcursor.moveToFirst();
}
return mcursor;
}
}
My activity To save and get the record.
public class MyDbActivity extends AppCompatActivity {
@Bind(R.id.edt_todo)
EditText edtTodo;
@Bind(R.id.btn_save)
Button btnSave;
MyDatabaseHelper db;
@Bind(R.id.btn_getTodo)
Button btnGetTodo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_db);
ButterKnife.bind(this);
// creating database object
db = new MyDatabaseHelper(this);
}
@OnClick(R.id.btn_save)
public void onViewClicked() {
String datetime = "";
try {
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
datetime = dateformat.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
db.InsertTodoDetails(edtTodo.getText().toString().trim(), datetime);
}
@OnClick(R.id.btn_getTodo)
public void onGetTodoClicked() {
String todos = "";
Cursor TodoList = db.GetAllTodoDetails();
if (TodoList.moveToFirst()) {
do {
if (todos.equals("")) {
todos = TodoList.getString(TodoList.getColumnIndex("todoDescr"));
} else {
todos = todos + ", " + TodoList.getString(TodoList.getColumnIndex("todoDescr"));
}
// do what ever you want here
} while (TodoList.moveToNext());
}
TodoList.close();
Toast.makeText(this, "" + todos, Toast.LENGTH_SHORT).show();
}
}
Probably the cleaner approach would be the following :
<a data-ui-sref="directory.organisations.details" data-ui-sref-opts="{reload: true}">Details State</a>
We can reload the state from the HTML only.
There's also the DateTime class which implements a function for comparison operators.
// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');
if ( $dtA > $dtB ) {
echo 'dtA > dtB';
}
else {
echo 'dtA <= dtB';
}
You can use data:
URL in the src
:
var html = 'Hello from <img src="http://stackoverflow.com/favicon.ico" alt="SO">';_x000D_
var iframe = document.querySelector('iframe');_x000D_
iframe.src = 'data:text/html,' + encodeURIComponent(html);
_x000D_
<iframe></iframe>
_x000D_
Difference between srcdoc=“…” and src=“data:text/html,…” in an iframe.
my friend this the will fix ur problem ;)
in root of folder ( xampp ) just run this file ( setup_xampp.bat ) then press enter
and try to start the apache server
every things will work like charm ;)
The fix is really simple: just replace YOUR_API_KEY on the last line of your code with your actual API key!
If you don't have one, you can get it for free on the Google Developers Website.
I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers
still had the old server name.
I had to drop the old server name and add the new server name to sys.servers
on the new server
sp_dropserver 'Server_A'
GO
sp_addserver 'Server',local
GO
My typical expectation is than when "subject" is used a context like this, it means the target of the certificate. If you think of a certificate as a cryptographically secured description of a thing (person, device, communication channel, etc), then the subject is the stuff related to that thing.
It's not the thing itself. For example, no one would say "the subject takes his SmartCard and authenticates his PIN". That would be the "user".
But it usually relates to the various data items related to that that thing. For example:
Usually, it's used to distinguish between the other players in the PKI world. Namely the "issuer" and the "root". The issuer is the CA that issued the cert (to the subject), and the root is the CA that is end point of all the trust in the heirarchy. The typical relationship is root--->issuer--->subject.
From what I know
3 one-liners
a = 10 if <condition>
example:
a = 10 if true # a = 10
b = 10 if false # b = nil
a = 10 unless <condition>
example:
a = 10 unless false # a = 10
b = 10 unless true # b = nil
a = <condition> ? <a> : <b>
example:
a = true ? 10 : 100 # a = 10
a = false ? 10 : 100 # a = 100
I hope it helps.
To get fully qualified hostname use socket.getfqdn()
import socket
print socket.getfqdn()
The first example you link to shows how MongoDB references behave much like lazy loading not like a join. There isn't a query there that's happening on both collections, rather you query one and then you lookup items from another collection by reference.
I'm not sure if this is what you had in mind, but I ended up on this question because I was unable to install node_modules
inside my project dir as it was mounted on a filesystem that did not support symlinks (a VM "shared" folder).
I found the following workaround:
package.json
file to a temp folder on a different filesystemnpm install
therenode_modules
directory back into the project dir, using cp -r --dereference
to expand symlinks into copies.I hope this helps someone else who ends up on this question when looking for a way to move node_modules
to a different filesystem.
There is another workaround, which I found on the github issue that @Charminbear linked to, but this doesn't work with grunt
because it does not support NODE_PATH
as per https://github.com/browserify/resolve/issues/136:
lets say you have
/media/sf_shared
and you can't install symlinks in there, which means you can't actually npm install from/media/sf_shared/myproject
because some modules use symlinks.
$ mkdir /home/dan/myproject && cd /home/dan/myproject
$ ln -s /media/sf_shared/myproject/package.json
(you can symlink in this direction, just can't create one inside of /media/sf_shared)$ npm install
$ cd /media/sf_shared/myproject
$ NODE_PATH=/home/dan/myproject/node_modules node index.js
You can read data direct from some file and plot
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from sys import argv
x,y,z = np.loadtxt('your_file', unpack=True)
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.savefig('teste.pdf')
plt.show()
If necessary you can pass vmin and vmax to define the colorbar range, e.g.
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1, vmin=0, vmax=2000)
I was wondering how to do some interactive plots, in this case with artificial data
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import Image
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
def plot(i):
fig = plt.figure()
ax = plt.axes(projection='3d')
theta = 2 * np.pi * np.random.random(1000)
r = i * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)
ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none')
fig.tight_layout()
interactive_plot = interactive(plot, i=(2, 10))
interactive_plot
You have a tuple of tuples.
To convert every tuple to a list:
[list(i) for i in level] # list of lists
--- OR ---
map(list, level)
And after you are done editing, just convert them back:
tuple(tuple(i) for i in edited) # tuple of tuples
--- OR --- (Thanks @jamylak)
tuple(itertools.imap(tuple, edited))
You can also use a numpy array:
>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1]])
For manipulating:
if clicked[0] == 1:
x = (mousey + cameraY) // 60 # For readability
y = (mousex + cameraX) // 60 # For readability
a[x][y] = 1
As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList
)
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country(string _name)
{
Cities = new List<City>();
Name = _name;
}
}
List<Country> countries = new List<Country> { new Country("UK"),
new Country("Australia"),
new Country("France") };
var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;
comboBox1.DataSource = bindingSource1.DataSource;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";
To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;
.
If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource
implements IBindingList
; one such structure is BindingList<T>
.
Tip: make sure that you are binding the DisplayMember
to a Property on the class and not a public field. If you class uses public string Name { get; set; }
it will work but if it uses public string Name;
it will not be able to access the value and instead will display the object type for each line in the combo box.
This can be achieved purely with JavaScript.
I see the answer I wanted to write has been answered by lynx in comments to the question.
But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.
So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:
// Fetch the element
var el = document.getElementById("someElement");
// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top;
Thats it!
Hope this helps someone :)
try this :
@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem()
{ Text = "Newest to Oldest", Value = "0" }, new SelectListItem()
{ Text = "Oldest to Newest", Value = "1" }},
new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })
If you are using SQLAlchemy's ORM rather than the expression language, you might find yourself wanting to convert an object of type sqlalchemy.orm.query.Query
to a Pandas data frame.
The cleanest approach is to get the generated SQL from the query's statement attribute, and then execute it with pandas's read_sql()
method. E.g., starting with a Query object called query
:
df = pd.read_sql(query.statement, query.session.bind)
Given
d = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
and your specific question: How can I remove the brackets?
Using list comprehension :
new_d = [i[0] for i in d]
will give you this
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]
then you can access individual items with the appropriate index, e.g., new_d[0]
will give you 180.0
etc which you can then use for math.
If you are going to have a collection of data, you will have some sort of bracket or parenthesis.
Note, this solution is aimed specifically at your question/problem, it doesn't provide a generalized solution. I.e., it will work for your case.
Be careful of difference between 'c'
and "c"
'c'
is a char suitable for formatting with %c
"c"
is a char* pointing to a memory block with a length of 2 (with the null terminator).
Here is how you would add query string parameters using HttpClient 4.2 and later:
URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");
HttpPost post = new HttpPost(builder.build());
The resulting URI would look like:
http://example.com/?parts=all&action=finish
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
json
is a built-in module, you don't need to install it with pip
.
I think the canonical method is:
while IFS=, read field1 field2 field3 field4 field5 field6; do
do stuff
done < CSV.file
If you don't know or don't care about how many fields there are:
IFS=,
while read line; do
# split into an array
field=( $line )
for word in "${field[@]}"; do echo "$word"; done
# or use the positional parameters
set -- $line
for word in "$@"; do echo "$word"; done
done < CSV.file
GetFile should be closing the file (or opening it within a using). Then you can delete the file after conversion to bytes-- the download will be done on that byte buffer.
byte[] GetFile(string s)
{
byte[] data;
using (System.IO.FileStream fs = System.IO.File.OpenRead(s))
{
data = new byte[fs.Length];
int br = fs.Read(data, 0, data.Length);
if (br != fs.Length)
throw new System.IO.IOException(s);
}
return data;
}
So in your download method...
byte[] fileBytes = GetFile(file);
// delete the file after conversion to bytes
System.IO.File.Delete(file);
// have the file download dialog only display the base name of the file return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(file));
$ gcc test.c -o testc $ file testc testc: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped $ ldd testc linux-vdso.so.1 => (0x00007fff227ff000) libc.so.6 => /lib64/libc.so.6 (0x000000391f000000) /lib64/ld-linux-x86-64.so.2 (0x000000391ec00000) $ gcc -m32 test.c -o testc $ file testc testc: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped $ ldd testc linux-gate.so.1 => (0x009aa000) libc.so.6 => /lib/libc.so.6 (0x00780000) /lib/ld-linux.so.2 (0x0075b000)
In short: use the -m32
flag to compile a 32-bit binary.
Also, make sure that you have the 32-bit versions of all required libraries installed (in my case all I needed on Fedora was glibc-devel.i386)
I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.
str1.toLowerCase().contains(str2.toLowerCase())
You can specify config file location with VM argument -Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"
As a matter of fact, if unsuccessful after following suggestions by marc_s, please keep in mind that a <security> element in server binding configuration (or lack thereof) in web.config on the server may cause this exception. For instance the server is expecting Message
-level security and client is configured to None
(or, if the server is not part of an Active Directory domain but the remote client host is).
Tip: In such cases the client app will most likely invoke the web service fine when executed directly on the server machine under administrative account in RDP session.
function onContentLoad() {_x000D_
var item = document.getElementById("id1");_x000D_
var x = item.dataset.x;_x000D_
var data = item.dataset.myData;_x000D_
_x000D_
var resX = document.getElementById("resX");_x000D_
var resData = document.getElementById("resData");_x000D_
_x000D_
resX.innerText = x;_x000D_
resData.innerText = data;_x000D_
_x000D_
console.log(x);_x000D_
console.log(data);_x000D_
}
_x000D_
<body onload="onContentLoad()">_x000D_
<div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
Read 'x':_x000D_
<label id="resX"></label>_x000D_
<br/>Read 'my-data':_x000D_
<label id="resData"></label>_x000D_
</body>
_x000D_
Yes, you could append ;Connection Timeout=30
to your connection string and specify the value you wish.
The timeout value set in the Connection Timeout
property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).
Moreover, setting the timeout value to 0
, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:
A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
As at PHP 7.3:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BEARER);
curl_setopt($ch,CURLOPT_XOAUTH2_BEARER,$bearerToken);
We may use a stringstream class.
bool isNumeric(string str)
{
stringstream stream;
double number;
stream<<str;
stream>>number;
return stream.eof();
}
Script is called before element exists.
You should try one of the following:
Try something like this in case you want to stop the loop from inside the function:
let timer = setInterval(function(){
// Have some code to do something
if(/*someStopCondition*/){
clearInterval(timer)
}
},1000);
You can also wrap this inside a another function, just make sure you have a timer variable and use clearInterval(theTimerVariable) to stop the loop
TreeMap, which is an implementation of the SortedMap interface, would work.
How do I use it ?
Map<Float, MyObject> map = new TreeMap<Float, MyObject>();
The filename should be a string. In other names it should be within quotes.
f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
thisline = i.split(" ");
You can also open the file using with
with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
lines = f.readlines()
for i in lines:
thisline = i.split(" ");
There is no need to add the semicolon(;
) in python. It's ugly.
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.