If you have some tiles that exceed the bounds of your diamond, I recommend drawing in depth order:
...1...
..234..
.56789.
..abc..
...d...
Depending on why you are doing this, using a std::set might be a better idea than std::vector.
It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.
This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.
In my case the problem was introduced when I fixed a static analysis error that the return value of a method was not used.
Old working code in my Application.java was:
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
New code that introduced the problem was:
public static void main(String[] args) {
try (ConfigurableApplicationContext context =
SpringApplication.run(Application.class, args)) {
LOG.trace("context: " + context);
}
}
Obviously, the try with resource block will close the context after starting the application which will result in the application exiting with status 0. This was a case where the resource leak error reported by snarqube static analysis should be ignored.
The difference between 'exec' and 'system' is that exec replaces your current program with 'command' and NEVER returns to your program. system, on the other hand, forks and runs 'command' and returns you the exit status of 'command' when it is done running. The back tick runs 'command' and then returns a string representing its standard out (whatever it would have printed to the screen)
You can also use popen to run shell commands and I think that there is a shell module - 'use shell' that gives you transparent access to typical shell commands.
Hope that clarifies it for you.
on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve
ImportError: No module named six
when launching Wammu
If it's occurred for python3 program, six come with
pip3 install six
and if you don't have pip3:
apt install python3-pip
with sudo under Ubuntu!
Not something I would teach (or ever use in my code), but here's a codegolf-worthy solution without mutating a variable, no need for ES6:
Array.apply(null, {length: 10}).forEach(function(_, i){
doStuff(i);
})
More of an interesting proof-of-concept thing than a useful answer, really.
https://www.npmjs.com/package/typeof
Returns a string-representation of instanceof
(the constructors name)
function instanceOf(object) {
var type = typeof object
if (type === 'undefined') {
return 'undefined'
}
if (object) {
type = object.constructor.name
} else if (type === 'object') {
type = Object.prototype.toString.call(object).slice(8, -1)
}
return type.toLowerCase()
}
instanceOf(false) // "boolean"
instanceOf(new Promise(() => {})) // "promise"
instanceOf(null) // "null"
instanceOf(undefined) // "undefined"
instanceOf(1) // "number"
instanceOf(() => {}) // "function"
instanceOf([]) // "array"
How about s.copy().pop()
? I haven't timed it, but it should work and it's simple. It works best for small sets however, as it copies the whole set.
Nouns.h
doesn't include <string>
, but it needs to. You need to add
#include <string>
at the top of that file, otherwise the compiler doesn't know what std::string
is when it is encountered for the first time.
Using pathlib
I came up this one-liner to get the size of a folder:
sum(file.stat().st_size for file in Path(folder).rglob('*'))
And this is what I came up with for a nicely formatted output:
from pathlib import Path
def get_folder_size(folder):
return ByteSize(sum(file.stat().st_size for file in Path(folder).rglob('*')))
class ByteSize(int):
_kB = 1024
_suffixes = 'B', 'kB', 'MB', 'GB', 'PB'
def __new__(cls, *args, **kwargs):
return super().__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
self.bytes = self.B = int(self)
self.kilobytes = self.kB = self / self._kB**1
self.megabytes = self.MB = self / self._kB**2
self.gigabytes = self.GB = self / self._kB**3
self.petabytes = self.PB = self / self._kB**4
*suffixes, last = self._suffixes
suffix = next((
suffix
for suffix in suffixes
if 1 < getattr(self, suffix) < self._kB
), last)
self.readable = suffix, getattr(self, suffix)
super().__init__()
def __str__(self):
return self.__format__('.2f')
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, super().__repr__())
def __format__(self, format_spec):
suffix, val = self.readable
return '{val:{fmt}} {suf}'.format(val=val, fmt=format_spec, suf=suffix)
def __sub__(self, other):
return self.__class__(super().__sub__(other))
def __add__(self, other):
return self.__class__(super().__add__(other))
def __mul__(self, other):
return self.__class__(super().__mul__(other))
def __rsub__(self, other):
return self.__class__(super().__sub__(other))
def __radd__(self, other):
return self.__class__(super().__add__(other))
def __rmul__(self, other):
return self.__class__(super().__rmul__(other))
Usage:
>>> size = get_folder_size("c:/users/tdavis/downloads")
>>> print(size)
5.81 GB
>>> size.GB
5.810891855508089
>>> size.gigabytes
5.810891855508089
>>> size.PB
0.005674699077644618
>>> size.MB
5950.353260040283
>>> size
ByteSize(6239397620)
I also came across this question, which has some more compact and probably more performant strategies for printing file sizes.
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
params
also allows you to call the method with a single argument.
private static int Foo(params int[] args) {
int retVal = 0;
Array.ForEach(args, (i) => retVal += i);
return retVal;
}
i.e. Foo(1);
instead of Foo(new int[] { 1 });
. Can be useful for shorthand in scenarios where you might need to pass in a single value rather than an entire array. It still is handled the same way in the method, but gives some candy for calling this way.
Try ALT+SHIFT+UP/DOWN
It worked for me!
Suppose you want to copy the contents from a folder where you have docker file into your container. Use ADD:
RUN mkdir /temp
ADD folder /temp/Newfolder
it will add to your container with temp/newfolder
folder is the folder/directory where you have the dockerfile, more concretely, where you put your content and want to copy that.
Now can you check your copied/added folder by runining container and see the content using ls
if vs2010 installed correctly
check file type (.cpp)
just build it again It will automatically fix,, ( if you are using VS 2010 )
Simple & Best way:
onclick="parentNode.remove()"
Deletes the complete parent from html
For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.
Try something like
convert -density 300 image.eps -resize 1024x1024 image.jpg
Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.
The order of the arguments matters! The -density X
argument needs to go before image.eps
because you want to affect the resolution that the input file is rendered at.
This is not super obvious in the manpage for convert
, but is hinted at:
SYNOPSIS
convert [input-option] input-file [output-option] output-file
The microsoft telnet.exe
is not scriptable without using another script (which needs keyboard focus), as shown in another answer to this question, but there is a free
Telnet Scripting Tool v.1.0 by Albert Yale
that you can google for and which is both scriptable and loggable and can be launched from a batch file without needing keyboard focus.
The problem with telnet.exe and a second script when keyboard focus is being used is that if someone is using the computer at the time the script runs, then it is highly likely that the script will fail due to mouse clicks and keyboard use at that moment in time.
For Intellij IDEA version 11.0.2
File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Next goto Build | Build artifacts --> choose your artifact.
source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/
I don't recommend storing passwords in a script, but this is a way to what you indicate:
use 5.010;
my %user_table = ( tom => '123!', frank => '321!' );
say ( $user_table{ $name } eq $password ? 'You have gained access.'
: 'Access denied!'
);
Any time you want to enforce an association like this, it's a good idea to think of a table, and the most common form of table in Perl is the hash.
another solution will be to grab the text inside the title
tag & then use .html()
method of jQuery to construct the content of the tooltip.
$(function() {
$(document).tooltip({
position: {
using: function(position, feedback) {
$(this).css(position);
var txt = $(this).text();
$(this).html(txt);
$("<div>")
.addClass("arrow")
.addClass(feedback.vertical)
.addClass(feedback.horizontal)
.appendTo(this);
}
}
});
});
If you use several projects on a solution, and call method in one project to another project, make sure that all projects (called project and caller project) use the unique 'System.Net.Http'
version.
seems when the elements of the table is added by insert method, getn will return correctly. Otherwise, we have to count all elements
mytable = {}
element1 = {version = 1.1}
element2 = {version = 1.2}
table.insert(mytable, element1)
table.insert(mytable, element2)
print(table.getn(mytable))
It will print 2 correctly
Unset($array[0]);
Sort($array);
I don't know why this is being downvoted, but if anyone has bothered to try it, you will notice that it works.
Using sort on an array reassigns the keys of the the array. The only drawback is it sorts the values.
Since the keys will obviously be reassigned, even with array_values
, it does not matter is the values are being sorted or not.
SQL Server requires a transaction log in order to function.
That said there are two modes of operation for the transaction log:
In Full mode the transaction log keeps growing until you back up the database. In Simple mode: space in the transaction log is 'recycled' every Checkpoint.
Very few people have a need to run their databases in the Full recovery model. The only point in using the Full model is if you want to backup the database multiple times per day, and backing up the whole database takes too long - so you just backup the transaction log.
The transaction log keeps growing all day, and you keep backing just it up. That night you do your full backup, and SQL Server then truncates the transaction log, begins to reuse the space allocated in the transaction log file.
If you only ever do full database backups, you don't want the Full recovery mode.
Thanks @Laura Slocum for your answer
I messed things up while rebasing and got a detached HEAD with an
error: could not read orig-head
that prevented me from finishing the rebasing.
The detached HEAD seem to contain precisely my correct rebase desired state, so I ran
rebase --quit
and after that I checked out a new temp branch to bind it to the detached head.
By comparing it with the branch I wanted to rebase, I can see the new temp branch is exactly in the state I wanted to reach. Thanks
You can use Keras, one-line answer will be to use eval
method like so:
import keras.backend as K
print(K.eval(your_tensor))
If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:
npm install iconv
npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.
fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.
Below steps are worked for me, Hope this will work for you as well,
then write below code in a java file and run
System.setProperty("webdriver.ie.driver","path of your IE driver exe\IEDriverServer.exe");
InternetExplorerDriver driver=new InternetExplorerDriver();
driver.manage().window().maximize();
Thread.Sleep(10100);
driver.get("http://www.Google.com");
Thread.Sleep(10000);
The latest JDBC MSSQL connectivity driver can be found on JDBC 4.0
The class file should be in the classpath. If you are using eclipse you can easily do the same by doing the following -->
Right Click Project Name --> Properties --> Java Build Path --> Libraries --> Add External Jars
Also as already been pointed out by @Cheeso the correct way to access is jdbc:sqlserver://server:port;DatabaseName=dbname
Meanwhile please find a sample class for accessing MSSQL DB (2008 in my case).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from SampleTable";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://xx.xx.xx.xxxx:1433;databaseName=MyDBName", "DB_USER","DB_PASSWORD");
}
}
Hope this helps.
In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO TableName ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
Another way
INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
I had the same issue with Angular 2.0.1 because I was importing Observable from
import { Observable } from 'rxjs/Observable';
I resolve my problem on importing Observable from this path instead
import { Observable } from 'rxjs';
A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)
<p> represents a paragraph and <div> represents a 'division', I suppose the main difference is that divs are semantically 'meaningless', where as a <p> is supposed to represent something relating to the text itself.
You wouldn't want to have nested <p>s for example, since that wouldn't make much semantic sense (except in the sense of quotations) Whereas people use nested <div>s for page layout.
According to Wikipedia
In HTML, the span and div elements are used where parts of a document cannot be semantically described by other HTML elements.
Use this lightweight npm
package: system-commands
Look at it here.
Import it like this:
const system = require('system-commands')
Run commands like this:
system('ls').then(output => {
console.log(output)
}).catch(error => {
console.error(error)
})
One way to center any element of unknown height and width both horizontally and vertically:
table {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Alternatively, use a flex container:
.parent-element {
display: flex;
justify-content: center;
align-items: center;
}
You could try something like XLLoop. This lets you implement excel functions (UDFs) on an external server (server implementations in many different languages are provided).
For example you could use a MySQL database and Apache web server and then write the functions in PHP to serve up the data to your users.
BTW, I work on the project so let me know if you have any questions.
Quoting directly from the help page for factor
:
To transform a factor f to its original numeric values, as.numeric(levels(f))[f]
is recommended and slightly more efficient than as.numeric(as.character(f))
.
Another simple solution:
class Color(const):
BLUE = 0
RED = 1
GREEN = 2
@classmethod
def get_all(cls):
return [cls.BLUE, cls.RED, cls.GREEN]
Usage: Color.get_all()
For Sybase aka SQL Anywhere the following command outputs the structure of a table:
DESCRIBE 'TABLE_NAME';
As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try
block. Try changing your code to:
try{
Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
throw new MojException("Bledne dane");
}
Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.
You can also use the Apache Commons IO library and the FileUtils class. In case you are using maven you can load it using the above dependency.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
The source for the MultipartFile save to disk.
File file = new File(directory, filename);
// Create the file using the touch method of the FileUtils class.
// FileUtils.touch(file);
// Write bytes from the multipart file to disk.
FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
If you are in an environment where you are not an administrator, you can set the Execution Policy just for you, and it will not require administrator.
Set-ExecutionPolicy -Scope "CurrentUser" -ExecutionPolicy "RemoteSigned"
or
Set-ExecutionPolicy -Scope "CurrentUser" -ExecutionPolicy "Unrestricted"
You can read all about it in the help entry.
Help Get-ExecutionPolicy -Full
Help Set-ExecutionPolicy -Full
I believe it was already mentioned in other threads:
calc(){ awk "BEGIN { print "$*" }"; }
then you can simply type :
calc 7.5/3.2
2.34375
In your case it will be:
x=20; y=3;
calc $x/$y
or if you prefer, add this as a separate script and make it available in $PATH so you will always have it in your local shell:
#!/bin/bash
calc(){ awk "BEGIN { print $* }"; }
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded
event or functions like $.ready
in jQuery.
I had the same problem, Android Studio just could not identify the android-sdk folder. All I did was to uninstall and reinstall android studio, and this time it actually identified the folder. Hope it also works out for you.
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
You should absolutely not do this
By disallowing and interfering with password completion you are making your users less safe. The correct coding for a password field should include:
autocomplete="current-password"
Making a user type a password means that that they have to use a weak password that they can accurately type, not use a password manager and a complex, unique, and long password. For a detailed discussion on this see: https://www.ncsc.gov.uk/blog-post/let-them-paste-passwords
You can do this using a group by:
select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)
Another way of writing this may seem clearer, but does not perform as well:
select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1
you can try this one also,
df= df.applymap(lambda s:s.lower() if type(s) == str else s)
I know that OP asked for Angular 5 solution, but yet for all of you who stumbles upon this question for newer (6+) Angular versions. Citing the Docs, regarding ActivatedRoute.queryParams (which most of other answers are based on):
Two older properties are still available. They are less capable than their replacements, discouraged, and may be deprecated in a future Angular version.
params — An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.
queryParams — An Observable that contains the query parameters available to all routes. Use queryParamMap instead.
According to the Docs, the simple way to get the query params would look like this:
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.param1 = this.route.snapshot.paramMap.get('param1');
this.param2 = this.route.snapshot.paramMap.get('param2');
}
For more advanced ways (e.g. advanced component re-usage) see this Docs chapter.
EDIT:
As it correctly stated in comments below, this answer is wrong - at least for the case specified by OP.
OP asks to get global query parameters (/app?param1=hallo¶m2=123); in this case you should use queryParamMap (just like in @dapperdan1985 answer).
paramMap, on the other hand, is used on parameters specific to the route (e.g. /app/:param1/:param2, resulting in /app/hallo/123).
Thanks to @JasonRoyle and @daka for pointing it out.
Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.
But more importantly why do you want to read an HTTPOnly
cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly
flag and "secure flag" (which forces the cookie to be sent over https) should always be set.
If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly
flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.
People have too much faith in the HTTPOnly
flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
Why can't you do it? Because the language doesn't allow you to initializa a base class' members in the derived class' initializer list.
How can you get this done? Like this:
class A
{
public:
A(int a, int b) : a_(a), b_(b) {};
int a_, b_;
};
class B : public A
{
public:
B() : A(0,0)
{
}
};
try running SHOW CREATE VIEW my_view_name
in the sql portion of phpmyadmin and you will have a better idea of what is inside the view
To modify the float output do this:
df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df
Out[33]:
a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000
pd.options.display.float_format = '{:,.0f}'.format
df
Out[35]:
a
0 0
1 1
2 2
3 3
4 4
Unix will only run commands if they are available on the system path, as you can view by the $PATH variable
echo $PATH
Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such
./my-exec
Where my-exec
is the name of your program.
C++ version of the same algorithm
#include <iostream>
#include <list>
void subset_sum_recursive(std::list<int> numbers, int target, std::list<int> partial)
{
int s = 0;
for (std::list<int>::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
{
s += *cit;
}
if(s == target)
{
std::cout << "sum([";
for (std::list<int>::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
{
std::cout << *cit << ",";
}
std::cout << "])=" << target << std::endl;
}
if(s >= target)
return;
int n;
for (std::list<int>::const_iterator ai = numbers.begin(); ai != numbers.end(); ai++)
{
n = *ai;
std::list<int> remaining;
for(std::list<int>::const_iterator aj = ai; aj != numbers.end(); aj++)
{
if(aj == ai)continue;
remaining.push_back(*aj);
}
std::list<int> partial_rec=partial;
partial_rec.push_back(n);
subset_sum_recursive(remaining,target,partial_rec);
}
}
void subset_sum(std::list<int> numbers,int target)
{
subset_sum_recursive(numbers,target,std::list<int>());
}
int main()
{
std::list<int> a;
a.push_back (3); a.push_back (9); a.push_back (8);
a.push_back (4);
a.push_back (5);
a.push_back (7);
a.push_back (10);
int n = 15;
//std::cin >> n;
subset_sum(a, n);
return 0;
}
In my case I had to install the extension:
yum install php php-mysql httpd
and then restart apache:
service httpd restart
That solved the problem.
GUIDs are 128bits, or
0 through ffffffffffffffffffffffffffffffff (hex) or
0 through 340282366920938463463374607431768211455 (decimal) or
0 through 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 (binary, base 2) or
0 through 91"<b.PX48m!wVmVA?1y (base 95)
So yes, min 20 characters long, which is actually wasting more than 4.25 bits, so you can be just as efficient using smaller bases than 95 as well; base 85 being the smallest possible one that still fits into 20 chars:
0 through -r54lj%NUUO[Hi$c2ym0 (base 85, using 0-9A-Za-z!"#$%&'()*+,- chars)
:-)
From Official documents about Re-using Layouts
Although Android offers a variety of widgets to provide small and re-usable interactive elements, you might also need to re-use larger components that require a special layout. To efficiently re-use complete layouts, you can use the tag to embed another layout inside the current layout.
Here is my header.xml file which i can reuse using include tag
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="@string/app_name"
android:textColor="#000000" />
</RelativeLayout>
No I use the tag in XML to add another layout from another XML file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f0f0f0" >
<include
android:id="@+id/header_VIEW"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="@layout/header" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#ffffff"
android:orientation="vertical"
android:padding="5dp" >
</LinearLayout>
Here is the correct command: set path=%path%;C:\Python34 [Replace with the correct path of your python installation]
I had the same problem and I just solved this like that.
As some other people pointed out, this is volatile configuration, it only works for the current cmd session, and (obviously) you have to set your path before you run npm install.
I hope this helps.
This will done by using jquery. Here is the code
<select class="chosen" style="width:500px;">
<option>Html</option>
<option>Css</option>
<option>Css3</option>
<option>Php</option>
<option>MySql</option>
<option>Javascript</option>
<option>Jquery</option>
<option>Html5</option>
<option>Wordpress</option>
<option>Joomla</option>
<option>Druple</option>
<option>Json</option>
<option>Angular Js</option>
</select>
</div>
<script type="text/javascript">
$(".chosen").chosen();
</script>
I've managed to successfully install wkhtmltopdf-amd64 on my shared hosting account without root access.
Here's what i did:
Downloaded the relevant static binary v0.10.0 from here: http://code.google.com/p/wkhtmltopdf/downloads/list
EDIT: The above has moved to here
via ssh on my shared host typed the following:
$ wget {relavant url to binary from link above}
$ tar -xvf {filename of above wget'd file}
you'll then have the binary on your host and will be able to run it regardless of if its in the /usr/bin/ folder or not. (or at least i was able to)
To test:
$ ./wkhtmltopdf-amd64 http://www.example.com example.pdf
./
just to be sure.Worked for me anyway
Use it as a top level function in some common class of your project such as Utils.kt
// Vibrates the device for 100 milliseconds.
fun vibrateDevice(context: Context) {
val vibrator = getSystemService(context, Vibrator::class.java)
vibrator?.let {
if (Build.VERSION.SDK_INT >= 26) {
it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
@Suppress("DEPRECATION")
it.vibrate(100)
}
}
}
And then call it anywhere in your code as following:
vibrateDevice(requireContext())
Using Vibrator::class.java
is more type safe than using String
constants.
We check the vibrator
for nullability using let { }
, because if the vibration is not available for the device, the vibrator
will be null
.
It's ok to supress deprecation in else
clause, because the warning is from newer SDK.
We don't need to ask for permission at runtime for using vibration. But we need to declare it in AndroidManifest.xml
as following:
<uses-permission android:name="android.permission.VIBRATE"/>
(1:nrow(mydata_2))[mydata_2[,4] == 1578]
Of course there may be more than one row with a value of 1578.
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job. Possibly, LTRIM uses Convert or STR under the hood.
LTRIM also removes need for providing length and usually default 10 is good enough for integer to string conversion.
SELECT LTRIM(ColumnName) FROM TableName
Like ctrlplusb said, I recommend you to use the package dotenv
, but another way to do this is creating a js file and requiring it on the first line of your app server.
env.js:
process.env.VAR1="Some value"
process.env.VAR2="Another Value"
app.js:
require('env')
console.log(process.env.VAR1) // Some value
I had to disable the File Publish Option "Precompile during publishing."
This is a C# version of the answer from dhanushka using OpenCVSharp
Mat large = new Mat(INPUT_FILE);
Mat rgb = new Mat(), small = new Mat(), grad = new Mat(), bw = new Mat(), connected = new Mat();
// downsample and use it for processing
Cv2.PyrDown(large, rgb);
Cv2.CvtColor(rgb, small, ColorConversionCodes.BGR2GRAY);
// morphological gradient
var morphKernel = Cv2.GetStructuringElement(MorphShapes.Ellipse, new OpenCvSharp.Size(3, 3));
Cv2.MorphologyEx(small, grad, MorphTypes.Gradient, morphKernel);
// binarize
Cv2.Threshold(grad, bw, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
// connect horizontally oriented regions
morphKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(9, 1));
Cv2.MorphologyEx(bw, connected, MorphTypes.Close, morphKernel);
// find contours
var mask = new Mat(Mat.Zeros(bw.Size(), MatType.CV_8UC1), Range.All);
Cv2.FindContours(connected, out OpenCvSharp.Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point(0, 0));
// filter contours
var idx = 0;
foreach (var hierarchyItem in hierarchy)
{
idx = hierarchyItem.Next;
if (idx < 0)
break;
OpenCvSharp.Rect rect = Cv2.BoundingRect(contours[idx]);
var maskROI = new Mat(mask, rect);
maskROI.SetTo(new Scalar(0, 0, 0));
// fill the contour
Cv2.DrawContours(mask, contours, idx, Scalar.White, -1);
// ratio of non-zero pixels in the filled region
double r = (double)Cv2.CountNonZero(maskROI) / (rect.Width * rect.Height);
if (r > .45 /* assume at least 45% of the area is filled if it contains text */
&&
(rect.Height > 8 && rect.Width > 8) /* constraints on region size */
/* these two conditions alone are not very robust. better to use something
like the number of significant peaks in a horizontal projection as a third condition */
)
{
Cv2.Rectangle(rgb, rect, new Scalar(0, 255, 0), 2);
}
}
rgb.SaveImage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "rgb.jpg"));
You can do this:
if(in_array($value, range(1, 10)) || in_array($value, range(20, 40))) {
# enter code here
}
Pass Today as value as mentioned below in $viewQuery property :
$web = Get-SPWeb "http://sitename"
$list = $web.Lists.TryGetList($listtitle)
write-host "Exporting '$($list.Title)' data from '$($web.Title)' site.."
$viewTitle = "Program Events" #Title property
#Add the column names from the ViewField property to a string collection
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("Event Date") > $null
$viewFields.Add("Title") > $null
#Query property
$viewQuery = "<Where><Geq><FieldRef Name='EventDate' /><Value IncludeTimeValue='TRUE' Type='DateTime'><Today/></Value></Geq></Where><OrderBy><FieldRef Name='EventDate' Ascending='True' /></OrderBy>"
#RowLimit property
$viewRowLimit = 30
#Paged property
$viewPaged = $true
#DefaultView property
$viewDefaultView = $false
#Create the view in the destination list
$newview = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
Write-Host ("View '" + $newview.Title + "' created in list '" + $list.Title + "' on site " + $web.Url)
$web.Dispose()
Well try my code, atleast it gives you a string as overlay, you can very well replace it with a button or an image. You wont believe this is my first ever android app LOL. Anyways if you are more experienced with android apps than me, please try
Here you can find info on how to upgrade to v3: http://tosbourn.com/2013/08/javascript/upgrading-from-bootstraps-typeahead-to-typeahead-js/
Here are some examples too: http://twitter.github.io/typeahead.js/examples/
I have created a new library to implement swippable buttons which supports a variety of transitions and expandable buttons like iOS 8 mail app.
https://github.com/MortimerGoro/MGSwipeTableCell
This library is compatible with all the different ways to create a UITableViewCell and its tested on iOS 5, iOS 6, iOS 7 and iOS 8.
Here a sample of some transitions:
Border transition:
Clip transition
3D Transition:
The Python itertools
page has exactly a powerset
recipe for this:
from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Output:
>>> list(powerset("abcd"))
[(), ('a',), ('b',), ('c',), ('d',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd'), ('a', 'b', 'c', 'd')]
If you don't like that empty tuple at the beginning, you can just change the range
statement to range(1, len(s)+1)
to avoid a 0-length combination.
Mongoose 5.4 supports this
Project.find(query)
.populate({
path: 'pages.page.components',
model: 'Component'
})
You can call bash
directly, use the -c
flag:
bash -c "diff <(sort file1) <(sort file2) > $@"
Of course, you may not be able to redirect to the variable $@, but when I tried to do this, I got -bash: $@: ambiguous redirect
as an error message, so you may want to look into that before you get too into this (though I'm using bash 3.2.something, so maybe yours works differently).
I have faced the same problem once:
Pattern ptr = Pattern.compile("^[a-zA-Z][\\']?[a-zA-Z\\s]+$");
The above failed!
Pattern ptr = Pattern.compile("(^[a-zA-Z][\\']?[a-zA-Z\\s]+$)");
The above worked with pattern within (
and )
.
You can convert BigDecimal
to double
using .doubleValue()
. But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal
objects directly. Precision loss in these calculations are big time problems in currency related calculations.
You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:
public class ProgramViwer : Form{
public ProgramViwer()
{
InitializeComponent();
Load += new EventHandler(ProgramViwer_Load);
}
private void ProgramViwer_Load(object sender, System.EventArgs e)
{
formPanel.Controls.Clear();
formPanel.Controls.Add(wel);
}
}
window.scrollTo()
doesn't work for me in Angular 5, so I have used document.body.scrollTop
like,
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
document.body.scrollTop = 0;
}
});
ifstream inFile;
string name, temp;
int age;
inFile.open("file.txt");
getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
You can open a command prompt and do a
route print
and see your current routing table.
You can modify it by
route add d.d.d.d mask m.m.m.m g.g.g.g
route delete d.d.d.d mask m.m.m.m g.g.g.g
route change d.d.d.d mask m.m.m.m g.g.g.g
these seem to work
I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)
no, CURL does not have anything with parsing XML, it does not know anything about the content returned. it serves as a proxy to get content. it's up to you what to do with it.
use JSON if possible (and json_decode) - it's easier to work with, if not possible, use any XML library for parsin such as DOMXML: http://php.net/domxml
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
Exemple :
$string = file_get_contents(".../File.txt");
$string = mb_convert_encoding($string, 'UTF-8', "ISO-8859-1");
echo $string;
Since I haven't seen it in the answers above, I thought I would add my simple workaround, which is just to add a global_dict
argument to the function requiring the calling module's globals, and then pass the dict into the function when calling; e.g:
# external_module
def imported_function(global_dict=None):
print(global_dict["a"])
# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())
>>> 12
Input Dimension Clarified:
Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:
It (the word dimension alone) can refer to:
a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"
b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or
"Input Layer / Input Feature Dimension"
c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.
"N Dimensionality of Input"
d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:
Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature
model = Sequential()
model.add(Dense(32, input_dim=784)) #or 3 in the current posted example above
model.add(Activation('relu'))
In Keras LSTM, it refers to the total Time Steps
The term has been very confusing, is correct and we live in a very confusing world!!
I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.
If you have to log all args or your method have one argument, you can simply use getArgs like described in previous answers.
If you have to log a specific arg, you can annoted it and then recover its value like this :
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Data {
String methodName() default "";
}
@Aspect
public class YourAspect {
@Around("...")
public Object around(ProceedingJoinPoint point) throws Throwable {
Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
Object[] args = point.getArgs();
StringBuilder data = new StringBuilder();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int argIndex = 0; argIndex < args.length; argIndex++) {
for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
if (!(paramAnnotation instanceof Data)) {
continue;
}
Data dataAnnotation = (Data) paramAnnotation;
if (dataAnnotation.methodName().length() > 0) {
Object obj = args[argIndex];
Method dataMethod = obj.getClass().getMethod(dataAnnotation.methodName());
data.append(dataMethod.invoke(obj));
continue;
}
data.append(args[argIndex]);
}
}
}
}
Examples of use :
public void doSomething(String someValue, @Data String someData, String otherValue) {
// Apsect will log value of someData param
}
public void doSomething(String someValue, @Data(methodName = "id") SomeObject someData, String otherValue) {
// Apsect will log returned value of someData.id() method
}
For 500 records efficiency is probably not an issue, but if you have millions of records then it can be advantageous to use a WHERE clause to select the next page:
SELECT *
FROM yourtable
WHERE id > 234374
ORDER BY id
LIMIT 20
The "234374" here is the id of the last record from the prevous page you viewed.
This will enable an index on id to be used to find the first record. If you use LIMIT offset, 20
you could find that it gets slower and slower as you page towards the end. As I said, it probably won't matter if you have only 200 records, but it can make a difference with larger result sets.
Another advantage of this approach is that if the data changes between the calls you won't miss records or get a repeated record. This is because adding or removing a row means that the offset of all the rows after it changes. In your case it's probably not important - I guess your pool of adverts doesn't change too often and anyway no-one would notice if they get the same ad twice in a row - but if you're looking for the "best way" then this is another thing to keep in mind when choosing which approach to use.
If you do wish to use LIMIT with an offset (and this is necessary if a user navigates directly to page 10000 instead of paging through pages one by one) then you could read this article about late row lookups to improve performance of LIMIT with a large offset.
i had a same issue because of my Nvidea Graphics card Driver Problem.
If your System has Dedicated Graphics card then Check for the latest Driver and Install it.
Other wise simply Choose Emulated Performance as Software in Emulator Configurations
After Updating the driver the issue is resolved :)
var obj = {_x000D_
no: ["no", 32],_x000D_
nt: ["no", 32],_x000D_
nf: ["no", 32, 90]_x000D_
};_x000D_
_x000D_
count = -1; // which must be static value_x000D_
for (i in obj) {_x000D_
count++;_x000D_
if (obj.hasOwnProperty(i)) {_x000D_
console.log(obj[i][count])_x000D_
};_x000D_
};
_x000D_
in this code i used brackets method for call values in array because it contained array , however briefly the idea which a variable i has a key of property and with a loop called both values of associate array
perfect Method , if you interested, press like
Start cmd.exe and run ipconfig /all
. You should see lines:
Ethernet adapter VirtualBox Host-Only Network:
...
IPv4 Address. . . . . . . . . . . : 192.168.59.1
Second adapter in guest should also be in 192.168.59.*.
Start VM.
ifconfig -a
. You should see e1000g0 and e1000g1. We are interested in e1000g1.ifconfig e1000g down
ifconfig e1000g 192.168.56.10 netmask 255.255.255.0 up
ping 192.168.56.10
# vi /etc/hostname.e1000g1
192.168.56.10 netmask 255.255.255.0
# reboot
Check if ssh is enabled
# svcs -a | grep ssh
online 15:29:57 svc:/network/ssh:default
Modify /etc/ssh/sshd_config so there is
PermitRootLogin yes
Restart ssh service
svcadm restart ssh
From host check it
ssh [email protected]
List interfaces:
ip addr
You should see three interfaces like lo, enp0s3, enp0s8. We will use the third.
Edit /etc/network/interfaces
auto enp0s8
iface enp0s8 inet static
address 192.168.56.10
netmask 255.255.255.0
Then sudo ifup enp0s8
. Check if enp0s8 got correct address. You should see your ip:
$ ip addr show enp0s8
...
inet 192.168.56.10/24 brd 192.168.56.255 scope global secondary enp0s8
If not, you may run sudo ifdown enp0s8 && sudo ifup enp0s8
https://superuser.com/questions/424083/virtualbox-host-ssh-to-guest/424115#424115
This should work
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)
I forgot to mention. This should also accept whitespace.
You could use:
/^[-@.\/#&+\w\s]*$/
Note how this makes use of the character classes \w
and \s
.
EDIT:- Added \ to escape /
you can use css property to hide style="display:none;"
<div style="display:none;">CREDITS_HERE</div>
Solution without using loops and recursion.
Use the required pattern in compile method and enter the desired occurrence in variable 'n' and the last statement will print the starting index of the nth occurrence of the pattern in the given string. Here the result of finditer i.e. iterator is being converted to list and directly accessing the nth index.
import re
n=2
sampleString="this is history"
pattern=re.compile("is")
matches=pattern.finditer(sampleString)
print(list(matches)[n].span()[0])
File?Settings?Build, Execution, Deployment?Build Tools?Gradle?Use default Gradle wrapper (recommended)
File?Project Structure?Project
The following table shows compatibility between Android plugin for Gradle and Gradle:
Latest stable versions you can use with Android Studio 4.1.1 (November 2020):
Android Gradle Plugin version: 4.1.1
Gradle version: 6.5
It's all in the "magic" syntax of calling a method:
object.property();
When you get the property from the object and call it in one go, the object will be the context for the method. If you call the same method, but in separate steps, the context is the global scope (window) instead:
var f = object.property;
f();
When you get the reference of a method, it's no longer attached to the object, it's just a reference to a plain function. The same happens when you get the reference to use as a callback:
this.saveNextLevelData(this.setAll);
That's where you would bind the context to the function:
this.saveNextLevelData(this.setAll.bind(this));
If you are using jQuery you should use the $.proxy
method instead, as bind
is not supported in all browsers:
this.saveNextLevelData($.proxy(this.setAll, this));
I have used a syntax like this before:
$(ProjectDir)..\headers
or
..\headers
As other have pointed out, the starting directory is the one your project file is in(vcproj
or vcxproj
), not where your main code is located.
Or even just:
<div id="full-size">
Your contents go here
</div>
html,body{ margin:0; padding:0; height:100%; width:100%; }
#full-size{
height:100%;
width:100%;
overflow:hidden; /* or overflow:auto; if you want scrollbars */
}
(html, body can be set to like.. 95%-99% or some such to account for slight inconsistencies in margins, etc.)
As well as the previous answers are you could always use the Pull attrib as well:
<ol class="row" id="possibilities">
<li class="span6">
<div class="row">
<div class="span3">
<p>some text here</p>
<p>Text Here too</p>
</div>
<figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
</div>
</li>
<li class="span6">
<div class="row">
<figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
<div class="span3">
<p>Some text</p>
<p>Some text here too.</p>
</div>
</div>
</li>
I used a hybrid approach for fragments containing a list view. It seems to be performant since I don't replace the current fragment but rather add the new fragment and hide the current one. I have the following method in the activity that hosts my fragments:
public void addFragment(Fragment currentFragment, Fragment targetFragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(0,0,0,0);
transaction.hide(currentFragment);
// use a fragment tag, so that later on we can find the currently displayed fragment
transaction.add(R.id.frame_layout, targetFragment, tag)
.addToBackStack(tag)
.commit();
}
I use this method in my fragment (containing the list view) whenever a list item is clicked/tapped (and thus I need to launch/display the details fragment):
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
SearchFragment currentFragment = (SearchFragment) fragmentManager.findFragmentByTag(getFragmentTags()[0]);
DetailsFragment detailsFragment = DetailsFragment.newInstance("some object containing some details");
((MainActivity) getActivity()).addFragment(currentFragment, detailsFragment, "Details");
getFragmentTags()
returns an array of strings that I use as tags for different fragments when I add a new fragment (see transaction.add
method in addFragment
method above).
In the fragment containing the list view, I do this in its onPause() method:
@Override
public void onPause() {
// keep the list view's state in memory ("save" it)
// before adding a new fragment or replacing current fragment with a new one
ListView lv = (ListView) getActivity().findViewById(R.id.listView);
mListViewState = lv.onSaveInstanceState();
super.onPause();
}
Then in onCreateView of the fragment (actually in a method that is invoked in onCreateView), I restore the state:
// Restore previous state (including selected item index and scroll position)
if(mListViewState != null) {
Log.d(TAG, "Restoring the listview's state.");
lv.onRestoreInstanceState(mListViewState);
}
drop returns a new array so that is why it choked in the og post; I had a similar requirement to rename some column headers and deleted some rows due to an ill formed csv file converted to Dataframe, so after reading this post I used:
newList = pd.DataFrame(newList)
newList.columns = ['Area', 'Price']
print(newList)
# newList = newList.drop(0)
# newList = newList.drop(len(newList))
newList = newList[1:-1]
print(newList)
and it worked great, as you can see with the two commented out lines above I tried the drop.() method and it work but not as kool and readable as using [n:-n], hope that helps someone, thanks.
<a href="#">
<img src="p.png"></img>
</a>
The Key is the AssemblyResolve event raised by the AppDomain.
[STAThread]
static void Main(string[] args)
{
fileDialog.ShowDialog();
string fileName = fileDialog.FileName;
if (string.IsNullOrEmpty(fileName) == false)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
if (Directory.Exists(@"c:\Provisioning\") == false)
Directory.CreateDirectory(@"c:\Provisioning\");
assemblyDirectory = Path.GetDirectoryName(fileName);
Assembly loadedAssembly = Assembly.LoadFile(fileName);
List<Type> assemblyTypes = loadedAssembly.GetTypes().ToList<Type>();
foreach (var type in assemblyTypes)
{
if (type.IsInterface == false)
{
StreamWriter jsonFile = File.CreateText(string.Format(@"c:\Provisioning\{0}.json", type.Name));
JavaScriptSerializer serializer = new JavaScriptSerializer();
jsonFile.WriteLine(serializer.Serialize(Activator.CreateInstance(type)));
jsonFile.Close();
}
}
}
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string[] tokens = args.Name.Split(",".ToCharArray());
System.Diagnostics.Debug.WriteLine("Resolving : " + args.Name);
return Assembly.LoadFile(Path.Combine(new string[]{assemblyDirectory,tokens[0]+ ".dll"}));
}
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
The best way to align a div in center both horizontally and vertically will be
HTML
<div></div>
CSS:
div {
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: blue;
}
You can use the IF
statement in a new cell to replace text, such as:
=IF(A4="C", "Other", A4)
This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.
EDIT
Assuming that the Employee_Count
values are in B1-B10, you can use this:
=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)
This function doesn't even require the data to be sorted; the LARGE
function will find the 10th largest number in the series, and then the rest of the formula will compare against that.
You can pass --force-recreate
to docker compose up
, which should use fresh containers.
I think the reasoning behind reusing containers is to preserve any changes during development. Note that Compose does something similar with volumes, which will also persist between container recreation (a recreated container will attach to its predecessor's volumes). This can be helpful, for example, if you have a Redis container used as a cache and you don't want to lose the cache each time you make a small change. At other times it's just confusing.
I don't believe there is any way you can force this from the Compose file.
Arguably it does clash with immutable infrastructure principles. The counter-argument is probably that you don't use Compose in production (yet). Also, I'm not sure I agree that immutable infra is the basic idea of Docker, although it's certainly a good use case/selling point.
if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.
# shell script ,ignore the first
$ $(dirname `which mysql`)\/mysql.server start
May be helpful.
from ..gen_py.lib import MyService
or
from main.gen_py.lib import MyService
Make sure you have a (at least empty) __init__.py
file on each directory.
Sorry, but I think you need two queries. One for total views and another one for grouped records.
You can find useful this answer
Jenkins "boolean" parameters are really just a shortcut for the "choice parameter" type with the choices hardcoded to the strings "true" and "false", and with a checkbox to set the string variable. But in the end, it is just that: a string variable, with nothing to do with a true boolean. That's why you need to convert the string to a boolean if you don't want to do a string comparison like:
if (myBoolean == "true")
Some handy quick functions (if you're not using Boost):
template<typename T>
std::string ToString(const T& v)
{
std::ostringstream ss;
ss << v;
return ss.str();
}
template<typename T>
T FromString(const std::string& str)
{
std::istringstream ss(str);
T ret;
ss >> ret;
return ret;
}
Example:
int i = FromString<int>(s);
std::string str = ToString(i);
Works for any streamable types (floats etc). You'll need to #include <sstream>
and possibly also #include <string>
.
I think an option for your purposes is git log --online --decorate
. This lets you know the checked commit, and the top commits for each branch that you have in your story line. By doing this, you have a nice view on the structure of your repo and the commits associated to a specific branch. I think reading this might help.
Git is warning that you might lose history by deleting this branch. Even though it would not actually delete any commits right away, some or all of the commits on the branch would become unreachable if they are not part of some other branch as well.
For the branch experiment
to be “fully merged” into another branch, its tip commit must be an ancestor of the other branch’s tip, making the commits in experiment
a subset of the other branch. This makes it safe to delete experiment
, since all its commits will remain part of the repository history via the other branch. It must be “fully” merged, because it may have been merged several times already, but now have commits added since the last merge that are not contained in the other branch.
Git doesn’t check every other branch in the repository, though; just two:
The “upstream branch” for experiment
, as in your case, is probably origin/experiment
. If experiment
is fully merged in the current branch, then Git deletes it with no complaint. If it is not, but it is fully merged in its upstream branch, then Git proceeds with a warning seeming like:
warning: deleting branch 'experiment' that has been merged
to 'refs/remotes/origin/experiment', but not yet merged to
HEAD.
Deleted branch experiment (was xxxxxxxx).
Where xxxxxxxx
indicates a commit id. Being fully merged in its upstream indicates that the commits in experiment
have been pushed to the origin repository, so that even if you lose them here, they may at least be saved elsewhere.
Since Git doesn’t check other branches, it may be safe to delete a branch because you know it is fully merged into another one; you can do this with the -D
option as indicated, or switch to that branch first and let Git confirm the fully merged status for you.
Below are scripts for emptying and deleting a Kafka topic assuming localhost as the zookeeper server and Kafka_Home is set to the install directory:
The script below will empty a topic by setting its retention time to 1 second and then removing the configuration:
#!/bin/bash
echo "Enter name of topic to empty:"
read topicName
/$Kafka_Home/bin/kafka-configs --zookeeper localhost:2181 --alter --entity-type topics --entity-name $topicName --add-config retention.ms=1000
sleep 5
/$Kafka_Home/bin/kafka-configs --zookeeper localhost:2181 --alter --entity-type topics --entity-name $topicName --delete-config retention.ms
To fully delete topics you must stop any applicable kafka broker(s) and remove it's directory(s) from the kafka log dir (default: /tmp/kafka-logs) and then run this script to remove the topic from zookeeper. To verify it's been deleted from zookeeper the output of ls /brokers/topics should no longer include the topic:
#!/bin/bash
echo "Enter name of topic to delete from zookeeper:"
read topicName
/$Kafka_Home/bin/zookeeper-shell localhost:2181 <<EOF
rmr /brokers/topics/$topicName
ls /brokers/topics
quit
EOF
This solution allows you to change the name of the downloaded file:
HTML:
<a id="link"></a>
JAVASCRIPT:
var link = document.getElementById('link');
link.setAttribute('download', 'MintyPaper.png');
link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
link.click();
If you have Excel 2007 you can write VBA to alter the connections (i.e. the external data queries) in a workbook and update the CommandText property. If you simply add ?
where you want a parameter, then next time you refresh the data it'll prompt for the values for the connections! magic. When you look at the properties of the Connection the Parameters button will now be active and useable as normal.
E.g. I'd write a macro, step through it in the debugger, and make it set the CommandText appropriately. Once you've done this you can remove the macro - it's just a means to update the query.
Sub UpdateQuery
Dim cn As WorkbookConnection
Dim odbcCn As ODBCConnection, oledbCn As OLEDBConnection
For Each cn In ThisWorkbook.Connections
If cn.Type = xlConnectionTypeODBC Then
Set odbcCn = cn.ODBCConnection
' If you do have multiple connections you would want to modify
' the line below each time you run through the loop.
odbcCn.CommandText = "select blah from someTable where blah like ?"
ElseIf cn.Type = xlConnectionTypeOLEDB Then
Set oledbCn = cn.OLEDBConnection
oledbCn.CommandText = "select blah from someTable where blah like ?"
End If
Next
End Sub
Alan already gave you the right answer - use the sAMAccountName
to filter your user.
I would add a recommendation on your use of DirectorySearcher
- if you only want one or two pieces of information, add them into the "PropertiesToLoad"
collection of the DirectorySearcher
.
Instead of retrieving the whole big user object and then picking out one or two items, this will just return exactly those bits you need.
Sample:
adSearch.PropertiesToLoad.Add("sn"); // surname = last name
adSearch.PropertiesToLoad.Add("givenName"); // given (or first) name
adSearch.PropertiesToLoad.Add("mail"); // e-mail addresse
adSearch.PropertiesToLoad.Add("telephoneNumber"); // phone number
Those are just the usual AD/LDAP property names you need to specify.
px
? PixelsAll of these answers seem to be incorrect. Contrary to intuition, in CSS the px
is not pixels. At least, not in the simple physical sense.
Read this article from the W3C, EM, PX, PT, CM, IN…, about how px
is a "magical" unit invented for CSS. The meaning of px
varies by hardware and resolution. (That article is fresh, last updated 2014-10.)
My own way of thinking about it: 1 px is the size of a thin line intended by a designer to be barely visible.
To quote that article:
The px unit is the magic unit of CSS. It is not related to the current font and also not related to the absolute units. The px unit is defined to be small but visible, and such that a horizontal 1px wide line can be displayed with sharp edges (no anti-aliasing). What is sharp, small and visible depends on the device and the way it is used: do you hold it close to your eyes, like a mobile phone, at arms length, like a computer monitor, or somewhere in between, like a book? The px is thus not defined as a constant length, but as something that depends on the type of device and its typical use.
To get an idea of the appearance of a px, imagine a CRT computer monitor from the 1990s: the smallest dot it can display measures about 1/100th of an inch (0.25mm) or a little more. The px unit got its name from those screen pixels.
Nowadays there are devices that could in principle display smaller sharp dots (although you might need a magnifier to see them). But documents from the last century that used px in CSS still look the same, no matter what the device. Printers, especially, can display sharp lines with much smaller details than 1px, but even on printers, a 1px line looks very much the same as it would look on a computer monitor. Devices change, but the px always has the same visual appearance.
That article gives some guidance about using pt
vs px
vs em
, to answer this Question.
You're thinking too complicated. It's actually just $('#'+openaddress)
.
In Swift 4.2 and Xcode 10
let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl.textAlignment = .center //For center alignment
lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl.textColor = .white
lbl.backgroundColor = .lightGray//If required
lbl.font = UIFont.systemFont(ofSize: 17)
//To display multiple lines in label
lbl.numberOfLines = 0
lbl.lineBreakMode = .byWordWrapping
lbl.sizeToFit()//If required
yourView.addSubview(lbl)
@hydroo: Without the extra file:
#define SOME_ENUM(DO) \
DO(Foo) \
DO(Bar) \
DO(Baz)
#define MAKE_ENUM(VAR) VAR,
enum MetaSyntacticVariable{
SOME_ENUM(MAKE_ENUM)
};
#define MAKE_STRINGS(VAR) #VAR,
const char* const MetaSyntacticVariableNames[] = {
SOME_ENUM(MAKE_STRINGS)
};
If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));
Here's the simplest solution (Jibwa made it seem complicated in another answer), without having to generate indices yourself - just using the ShuffleSplit object to generate 1 split.
import numpy as np
from sklearn.model_selection import ShuffleSplit # or StratifiedShuffleSplit
sss = ShuffleSplit(n_splits=1, test_size=0.1)
data_size = 100
X = np.reshape(np.random.rand(data_size*2),(data_size,2))
y = np.random.randint(2, size=data_size)
sss.get_n_splits(X, y)
train_index, test_index = next(sss.split(X, y))
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
you could register an interval on the page using setInterval, ie:
setInterval(function(){
//code goes here that will be run every 5 seconds.
}, 5000);
Try this version which does not require order to be the same but does support having multiple of the same value. They match only if each has the same quantity of any value.
public boolean arraysMatch(List<String> elements1, List<String> elements2) {
// Optional quick test since size must match
if (elements1.size() != elements2.size()) {
return false;
}
List<String> work = newArrayList(elements2);
for (String element : elements1) {
if (!work.remove(element)) {
return false;
}
}
return work.isEmpty();
}
You might want to look at "JavaScript HTML DOM Events" for a general overview of events:
http://www.w3schools.com/jsref/dom_obj_event.asp
PrimeFaces is built on jQuery, so here's jQuery's "Events" documentation:
http://api.jquery.com/category/events/
http://api.jquery.com/category/events/form-events/
http://api.jquery.com/category/events/keyboard-events/
http://api.jquery.com/category/events/mouse-events/
http://api.jquery.com/category/events/browser-events/
Below, I've listed some of the more common events, with comments about where they can be used (taken from jQuery documentation).
Mouse Events
(Any HTML element can receive these events.)
click
dblclick
mousedown
mousemove
mouseover
mouseout
mouseup
Keyboard Events
(These events can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for these event types.)
keydown
keypress
keyup
Form Events
blur
(In recent browsers, the domain of the event has been extended to include all element types.)
change
(This event is limited to <input>
elements, <textarea>
boxes and <select>
elements.)
focus
(This event is implicitly applicable to a limited set of elements, such as form elements (<input>
, <select>
, etc.) and links (<a href>
). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.)
select
(This event is limited to <input type="text">
fields and <textarea>
boxes.)
submit
(It can only be attached to <form>
elements.)
I wrote a script, viewtab , in Groovy for just this purpose. You invoke it like:
viewtab filename.csv
It is basically a super-lightweight spreadsheet that can be invoked from the command line, handles CSV and tab separated files, can read VERY large files that Excel and Numbers choke on, and is very fast. It's not command-line in the sense of being text-only, but it is platform independent and will probably fit the bill for many people looking for a solution to the problem of quickly inspecting many or large CSV files while working in a command line environment.
The script and how to install it are described here:
http://bayesianconspiracy.blogspot.com/2012/06/quick-csvtab-file-viewer.html
void Keep()
Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "About";
var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
TempData.Keep(); // retains all strings values
}
void Keep(string key)
Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "About";
var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
TempData.Keep("emp"); // retains only "emp" string values
}
For the second part of your question, you can also use shift
, for example:
df['t-1'] = df['t'].shift(1)
t-1
would then contain the values from t one row above.
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html
See What is the maximum length of a URL in different browsers?
The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.
To hard reset a single file to HEAD:
git checkout @ -- myfile.ext
Note that @
is short for HEAD
. An older version of git may not support the short form.
To hard reset a single file to the index, assuming the index is non-empty, otherwise to HEAD:
git checkout -- myfile.ext
The point is that to be safe, you don't want to leave out @
or HEAD
from the command unless you specifically mean to reset to the index only.
just disable eslint for the next line;
useEffect(() => {
fetchBusinesses();
// eslint-disable-next-line
}, []);
in this way you are using it just like a component did mount (called once)
updated
or
const fetchBusinesses = useCallback(() => {
// your logic in here
}, [someDeps])
useEffect(() => {
fetchBusinesses();
// no need to skip eslint warning
}, [fetchBusinesses]);
fetchBusinesses will be called everytime someDeps will change
"Please mark your answers with an acceptance to put the code in the Codeplex project."
Why? All the Stuff on this site under CC-by-sa-2.5, so just put your Extension overflow Project under the same license and you can freely use it.
Anyway, here is a String.Reverse function, based on this question.
/// <summary>
/// Reverse a String
/// </summary>
/// <param name="input">The string to Reverse</param>
/// <returns>The reversed String</returns>
public static string Reverse(this string input)
{
char[] array = input.ToCharArray();
Array.Reverse(array);
return new string(array);
}
I believe telnet 74.255.12.25 8089
. Why don't u try both
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
Version 2 of the API has been deprecated since March 2014, which some of these other answers are using.
Here is a very simple code snippet to get the views count from a video, using JQuery in the YouTube API v3.
You will need to create an API key via Google Developer Console first.
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Qq7mpb-hCBY&key={{YOUR-KEY}}', function(data) {
alert("viewCount: " + data.items[0].statistics.viewCount);
});
</script>
Note that dangerouslySetInnerHTML
can be dangerous if you do not know what is in the HTML string you are injecting. This is because malicious client side code can be injected via script tags.
It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.
Example:
import DOMPurify from 'dompurify'
const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
render: function() {
return (
<div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
);
}
I think you have put command like java -VERSION
. This is in capital letters
You need to put all command in lowercase letters
javac -version
java -version
All characters must be in lowercase letter
If you can use jQuery with Moment.js (great library), this is the way:
var crClockInit1 = null;
var crClockInterval = null;
function crInitClock() {
crClockInit1 = setInterval(function() {
if (moment().format("SSS") <= 40) {
clearInterval(crClockInit1);
crStartClockNow();
}
}, 30);
}
function crStartClockNow() {
crClockInterval = setInterval(function() {
$('#clock').html(moment().format('D. MMMM YYYY H:mm:ss'));
}, 1000);
}
Start clock initialization with crInitClock()
. It's done this way to synchronize seconds. Without synchronization, you would start 1 second timer in half of second and it will be half second late after real time.
In this instance, your div
elements have been changed from block
level elements to inline
elements. A typical characteristic of inline
elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)
There are a few solutions that can be used to solve this.
Example 1 - Comment the whitespace out: (example)
<div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div>
Example 2 - Remove the line breaks: (example)
<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>
Example 3 - Close part of the tag on the next line (example)
<div>text</div
><div>text</div
><div>text</div
><div>text</div
><div>text</div>
Example 4 - Close the entire tag on the next line: (example)
<div>text
</div><div>text
</div><div>text
</div><div>text
</div><div>text
</div>
font-size
Since the whitespace between the inline
elements is determined by the font-size
, you could simply reset the font-size
to 0
, and thus remove the space between the elements.
Just set font-size: 0
on the parent elements, and then declare a new font-size
for the children elements. This works, as demonstrated here (example)
#parent {
font-size: 0;
}
#child {
font-size: 16px;
}
This method works pretty well, as it doesn't require a change in the markup; however, it doesn't work if the child element's font-size
is declared using em
units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by inline
elements.
display: flex
In some cases, you can also set the display
of the parent element to flex
. (example)
This effectively removes the spaces between the elements in supported browsers. Don't forget to add appropriate vendor prefixes for additional support.
.parent {
display: flex;
}
.parent > div {
display: inline-block;
padding: 1em;
border: 2px solid #f00;
}
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.parent > div {_x000D_
display: inline-block;_x000D_
padding: 1em;_x000D_
border: 2px solid #f00;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
</div>
_x000D_
It is incredibly unreliable to use negative margins to remove the space between inline
elements. Please don't use negative margins if there are other, more optimal, solutions.
you also should specify def name in the project settings here:
Configuration > Properties/Input/Advanced/Module > Definition File
I solved my problem using entire address where my code is: Before:
if(!exists("foo", mode="function")) source("utils.r")
After:
if(!exists("foo", mode="function")) source("C:/tests/utils.r")
The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.
Once changing this value to DEFAULT, run the following command:
/usr/bin/update-crypto-policies --set DEFAULT
Rerun the curl command and it should work.
You can paste the following code to the console to scroll up/down using the a/z keyboard keys. If you want to set your own keys you can visit this page to get the keycodes
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 90) {
window.scrollBy(0, 100)
}
if (evtobj.keyCode == 65) {
window.scrollBy(0, -100)
}
}
document.onkeydown = KeyPress;
It's better to use JSON.parse(yourUnescapedJson);
For those interested in what Microsoft thinks should be included in the gitignore, here's the default one which Visual Studio 2013 RTM
automatically generates when creating a new Git-Repository:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
x64/
build/
[Bb]in/
[Oo]bj/
# Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
!packages/*/build/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.Publish.xml
# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.pfx
*.publishsettings
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
#LightSwitch generated files
GeneratedArtifacts/
_Pvt_Extensions/
ModelManifest.xml
# =========================
# Windows detritus
# =========================
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Mac desktop service store files
.DS_Store
I would suggest doing this in a more functional style :P
function CreateMessageboard(BoardMessages) {
var htmlMessageboardString = BoardMessages
.map(function(BoardMessage) {
return MessageToHTMLString(BoardMessage);
})
.join('');
}
Try this
You can use "Gena" library. It closely resembles stl::vector
in pure C89.
From the README, it features:
vec[k][j]
;You can check it out here:
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
try out this if you want to assign value to object and it is showing this error in angular..
crate object in construtor
this.modelObj = new Model();
//<---------- after declaring object above
Try running fuser command
[root@guest2 ~]# fuser -mv /home
USER PID ACCESS COMMAND
/home: root 2919 f.... automount
[root@guest2 ~]# kill -9 2919
autofs
service is known to cause this issue.
You can use command
#service autofs stop
And try again.
If you're using javascript with jQuery to generate the token in your form, this works:
<input name="authenticity_token"
type="hidden"
value="<%= $('meta[name=csrf-token]').attr('content') %>" />
Obviously, you need to have the <%= csrf_meta_tag %>
in your Ruby layout.
Additionally, if your application uses SQL SERVER you can use the SQL Agent to schedule your tasks. This is where we commonly put re-occurring code that is data driven (email reminders, scheduled maintenance, purges, etc...). A great feature that is built in with the SQL Agent is failure notification options, which can alert you if a critical task fails.
You should create an interface for that like it is working well
public interface Service {
@FormUrlEncoded
@POST("v1/EmergencyRequirement.php/?op=addPatient")
Call<Result> addPerson(@Field("BloodGroup") String bloodgroup,
@Field("Address") String Address,
@Field("City") String city, @Field("ContactNumber") String contactnumber,
@Field("PatientName") String name,
@Field("Time") String Time, @Field("DonatedBy") String donar);
}
or you can visit to http://teachmeandroidhub.blogspot.com/2018/08/post-data-using-retrofit-in-android.html
and youcan vist to https://github.com/rajkumu12/GetandPostUsingRatrofit
I wrote a custom classloader, from which it is possible to unload individual classes without GCing the classloader. Jar Class Loader
Found out these problems can be addressed by using
ObjectMapper#convertValue(Object fromValue, Class<T> toValueType)
As a result, the origal quuestion can be solved in a 2-step converison:
Demarshall the JSON back to an object - in which the Map<String, Object>
is demarshalled as a HashMap<String, LinkedHashMap>
, by using bjectMapper#readValue().
Convert inner LinkedHashMaps back to proper objects
ObjectMapper mapper = new ObjectMapper();
Class clazz = (Class) Class.forName(classType);
MyOwnObject value = mapper.convertValue(value, clazz);
To prevent the 'classType' has to be known in advance, I enforced during marshalling an extra Map was added, containing <key, classNameString>
pairs. So at unmarshalling time, the classType can be extracted dynamically.
Although some answers here maybe great, none helped my case (which is very similar to OP's error message).
This error needed fixing because even though my components rendered with their data (pulled from API), when deployed to firebase hosting, it did not render some of my components (the components that rely on data).
To fix it (and given you followed the suggestions in the accepted answer), in the Parent component (the ones pulling data and passing to child component), I did:
// pulled data in this life cycle hook, saving it to my store
created() {
FetchData.getProfile()
.then(myProfile => {
const mp = myProfile.data;
console.log(mp)
this.$store.dispatch('dispatchMyProfile', mp)
this.propsToPass = mp;
})
.catch(error => {
console.log('There was an error:', error.response)
})
}
// called my store here
computed: {
menu() {
return this.$store.state['myProfile'].profile
}
},
// then in my template, I pass this "menu" method in child component
<LeftPanel :data="menu" />
_x000D_
This cleared that error away. I deployed it again to firebase hosting, and viola!
Hope this bit helps you.
While it's true that floating point type can represent only approximatively decimal data, it's also true that if one rounds numbers to the necessary precision before presenting them, one obtains the correct result. Usually.
Usually because the double type has a precision less than 16 figures. If you require better precision it's not a suitable type. Also approximations can accumulate.
It must be said that even if you use fixed point arithmetic you still have to round numbers, were it not for the fact that BigInteger and BigDecimal give errors if you obtain periodic decimal numbers. So there is an approximation also here.
For example COBOL, historically used for financial calculations, has a maximum precision of 18 figures. So there is often an implicit rounding.
Concluding, in my opinion the double is unsuitable mostly for its 16 digit precision, which can be insufficient, not because it is approximate.
Consider the following output of the subsequent program. It shows that after rounding double give the same result as BigDecimal up to precision 16.
Precision 14
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.000051110111115611
Double : 56789.012345 / 1111111111 = 0.000051110111115611
Precision 15
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.0000511101111156110
Double : 56789.012345 / 1111111111 = 0.0000511101111156110
Precision 16
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.00005111011111561101
Double : 56789.012345 / 1111111111 = 0.00005111011111561101
Precision 17
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.000051110111115611011
Double : 56789.012345 / 1111111111 = 0.000051110111115611013
Precision 18
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.0000511101111156110111
Double : 56789.012345 / 1111111111 = 0.0000511101111156110125
Precision 19
------------------------------------------------------
BigDecimalNoRound : 56789.012345 / 1111111111 = Non-terminating decimal expansion; no exact representable decimal result.
DoubleNoRound : 56789.012345 / 1111111111 = 5.111011111561101E-5
BigDecimal : 56789.012345 / 1111111111 = 0.00005111011111561101111
Double : 56789.012345 / 1111111111 = 0.00005111011111561101252
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.MathContext;
public class Exercise {
public static void main(String[] args) throws IllegalArgumentException,
SecurityException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
String amount = "56789.012345";
String quantity = "1111111111";
int [] precisions = new int [] {14, 15, 16, 17, 18, 19};
for (int i = 0; i < precisions.length; i++) {
int precision = precisions[i];
System.out.println(String.format("Precision %d", precision));
System.out.println("------------------------------------------------------");
execute("BigDecimalNoRound", amount, quantity, precision);
execute("DoubleNoRound", amount, quantity, precision);
execute("BigDecimal", amount, quantity, precision);
execute("Double", amount, quantity, precision);
System.out.println();
}
}
private static void execute(String test, String amount, String quantity,
int precision) throws IllegalArgumentException, SecurityException,
IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
Method impl = Exercise.class.getMethod("divideUsing" + test, String.class,
String.class, int.class);
String price;
try {
price = (String) impl.invoke(null, amount, quantity, precision);
} catch (InvocationTargetException e) {
price = e.getTargetException().getMessage();
}
System.out.println(String.format("%-30s: %s / %s = %s", test, amount,
quantity, price));
}
public static String divideUsingDoubleNoRound(String amount,
String quantity, int precision) {
// acceptance
double amount0 = Double.parseDouble(amount);
double quantity0 = Double.parseDouble(quantity);
//calculation
double price0 = amount0 / quantity0;
// presentation
String price = Double.toString(price0);
return price;
}
public static String divideUsingDouble(String amount, String quantity,
int precision) {
// acceptance
double amount0 = Double.parseDouble(amount);
double quantity0 = Double.parseDouble(quantity);
//calculation
double price0 = amount0 / quantity0;
// presentation
MathContext precision0 = new MathContext(precision);
String price = new BigDecimal(price0, precision0)
.toString();
return price;
}
public static String divideUsingBigDecimal(String amount, String quantity,
int precision) {
// acceptance
BigDecimal amount0 = new BigDecimal(amount);
BigDecimal quantity0 = new BigDecimal(quantity);
MathContext precision0 = new MathContext(precision);
//calculation
BigDecimal price0 = amount0.divide(quantity0, precision0);
// presentation
String price = price0.toString();
return price;
}
public static String divideUsingBigDecimalNoRound(String amount, String quantity,
int precision) {
// acceptance
BigDecimal amount0 = new BigDecimal(amount);
BigDecimal quantity0 = new BigDecimal(quantity);
//calculation
BigDecimal price0 = amount0.divide(quantity0);
// presentation
String price = price0.toString();
return price;
}
}
I think this should work no?
ViewData["currentIndex"] = index;
The difference is that if you only specify the DOCTYPE
, IE’s Compatibility View Settings take precedence. By default these settings force all intranet sites into Compatibility View regardless of DOCTYPE
. There’s also a checkbox to use Compatibility View for all websites, regardless of DOCTYPE
.
X-UA-Compatible
overrides the Compatibility View Settings, so the page will render in standards mode regardless of the browser settings. This forces standards mode for:
DOCTYPE
alone cannot do that; you will end up in one of the Compatibility View modes in these cases regardless of DOCTYPE
.
If both the meta
tag and the HTTP header are specified, the meta
tag takes precedence.
This answer is based on examining the complete rules for deciding document mode in IE8, IE9, and IE10. Note that looking at the DOCTYPE
is the very last fallback for deciding the document mode.
First you have to know what is a determinant? the determinant is an attribute that used to determine another attribute in the same table. SO the determinant must be a candidate key. And you can have more than one determinant. But primary key is used to determine the whole record and you can have only one primary key. Both primary and candidate key can consist of one or more attributes
Below code works for me:
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var myCenter = new google.maps.LatLng(51.528308, -0.3817765);
function initialize() {
var mapProp = {
center:myCenter,
zoom:15,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
icon: {
url: '/images/marker.png',
size: new google.maps.Size(70, 86), //marker image size
origin: new google.maps.Point(0, 0), // marker origin
anchor: new google.maps.Point(35, 86) // X-axis value (35, half of marker width) and 86 is Y-axis value (height of the marker).
}
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
easy if its pdf or img use
return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));
I had received a similar error message. Think I inadvertently typed "9o" at start of first line of php.ini file. Once I removed that, I no longer received the "fatal error" messages. Hope this helps.
This will uninstall a gem installed by bundler:
bundle exec gem uninstall GEM_NAME
Note that this throws
ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>
but the gem is actually removed. Next time you run bundle install
the gem will be reinstalled.
As far as I know PKCS#12 is just a certificate/public/private key store. If you extracted a public key from PKCS#12 file, OpenSSH should be able to use it as long as it was extracted in PEM format. You probably already know that you also need a corresponding private key (also in PEM) in order to use it for ssh-public-key authentication.
Create a Dockerfile
#
# Build stage
#
FROM maven:3.6.3-jdk-11-slim AS build
WORKDIR usr/src/app
COPY . ./
RUN mvn clean package
#
# Package stage
#
FROM openjdk:11-jre-slim
ARG JAR_NAME="project-name"
WORKDIR /usr/src/app
EXPOSE ${HTTP_PORT}
COPY --from=build /usr/src/app/target/${JAR_NAME}.jar ./app.jar
CMD ["java","-jar", "./app.jar"]
To install TF on windows, follow the below-mentioned steps:
conda create --name tensorflow python=3.5
activate tensorflow
conda install jupyter
conda install scipy
pip install tensorflow-gpu
Use pip install tensorflow
in place of pip install tensorflow-gpu
, in case if you want to install CPU only version of TF.
Note: This installation has been tested with Anaconda Python 3.5 (64 bit). I have also tried the same installation steps with (a) Anaconda Python 3.6 (32 bit), (b) Anaconda Python 3.6 (64 bit), and (c) Anaconda Python 3.5 (32 bit), but all of them (i.e. (a), (b) and (c) ) failed.
@media only screen and (max-width: 1026px) {
#fadeshow1 {
display: none;
}
}
Any time the screen is less than 1026 pixels wide, anything inside the { }
will apply.
Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS
I believe you are misinterpreting the JSON format for key values. You should store your string as
NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Now if you do following NSLog statement
NSLog(@"%@",[json objectForKey:@"ID"]);
Result would be another NSDictionary.
{
Content = 268;
type = text;
}
Hope this helps to get clear understanding.
When you talk about presentation, service, data, network layer, you are talking about layers. When you "deploy them separately", you talk about tiers.
Tiers is all about deployment. Take it this way: We have an application which has a frontend created in Angular, it has a backend as MongoDB and a middle layer which interacts between the frontend and the backend. So, when this frontend application, database application, and the middle layer is all deployed separately, we say it's a 3 tier application.
Benefit: If we need to scale our backend in the future, we only need to scale the backend independently and there's no need to scale up the frontend.
You can do the following if you already know the number of fields of the input:
client_name = raw_input("Enter you first and last name: ")
first_name, last_name = client_name.split()
and in case you want to iterate through the fields separated by spaces, you can do the following:
some_input = raw_input() # This input is the value separated by spaces
for field in some_input.split():
print field # this print can be replaced with any operation you'd like
# to perform on the fields.
A more generic use of the "split()" function would be:
result_list = some_string.split(DELIMITER)
where DELIMETER is replaced with the delimiter you'd like to use as your separator, with single quotes surrounding it.
An example would be:
result_string = some_string.split('!')
The code above takes a string and separates the fields using the '!' character as a delimiter.
git config --global credential.helper cache
Twisted has SSH support : http://www.devshed.com/c/a/Python/SSH-with-Twisted/
The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules in twisted.conch to build SSH servers and clients.
Setting Up a Custom SSH Server
The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.
You can use twisted.conch to create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.
How Do I Do That? Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver , but with higher-level features for controlling the terminal.
Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.
To make your shell available through SSH, you need to implement a few different classes that twisted.conch needs to build an SSH server. First, you need the twisted.cred authentication classes: a portal, credentials checkers, and a realm that returns avatars. Use twisted.conch.avatar.ConchUser as the base class for your avatar. Your avatar class should also implement twisted.conch.interfaces.ISession , which includes an openShell method in which you create a Protocol to manage the user’s interactive session. Finally, create a twisted.conch.ssh.factory.SSHFactory object and set its portal attribute to an instance of your portal.
Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.
Example 10-1. sshserver.py
from twisted.cred import portal, checkers, credentials
from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
from zope.interface import implements
import os
class SSHDemoProtocol(recvline.HistoricRecvLine):
def __init__(self, user):
self.user = user
def connectionMade(self) :
recvline.HistoricRecvLine.connectionMade(self)
self.terminal.write("Welcome to my test SSH server.")
self.terminal.nextLine()
self.do_help()
self.showPrompt()
def showPrompt(self):
self.terminal.write("$ ")
def getCommandFunc(self, cmd):
return getattr(self, ‘do_’ + cmd, None)
def lineReceived(self, line):
line = line.strip()
if line:
cmdAndArgs = line.split()
cmd = cmdAndArgs[0]
args = cmdAndArgs[1:]
func = self.getCommandFunc(cmd)
if func:
try:
func(*args)
except Exception, e:
self.terminal.write("Error: %s" % e)
self.terminal.nextLine()
else:
self.terminal.write("No such command.")
self.terminal.nextLine()
self.showPrompt()
def do_help(self, cmd=”):
"Get help on a command. Usage: help command"
if cmd:
func = self.getCommandFunc(cmd)
if func:
self.terminal.write(func.__doc__)
self.terminal.nextLine()
return
publicMethods = filter(
lambda funcname: funcname.startswith(‘do_’), dir(self))
commands = [cmd.replace(‘do_’, ”, 1) for cmd in publicMethods]
self.terminal.write("Commands: " + " ".join(commands))
self.terminal.nextLine()
def do_echo(self, *args):
"Echo a string. Usage: echo my line of text"
self.terminal.write(" ".join(args))
self.terminal.nextLine()
def do_whoami(self):
"Prints your user name. Usage: whoami"
self.terminal.write(self.user.username)
self.terminal.nextLine()
def do_quit(self):
"Ends your session. Usage: quit"
self.terminal.write("Thanks for playing!")
self.terminal.nextLine()
self.terminal.loseConnection()
def do_clear(self):
"Clears the screen. Usage: clear"
self.terminal.reset()
class SSHDemoAvatar(avatar.ConchUser):
implements(conchinterfaces.ISession)
def __init__(self, username):
avatar.ConchUser.__init__(self)
self.username = username
self.channelLookup.update({‘session’:session.SSHSession})
def openShell(self, protocol):
serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
serverProtocol.makeConnection(protocol)
protocol.makeConnection(session.wrapProtocol(serverProtocol))
def getPty(self, terminal, windowSize, attrs):
return None
def execCommand(self, protocol, cmd):
raise NotImplementedError
def closed(self):
pass
class SSHDemoRealm:
implements(portal.IRealm)
def requestAvatar(self, avatarId, mind, *interfaces):
if conchinterfaces.IConchUser in interfaces:
return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
else:
raise Exception, "No supported interfaces found."
def getRSAKeys():
if not (os.path.exists(‘public.key’) and os.path.exists(‘private.key’)):
# generate a RSA keypair
print "Generating RSA keypair…"
from Crypto.PublicKey import RSA
KEY_LENGTH = 1024
rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
publicKeyString = keys.makePublicKeyString(rsaKey)
privateKeyString = keys.makePrivateKeyString(rsaKey)
# save keys for next time
file(‘public.key’, ‘w+b’).write(publicKeyString)
file(‘private.key’, ‘w+b’).write(privateKeyString)
print "done."
else:
publicKeyString = file(‘public.key’).read()
privateKeyString = file(‘private.key’).read()
return publicKeyString, privateKeyString
if __name__ == "__main__":
sshFactory = factory.SSHFactory()
sshFactory.portal = portal.Portal(SSHDemoRealm())
users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’}
sshFactory.portal.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))
pubKeyString, privKeyString =
getRSAKeys()
sshFactory.publicKeys = {
‘ssh-rsa’: keys.getPublicKeyString(data=pubKeyString)}
sshFactory.privateKeys = {
‘ssh-rsa’: keys.getPrivateKeyObject(data=privKeyString)}
from twisted.internet import reactor
reactor.listenTCP(2222, sshFactory)
reactor.run()
{mospagebreak title=Setting Up a Custom SSH Server continued}
sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands:
$ ssh admin@localhost -p 2222
admin@localhost’s password: aaa
>>> Welcome to my test SSH server.
Commands: clear echo help quit whoami
$ whoami
admin
$ help echo
Echo a string. Usage: echo my line of text
$ echo hello SSH world!
hello SSH world!
$ quit
Connection to localhost closed.
var appName:String ="test"
val conf = new SparkConf().setAppName(appName).setMaster("local[*]").set("spark.executor.memory","1g");
val sc = SparkContext.getOrCreate(conf)
sc.setLogLevel("WARN")
JOIN with different tables
SELECT COUNT(*) FROM (
SELECT DISTINCT table_a.ID FROM table_a JOIN table_c ON table_a.ID = table_c.ID );
Why not use the simpler syntax?
<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>
This is the template control "Eval" that takes in the expression and the string format:
protected internal string Eval(
string expression,
string format
)
This depends on the shell you prefer to use.
If you are using the cmd shell on Windows then the following should work:
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S bin') DO RMDIR /S /Q "%%G"
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G"
If you are using a bash or zsh type shell (such as git bash or babun on Windows or most Linux / OS X shells) then this is a much nicer, more succinct way to do what you want:
find . -iname "bin" | xargs rm -rf
find . -iname "obj" | xargs rm -rf
and this can be reduced to one line with an OR:
find . -iname "bin" -o -iname "obj" | xargs rm -rf
Note that if your directories of filenames contain spaces or quotes, find will send those entries as-is, which xargs may split into multiple entries. If your shell supports them, -print0
and -0
will work around this short-coming, so the above examples become:
find . -iname "bin" -print0 | xargs -0 rm -rf
find . -iname "obj" -print0 | xargs -0 rm -rf
and:
find . -iname "bin" -o -iname "obj" -print0 | xargs -0 rm -rf
If you are using Powershell then you can use this:
Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
as seen in Robert H's answer below - just make sure you give him credit for the powershell answer rather than me if you choose to up-vote anything :)
It would of course be wise to run whatever command you choose somewhere safe first to test it!
You may be looking for the special HTML character,
.
You can use this to get a line break, and it can be inserted immediately following the last character in the current line. One place this is especially useful is if you want to include multiple lines in a list within a title or alt
label.
I had a lot of trouble with the ExecuteSqlCommand
and ExecuteSqlCommandAsync
, IN parameters were easy, but OUT parameters were very difficult.
I had to revert to using DbCommand
like so -
DbCommand cmd = _context.Database.GetDbConnection().CreateCommand();
cmd.CommandText = "dbo.sp_DoSomething";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@firstName", SqlDbType.VarChar) { Value = "Steve" });
cmd.Parameters.Add(new SqlParameter("@lastName", SqlDbType.VarChar) { Value = "Smith" });
cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.BigInt) { Direction = ParameterDirection.Output });
I wrote more about it in this post.
This function trims a string from left and right. Also it removes carriage returns from the string, an action which is not done by the LTRIM and RTRIM
IF OBJECT_ID(N'dbo.TRIM', N'FN') IS NOT NULL
DROP FUNCTION dbo.TRIM;
GO
CREATE FUNCTION dbo.TRIM (@STR NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)
BEGIN
RETURN(LTRIM(RTRIM(REPLACE(REPLACE(@STR ,CHAR(10),''),CHAR(13),''))))
END;
GO
I think you can try to load that csv into a RDD and then create a dataframe from that RDD, here is the document of creating dataframe from rdd:http://spark.apache.org/docs/latest/sql-programming-guide.html#interoperating-with-rdds
There are two ways to do the same instruction, that is, an empty string. The first way is to allocate an empty string on static memory:
char* my_variable = "";
or, if you want to be explicit:
char my_variable = '\0';
The way posted above is only for a character. And, the second way:
#include <string.h>
char* my_variable = strdup("");
Don't forget to use free() with this one because strdup() use malloc inside.
I came up with my own solution. Use this method, pass any document (dict,list, ObjectId etc) to serialize.
def getSerializable(doc):
# check if it's a list
if isinstance(doc, list):
for i, val in enumerate(doc):
doc[i] = getSerializable(doc[i])
return doc
# check if it's a dict
if isinstance(doc, dict):
for key in doc.keys():
doc[key] = getSerializable(doc[key])
return doc
# Process ObjectId
if isinstance(doc, ObjectId):
doc = str(doc)
return doc
# Use any other custom serializting stuff here...
# For the rest of stuff
return doc
you have to use bash instead or rewrite your script using standard sh
sh -c 'test "$choose" = "y" -o "$choose" = "Y"'
Your wildcard *.example.com
does not cover the root domain example.com
but will cover any variant on a sub-domain such as www.example.com
or test.example.com
The preferred method is to establish Subject Alternative Names like in Fabian's Answer but keep in mind that Chrome currently requires the Common Name to be listed additionally as one of the Subject Alternative Names (as it is correctly demonstrated in his answer). I recently discovered this problem because I had the Common Name example.com
with SANs www.example.com
and test.example.com
, but got the NET::ERR_CERT_COMMON_NAME_INVALID
warning from Chrome. I had to generate a new Certificate Signing Request with example.com
as both the Common Name and one of the SANs. Then Chrome fully trusted the certificate. And don't forget to import the root certificate into Chrome as a trusted authority for identifying websites.
This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:
var abc = 1; // we want to use this variable in embedded functions
function xyz(){
console.log(abc); // it is available here!
function qwe(){
console.log(abc); // it is available here too!
}
...
};
This technique relies on using a closure. But it doesn't work with this
because this
is a pseudo variable that may change from scope to scope dynamically:
// we want to use "this" variable in embedded functions
function xyz(){
// "this" is different here!
console.log(this); // not what we wanted!
function qwe(){
// "this" is different here too!
console.log(this); // not what we wanted!
}
...
};
What can we do? Assign it to some variable and use it through the alias:
var abc = this; // we want to use this variable in embedded functions
function xyz(){
// "this" is different here! --- but we don't care!
console.log(abc); // now it is the right object!
function qwe(){
// "this" is different here too! --- but we don't care!
console.log(abc); // it is the right object here too!
}
...
};
this
is not unique in this respect: arguments
is the other pseudo variable that should be treated the same way — by aliasing.
In my case the reason was in this line:
Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.
In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.
My project used a third-party plugin, that is incompatible with the newest gradle plugin version. So updating plugins versions may help to solve the issue.
You will need to configure you IIS (assuming this is the web server your are/will using) allowing access from WLAN/LAN to specific users (or anonymous). Allow IIS trought your firewall if you have one.
Your application won't need to be changed, that's just networking problems ans configuration you will have to face to allow acces only trought LAN and WLAN.
I was facing the same problem because some of the images are grey scale images in my data set, so i solve my problem by doing this
from PIL import Image
img = Image.open('my_image.jpg').convert('RGB')
# a line from my program
positive_images_array = np.array([np.array(Image.open(img).convert('RGB').resize((150, 150), Image.ANTIALIAS)) for img in images_in_yes_directory])
var count_elements = $('.class').length;
From: http://api.jquery.com/size/
The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.
Please see: