There's also MSMQ (Microsoft Message Queueing) which can operate across networks as well as on a local computer. Although there are better ways to communicate it's worth looking into: https://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx
CoreUtils referred to in other posts does NOT show the real implementation of most of the functionality which I think you seek. In most cases it provides front-ends for the actual functions that retrieve the data, which can be found here:
It is build upon Gnulib with the actual source code in the lib-subdirectory
You can use this
var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
Java's URI Class can help you out of this:
public static String getCurrentUrl(HttpServletRequest request){
URL url = new URL(request.getRequestURL().toString());
String host = url.getHost();
String userInfo = url.getUserInfo();
String scheme = url.getProtocol();
String port = url.getPort();
String path = request.getAttribute("javax.servlet.forward.request_uri");
String query = request.getAttribute("javax.servlet.forward.query_string");
URI uri = new URI(scheme,userInfo,host,port,path,query,null)
return uri.toString();
}
You need to specify workseet. Change line
If Worksheet.Cells(i, 1).Value = "X" Then
to
If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then
UPD:
Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):
Sub LastRowInOneColumn()
Dim LastRow As Long
Dim i As Long, j As Long
'Find the last used row in a Column: column A in this example
With Worksheets("Sheet2")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
MsgBox (LastRow)
'first row number where you need to paste values in Sheet1'
With Worksheets("Sheet1")
j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
For i = 1 To LastRow
With Worksheets("Sheet2")
If .Cells(i, 1).Value = "X" Then
.Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
j = j + 1
End If
End With
Next i
End Sub
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
Use below command at cmd or GIT Bash or other prompt
$ npm config set proxy "http://192.168.1.101:4128"
$ npm config set https-proxy "http://192.168.1.101:4128"
where 192.168.1.101 is proxy ip and 4128 is port. change according to your proxy settings. its works for me.
I have head around lots of solutions and none of them works perfectly. I've used variation of solutions available in my project which is here as below. Please use this code inside class where you are initialising toolbar and drawer layout.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);// show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
//show hamburger
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerFragment.mDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerFragment.mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
Try this:
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = 'dodge', stat='identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)
In my case , I have hadoop on windows, over C:/, this file according to core-site.xml, etc , it was in tmp/Administrator/dfs/data... name, etc, so erase it.
Then, namenode -format. and try again,
Before truncating the tables you have to remove all foreign keys. Use this script to generate final scripts to drop and recreate all foreign keys in database. Please set the @action variable to 'CREATE' or 'DROP'.
If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:
fit: your fit of a logistic regression curve
#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new
#doses:
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)
ggplot(data=data,aes(x=log10(DOSE),y=log(viability)))+geom_point()+
geom_line(data=fit.ggplot,aes(x=log10(x),y=log(y)))
The expires
and add_header
directives have no impact on NGINX caching the files, those are purely about what the browser sees.
What you likely want instead is:
location stuffyoudontwanttocache {
# don't cache it
proxy_no_cache 1;
# even if cached, don't try to use it
proxy_cache_bypass 1;
}
Though usually .js etc is the thing you would cache, so perhaps you should just disable caching entirely?
I need to do this from time to time and end up hacking the command line until it works.
For example, here I want to see if I have any SSH connections, (the 8th column returned by "ps" is the running "path-to-procname" and is filtered by "awk":
ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g'
Then I put it in a shell-script, ("eval"-ing the command line inside of backticks), like this:
#!/bin/bash
VNC_STRING=`ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g'`
if [ ! -z "$VNC_STRING" ]; then
echo "The VNC STRING is not empty, therefore your process is running."
fi
The "sed" part trims the path to the exact token and might not be necessary for your needs.
Here's my example I used to get your answer. I wrote it to automatically create 2 SSH tunnels and launch a VNC client for each.
I run it from my Cygwin shell to do admin to my backend from my windows workstation, so I can jump to UNIX/LINUX-land with one command, (this also assumes the client rsa keys have already been "ssh-copy-id"-ed and are known to the remote host).
It's idempotent in that each proc/command only fires when their $VAR eval's to an empty string.
It appends " | wc -l" to store the number of running procs that match, (i.e., number of lines found), instead of proc-name for each $VAR to suit my needs. I keep the "echo" statements so I can re-run and diagnose the state of both connections.
#!/bin/bash
SSH_COUNT=`eval ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g' | wc -l`
VNC_COUNT=`eval ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g' | wc -l`
if [ $SSH_COUNT = "2" ]; then
echo "There are already 2 SSH tunnels."
elif [ $SSH_COUNT = "1" ]; then
echo "There is only 1 SSH tunnel."
elif [ $SSH_COUNT = "0" ]; then
echo "connecting 2 SSH tunnels."
ssh -L 5901:localhost:5901 -f -l USER1 HOST1 sleep 10;
ssh -L 5904:localhost:5904 -f -l USER2 HOST2 sleep 10;
fi
if [ $VNC_COUNT = "2" ]; then
echo "There are already 2 VNC sessions."
elif [ $VNC_COUNT = "1" ]; then
echo "There is only 1 VNC session."
elif [ $VNC_COUNT = "0" ]; then
echo "launching 2 vnc sessions."
vncviewer.exe localhost:1 &
vncviewer.exe localhost:4 &
fi
This is very perl-like to me and possibly more unix utils than true shell scripting. I know there are lots of "MAGIC" numbers and cheezy hard-coded values but it works, (I think I'm also in poor taste for using so much UPPERCASE too). Flexibility can be added with some cmd-line args to make this more versatile but I wanted to share what worked for me. Please improve and share. Cheers.
simply used the +
operator. Javascript concats strings with +
From Implementing toString:
public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append( this.getClass().getName() );
result.append( " Object {" );
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
return result.toString();
}
I tried @PhilNicholas 's code and got the same problem of @its_me said in the comments that search bar show up on the next line of navbar, and I found that form
need to be added an attribute width
.
<form role="search" style="width: 15em; margin: 0.3em 2em;">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
</div>
</form>
How to do a redirect to another route with react-router?
For example, when a user clicks a link <Link to="/" />Click to route</Link>
react-router will look for /
and you can use Redirect to
and send the user somewhere else like the login route.
From the docs for ReactRouterTraining:
Rendering a
<Redirect>
will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
import { Route, Redirect } from 'react-router'
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/dashboard"/>
) : (
<PublicHomePage/>
)
)}/>
to: string, The URL to redirect to.
<Redirect to="/somewhere/else"/>
to: object, A location to redirect to.
<Redirect to={{
pathname: '/login',
search: '?utm=your+face',
state: { referrer: currentLocation }
}}/>
On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)
Just go to Settings>PermissionsAutostart
I guess the easiest and most basic way is this
import math
number = int (input ('Enter number: '))
if number % 2 == 0 and number != 0:
print ('Even number')
elif number == 0:
print ('Zero is neither even, nor odd.')
else:
print ('Odd number')
Just basic conditions and math. It also minds zero, which is neither even, nor odd and you give any number you want by input so it's very variable.
To keep your Docker images small, don't install unnecessary editors. You can edit the files over SSH from the Docker host to the container:
vim scp://remoteuser@containerip//path/to/document
Try this code, I got it from here
$input = Array(1,2,3,1,2,3,4,5,6);
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
The most elegant way to do this is with a ByteArrayOutputStream
.
byte a[];
byte b[];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write( a );
outputStream.write( b );
byte c[] = outputStream.toByteArray( );
Agree that
Options -Indexes
should work if the main server is configured to allow option overrides, but if not, this will hide all files from the listing (so every directory appears empty):
IndexIgnore *
set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.
Use Dialog for simple yes or no dialogs.
When you need more complex views in which you need get hold of the lifecycle such as oncreate, request permissions, any life cycle override I would use a dialog fragment. Thus you separate the permissions and any other code the dialog needs to operate without having to communicate with the calling activity.
If you are trying to make more than just one folder on the root of the sdcard,
ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"
then instead of folder.mkdir()
you would use folder.mkdirs()
I've made this mistake in the past & I took forever to figure it out.
Try something like:
WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else
Fire the below command. It gives a list of modules.
sudo apt-cache search php5-
Then fire the below command with the module name to be installed:
sudo apt-get install name of the module
For reference, see How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu.
You can use the data.table package:
How to reorder data.table columns (without copying)
require(data.table)
setcolorder(DT,myOrder)
I ended up here because I was having an issue with Bootstrap 4 grid system and an Angular *ngFor loop. I fixed it by applying a col justify-content-center class to the div implementing the ngFor:
<div class="row" style="border:1px solid red;">
<div class="col d-flex justify-content-center">
<button mat-raised-button>text</button>
</div>
<div *ngFor="let text of buttonText" class="col d-flex justify-content-center">
<button mat-raised-button>text</button>
</div>
</div>
Because you can break out of a do/while loop, let us "do" one round. With a while(false) at the end, the condition is never true and will not repeat, again.
do
{
$subjectText = trim(filter_input(INPUT_POST, 'subject'));
if(!$subjectText)
{
$smallInfo = 'Please give a subject.';
break;
}
$messageText = trim(filter_input(INPUT_POST, 'message'));
if(!$messageText)
{
$smallInfo = 'Please supply a message.';
break;
}
} while(false);
This function shortens a string by adding "..."
at a word boundary whenever possible. The returned string will have a maximum length of $len
including "..."
.
function truncate($str, $len) {
$tail = max(0, $len-10);
$trunk = substr($str, 0, $tail);
$trunk .= strrev(preg_replace('~^..+?[\s,:]\b|^...~', '...', strrev(substr($str, $tail, $len-$tail))));
return $trunk;
}
Examples outputs:
truncate("Thanks for contributing an answer to Stack Overflow!", 15)
"Thanks for..."
truncate("To learn more, see our tips on writing great answers.", 15)
"To learn more..."
(comma also truncated)truncate("Pseudopseudohypoparathyroidism", 15)
"Pseudopseudo..."
This works for SQL Server Management Studio v18.0
The file "SqlStudio.bin" doesn't seem to exist any longer. Instead my settings are all stored in this file:
C:\Users\*********\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml
<Element>.......</Element>
block
that surrounds it.A solution improving on the great one from @sparrow.
Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.
Let's suppose you want to call your new column simply, new_column
First make the list into a Series:
column_values = pd.Series(mylist)
Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column. In the following example we will position the new column in the first position from left (by setting loc=0)
df.insert(loc=0, column='new_column', value=column_values)
byte[] b = IOUtils.toByteArray((new URL( )).openStream()); //idiom
Note however, that stream is not closed in the above example.
if you want a (76-character) chunk (using commons codec)...
byte[] b = Base64.encodeBase64(IOUtils.toByteArray((new URL( )).openStream()), true);
There is one more option now ( January-2015 )
Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.
To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source
Add a file to your repository like this:
mvn install:install-file \
-Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID
-DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
-Dpackaging=jar \
-DlocalRepositoryPath=/var/www/html/mavenRepository
If your domain is example.com
and the root directory of the web server is located at /var/www/html/
, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>
.
From the docs
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
As you say:
error: missing method body, or declare abstract public static void main(String[] args); ^ this is what i got after i added it after the class name
You probably haven't declared main with a body (as ';" would suggest in your error).
You need to have main method with a body, which means you need to add { and }:
public static void main(String[] args) {
}
Add it inside your class definition.
Although sometimes error messages are not very clear, most of the time they contain enough information to point to the issue. Worst case, you can search internet for the error message. Also, documentation can be really helpful.
first of all check your internet its connect!
second is turn on WP_DEBUG and write this codes in wp-config.php
define('WP_DEBUG',true);
error_reporting('E_ALL');
ini_set('display_errors',1);
third is rename themes and plugins folder that in wp-content folder to other name sush as
pluginss , themess
S F my english!
The short answer is "yes". A sample ldapsearch
command to query an Active Directory server is:
ldapsearch \
-x -h ldapserver.mydomain.com \
-D "[email protected]" \
-W \
-b "cn=users,dc=mydomain,dc=com" \
-s sub "(cn=*)" cn mail sn
This would connect to an AD server at hostname ldapserver.mydomain.com
as user [email protected]
, prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com
subtree.
See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.
I had the same problem and could not find a solution. Mark90 is right there are a lot info.plist files and you should edit the correct. Go to Project, under TARGETS select the project (not the tests), in the tab bar select Info and add the permission under "Custom iOS Target Properties".
How about this? (If you're using jQuery)
var $window = $(window);
var $body = $(window.document.body);
window.onscroll = function() {
var overlay = $body.children(".ui-widget-overlay").first();
// Check if the overlay is visible and restore the previous scroll state
if (overlay.is(":visible")) {
var scrollPos = $body.data("scroll-pos") || { x: 0, y: 0 };
window.scrollTo(scrollPos.x, scrollPos.y);
}
else {
// Just store the scroll state
$body.data("scroll-pos", { x: $window.scrollLeft(), y: $window.scrollTop() });
}
};
use to .onBackPressed() to back Activity specify
@Override
public void onBackPressed(){
backpress = (backpress + 1);
Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();
if (backpress>1) {
this.finish();
}
}
It’s a holdover from the Netscape days:
Missing digits are treated as 0[...]. An incorrect digit is simply interpreted as 0. For example the values #F0F0F0, F0F0F0, F0F0F, #FxFxFx and FxFxFx are all the same.
It is from the blog post A little rant about Microsoft Internet Explorer's color parsing which covers it in great detail, including varying lengths of color values, etc.
If we apply the rules in turn from the blog post, we get the following:
Replace all nonvalid hexadecimal characters with 0’s:
chucknorris becomes c00c0000000
Pad out to the next total number of characters divisible by 3 (11 ? 12):
c00c 0000 0000
Split into three equal groups, with each component representing the corresponding colour component of an RGB colour:
RGB (c00c, 0000, 0000)
Truncate each of the arguments from the right down to two characters.
Which, finally, gives the following result:
RGB (c0, 00, 00) = #C00000 or RGB(192, 0, 0)
Here’s an example demonstrating the bgcolor
attribute in action, to produce this “amazing” colour swatch:
<table>
<tr>
<td bgcolor="chucknorris" cellpadding="8" width="100" align="center">chuck norris</td>
<td bgcolor="mrt" cellpadding="8" width="100" align="center" style="color:#ffffff">Mr T</td>
<td bgcolor="ninjaturtle" cellpadding="8" width="100" align="center" style="color:#ffffff">ninjaturtle</td>
</tr>
<tr>
<td bgcolor="sick" cellpadding="8" width="100" align="center">sick</td>
<td bgcolor="crap" cellpadding="8" width="100" align="center">crap</td>
<td bgcolor="grass" cellpadding="8" width="100" align="center">grass</td>
</tr>
</table>
_x000D_
This also answers the other part of the question: Why does bgcolor="chucknorr"
produce a yellow colour? Well, if we apply the rules, the string is:
c00c00000 => c00 c00 000 => c0 c0 00 [RGB(192, 192, 0)]
Which gives a light yellow gold colour. As the string starts off as 9 characters, we keep the second ‘C’ this time around, hence it ends up in the final colour value.
I originally encountered this when someone pointed out that you could do color="crap"
and, well, it comes out brown.
As simple as this
mCalendar = Calendar.getInstance();
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
Calendar.LONG is to get the full name of the month and Calendar.SHORT gives the name in short. For eg: Calendar.LONG will return January Calendar.SHORT will return Jan
IO bound processes: spend more time doing IO than computations, have many short CPU bursts. CPU bound processes: spend more time doing computations, few very long CPU bursts
This happens because the scipy
module doesn't have any attribute named sparse
. That attribute only gets defined when you import scipy.sparse
.
Submodules don't automatically get imported when you just import scipy
; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py
included a statement import scipy.sparse
, then the sparse
submodule would be imported whenever you import scipy
.)
Edit: As in a comment rightly requested here some more information. Use the include
tag
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/yourlayout" />
to include the layout you want to reuse.
Check this link out...
I would prevent loops in general if i can, set approaches are much more efficient:
INSERT INTO tblFoo
SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id])
FROM sys.all_objects ORDER BY n;
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
For VS Code 1.38 or if you could not find any "lightbulb" button. Pay close attention to the greyed out text above the conflicts; there is a list of actions you can take.
Well, performance impact is mostly insignificant, but isn't zero. If you look at JavaDoc of RandomAccess
interface:
As a rule of thumb, a List implementation should implement this interface if, for typical instances of the class, this loop:
for (int i=0, n=list.size(); i < n; i++) list.get(i);
runs faster than this loop:
for (Iterator i=list.iterator(); i.hasNext();) i.next();
And for-each loop is using version with iterator, so for ArrayList
for example, for-each loop isn't fastest.
You can also use "or" operator,
for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {
...
}
(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)
I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:
except Exception as e:
print(e)
will print the error output to sys.stdout
by default. A more appropriate approach to error handling in general would be:
except Exception as e:
print(e, file=sys.stderr)
(Note that you have to import sys
for this to work.) This way, the error is printed to STDERR
instead of STDOUT
, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.
I haven't used the traceback
module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.
<br>
is sufficient but in XHTML <br />
is preferred according to the WHATWG and according to the W3C.
To quote Section 8.1.2.1 of HTML 5.2 W3C Recommendation, 14 December 2017
Start tags must have the following format:
…
After the attributes, or after the tag name if there are no attributes, there may be one or more space characters. (Some attributes are required to be followed by a space. See §8.1.2.3 Attributes below.)
Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS character (/). This character has no effect on void elements, but on foreign elements it marks the start tag as self-closing.
If you use Dreamweaver CS6, then it will autocomplete as <br />
.
To validate your HTML file on W3C see : http://validator.w3.org/
What you need is properly a service:
.factory('DataLayer', ['$http',
function($http) {
var factory = {};
var locations;
factory.getLocations = function(success) {
if(locations){
success(locations);
return;
}
$http.get('locations/locations.json').success(function(data) {
locations = data;
success(locations);
});
};
return factory;
}
]);
The locations
would be cached in the service which worked as singleton model. This is the right way to fetch data.
Use this service DataLayer
in your controller and directive is ok as following:
appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
DataLayer.getLocations(function(data){
$scope.locations = data;
});
});
.directive('map', function(DataLayer) {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function(scope, element, attrs) {
DataLayer.getLocations(function(data) {
angular.forEach(data, function(location, key){
//do something
});
});
}
};
});
I just want to add my method to do this.
just define a custome json encoder to serilize your db models.
class ParentEncoder(json.JSONEncoder):
def default(self, obj):
# convert object to a dict
d = {}
if isinstance(obj, Parent):
return {"id": obj.id, "name": obj.name, 'children': list(obj.child)}
if isinstance(obj, Child):
return {"id": obj.id, "name": obj.name}
d.update(obj.__dict__)
return d
then in your view function
parents = Parent.query.all()
dat = json.dumps({"data": parents}, cls=ParentEncoder)
resp = Response(response=dat, status=200, mimetype="application/json")
return (resp)
it works well though the parent have relationships
I am asking in general, how to write a compatible awk script that performs the same functionality ...
To solve the problem in your quesiton is easy. (check others' answer).
If you want to write an awk script, which portable to any awk implementations and versions (gawk/nawk/mawk...) it is really hard, even if with --posix (gawk)
for example:
\x
escape, some notFS
interpreter works differentlywell all the points above are just spoken in general. Back to your problem, you problem is only related to fundamental feature of awk. awk '{print $x}'
the line like that will work all awks.
There are two reasons why your awk line behaves differently on gawk and mawk:
your used substr()
function wrongly. this is the main cause. you have substr($0, 0, RSTART - 1)
the 0
should be 1
, no matter which awk do you use. awk array, string idx etc are 1-based.
gawk and mawk implemented substr()
differently.
Change your network adapter to a bridged connection, this will directly connect to your computers physical network.
Some supplementary info. Both flag and interrupt are suggested in the Java doc.
https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
For a thread that waits for long periods (e.g., for input), use Thread.interrupt
public void stop() {
Thread moribund = waiter;
waiter = null;
moribund.interrupt();
}
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
Update: Angular 8 finally got method to clear the Array FormArray.clear()
Filestash is the perfect tool for that:
Also Filestash is open source. (Disclaimer: I am the author)
Another option, this DOESN'T support comments, very useful with AmaterasERD DDL export for Apache Derby:
public void executeSqlScript(Connection conn, File inputFile) {
// Delimiter
String delimiter = ";";
// Create scanner
Scanner scanner;
try {
scanner = new Scanner(inputFile).useDelimiter(delimiter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
// Loop through the SQL file statements
Statement currentStatement = null;
while(scanner.hasNext()) {
// Get statement
String rawStatement = scanner.next() + delimiter;
try {
// Execute statement
currentStatement = conn.createStatement();
currentStatement.execute(rawStatement);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
if (currentStatement != null) {
try {
currentStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
currentStatement = null;
}
}
scanner.close();
}
You can use sprintf: http://php.net/manual/en/function.sprintf.php
<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>
It will only add the zero if it's less than the required number of characters.
Edit: As pointed out by @FelipeAls:
When working with numbers, you should use %d
(rather than %s
), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.
For example:
sprintf("%04s", 10);
returns 0010
sprintf("%04s", -10);
returns 0-10
Where as:
sprintf("%04d", 10);
returns 0010
sprintf("%04d", -10);
returns -010
What that build error is telling you, that you have to either have an instance of Program
or make Add
static.
There is no native boolean data type for SQLite. Per the Datatypes doc:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
Create a Random object with a seed and get the array random by doing:
public static final int ARRAY_LENGTH = 20;
byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);
The above answers are also the ways to fix the error but if does not work for anyone then i have an option...
Just Close the project and nothing else and start it again so it will load References... Follow the ScreenShots.
I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.
According to https://reacttraining.com/react-router/web/api/history
For "react-router-dom": "^5.1.2",
,
const { history } = this.props;
<Button onClick={history.goBack}>
Back
</Button>
YourComponent.propTypes = {
history: PropTypes.shape({
goBack: PropTypes.func.isRequired,
}).isRequired,
};
Just my 2 cents in case someone stumble upon this :)
What I am suggesting here will have the same result as the current answer however it has been recommended to write your controller the way that I have mentioned here.
Reference scroll to the first "Note" (Sorry it doesn't have anchor)
Here is the recommended way:
Controller:
var app = angular.module('myApp', []);
app.controller( 'MyCtrl', ['$scope', function($scope) {
$scope.date = new Date();
}]);
View:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
{{date | date:'yyyy-MM-dd'}}
</div>
</div>
There's a couple of ways you can do this. If the onchange
listener is a function set via the element.onchange
property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:
element.onchange();
If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener
/attachEvent
, you need to do a bit of feature detection to correctly fire the event:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
You've got a couple of issues here.
Firstly, you're defining your code within an anonymous function. This construct:
(function() {
...
)();
does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout()
. The problem is that update()
is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
)();
because the function pointer update
is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
or
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
}
and both of these work. The second works because the update()
within the code block is within scope now.
I also prefer the $(function() { ... }
shortened block form and rather than calling setTimeout()
within update()
you can just use setInterval()
instead:
$(function() {
setInterval(update, 1000);
});
function update() {
$("#board").append(".");
}
Hope that clears that up.
The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):
This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
There is an alternate form of Throwable.printStackTrace() that takes a print stream as an argument. http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)
E.g.
catch(Exception e) {
e.printStackTrace(System.out);
}
This will print the stack trace to std out instead of std error.
The value of the certificate comes mostly from the trust of the internet users in the issuer of the certificate. To that end, Verisign is tough to beat. A certificate says to the client that you are who you say you are, and the issuer has verified that to be true.
You can get a free SSL certificate signed, for example, by StartSSL. This is an improvement on self-signed certificates, because your end-users would stop getting warning pop-ups informing them of a suspicious certificate on your end. However, the browser bar is not going to turn green when communicating with your site over https, so this solution is not ideal.
The cheapest SSL certificate that turns the bar green will cost you a few hundred dollars, and you would need to go through a process of proving the identity of your company to the issuer of the certificate by submitting relevant documents.
'@icon sushi' is a portable utility that can create multiple icon ico file for free.
Drag & drop the different icon sizes, select them all and choose file -> create multiple icon.
You can download if from http://www.towofu.net/soft/e-aicon.php
I know its a old question but if you are looking to make the button on c# instead of xaml you can set the CornerRadius
that will round your button.
Button buttonRouded = new Button
{
CornerRadius = 10,
};
try:
gsub('\\$', '', '$5.00$')
Array(n).map((value, index) ....) is 80% of the way there. But for some odd reason it does not work. But there is a workaround.
Array(n).map((v,i) => i) // does not work
Array(n).fill().map((v,i) => i) // does dork
For a range
Array(end-start+1).fill().map((v,i) => i + start) // gives you a range
Odd, these two iterators return the same result: Array(end-start+1).entries()
and Array(end-start+1).fill().entries()
I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.
/**
* Delets a dir recursively deleting anything inside it.
* @param dir The dir to delete
* @return true if the dir was successfully deleted
*/
public static boolean deleteDirectory(File dir) {
if(! dir.exists() || !dir.isDirectory()) {
return false;
}
String[] files = dir.list();
for(int i = 0, len = files.length; i < len; i++) {
File f = new File(dir, files[i]);
if(f.isDirectory()) {
deleteDirectory(f);
}else {
f.delete();
}
}
return dir.delete();
}
For use in scripts/programs which need to support both python 2 and 3, the six module provides quote and urlencode functions:
>>> from six.moves.urllib.parse import urlencode, quote
>>> data = {'some': 'query', 'for': 'encoding'}
>>> urlencode(data)
'some=query&for=encoding'
>>> url = '/some/url/with spaces and %;!<>&'
>>> quote(url)
'/some/url/with%20spaces%20and%20%25%3B%21%3C%3E%26'
How about a bitwise operator? Instead of strings, you're dealing with "enums", which looks more "elegant."
// Declare slider's state "enum"
var SliderOne = {
A: 1,
B: 2,
C: 4,
D: 8,
E: 16
};
var SliderTwo = {
A: 32,
B: 64,
C: 128,
D: 256,
E: 512
};
// Set state
var s1 = SliderOne.A,
s2 = SliderTwo.B;
// Switch state
switch (s1 | s2) {
case SliderOne.A | SliderTwo.A :
case SliderOne.A | SliderTwo.C :
// Logic when State #1 is A, and State #2 is either A or C
break;
case SliderOne.B | SliderTwo.C :
// Logic when State #1 is B, and State #2 is C
break;
case SliderOne.E | SliderTwo.E :
default:
// Logic when State #1 is E, and State #2 is E or
// none of above match
break;
}
I however agree with others, 25 cases in a switch-case logic is not too pretty, and if-else might, in some cases, "look" better. Anyway.
Swift 3+
Example to assign new values to Dictionary. You need to declare it as NSMutableDictionary:
var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)
>>> r = re.compile("([a-zA-Z]+)([0-9]+)")
>>> m = r.match("foobar12345")
>>> m.group(1)
'foobar'
>>> m.group(2)
'12345'
So, if you have a list of strings with that format:
import re
r = re.compile("([a-zA-Z]+)([0-9]+)")
strings = ['foofo21', 'bar432', 'foobar12345']
print [r.match(string).groups() for string in strings]
Output:
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
Have you tried what is on the sample. I am new to this but here is the command: puppet --test --trace --debug. I hope this helps.
NetManager that you can use to check internet connection on Android with Kotlin
If you use minSdkVersion >= 23
class NetManager @Inject constructor(var applicationContext: Context) {
val isConnectedToInternet: Boolean?
get() = with(
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
) {
isConnectedToInternet()
}
}
fun ConnectivityManager.isConnectedToInternet() = isConnected(getNetworkCapabilities(activeNetwork))
fun isConnected(networkCapabilities: NetworkCapabilities?): Boolean {
return when (networkCapabilities) {
null -> false
else -> with(networkCapabilities) { hasTransport(TRANSPORT_CELLULAR) || hasTransport(TRANSPORT_WIFI) }
}
}
If you use minSdkVersion < 23
class NetManager @Inject constructor(var applicationContext: Context) {
val isConnectedToInternet: Boolean?
get() = with(
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
) {
isConnectedToInternet()
}
}
fun ConnectivityManager.isConnectedToInternet(): Boolean = if (Build.VERSION.SDK_INT < 23) {
isConnected(activeNetworkInfo)
} else {
isConnected(getNetworkCapabilities(activeNetwork))
}
fun isConnected(network: NetworkInfo?): Boolean {
return when (network) {
null -> false
else -> with(network) { isConnected && (type == TYPE_WIFI || type == TYPE_MOBILE) }
}
}
fun isConnected(networkCapabilities: NetworkCapabilities?): Boolean {
return when (networkCapabilities) {
null -> false
else -> with(networkCapabilities) { hasTransport(TRANSPORT_CELLULAR) || hasTransport(TRANSPORT_WIFI) }
}
}
In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".
I had the same problem, to resolve it, go windows -> preferences -> servers and select runtime environment, and now you will see a new window, in the upper right you will see a option: Download additional server adapter, click and install the glassfish server.
I got same problem and solved using a flag.
bool flag = false;
while(true) {
switch(msg->state) {
case MSGTYPE: // ...
break;
// ... more stuff ...
case DONE:
flag = true; // **HERE, I want to break out of the loop itself**
}
if(flag) break;
}
String loudScreaming = json.getJSONObject("LabelData").getString("slogan");
The following code downloads an image from a direct link to the disk into the project directory. Also note that it uses try-with-resources
.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FilenameUtils;
public class ImageDownloader
{
public static void main(String[] arguments) throws IOException
{
downloadImage("https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg",
new File("").getAbsolutePath());
}
public static void downloadImage(String sourceUrl, String targetDirectory)
throws MalformedURLException, IOException, FileNotFoundException
{
URL imageUrl = new URL(sourceUrl);
try (InputStream imageReader = new BufferedInputStream(
imageUrl.openStream());
OutputStream imageWriter = new BufferedOutputStream(
new FileOutputStream(targetDirectory + File.separator
+ FilenameUtils.getName(sourceUrl)));)
{
int readByte;
while ((readByte = imageReader.read()) != -1)
{
imageWriter.write(readByte);
}
}
}
}
You should escape the quotes like this:
curl -i -X POST -d '{\"screencast\":{\"subject\":\"tools\"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
Try this.
Here is the service part.
[ServiceContract]
public interface IService
{
[OperationContract]
void HelloWorld();
}
public class Service : IService
{
public void HelloWorld()
{
//Hello World
}
}
Here is the Proxy
public class ServiceProxy : ClientBase<IService>
{
public ServiceProxy()
: base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
{
}
public void InvokeHelloWorld()
{
Channel.HelloWorld();
}
}
And here is the service hosting part.
var serviceHost = new ServiceHost
(typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
serviceHost.Open();
Console.WriteLine("Service started. Available in following endpoints");
foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
{
Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
}
Use the query below to find out pending transaction.
If it returns a value, it means there is a pending transaction.
Here is the query:
select dbms_transaction.step_id from dual
;
References:
http://www.acehints.com/2011/07/how-to-check-pending-transaction-in.html
http://www.acehints.com/p/site-map.html
Java doesn't support default parameters. You will need to have two constructors to do what you want.
An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.
e.g.
public class Foo {
private final String param1;
private final String param2;
private Foo(Builder builder) {
this.param1 = builder.param1;
this.param2 = builder.param2;
}
public static class Builder {
private String param1 = "defaultForParam1";
private String param2 = "defaultForParam2";
public Builder param1(String param1) {
this.param1 = param1;
return this;
}
public Builder param2(String param1) {
this.param2 = param2;
return this;
}
public Foo build() {
return new Foo(this);
}
}
}
which allows you to say:
Foo myFoo = new Foo.Builder().param1("myvalue").build();
which will have a default value for param2
.
You cannot load images directly with @2x
or @3x
, system selects appropriate image automatically, just specify the name using UIImage
:
UIImage(named: "green-square-Retina")
While Configuring a new project
the company name should end as .app for example it should be android.example.com.app and it should not be android.example.com
The Date
object is used to work with dates and times.
Date objects are created with new Date()
var now = new Date();
now - Current date and time object.
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
----------------------------------
}
I'd go with @sandeep's display: table-cell
answer if you don't care about IE7.
Otherwise, here's an alternative, with one downside: the "right" div
has to come first in the HTML.
See: http://jsfiddle.net/thirtydot/qLTMf/
and exactly the same, but with the "right div" removed: http://jsfiddle.net/thirtydot/qLTMf/1/
#parent {
overflow: hidden;
border: 1px solid red
}
.right {
float: right;
width: 100px;
height: 100px;
background: #888;
}
.left {
overflow: hidden;
height: 100px;
background: #ccc
}
<div id="parent">
<div class="right">right</div>
<div class="left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam semper porta sem, at ultrices ante interdum at. Donec condimentum euismod consequat. Ut viverra lorem pretium nisi malesuada a vehicula urna aliquet. Proin at ante nec neque commodo bibendum. Cras bibendum egestas lacus, nec ullamcorper augue varius eget.</div>
</div>
gc()
can help
saving data as .RData, closing, re-opening R, and loading the RData can help.
see my answer here: https://stackoverflow.com/a/24754706/190791 for more details
CAST(CONVERT(CHAR(8),GETUTCDATE(),114) AS DATETIME)
IN SQL Server 2008+
CAST(GETUTCDATE() AS TIME)
Bitmap memoryImage;
//Set full width, height for image
memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
Size s = new Size(memoryImage.Width, memoryImage.Height);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
string str = "";
try
{
str = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
@"\Screenshot.png");//Set folder to save image
}
catch { };
memoryImage.save(str);
if ( getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
CameraManager cameraManager=(CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId,true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
If you have to do private key validation; at Command Prompt(cmd), run
First;
set PATH=C:\PuttySetupLocation
Second;
pscp -i C:/MyPrivateKeyFile.ppk C:/MySourceFile.jar [email protected]:/home/ubuntu
Also, if you need extra options look at the following link. https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html
The order() function fails when the column has levels or factor. It works properly when stringsAsFactors=FALSE is used in data.frame creation.
Not saying this is the best way to go, but its good to have options. Necessitas is a project that ports Qt to android. It is still in its early stages and lacking full features, but for those who know Qt and don't wanna bother with the terrible lack of good tools for Android UI would be wise to at least consider using this.
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
I know the answer is already accepted here, but I just wanted to share what I found when I tried to escape double quotes and single quotes.
Here's what I have done: and this works :)
to escape double quotes:
if(string.contains("\"")) {
string = string.replaceAll("\"", "\\\\\"");
}
and to escape single quotes:
if(string.contains("\'")) {
string = string.replaceAll("\'", "\\\\'");
}
PS: Please note the number of backslashes used above.
You probably want the answer to "How to call an external command in Python".
The simplest approach is to use the os.system
function, e.g.:
import os
os.system("some_command &")
Basically, whatever you pass to the system
function will be executed the same as if you'd passed it to the shell in a script.
You could put the body of your script into a function and then you could return from that function.
def main():
done = True
if done:
return
# quit/stop/exit
else:
# do other stuff
if __name__ == "__main__":
#Run as main program
main()
In order to remotely access a PostgreSQL database, you must set the two main PostgreSQL configuration files:
postgresql.conf
pg_hba.conf
Here is a brief description about how you can set them (note that the following description is purely indicative: To configure a machine safely, you must be familiar with all the parameters and their meanings)
First of all configure PostgreSQL service to listen on port 5432 on all network interfaces in Windows 7 machine:
open the file postgresql.conf
(usually located in C:\Program Files\PostgreSQL\9.2\data) and sets the parameter
listen_addresses = '*'
Check the network address of WindowsXP virtual machine, and sets parameters in pg_hba.conf file (located in the same directory of postgresql.conf) so that postgresql can accept connections from virtual machine hosts.
For example, if the machine with Windows XP have 192.168.56.2 IP address, add in the pg_hba.conf
file:
host all all 192.168.56.1/24 md5
this way, PostgreSQL will accept connections from all hosts on the network 192.168.1.XXX.
Restart the PostgreSQL service in Windows 7 (Services-> PosgreSQL 9.2: right click and restart sevice). Install pgAdmin on windows XP machine and try to connect to PostgreSQL.
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
On CentOS 7, the pip
version is pip3.4
and is located here:
/usr/local/bin/pip3.4
You are putting there a two-digits year. The first century. And the Gregorian calendar started in the 16th century. I think you should add 2000 to the year.
Month in the function new GregorianCalendar(year, month, days)
is 0-based. Subtract 1 from the month there.
Change the body of the second function as follows:
String dateFormatted = null;
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
try {
dateFormatted = fmt.format(date);
}
catch ( IllegalArgumentException e){
System.out.println(e.getMessage());
}
return dateFormatted;
After debugging, you'll see that simply GregorianCalendar
can't be an argument of the fmt.format();
.
Really, nobody needs GregorianCalendar
as output, even you are told to return "a string".
Change the header of your format function to
public static String format(final Date date)
and make the appropriate changes. fmt.format()
will take the Date
object gladly.
Google "Freeware MSI installer".
e.g. https://www.advancedinstaller.com/
Several options here:
http://rbytes.net/software/development_c/install-and-setup_s/
Though being Windows, most are "shareware" rather than truly free and open source.
You can try like below with sqljdbc4-2.0.jar:
public void getConnection() throws ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
String url = "jdbc:sqlserver://<SERVER_IP>:<PORT_NO>;databaseName=" + DATABASE_NAME;
Connection conn = DriverManager.getConnection(url, USERNAME, PASSWORD);
System.out.println("DB Connection started");
Statement sta = conn.createStatement();
String Sql = "select * from TABLE_NAME";
ResultSet rs = sta.executeQuery(Sql);
while (rs.next()) {
System.out.println(rs.getString("COLUMN_NAME"));
}
}
In C++11, the using
keyword when used for type alias
is identical to typedef
.
7.1.3.2
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.
Bjarne Stroustrup provides a practical example:
typedef void (*PFD)(double); // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double); // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP
Pre-C++11, the using
keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):
class Derived : public Base {
public:
using Base::f; // lift Base's f into Derived's scope -- works in C++98
void f(char); // provide a new f
void f(int); // prefer this f to Base::f(int)
using Base::Base; // lift Base constructors Derived's scope -- C++11 only
Derived(char); // provide a new constructor
Derived(int); // prefer this constructor to Base::Base(int)
// ...
};
Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard
, Design decisions
, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.
Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.
First let’s consider a toy example:
template <typename T> class MyAlloc {/*...*/}; template <typename T, class A> class MyVector {/*...*/}; template <typename T> struct Vec { typedef MyVector<T, MyAlloc<T> > type; }; Vec<int>::type p; // sample usage
The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.
template <typename T> void foo (Vec<T>::type&);
So, the syntax is somewhat ugly. We would rather avoid the nested
::type
We’d prefer something like the following:template <typename T> using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below Vec<int> p; // sample usage
Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on
Vec<T>
in deducible context, and the syntax is improved as well. For example we could rewrite foo as:template <typename T> void foo (Vec<T>&);
We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to
foo(p)
will succeed.
The follow-up paper n1489 explains why using
instead of using typedef
:
It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:
template<class T> typedef std::vector<T, MyAllocator<T> > Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector< [bullet] , MyAllocator< [bullet] > >
– where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentencetemplate<class T> using Vec = std::vector<T, MyAllocator<T> >;
can be read/interpreted as: from now on, I’ll be using
Vec<T>
as a synonym forstd::vector<T, MyAllocator<T> >
. With that reading, the new syntax for aliasing seems reasonably logical.
I think the important distinction is made here, aliases instead of types. Another quote from the same document:
An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.
Summary, for the role of using
:
namespace PO = boost::program_options
and using PO = ...
equivalent)A typedef declaration can be viewed as a special case of non-template alias-declaration
. It's an aesthetic change, and is considered identical in this case.namespace std
into the global scope), member functions, inheriting constructorsIt cannot be used for:
int i;
using r = i; // compile-error
Instead do:
using r = decltype(i);
Naming a set of overloads.
// bring cos into scope
using std::cos;
// invalid syntax
using std::cos(double);
// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);
this command can download jdk8 tgz package at now (2018-09-06), good luck !
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u141-b15/336fa29ff2bb4ef291e347e091f7f4a7/jdk-8u141-linux-x64.tar.gz"
Check out the sample code. It help you.
private ProgressBar progressBar;
progressBar=(ProgressBar)findViewById(R.id.webloadProgressBar);
WebView urlWebView= new WebView(Context);
urlWebView.setWebViewClient(new AppWebViewClients(progressBar));
urlWebView.getSettings().setJavaScriptEnabled(true);
urlWebView.loadUrl(detailView.getUrl());
public class AppWebViewClients extends WebViewClient {
private ProgressBar progressBar;
public AppWebViewClients(ProgressBar progressBar) {
this.progressBar=progressBar;
progressBar.setVisibility(View.VISIBLE);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
Thanks.
Put this in your server directive:
location /issue {
rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
}
Or duplicate it:
location /issue1 {
rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
...
xxd -p file
Or if you want it all on a single line:
xxd -p file | tr -d '\n'
Don't confuse thread safety with determinism. Thread-safe code can also be non-deterministic. Given the difficulty of debugging problems with threaded code, this is probably the normal case. :-)
Thread safety simply ensures that when a thread is modifying or reading shared data, no other thread can access it in a way that changes the data. If your code depends on a certain order for execution for correctness, then you need other synchronization mechanisms beyond those required for thread safety to ensure this.
In my opinion, most answers proposed here as sub-optimal. The one coming closest is the original one proposed initially by Brann.
A Temp Filename must be
Because of these requirements, it is not a godd idea to program such a beast on your own. Smart People writing IO Libraries worry about things like locking (if needed) etc. Therefore, I see no need to rewrite System.IO.Path.GetTempFileName().
This, even if it looks clumsy, should do the job:
//Note that this already *creates* the file
string filename1 = System.IO.Path.GetTempFileName()
// Rename and move
filename = filename.Replace(".tmp", ".csv");
File.Move(filename1 , filename);
The following code works on both Linux and Windows, and not depending on external modules
import os
import subprocess
import platform
import re
def pid_alive(pid:int):
""" Check For whether a pid is alive """
system = platform.uname().system
if re.search('Linux', system, re.IGNORECASE):
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
elif re.search('Windows', system, re.IGNORECASE):
out = subprocess.check_output(["tasklist","/fi",f"PID eq {pid}"]).strip()
# b'INFO: No tasks are running which match the specified criteria.'
if re.search(b'No tasks', out, re.IGNORECASE):
return False
else:
return True
else:
raise RuntimeError(f"unsupported system={system}")
It can be easily enhanced in case you need
you can use this command to acheive it:
mongo admin -u <userName> -p <password> --quiet --eval "cursor = rs.status(); printjson(cursor)" > output.json
You can use this library:
https://github.com/kmfish/MultiTypeListViewAdapter (written by me)
Setup adapter:
adapter = new BaseRecyclerAdapter();
adapter.registerDataAndItem(TextModel.class, LineListItem1.class);
adapter.registerDataAndItem(ImageModel.class, LineListItem2.class);
adapter.registerDataAndItem(AbsModel.class, AbsLineItem.class);
For each line item:
public class LineListItem1 extends BaseListItem<TextModel, LineListItem1.OnItem1ClickListener> {
TextView tvName;
TextView tvDesc;
@Override
public int onGetLayoutRes() {
return R.layout.list_item1;
}
@Override
public void bindViews(View convertView) {
Log.d("item1", "bindViews:" + convertView);
tvName = (TextView) convertView.findViewById(R.id.text_name);
tvDesc = (TextView) convertView.findViewById(R.id.text_desc);
tvName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != attachInfo) {
attachInfo.onNameClick(getData());
}
}
});
tvDesc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != attachInfo) {
attachInfo.onDescClick(getData());
}
}
});
}
@Override
public void updateView(TextModel model, int pos) {
if (null != model) {
Log.d("item1", "updateView model:" + model + "pos:" + pos);
tvName.setText(model.getName());
tvDesc.setText(model.getDesc());
}
}
public interface OnItem1ClickListener {
void onNameClick(TextModel model);
void onDescClick(TextModel model);
}
}
Clone is slow. For performance should probably start with blank hash and merge. Doesn't cover case of nested hashes...
require 'benchmark'
def bench Benchmark.bm do |b|
test = {'a' => 1, 'b' => 2, 'c' => 3, 4 => 'd'}
b.report 'clone' do
1_000_000.times do |i|
h = test.clone
h['new'] = 5
end
end
b.report 'merge' do
1_000_000.times do |i|
h = {}
h['new'] = 5
h.merge! test
end
end
b.report 'inject' do
1_000_000.times do |i|
h = test.inject({}) do |n, (k, v)|
n[k] = v;
n
end
h['new'] = 5
end
end
end
end
bench user system total ( real) clone 1.960000 0.080000 2.040000 ( 2.029604) merge 1.690000 0.080000 1.770000 ( 1.767828) inject 3.120000 0.030000 3.150000 ( 3.152627)
1) Html
<input type="text" id="firstDate" name="firstDate"/>
<input type="text" id="secondDate" name="secondDate"/>
2) Jquery
$("#firstDate").datepicker({
});
$("#secondDate").datepicker({
onSelect: function () {
myfunc();
}
});
function myfunc(){
var start= $("#firstDate").datepicker("getDate");
var end= $("#secondDate").datepicker("getDate");
days = (end- start) / (1000 * 60 * 60 * 24);
alert(Math.round(days));
}
Jsfiddle working example here
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
I think, the easiest way is to read readme file inside your Eclipse directory at path eclipse/readme/eclipse_readme
.
At the very top of this file it clearly tells the version number:
For My Eclipse Juno; it says version as Release 4.2.0
There are a few possible ways to do this:
PYTHONPATH
to a colon-separated list of directories to search for imported modules.sys.path.append('/path/to/search')
to add the names of directories you want Python to search for imported modules. sys.path
is just the list of directories Python searches every time it gets asked to import a module, and you can alter it as needed (although I wouldn't recommend removing any of the standard directories!). Any directories you put in the environment variable PYTHONPATH
will be inserted into sys.path
when Python starts up.site.addsitedir
to add a directory to sys.path
. The difference between this and just plain appending is that when you use addsitedir
, it also looks for .pth
files within that directory and uses them to possibly add additional directories to sys.path
based on the contents of the files. See the documentation for more detail.Which one of these you want to use depends on your situation. Remember that when you distribute your project to other users, they typically install it in such a manner that the Python code files will be automatically detected by Python's importer (i.e. packages are usually installed in the site-packages
directory), so if you mess with sys.path
in your code, that may be unnecessary and might even have adverse effects when that code runs on another computer. For development, I would venture a guess that setting PYTHONPATH
is usually the best way to go.
However, when you're using something that just runs on your own computer (or when you have nonstandard setups, e.g. sometimes in web app frameworks), it's not entirely uncommon to do something like
import sys
from os.path import dirname
sys.path.append(dirname(__file__))
In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account. The quick fix:
sudo rm ~/.rnd
For more information, here's the entry from the OpenSSL FAQ:
Sometimes the openssl command line utility does not abort with a "PRNG not seeded" error message, but complains that it is "unable to write 'random state'". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file ".rnd" in the current directory in this case, but this has changed with 0.9.6a.)
So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem.
If everything seems to be in order, you could try running with strace and see what exactly is going on.
Have a look at jsonpath-object-transform
What about naming your column?
INSERT INTO dbo.rLicenses (name) VALUES ('test')
It's been years since I tried updating via a view so YMMV as HLGEM mentioned.
I would consider an "INSTEAD OF" trigger on the view to allow a simple INSERT dbo.Licenses
(ie the table) in the trigger
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
Simple way to solve
var day = document.getElementById("DayTextBox").value;
var regExp = /^([1-9]|[1][012])\/|-([1-9]|[1][0-9]|[2][0-9]|[3][01])\/|-([1][6-9][0-9][0-9]|[2][0][01][0-9])$/;
return regExp.test(day);
Modern processors are too fast to register the running time. Hence it may return zero. In this case, the time you started and ended is too small and therefore both the times are the same after round of.
Make some invisible HTML tags like <label>, <p>, <input>
etc. and name its id, and the class name is a pattern so that you can retrieve it later.
Let you have two lists maintenance_next[] and maintenance_block_time[] of the same length, and you want to pass these two list's data to javascript using the flask. So you take some invisible label tag and set its tag name is a pattern of list's index and set its class name as value at index.
{% for i in range(maintenance_next|length): %}_x000D_
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>_x000D_
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>_x000D_
{% endfor%}
_x000D_
Now you can retrieve the data in javascript using some javascript operation like below -
<script>_x000D_
var total_len = {{ total_len }};_x000D_
_x000D_
for (var i = 0; i < total_len; i++) {_x000D_
var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");_x000D_
var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");_x000D_
_x000D_
//Do what you need to do with tm1 and tm2._x000D_
_x000D_
console.log(tm1);_x000D_
console.log(tm2);_x000D_
}_x000D_
</script>
_x000D_
If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306
- you provided 3360
. The 3306
is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect()
is the port, which is where it should be specified.
You could just remove the port specification altogether, as you're using the default port, making it
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'test_db13';
References
<form id="form1" runat="server">
<input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
required="">
<datalist id="datalist1" runat="server">
</datalist>
</form>
protected void Page_Load(object sender, EventArgs e)
{
autocomplete();
}
protected void autocomplete()
{
Database p = new Database();
DataSet ds = new DataSet();
ds = p.sqlcall("select [name] from [stu_reg]");
int row = ds.Tables[0].Rows.Count;
string abc="";
for (int i = 0; i < row;i++ )
abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
datalist1.InnerHtml = abc;
}
Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.
I had a similar problem just recently. The way it worked for me it was realizing that "setup.py" was wrong
Previously I deleted my previous src
folder, and added a new one with other name, but I didn't change anything on the setup.py
(newbie mistake I guess).
So pointing setup.py
to the right packages folder did the trick for me
from setuptools import find_packages, setup
setup(
name="-> YOUR SERVICE NAME <-",
extras_Require=dict(test=["pytest"]),
packages=find_packages(where="->CORRECT FOLDER<-"),
package_dir={"": "->CORRECT FOLDER<-"},
)
Also, not init.py
in test folder nor in the root one.
Hope it helps someone =)
Best!
I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear:
And trying to move a not-too-long basename to a too-long-pathname is also very clear:
The pathname error is deceptive, though. Quite unhelpful:
This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.
By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.
Try ulimit -c unlimited
before running your program.
Use .closest()
with a selector:
var $div = $('#divid').closest('div[class^="div-a"]');
I do not have factual evidence to prove this but I already ran into this issue. It seems that triggering a click() event on an <a>
tag doesn't seem to behave the same way you would expect with say, a input button.
The workaround I employed was to set the location.href property on the window which causes the browser to load the request resource like so:
$(document).ready(function()
{
var href = $('.cssbuttongo').attr('href');
window.location.href = href; //causes the browser to refresh and load the requested url
});
});
Edit:
I would make a js fiddle but the nature of the question intermixed with how jsfiddle uses an iframe to render code makes that a no go.
Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress)
, which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation
namespace contains a class called PingReply
that has properties designed to translate the ICMP
response and deliver useful information about the pinged server such as:
The following is a simple example using WinForms
to demonstrate how ping works in c#. By providing a valid IP address in textBox1
and clicking button1
, we are creating an instance of the Ping
class, a local variable PingReply
, and a string to store the IP or URL address. We assign PingReply
to the ping Send
method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success
status. Finally, we extract from PingReply
the information we need to display for the user, which is described above.
using System;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace PingTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Ping p = new Ping();
PingReply r;
string s;
s = textBox1.Text;
r = p.Send(s);
if (r.Status == IPStatus.Success)
{
lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
+ " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
}
}
private void textBox1_Validated(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
{
MessageBox.Show("Please use valid IP or web address!!");
}
}
}
}
Based on this SO answer, I just had to change path="*."
to path="*"
for the added ExtensionlessUrlHandler-Integrated-4.0
in configuration>system.WebServer>handlers
in my web.config
Before:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
After:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
SELECT TOP 10 *
FROM Users
Note that if you don't specify an ORDER BY
clause then any 10 rows could be returned, because "first 10 rows" doesn't really mean anything until you tell the database what ordering to use.
If you don't care about row order (which I don't think you do), then you can use a Linux/FreeBSD/Mac OS X/Cygwin box and do:
$ cat yourfile | sort | uniq > yourfile_nodups
Then open the file again in Notepad++.
// in foo.h
class Foo {
static const unsigned char* Msg;
};
// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;
math.log10 is fast but gives problem when your number is greater than 999999999999997. This is because the float have too many .9s, causing the result to round up.
The solution is to use a while counter method for numbers above that threshold.
To make this even faster, create 10^16, 10^17 so on so forth and store as variables in a list. That way, it is like a table lookup.
def getIntegerPlaces(theNumber):
if theNumber <= 999999999999997:
return int(math.log10(theNumber)) + 1
else:
counter = 15
while theNumber >= 10**counter:
counter += 1
return counter
I heard of RTM (The RT FAQ Manager). Never used it, however.
I found this maven
repo where you could download from directly a zip
file containing all the jars you need.
The solution I prefer is using Maven
, it is easy and you don't have to download each jar
alone. You can do it with the following steps:
Create an empty folder anywhere with any name you prefer, for example spring-source
Create a new file named pom.xml
Copy the xml below into this file
Open the spring-source
folder in your console
Run mvn install
After download finished, you'll find spring jars in /spring-source/target/dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-source-download</groupId>
<artifactId>SpringDependencies</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>download-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Also, if you need to download any other spring project, just copy the dependency
configuration from its corresponding web page.
For example, if you want to download Spring Web Flow
jars, go to its web page, and add its dependency
configuration to the pom.xml
dependencies
, then run mvn install
again.
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
If you use the Eclipse "New Android Project" wizard in a recent ADT bundle, you'll automatically get tabs implemented as a Fragments. This makes the conversion of your application to the tablet format much easier in the future.
For simple single screen layouts you may still use Activity
.
Setting the content type and the content disposition as described above produces wildly varying results with different browsers:
IE8: SaveAs dialog as desired, and Excel as the default app. 100% good.
Firefox: SaveAs dialog does show up, but Firefox has no idea it is a spreadsheet. Suggests opening it with Visual Studio! 50% good
Chrome: the hints are fully ignored. The CSV data is shown in the browser. 0% good.
Of course in all of these cases I'm referring to the browsers as they come out of they box, with no customization of the mime/application mappings.
I get into this problem in my Xubuntu desktop. I fixed it by renaming all my files and folders so there is no space in the file path.
This easy method works for me when i want to change the background color of the bootstrap tooltips:
$(function(){
//$('.tooltips.red-tooltip').tooltip().data('bs.tooltip').tip().addClass('red-tooltip');
$('.tooltips.red-tooltip').tooltip().data('tooltip').tip().addClass('red-tooltip');
});
_x000D_
.red-tooltip.tooltip.tooltip.bottom .tooltip-arrow,
.red-tooltip.tooltip.tooltip.bottom-left .tooltip-arrow,
.red-tooltip.tooltip.tooltip.bottom-right .tooltip-arrow{border-bottom-color: red;}
.red-tooltip.tooltip.top .tooltip-arrow {border-top-color: red;}
.red-tooltip.tooltip.left .tooltip-arrow {border-left-color: red;}
.red-tooltip.tooltip.right .tooltip-arrow {border-right-color: red;}
.red-tooltip.tooltip > .tooltip-inner{background-color:red;}
_x000D_
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap-tooltip.js"></script>
<a href="#" data-toggle="tooltip" data-placement="bottom"
title="" data-original-title="Made by @Ram"
class="tooltips red-tooltip">My link with red tooltip</a>
_x000D_
Note A:
If
js
code include.data('tooltip')
not working for you then please comment its line and uncommentjs
code include.data('bs-tooltip')
.Note B:
If your bootstrap tooltip function add a tooltip to the end of body (not right after the element), my solution works well yet but some other answers in this pages did not works like @Praveen Kumar and @technoTarek in this scenario.
Note C:
This codes support
tooltip arrow
color in all placements of the tooltip (top
,bottom
,left
,right
).
This like your css code:
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
For the class below:
public class Page
{
private string data;
public Page()
{
}
public Page(string data)
{
this.Data = data;
}
public string Data
{
get
{
return this.data;
}
set
{
this.data = value;
}
}
}
you can initialize the array of above object as below.
Pages = new Page[] { new Page("a string") };
Hope this helps.
for me the problem was solved by installing another supportive package.
so I installed graphviz package through anaconda then I failed to import it
after that I installed a second package named python-graphviz
also through anaconda
then I succeeded in importing graphviz
module into my code
I hope this will help someone :)
Try to do this way
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
or if you use .net core try it
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Usuario>().ToTable("Usuario");
}
Replace Usuario for your Entity Name, like a DbSet<<EntityName>> Entities without Plural
Really, if you care about Internet Explorer 9+ only, this code would be enough to replace jQuery.ready
:
document.addEventListener("DOMContentLoaded", callback);
If you worry about Internet Explorer 6 and some really strange and rare browsers, this will work:
domReady: function (callback) {
// Mozilla, Opera and WebKit
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", callback, false);
// If Internet Explorer, the event model is used
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete" ) {
callback();
}
});
// A fallback to window.onload, that will always work
} else {
var oldOnload = window.onload;
window.onload = function () {
oldOnload && oldOnload();
callback();
}
}
},
I have to put
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<host>Your proxy host</host>
<port>proxy host ip</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
Before
<proxy>
<id>optional</id>
<active>true</active>
<protocol>https</protocol>
<host>Your proxy host</host>
<port>proxy host ip</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
Weird, but yes!, <protocol>http</protocol>
has to come before <protocol>https</protocol>
.
It solved my problem. Hope it helps someone who faces connections issue even after enabling proxy settings in conf/settings.xml
.
Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.
...assuming that bgbody.png actually exists :)
Is your CSS in a stylesheet file or in a <style>
block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.
Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.
Got the same error when using curl on https site like
curl https://api.dis...
as pointed out by ganesh, it was because my version of curl wasn't ssl enabled. went back and downloaded the version with ssl and it worked fine.
It depends on what you're trying to do.
You currently have it set up as a normalized database, which is fine, and the way you are doing it is appropriate.
However, there are other ways of doing it.
You could have a posts collection that has imbedded comments for each post with references to the users that you can iteratively query to get. You could store the user's name with the comments, you could store them all in one document.
The thing with NoSQL is it's designed for flexible schemas and very fast reading and writing. In a typical Big Data farm the database is the biggest bottleneck, you have fewer database engines than you do application and front end servers...they're more expensive but more powerful, also hard drive space is very cheap comparatively. Normalization comes from the concept of trying to save space, but it comes with a cost at making your databases perform complicated Joins and verifying the integrity of relationships, performing cascading operations. All of which saves the developers some headaches if they designed the database properly.
With NoSQL, if you accept that redundancy and storage space aren't issues because of their cost (both in processor time required to do updates and hard drive costs to store extra data), denormalizing isn't an issue (for embedded arrays that become hundreds of thousands of items it can be a performance issue, but most of the time that's not a problem). Additionally you'll have several application and front end servers for every database cluster. Have them do the heavy lifting of the joins and let the database servers stick to reading and writing.
TL;DR: What you're doing is fine, and there are other ways of doing it. Check out the mongodb documentation's data model patterns for some great examples. http://docs.mongodb.org/manual/data-modeling/
An alternative to the answer by @Marco Ponti, and avoiding the checkout:
git diff --name-only <notMainDev> $(git merge-base <notMainDev> <mainDev>)
If your particular shell doesn't understand the $() construct, use back-ticks instead.
There are no implicit copies made in java via the assignment operator. Variables contain a reference value (pointer) and when you use =
you're only coping that value.
In order to preserve the contents of myTempObject
you would need to make a copy of it.
This can be done by creating a new ArrayList
using the constructor that takes another ArrayList
:
ArrayList<Object> myObject = new ArrayList<Object>(myTempObject);
Edit: As Bohemian points out in the comments below, is this what you're asking? By doing the above, both ArrayList
s (myTempObject
and myObject
) would contain references to the same objects. If you actually want a new list that contains new copies of the objects contained in myTempObject
then you would need to make a copy of each individual object in the original ArrayList
My gremlin for this problem was bad directory permissions:
Good permissions:
drwxr-x--x u0_a20 u0_a20 2013-11-13 20:45 com.google.earth
drwxr-x--x u0_a63 u0_a63 2013-11-13 20:46 com.nuance.xt9.input
drwxr-x--x u0_a53 u0_a53 2013-11-13 20:45 com.tf.thinkdroid.sg
drwxr-x--x u0_a68 u0_a68 2013-12-24 15:03 eu.chainfire.supersu
drwxr-x--x u0_a59 u0_a59 2013-11-13 20:45 jp.co.omronsoft.iwnnime.ml
drwxr-x--x u0_a60 u0_a60 2013-11-13 20:45 jp.co.omronsoft.iwnnime.ml.kbd.white
drwxr-x--x u0_a69 u0_a69 2013-12-24 15:03 org.mozilla.firefox
Bad permissions:
root@grouper:/data/data # ls -lad com.mypackage
drw-rw-r-- u0_a70 u0_a70 2014-01-11 14:18 com.mypackage
How did they get that way? I set them that way, while fiddling around trying to get adb pull
to work. Clearly I did it wrong.
Hey Google, it would be awful nice if a permission error produced a meaningful error message, or failing that if you didnt have to hand tweak permissions to use the tools.
In my case
$psql
postgres=# \g
postgres=# SELECT version();
version
---------------------------------------------------------------------------------------------------------------------
PostgreSQL 8.4.21 on x86_64-pc-linux-gnu, compiled by GCC gcc-4.6.real (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3, 64-bit
(1 row)
Hope it will help someone
I have use this method
function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();
Short version:
$ svn st
! + C foo
> local edit, incoming delete upon update
! + C bar
> local edit, incoming delete upon update
$ touch foo bar
$ svn revert foo bar
$ rm foo bar
If the conflict is about directories instead of files then replace touch
with mkdir
and rm
with rm -r
.
Note: the same procedure also work for the following situation:
$ svn st
! C foo
> local delete, incoming delete upon update
! C bar
> local delete, incoming delete upon update
Long version:
This happens when you edit a file while someone else deleted the file and commited first. As a good svn citizen you do an update before a commit. Now you have a conflict. Realising that deleting the file is the right thing to do you delete the file from your working copy. Instead of being content svn now complains that the local files are missing and that there is a conflicting update which ultimately wants to see the files deleted. Good job svn.
Should svn resolve
not work, for whatever reason, you can do the following:
Initial situation: Local files are missing, update is conflicting.
$ svn st
! + C foo
> local edit, incoming delete upon update
! + C bar
> local edit, incoming delete upon update
Recreate the conflicting files:
$ touch foo bar
If the conflict is about directories then replace touch
with mkdir
.
New situation: Local files to be added to the repository (yeah right, svn, whatever you say), update still conflicting.
$ svn st
A + C foo
> local edit, incoming delete upon update
A + C bar
> local edit, incoming delete upon update
Revert the files to the state svn likes them (that means deleted):
$ svn revert foo bar
New situation: Local files not known to svn, update no longer conflicting.
$ svn st
? foo
? bar
Now we can delete the files:
$ rm foo bar
If the conflict is about directories then replace rm
with rm -r
.
svn no longer complains:
$ svn st
Done.
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.
Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.
add by user root this command : ssh user_to_acces@hostName -X
user_to_acces = user hostName = hostname machine
$('#OvernightOnshore').click(function () {
if ($('#OvernightOnshore').prop("checked") == true) {
if ($('#OvernightOffshore').prop("checked") == true) {
$('#OvernightOffshore').attr('checked', false)
}
}
})
$('#OvernightOffshore').click(function () {
if ($('#OvernightOffshore').prop("checked") == true) {
if ($('#OvernightOnshore').prop("checked") == true) {
$('#OvernightOnshore').attr('checked', false);
}
}
})
This above code snippet will allow you to use checkboxes over radio buttons, but have the same functionality of radio buttons where you can only have one selected.
It depends on what the thing is.
Top-level types (that is, classes, enums, interfaces, and annotation types not declared inside another type) are package-private by default. (JLS §6.6.1)
In classes, all members (that means fields, methods, and nested type declarations) and constructors are package-private by default. (JLS §6.6.1)
In enums, constructors are private by default. Indeed, enum contructors must be private, and it is an error to specify them as public or protected. Enum constants are always public, and do not permit any access specifier. Other members of enums are package-private by default. (JLS §8.9)
In interfaces and annotation types, all members (again, that means fields, methods, and nested type declarations) are public by default. Indeed, members of interfaces and annotation types must be public, and it is an error to specify them as private or protected. (JLS §9.3 to 9.5)
Local classes are named classes declared inside a method, constructor, or initializer block. They are scoped to the {
..}
block in which they are declared and do not permit any access specifier. (JLS §14.3) Using reflection, you can instantiate local classes from elsewhere, and they are package-private, although I'm not sure if that detail is in the JLS.
Anonymous classes are custom classes created with new
which specify a class body directly in the expression. (JLS §15.9.5) Their syntax does not permit any access specifier. Using reflection, you can instantiate anonymous classes from elsewhere, and both they and their generated constructors are are package-private, although I'm not sure if that detail is in the JLS.
Instance and static initializer blocks do not have access specifiers at the language level (JLS §8.6 & 8.7), but static initializer blocks are implemented as a method named <clinit>
(JVMS §2.9), so the method must, internally, have some access specifier. I examined classes compiled by javac and by Eclipse's compiler using a hex editor and found that both generate the method as package-private. However, you can't call <clinit>()
within the language because the <
and >
characters are invalid in a method name, and the reflection methods are hardwired to deny its existence, so effectively its access specifier is no access. The method can only be called by the VM, during class initialization. Instance initializer blocks are not compiled as separate methods; their code is copied into each constructor, so they can't be accessed individually, even by reflection.
I got this solution and it is working for me
if (myNewDT.MyDateTime == null)
{
myNewDT.MyDateTime = DateTime.Now();
}
You should use the Relativelayout instead of Linearlayout as main layout. If you use Relativelayout as main then easily handle the button on right side because relative layout provide us alignParent right, left,top and bottom.
Please make changes as per below to resolve this error.
Install Java SDK version: 14 or above.
JDK Download link: https://www.oracle.com/java/technologies/javase-jdk14-downloads.html
In
gradle-wrapper.properties
please use grade version 6.3 or above.
For e.g:distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip
Get counts of all tables in a schema and order by desc
select 'with tmp(table_name, row_number) as (' from dual
union all
select 'select '''||table_name||''',count(*) from '||table_name||' union ' from USER_TABLES
union all
select 'select '''',0 from dual) select table_name,row_number from tmp order by row_number desc ;' from dual;
Copy the entire result and execute
Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.
For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).
Greets
Changing sender on Gmail / Outlook.com email:
To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.
If you have a limited number of senders you can follow these instructions and then set the From
field to this address: Sending mail from a different address
If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :
msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));
This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.
If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
This DATE
-thing won't work in all Excel-versions.
=CELL_ID/(60 * 60 * 24) + "1/1/1970"
is a save bet instead.
The quotes are necessary to prevent Excel from calculating the term.
Method overloading is a compile time polymorphism, let's take an example to understand the concept.
class Person //person.java file
{
public static void main ( String[] args )
{
Eat e = new Eat();
e.eat(noodle); //line 6
}
void eat (Noodles n) //Noodles is a object line 8
{
}
void eat ( Pizza p) //Pizza is a object
{
}
}
In this example, Person has a eat method which represents that he can either eat Pizza or Noodles. That the method eat is overloaded when we compile this Person.java the compiler resolves the method call " e.eat(noodles) [which is at line 6] with the method definition specified in line 8 that is it method which takes noodles as parameter and the entire process is done by Compiler so it is Compile time Polymorphism. The process of replacement of the method call with method definition is called as binding, in this case, it is done by the compiler so it is called as early binding.
it's straight forward to do in programatic way. just follow these steps
add an observer to content length of textfield
[yourTextViewObject addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
implement observer
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
//Center vertical alignment
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
mTextViewHeightConstraint.constant = tv.contentSize.height;
[UIView animateWithDuration:0.2 animations:^{
[self.view layoutIfNeeded];
}];
}
if you want to stop textviewHeight to increase after some time during typing then implement this and set textview delegate to self.
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if(range.length + range.location > textView.text.length)
{
return NO;
}
NSUInteger newLength = [textView.text length] + [text length] - range.length;
return (newLength > 100) ? NO : YES;
}
You can also do this with ant contrib's if task.
<if>
<equals arg1="${condition}" arg2="true"/>
<then>
<copy file="${some.dir}/file" todir="${another.dir}"/>
</then>
<elseif>
<equals arg1="${condition}" arg2="false"/>
<then>
<copy file="${some.dir}/differentFile" todir="${another.dir}"/>
</then>
</elseif>
<else>
<echo message="Condition was neither true nor false"/>
</else>
</if>
Very good exaple. npt tipical with MAth in wwww....
https://www.java2novice.com/java-fundamentals/static-import/
public class MyStaticMembClass {
public static final int INCREMENT = 2;
public static int incrementNumber(int number){
return number+INCREMENT;
}
}
in onother file inlude
import static com.java2novice.stat.imp.pac1.MyStaticMembClass.*;
If the keys have any pattern to them then you can split the map into smaller maps and have a index map.
Example: Keys: 1,2,3,.... n 28 maps of 1 million each. Index map: 1-1,000,000 -> Map1 1,000,000-2,000,000 -> Map2
So you'll be doing two lookups but the key set would be 1,000,000 vs 28,000,000. You can easily do this with sting patterns also.
If the keys are completely random then this will not work
You could convert your wildcard string to a regular expression and use that with String's matches
method. Following your example:
String original = "../Test?/sample*.txt";
String regex = original.replace("?", ".?").replace("*", ".*?");
This works for your examples:
Assert.assertTrue("../Test1/sample22b.txt".matches(regex));
Assert.assertTrue("../Test4/sample-spiffy.txt".matches(regex));
And counter-examples:
Assert.assertTrue(!"../Test3/sample2.blah".matches(regex));
Assert.assertTrue(!"../Test44/sample2.txt".matches(regex));
I keep this handy utility nearby:
import inspect
myself = lambda: inspect.stack()[1][3]
Usage:
myself()