The official Jenkins documentation only mentions single line commands like the following:
// Declarative //
and (see)
pipeline {
/* insert Declarative Pipeline here */
}
The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:
/* a standalone multiline comment
spanning two lines */
println "hello" /* a multiline comment starting
at the end of a statement */
println 1 /* one */ + 2 /* two */
or
/**
* such a nice comment
*/
Complete code with error handling and added file stream closes. Add it to your class that you want to be able to serialize and deserialize. In my case the class name is CreateResumeForm
. You should change it to your own class name. Android
interface Serializable
is not sufficient to save your objects to the file, it only creates streams.
// Constant with a file name
public static String fileName = "createResumeForm.ser";
// Serializes an object and saves it to a file
public void saveToFile(Context context) {
try {
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Creates an object by reading it from a file
public static CreateResumeForm readFromFile(Context context) {
CreateResumeForm createResumeForm = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
createResumeForm = (CreateResumeForm) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return createResumeForm;
}
Use it like this in your Activity
:
form = CreateResumeForm.readFromFile(this);
In my case, the issue was with my Xcode build scheme. When you run react-native run-ios
you may see something like,
info Found Xcode workspace "myproject.xcworkspace"*
info Building (using "xcodebuild -workspace myproject.xcworkspace -configuration Debug -scheme myproject -destination id=xxxxxxxx-xxxxx-xxxxx-xxxx-xxxxxxxxx -derivedDataPath build/myproject")*
In this case, there should be a scheme named myproject in your ios configurations. The way I fixed it is,
Double clicked on myproject.xcworkspace in ios directory (to open workspace with Xcode)
Navigate into Product > Scheme > Manage Schemes...
Created a Scheme appropriately with name myproject (this name is case-sensitive)
Ran
react-native run-ios
in project directory
Well, I guess the other posters have provided you with a means to directly include an @section within your partial (by using 3rd party html helpers).
But, I reckon that, if your script is tightly coupled to your partial, just put your javascript directly inside an inline <script>
tag within your partial and be done with it (just be careful of script duplication if you intend on using the partial more than once in a single view);
Assuming that you have JAXB installed Go to the following directory C:\Program Files\jaxb\bin open command window here
> xjc -wsdl http://localhost/mywsdl/MyDWsdl.wsdl C:\Users\myname\Desktop
C:\Users\myname\Desktop is the ouput folder you can change that to your preference
http://localhost/mywsdl/MyDWsdl.wsdl is the link to the WSDL
Here's a snippet of helpful code:
using System.Diagnostics;
// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments;
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
proc.WaitForExit();
// Retrieve the app's exit code
exitCode = proc.ExitCode;
}
There is much more you can do with these objects, you should read the documentation: ProcessStartInfo, Process.
DataGridView.SelectedCells
is a collection of cells, so it's not as simple as calling ToString()
on it. You have to loop through each cell in the collection and get each cell's value instead.
The following will create a comma-delimited list of all selected cells' values.
C#
TextBox1.Text = "";
bool FirstValue = true;
foreach(DataGridViewCell cell in DataGridView1.SelectedCells)
{
if(!FirstValue)
{
TextBox1.Text += ", ";
}
TextBox1.Text += cell.Value.ToString();
FirstValue = false;
}
VB.NET (Translated from the code above)
TextBox1.Text = ""
Dim FirstValue As Boolean = True
Dim cell As DataGridViewCell
For Each cell In DataGridView1.SelectedCells
If Not FirstValue Then
TextBox1.Text += ", "
End If
TextBox1.Text += cell.Value.ToString()
FirstValue = False
Next
A couple of notes:
Apache ant doesn't know anything about JAVA_OPTS, while Tomcat's startup scripts do. For Apache ant, use ANT_OPTS to affect the environment for the JVM that runs /ant/, but not for the things that ant might launch.
The maximum heap size you can set depends entirely on the environment: for most 32-bit systems, the maximum amount of heap space you can request, regardless of available memory, is in the 2GiB range. The largest heap on a 64-bit system is "really big". Also, you are practically limited by physical memory as well, since the heap is managed by the JVM and you don't want a lot of swapping going on to the disk.
For server environments, you typically want to set -Xms and -Xmx to the same value: this will fix the size of the heap at a certain size and the garbage collector has less work to do because the heap will never have to be re-sized.
JavaScript's 'strict not equal' operator (!==
) on comparison with undefined
does not result in false
on null
values.
var createTouch = null;
isTouch = createTouch !== undefined // true
To achieve an equivalent behaviour in PHP, you can check whether the variable name exists in the keys of the result of get_defined_vars()
.
// just to simplify output format
const BR = '<br>' . PHP_EOL;
// set a global variable to test independence in local scope
$test = 1;
// test in local scope (what is working in global scope as well)
function test()
{
// is global variable found?
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test does not exist.
// is local variable found?
$test = null;
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test exists.
// try same non-null variable value as globally defined as well
$test = 1;
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test exists.
// repeat test after variable is unset
unset($test);
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.') . BR;
// $test does not exist.
}
test();
In most cases, isset($variable)
is appropriate. That is aquivalent to array_key_exists('variable', get_defined_vars()) && null !== $variable
. If you just use null !== $variable
without prechecking for existence, you will mess up your logs with warnings because that is an attempt to read the value of an undefined variable.
However, you can apply an undefined variable to a reference without any warning:
// write our own isset() function
function my_isset(&$var)
{
// here $var is defined
// and initialized to null if the given argument was not defined
return null === $var;
}
// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable); // $is_set is false
If you are looking for android apps, you can use
#00000000
For kotlin I use the following
val fcmtoken = FirebaseMessaging.getInstance().token.await()
and for the extension functions
public suspend fun <T> Task<T>.await(): T {
// fast path
if (isComplete) {
val e = exception
return if (e == null) {
if (isCanceled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
@Suppress("UNCHECKED_CAST")
result as T
}
} else {
throw e
}
}
return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
val e = exception
if (e == null) {
@Suppress("UNCHECKED_CAST")
if (isCanceled) cont.cancel() else cont.resume(result as T)
} else {
cont.resumeWithException(e)
}
}
}
}
command to change the remote url ( from https -> git@... ) is something like this
git remote set-url origin [email protected]:GitUserName/GitRepoName.git
origin here is the name of my remote ( do git remote and what comes out is your origin ).
Before you use DecimalFormat you need to use the following import or your code will not work:
import java.text.DecimalFormat;
The code for formatting is:
DecimalFormat precision = new DecimalFormat("0.00");
// dblVariable is a number variable and not a String in this case
txtTextField.setText(precision.format(dblVariable));
A little risky, but you could run a curl POST command with the values from the form from the JMX console, its URL and http authentication (if required):
curl -s -X POST --user 'myuser:mypass'
--data "action=invokeOp&name=App:service=ThisServiceOp&methodIndex=3&arg0=value1&arg1=value1&submit=Invoke"
http://yourhost.domain.com/jmx-console/HtmlAdaptor
Beware: the method index may change with changes to the software. And the implementation of the web form could change.
The above is based on source of the JMX service page for the operation you want to perform:
http://yourhost.domain.com/jmx-console/HtmlAdaptor?action=inspectMBean&name=YourJMXServiceName
Source of the form:
form method="post" action="HtmlAdaptor">
<input type="hidden" name="action" value="invokeOp">
<input type="hidden" name="name" value="App:service=ThisServiceOp">
<input type="hidden" name="methodIndex" value="3">
<hr align='left' width='80'>
<h4>void ThisOperation()</h4>
<p>Operation exposed for management</p>
<table cellspacing="2" cellpadding="2" border="1">
<tr class="OperationHeader">
<th>Param</th>
<th>ParamType</th>
<th>ParamValue</th>
<th>ParamDescription</th>
</tr>
<tr>
<td>p1</td>
<td>java.lang.String</td>
<td>
<input type="text" name="arg0">
</td>
<td>(no description)</td>
</tr>
<tr>
<td>p2</td>
<td>arg1Type</td>
<td>
<input type="text" name="arg1">
</td>
<td>(no description)</td>
</tr>
</table>
<input type="submit" value="Invoke">
</form>
If you prefer using GitHub Desktop, you can simply navigate inside the parent directory of your local repository and delete all of the files inside the parent directory. Then, commit and push your changes. Your repository will be cleansed of all files.
If you can afford working via the file data, you can do
find -mmin +14400 -delete
Some color-syntaxing enrichment can be applied with the following blockcode syntax
```json
Here goes your json object definition
```
Note: This won't prettify the json representation. To do so, one can previously rely on an external service such as jsbeautifier.org and paste the prettified result in the wiki.
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
This worked for me:
var dtFromMillisec = new Date(secs*1000);
var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.
What I am wondering is if this [os.system()] is the proper way to accomplish such a thing?
No. os.system()
is not the proper way. That's why everyone says to use subprocess
.
For more information, read http://docs.python.org/library/os.html#os.system
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.
I wrote gsudo
, a sudo
for windows: that elevates in the current console (no context switching to a new window), with a credentials cache (reduced UAC popups), and also elevates PowerShell commands.
It allows to elevate commands that require admin privileges, or the whole batch, if you want. Just prepend gsudo
before anything that needs to run elevated.
Example batch file that elevates itself using gsudo:
EDIT: New one liner version that works with any windows language and avoids whoami issues:
net session >nul 2>nul & net session >nul 2>nul || gsudo "%~f0" && exit /b || exit /b
:: This will run as admin ::
Alternative (original version):
@echo off
rem Test if current context is already elevated:
whoami /groups | findstr /b BUILTIN\Administrators | findstr /c:"Enabled group" 1> nul 2>nul && goto :isadministrator
echo You are not admin. (yet)
:: Use gsudo to launch this batch file elevated.
gsudo "%~f0"
goto end
:isadministrator
echo You are admin.
echo (Do admin stuff now).
:end
choco install gsudo
scoop install gsudo
See gsudo in action:
Using the accepted solution, I was finding that my "1.1" (when using the .floatValue conversion) would get converted to 1.10000002384186, which was not what I wanted. However, if I used the .doubleValue instead, I would get the 1.1 that I wanted.
So for example, instead of using the accepted solution, I used this instead:
var WageConversion = (Wage.text as NSString).doubleValue
In my case I did not need double-precision, but using the .floatValue was not giving me the proper result.
Just wanted to add this to the discussion in case someone else had been running into the same issue.
For sets:
var merged = new Set([...set1, ...set2, ...set3])
For maps:
var merged = new Map([...map1, ...map2, ...map3])
Note that if multiple maps have the same key, the value of the merged map will be the value of the last merging map with that key.
If you need to resume an scp transfer from local to remote, try with rsync:
rsync --partial --progress --rsh=ssh local_file user@host:remote_file
Short version, as pointed out by @aurelijus-rozenas:
rsync -P -e ssh local_file user@host:remote_file
In general the order of args for rsync is
rsync [options] SRC DEST
I think the simplest way is:
dos2unix $(find . -type f)
I don't blame you for getting frustrated about this. The best way to look at is this. There are potentially three versions of every remote branch:
refs/heads/master
)refs/remotes/...
)refs/remotes/origin/master
)refs/heads/master
)Let's start with git prune
. This removes objects that are no longer being referenced, it does not remove references. In your case, you have a local branch. That means there's a ref named random_branch_I_want_deleted
that refers to some objects that represent the history of that branch. So, by definition, git prune
will not remove random_branch_I_want_deleted
. Really, git prune
is a way to delete data that has accumulated in Git but is not being referenced by anything. In general, it doesn't affect your view of any branches.
git remote prune origin
and git fetch --prune
both operate on references under refs/remotes/...
(I'll refer to these as remote references). It doesn't affect local branches. The git remote
version is useful if you only want to remove remote references under a particular remote. Otherwise, the two do exactly the same thing. So, in short, git remote prune
and git fetch --prune
operate on number 2 above. For example, if you deleted a branch using the git web GUI and don't want it to show up in your local branch list anymore (git branch -r
), then this is the command you should use.
To remove a local branch, you should use git branch -d
(or -D
if it's not merged anywhere). FWIW, there is no git command to automatically remove the local tracking branches if a remote branch disappears.
On the above example I kept losing the values, I think that delaying the Validation will allow the new data types to be saved as part of the meta data.
On the connection Manager for 'Excel Connection Manager' set the Delay Validation to False from the Properties.
Then on the data flow Destination task for Excel set the ValidationExternalMetaData to False, again from the properties.
This will now allow you to right click on the Excel Destination Task and go to Advanced Editor for Excel Destination --> far right tab - Input and Output Properties. In the External Columns folder section you will be able to now change the Data Types and Length values of the problematic columns and this can now be saved.
Good Luck!
In your xml file just use a instead of the tag. The inflater tries to create an android.app.Fragment from which will fail on API < 10. So you need to create a view group of a different type.
A few others that have not been mentioned:
For mini pies, lines and bars, Peity is brilliant, simple, tiny, fast, uses really elegant markup.
I'm not sure of it's relationship with Flot (given its name), but Flotr2 is pretty good, certainly does better pies than Flot.
Bluff produces nice-looking line graphs, but I had a bit of trouble with its pies.
Not what I was after, but another commercial product (much like Highcharts) is TeeChart.
os.remove()
does not work on a directory, and os.rmdir()
will only work on an empty directory. And Python won't automatically expand "/home/me/test/*" like some shells do.
You can use shutil.rmtree()
on the directory to do this, however.
import shutil
shutil.rmtree('/home/me/test')
be careful as it removes the files and the sub-directories as well.
I was still getting these errors even after confirming that the correct python
and pylint
were being used from my virtual env.
Eventually I figured out that in Visual Studio Code I was A) opening my project directory, which is B) where my Python virtual environment was, but I was C) running my main Python program from two levels deeper. Those three things need to be in sync for everything to work.
Here's what I would recommend:
In Visual Studio Code, open the directory containing your main Python program. (This may or may not be the top level of the project directory.)
Select Terminal menu > New Terminal, and create an virtual environment directly inside the same directory.
python3 -m venv env
Install pylint in the virtual environment. If you select any Python file in the sidebar, Visual Studio Code will offer to do this for you. Alternatively, source env/bin/activate
then pip install pylint
.
In the blue bottom bar of the editor window, choose the Python interpreter env/bin/python
. Alternatively, go to Settings and set "Python: Python Path." This sets python.pythonPath
in Settings.json.
Guava is a pretty neat library from Google:
Joiner joiner = Joiner.on(", ");
joiner.join(sList);
var dictionary = (from x in y
select new SomeClass
{
prop1 = value1,
prop2 = value2
}
).ToDictionary(item => item.prop1);
That's assuming that SomeClass.prop1
is the desired Key
for the dictionary.
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
If you want to retain the last one of the duplicates you could use
tac a.csv | sort -u -t, -r -k1,1 |tac
Which was my requirement
here
tac
will reverse the file line by line
This is not the best practice in .NET framework (4 & +) to check equality
String.Compare(x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase) == 0
Use the following instead
String.Equals(x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase)
- Use an overload of the String.Equals method to test whether two strings are equal.
- Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.
The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:
<img src="..." onload="this.width/=2;this.onload=null;" />
The reason for the this.onload=null
addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:
<img src="..." onload="this.width/=2;" />
Which is quite succinct.
Here the defination of Rendersection from MSDN
In layout pages, renders the content of a named section.MSDN
In _layout.cs page put
@RenderSection("Bottom",false)
Here render the content of bootom section and specifies false
boolean property to specify whether the section is required or not.
@section Bottom{
This message form bottom.
}
That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.
with open('path/to/file') as infile: # try open('...', 'rb') as well
answer = [line.strip().split(',') for line in infile]
If you want the numbers as int
s:
with open('path/to/file') as infile:
answer = [[int(i) for i in line.strip().split(',')] for line in infile]
I got the same error when xampp was installed on windows 10.
www.example.com:443:0 server certificate does NOT include an ID which matches the server name
So I opened httpd-ssl.conf
file in xampp folder and changed the following line
ServerName www.example.com:443
To
ServerName localhost
And the problem was fixed.
It seems like there is permission on mobile keypad setting, so the easiest way to do this is:
editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
hope this will work
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
Use raw string literals for multi-line strings:
func main(){
multiline := `line
by line
and line
after line`
}
Raw string literals are character sequences between back quotes, as in
`foo`
. Within the quotes, any character may appear except back quote.
A significant part is that is raw literal not just multi-line and to be multi-line is not the only purpose of it.
The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning...
So escapes will not be interpreted and new lines between ticks will be real new lines.
func main(){
multiline := `line
by line \n
and line \n
after line`
// \n will be just printed.
// But new lines are there too.
fmt.Print(multiline)
}
Possibly you have long line which you want to break and you don't need new lines in it. In this case you could use string concatenation.
func main(){
multiline := "line " +
"by line " +
"and line " +
"after line"
fmt.Print(multiline) // No new lines here
}
Since " " is interpreted string literal escapes will be interpreted.
func main(){
multiline := "line " +
"by line \n" +
"and line \n" +
"after line"
fmt.Print(multiline) // New lines as interpreted \n
}
you can try below:
UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(0, cell.contentView.frame.size.height - 1.0, cell.contentView.frame.size.width, 1)];
separator.backgroundColor = myColor;
[cell.contentView addSubview:separator];
or
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"separator.png"]];
imageView.frame = CGRectMake(0, 100, 320, 1);
[customCell.contentView addSubview:imageView];
return customCell;
}
ECMAScript 6 introduced String.prototype.includes
:
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
includes
doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf
, which returns -1 when a substring cannot be found:
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
Yes, you can modify or update the values of objects in the list in your case likewise:
users.stream().forEach(u -> u.setProperty("some_value"))
However, the above statement will make updates on the source objects. Which may not be acceptable in most cases.
Luckily, we do have another way like:
List<Users> updatedUsers = users.stream().map(u -> u.setProperty("some_value")).collect(Collectors.toList());
Which returns an updated list back, without hampering the old one.
You need to have installed Microsoft Visual Studio Tools for Office (VSTO).
VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.
After that create common .NET project and add the reference to Microsoft.Office.Interop.Excel
via 'Add Reference... > Assemblies' dialog.
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Missing.Value
is a special reflection struct for unnecessary parameters replacement
In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library
. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library
, or an older version, but it is the same process to include.
For mine was caused by the imported library project, type something in build.gradle and delete it again and press sync now, the error gone.
A very simple portable solution would be, to place the following line of code somewhere in a crucial part of your code, a part of which you are sure that it will be run (for example right in the main method):
System.setProperty("javax.xml.accessExternalDTD", "all");
This sets the needed system property programmatically, without having to do tricky maven pom.xml changes (which for some reason didn't work for me).
Summary
This example assumes you always know where the apache root folder is '/var/www/' and you are trying to find the next folder path (e.g. '/var/www/my_website_folder'). Also this works from a script or the web browser which is why there is additional code.
Code PHP7
function getHtmlRootFolder(string $root = '/var/www/') {
// -- try to use DOCUMENT_ROOT first --
$ret = str_replace(' ', '', $_SERVER['DOCUMENT_ROOT']);
$ret = rtrim($ret, '/') . '/';
// -- if doesn't contain root path, find using this file's loc. path --
if (!preg_match("#".$root."#", $ret)) {
$root = rtrim($root, '/') . '/';
$root_arr = explode("/", $root);
$pwd_arr = explode("/", getcwd());
$ret = $root . $pwd_arr[count($root_arr) - 1];
}
return (preg_match("#".$root."#", $ret)) ? rtrim($ret, '/') . '/' : null;
}
Example
echo getHtmlRootFolder();
Output:
/var/www/somedir/
Details:
Basically first tries to get DOCUMENT_ROOT if it contains '/var/www/' then use it, else get the current dir (which much exist inside the project) and gets the next path value based on count of the $root path. Note: added rtrim statements to ensure the path returns ending with a '/' in all cases . It doesn't check for it requiring to be larger than /var/www/ it can also return /var/www/ as a possible response.
sort -u
will be slightly faster, because it does not need to pipe the output between two commands
also see my question on the topic: calling uniq and sort in different orders in shell
Connect to the Guest and find out the ip address:
ifconfig
example of result (ip address is 10.0.2.15):
eth0 Link encap:Ethernet HWaddr 08:00:27:AE:36:99
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
Go to Vbox instance window -> Menu -> Network adapters:
Go to host system and try it in browser:
http://127.0.0.1:8000
or your network ip address (find out on the host machine by running: ipconfig).
In this case port forwarding is not needed, the communication goes over the LAN back to the host.
On the host machine - find out your netw ip address:
ipconfig
example of result:
IP Address. . . . . . . . . . . . : 192.168.5.1
On the guest machine you can communicate directly with the host, e.g. check it with ping:
# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...
@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):
sudo ufw allow 8000
for finding out that user is new or old , Get user IP .
create a table for IPs and their visits timestamp .
check IF IP does not exists OR time()-saved_timestamp > 60*60*24 (for 1 day) ,edit the IP's timestamp to time()
(means now) and increase your view one .
else , do nothing .
FYI : user IP is stored in $_SERVER['REMOTE_ADDR']
variable
If you want to add this behaviour to a shorthand animation
property definition, the order of sub-properties is as follows
animation-name
- default none
animation-duration
- default 0s
animation-timing-function
- default ease
animation-delay
- default 0s
animation-iteration-count
- default 1
animation-direction
- default normal
animation-fill-mode
- you need to set this to forwards
animation-play-state
- default running
Therefore in the most common case, the result will be something like this
animation: colorchange 1s ease 0s 1 normal forwards;
See the MDN documentation here
The se argument from the example also isn't in the help or online documentation.
When 'se' in geom_smooth is set 'FALSE', the error shading region is not visible
Domain Driven Design is a methodology and process prescription for the development of complex systems whose focus is mapping activities, tasks, events, and data within a problem domain into the technology artifacts of a solution domain.
The emphasis of Domain Driven Design is to understand the problem domain in order to create an abstract model of the problem domain which can then be implemented in a particular set of technologies. Domain Driven Design as a methodology provides guidelines for how this model development and technology development can result in a system that meets the needs of the people using it while also being robust in the face of change in the problem domain.
The process side of Domain Driven Design involves the collaboration between domain experts, people who know the problem domain, and the design/architecture experts, people who know the solution domain. The idea is to have a shared model with shared language so that as people from these two different domains with their two different perspectives discuss the solution they are actually discussing a shared knowledge base with shared concepts.
The lack of a shared problem domain understanding between the people who need a particular system and the people who are designing and implementing the system seems to be a core impediment to successful projects. Domain Driven Design is a methodology to address this impediment.
It is more than having an object model. The focus is really about the shared communication and improving collaboration so that the actual needs within the problem domain can be discovered and an appropriate solution created to meet those needs.
Domain-Driven Design: The Good and The Challenging provides a brief overview with this comment:
DDD helps discover the top-level architecture and inform about the mechanics and dynamics of the domain that the software needs to replicate. Concretely, it means that a well done DDD analysis minimizes misunderstandings between domain experts and software architects, and it reduces the subsequent number of expensive requests for change. By splitting the domain complexity in smaller contexts, DDD avoids forcing project architects to design a bloated object model, which is where a lot of time is lost in working out implementation details — in part because the number of entities to deal with often grows beyond the size of conference-room white boards.
Also see this article Domain Driven Design for Services Architecture which provides a short example. The article provides the following thumbnail description of Domain Driven Design.
Domain Driven Design advocates modeling based on the reality of business as relevant to our use cases. As it is now getting older and hype level decreasing, many of us forget that the DDD approach really helps in understanding the problem at hand and design software towards the common understanding of the solution. When building applications, DDD talks about problems as domains and subdomains. It describes independent steps/areas of problems as bounded contexts, emphasizes a common language to talk about these problems, and adds many technical concepts, like entities, value objects and aggregate root rules to support the implementation.
Martin Fowler has written a number of articles in which Domain Driven Design as a methodology is mentioned. For instance this article, BoundedContext, provides an overview of the bounded context concept from Domain Driven Development.
In those younger days we were advised to build a unified model of the entire business, but DDD recognizes that we've learned that "total unification of the domain model for a large system will not be feasible or cost-effective" 1. So instead DDD divides up a large system into Bounded Contexts, each of which can have a unified model - essentially a way of structuring MultipleCanonicalModels.
For Mac OS X, save your CSV file in "Windows Comma Separated (.csv)" format.
I don't know if this is exactly what you want, but did you know you can use the CSS overflow
property to create scrollbars?
CSS:
div.box{
width: 200px;
height: 200px;
overflow: scroll;
}
HTML:
<div class="box">
All your text content...
</div>
In my case, simply giving the user permissions on the database fixed it.
So Right click on the database -> Click Properties -> [left hand menu] Click Permissions -> and scroll down to Backup database -> Tick "Grant"
You can try jstorage javascript plugin, it is an elegant way to maintain sessions check this http://www.jstorage.info/
include the jStorage.js script into your html
<script src="jStorage.js"></script>
Then in your javascript place the sessiontoken into the a key like this
$.jStorage.set("YOUR_KEY",session_id);
Where "YOUR_KEY" is the key using which you can access you session_id , like this:
var id = $.jStorage.get("YOUR_KEY");
Use pyplot.text()
(import matplotlib.pyplot as plt
)
import matplotlib.pyplot as plt
x=[1,2,3]
y=[9,8,7]
plt.plot(x,y)
for a,b in zip(x, y):
plt.text(a, b, str(b))
plt.show()
If your script is inside head tag in html file, try to put it inside body tag. CreateElement while script is inside head tag will give you a null warning
<head>
<title></title>
</head>
<body>
<h1>Game</h1>
<script type="text/javascript" src="script.js"></script>
</body>
In a Firebird database the AFTER myOtherColumn
does not work but you can try re-positioning the column using:
ALTER TABLE name ALTER column POSITION new_position
I guess it may work in other cases as well.
From the Microsoft documentation: Command prompt (Cmd. exe) command-line string limitation
On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters.
$(document).ready(function(){
$("#btnSubmit").bind("click",function(){$('#'+'<%=btnUpload.ClientID %>').trigger("click");return false;});
$("body, input, textarea").keypress(function(e){
if(e.which==13) $("#btnSubmit").click();
});
});
Hope this may help you!!!
This doesn't hide the button but will prevent the user from moving forward by shutting down the window.
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (e.Cancel == false)
{
Application.Current.Shutdown();
}
}
only css, quite simple I find it:
.checkmark {_x000D_
display: inline-block;_x000D_
transform: rotate(45deg);_x000D_
height: 25px;_x000D_
width: 12px;_x000D_
margin-left: 60%; _x000D_
border-bottom: 7px solid #78b13f;_x000D_
border-right: 7px solid #78b13f;_x000D_
}
_x000D_
<div class="checkmark"></div>
_x000D_
I think this is what you're looking for.
List<String> columnData = new List<String>();
using(SqlConnection connection = new SqlConnection("conn_string"))
{
connection.Open();
string query = "SELECT Column1 FROM Table1";
using(SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
columnData.Add(reader.GetString(0));
}
}
}
}
Not tested, but this should work fine.
You can use -m -c -r to make migration, model and controller.
php artisan make:model Post -m -c -r
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
another solution , you can add <br>
tag to your table
|Method name| Behavior |
|--|--|
| OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|
This works for anonymous types, ExpandoObject
, Nancy.DynamicDictionary
or anything else that can be cast to IDictionary<string, object>
.
public static bool PropertyExists(dynamic obj, string name) {
if (obj == null) return false;
if (obj is IDictionary<string, object> dict) {
return dict.ContainsKey(name);
}
return obj.GetType().GetProperty(name) != null;
}
Quick answer:
Doing list()
around a generator expression is (almost) exactly equivalent to having []
brackets around it. So yeah, you can do
>>> list((x for x in string.letters if x in (y for y in "BigMan on campus")))
But you can just as well do
>>> [x for x in string.letters if x in (y for y in "BigMan on campus")]
Yes, that will turn the generator expression into a list comprehension. It's the same thing and calling list() on it. So the way to make a generator expression into a list is to put brackets around it.
Detailed explanation:
A generator expression is a "naked" for
expression. Like so:
x*x for x in range(10)
Now, you can't stick that on a line by itself, you'll get a syntax error. But you can put parenthesis around it.
>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7485464>
This is sometimes called a generator comprehension, although I think the official name still is generator expression, there isn't really any difference, the parenthesis are only there to make the syntax valid. You do not need them if you are passing it in as the only parameter to a function for example:
>>> sorted(x*x for x in range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Basically all the other comprehensions available in Python 3 and Python 2.7 is just syntactic sugar around a generator expression. Set comprehensions:
>>> {x*x for x in range(10)}
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
>>> set(x*x for x in range(10))
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
Dict comprehensions:
>>> dict((x, x*x) for x in range(10))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> {x: x*x for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
And list comprehensions under Python 3:
>>> list(x*x for x in range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Under Python 2, list comprehensions is not just syntactic sugar. But the only difference is that x will under Python 2 leak into the namespace.
>>> x
9
While under Python 3 you'll get
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
This means that the best way to get a nice printout of the content of your generator expression in Python is to make a list comprehension out of it! However, this will obviously not work if you already have a generator object. Doing that will just make a list of one generator:
>>> foo = (x*x for x in range(10))
>>> [foo]
[<generator object <genexpr> at 0xb7559504>]
In that case you will need to call list()
:
>>> list(foo)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Although this works, but is kinda stupid:
>>> [x for x in foo]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Quoted from http://maven.apache.org/settings.html:
There are two locations where a settings.xml file may live:
The Maven install: $M2_HOME/conf/settings.xml
A user's install: ${user.home}/.m2/settings.xml
So, usually for a specific user you edit
/home/*username*/.m2/settings.xml
To set environment for all local users, you might think about changing the first path.
When there are multiple substrings to remove, one simple and effective option is to use re.sub
with a compiled pattern that involves joining all the substrings-to-remove using the regex OR (|
) pipe.
import re
to_remove = ['.good', '.bad']
strings = ['Apple.good','Orange.good','Pear.bad']
p = re.compile('|'.join(map(re.escape, to_remove))) # escape to handle metachars
[p.sub('', s) for s in strings]
# ['Apple', 'Orange', 'Pear']
java.time.Year::isLeap
I'd like to add the new java.time
way of doing this with the Year
class and isLeap
method:
java.time.Year.of(year).isLeap();
Android's preferred approach is int constants enforced with @IntDef:
public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;
@Retention(RetentionPolicy.SOURCE)
@IntDef ({GENDER_MALE, GENDER_FEMALE})
public @interface Gender{}
// Example usage...
void exampleFunc(@Gender int gender) {
switch(gender) {
case GENDER_MALE:
break;
case GENDER_FEMALE:
// TODO
break;
}
}
Docs: https://developer.android.com/studio/write/annotations.html#enum-annotations
the height of the status bar is 24dp in android 6.0
<!-- Height of the status bar -->
<dimen name="status_bar_height">24dp</dimen>
<!-- Height of the bottom navigation / system bar. -->
<dimen name="navigation_bar_height">48dp</dimen>
you can find the answer in the source code: frameworks\base\core\res\res\values\dimens.xml
You could store key/values in Redis differently to achieve this, by just adding a prefix or namespace to your keys when you store them e.g. "hset_"
Get a key/value GET hset_key
equals to HGET hset key
Add a key/value SET hset_key value
equals to HSET hset key
Get all keys KEYS hset_*
equals to HGETALL hset
Get all vals should be done in 2 ops, first get all keys KEYS hset_*
then get the value for each key
Add a key/value with TTL or expire which is the topic of question:
SET hset_key value
EXPIRE hset_key
Note: KEYS
will lookup up for matching the key in the whole database which may affect on performance especially if you have big database.
Note:
KEYS
will lookup up for matching the key in the whole database which may affect on performance especially if you have big database. while SCAN 0 MATCH hset_*
might be better as long as it doesn't block the server but still performance is an issue in case of big database.
You may create a new database for storing separately these keys that you want to expire especially if they are small set of keys.
Thanks to @DanFarrell who highlighted the performance issue related to
KEYS
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
In my case, with GitHub Desktop for Windows (as of June 2, 2016) & Android Studio 2.1:
This folder ->
C:\Users\(UserName)\AppData\Local\GitHub\PortableGit_<hash>\
Contained a BATCH file called something like 'post-install.bat'. Run this file to create a folder 'cmd' with 'git.exe' inside.
This path-->
C:\Users\(UserName)\AppData\Local\GitHub\PortableGit_<hash>\cmd\git.exe
would be the location of 'git.exe' after running the post-install script.
Resumee of Richard Fearn's answer , to make each second line gray:
jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
return c;
}
});
What you're looking for is:
if($variable === NULL) {...}
Note the ===
.
When use ==
, as you did, PHP treats NULL, false, 0, the empty string, and empty arrays as equal.
Try this;
string.Format(new CultureInfo("en-SG", false), "{0:c0}", 123423.083234);
It will convert 123423.083234 to $1,23,423 format.
I believe i have found the answer, This code converts the integer to a hex string an removes the alpha.
Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);
Note only use this code if you are sure that removing the alpha would not affect anything.
For whatever it's worth now: here is yet another solution:
display: inline-block
tabhead
)tabfull
)setTimeout(() => {/*...*/})
to execute code after render / after filling the table with results from fetch
clientWidth
) With a few tweaks, this is the method to use (for brevity / simplicity, I used d3js, the same operations can be done using plain DOM):
setTimeout(() => { // pass one cycle
d3.select('#tabfull')
.style('margin-top', (-1 * d3.select('#tabscroll').select('thead').node().getBoundingClientRect().height) + 'px')
.select('thead')
.style('visibility', 'hidden');
let widths=[]; // really rely on COMPUTED values
d3.select('#tabfull').select('thead').selectAll('th')
.each((n, i, nd) => widths.push(nd[i].clientWidth));
d3.select('#tabhead').select('thead').selectAll('th')
.each((n, i, nd) => d3.select(nd[i])
.style('padding-right', 0)
.style('padding-left', 0)
.style('width', widths[i]+'px'));
})
Waiting on render cycle has the advantage of using the browser layout engine thoughout the process - for any type of header; it's not bound to special condition or cell content lengths being somehow similar. It also adjusts correctly for visible scrollbars (like on Windows)
I've put up a codepen with a full example here: https://codepen.io/sebredhh/pen/QmJvKy
You have to override your ;
delimiter with something like $$
to avoid this kind of error.
After your function definition, you can set the delimiter back to ;
.
This should work:
DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal)
RETURNS decimal
DETERMINISTIC
BEGIN
DECLARE dist decimal;
SET dist = SQRT(x1 - y1);
RETURN dist;
END$$
DELIMITER ;
I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the SELECT 0
would be SELECT 0 FROM DUAL
)
SELECT SUM(sub.value)
FROM
(
SELECT SUM(columnA) as value FROM my_table
WHERE columnB = 1
UNION
SELECT 0 as value
) sub
Maybe this would work for postgresql too?
You may use
par(las=2) # make label text perpendicular to axis
It is written here: http://www.statmethods.net/graphs/bar.html
Use a custom UINavigationController
subclass, which implements the shouldPop
method.
In Swift:
class NavigationController: UINavigationController, UINavigationBarDelegate
{
var shouldPopHandler: (() -> Bool)?
func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool
{
if let shouldPopHandler = self.shouldPopHandler, !shouldPopHandler()
{
return false
}
self.popViewController(animated: true) // Needed!
return true
}
}
When set, your shouldPopHandler()
will be called to decide whether the controller will be pop or not. When not set it will just get popped as usual.
It is a good idea to disable UINavigationController
s interactivePopGestureRecognizer
as the gesture won't call your handler otherwise.
I found this in some other answer but eventually worked for me when I added the two answers.
import cv2
from matplotlib import pyplot as plt
import numpy as np
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
img = cv2.imread('image1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
These are the tools you see
Press the F12
In some situations you can hide the shadow by another container. Eg, if there is a DIV above and below the DIV with the shadow, you can use position: relative; z-index: 1;
on the surrounding DIVs.
In the Developer Tools in Chrome, there is a bar along the top, called the Execution Context Selector
(h/t felipe-sabino), just under the Elements, Network, Sources... tabs, that changes depending on the context of the current tab. When in the Console tab there is a dropdown in that bar that allows you to select the frame context in which the Console will operate. Select your frame in this drop down and you will find yourself in the appropriate frame context. :D
Chrome v59
Chrome v33
Chrome v32 & lower
If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.
HTML
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JS
$('button').click(function(){
$('#myModal').modal('show');
});
You need to specify the width
and height
in px
:
width: 10px; height: 10px;
In addition, you can use overflow: auto;
to prevent the horizontal scrollbar from showing.
Therefore, you may want to try the following:
<div style="width:100px; height:100px; overflow: auto;" >
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
text text text text text text text text text
</div>
Your helpful comments led me to the following solution:
class Word_Parser:
"""docstring for Word_Parser"""
def __init__(self, sentences):
self.sentences = sentences
def parser(self):
self.word_list = self.sentences.split()
word_list = []
word_list = self.word_list
return word_list
def sort_word_list(self):
self.sorted_word_list = sorted(self.sentences.split())
sorted_word_list = self.sorted_word_list
return sorted_word_list
def get_num_words(self):
self.num_words = len(self.word_list)
num_words = self.num_words
return num_words
test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.get_num_words()
print test.word_list
print test.sorted_word_list
print test.num_words
and returns: ['mary', 'had', 'a', 'little', 'lamb'] ['a', 'had', 'lamb', 'little', 'mary'] 5
Thank you all.
The details at http://net.tutsplus.com/tutorials/tools-and-tips/how-to-work-with-github-and-multiple-accounts/ linked to by mishaba work very well for me.
From that page:
$ touch ~/.ssh/config
Then edit that file to be something like this (one entry per account):
#Default GitHub
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
Host github-COMPANY
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_COMPANY
As others already pointed out you can use SharedPreferences generally but if you would like to store data encrypted it's a bit inconvenient. Fortunately, there is an easier and quicker way to encrypt data now since there is an implementation of SharedPreferences that encrypts keys and values. You can use EncryptedSharedPreferences in Android JetPack Security.
Just add AndroidX Security into your build.gradle:
implementation 'androidx.security:security-crypto:1.0.0-rc01'
And you can use it like this:
String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
// use the shared preferences and editor as you normally would
SharedPreferences.Editor editor = sharedPreferences.edit();
See more details: https://android-developers.googleblog.com/2020/02/data-encryption-on-android-with-jetpack.html
Official docs: https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences
If you can pick a reasonable maximum line length, you can seek to nearly the end of the file before you start reading.
myfile.seek(-max_line_length, os.SEEK_END)
line = myfile.readlines()[-1]
Found method to see your own html file (from here (scroll down to answer from prac): https://productforums.google.com/forum/#!topic/drive/YY_fou2vo0A)
-- use Get Link to get URL with id=... substring -- put uc instead of open in URL
A good question. Should tell you it took some time to crack this one. Here is my result.
DECLARE @TABLE TABLE
(
ID INT,
USERS VARCHAR(10),
ACTIVITY VARCHAR(10),
PAGEURL VARCHAR(10)
)
INSERT INTO @TABLE
VALUES (1, 'Me', 'act1', 'ab'),
(2, 'Me', 'act1', 'cd'),
(3, 'You', 'act2', 'xy'),
(4, 'You', 'act2', 'st')
SELECT T1.USERS, T1.ACTIVITY,
STUFF(
(
SELECT ',' + T2.PAGEURL
FROM @TABLE T2
WHERE T1.USERS = T2.USERS
FOR XML PATH ('')
),1,1,'')
FROM @TABLE T1
GROUP BY T1.USERS, T1.ACTIVITY
I think what you may be after is the CSS property touch-action. You just need a CSS rule like this:
html, body {touch-action: none;}
You will see it has pretty good support (https://caniuse.com/#feat=mdn-css_properties_touch-action_none), including Safari, as well as back to IE10.
I finally got it!
string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
request.PreAuthenticate = true;
and this is GetCredential()
private CredentialCache GetCredential()
{
string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
return credentialCache;
}
YAY!
I believe you are trying to compare two strings representing values, the function you are looking for is:
int atoi(const char *nptr);
or
long int strtol(const char *nptr, char **endptr, int base);
these functions will allow you to convert a string to an int/long int:
int val = strtol("555", NULL, 10);
and compare it to another value.
int main (int argc, char *argv[])
{
long int val = 0;
if (argc < 2)
{
fprintf(stderr, "Usage: %s number\n", argv[0]);
exit(EXIT_FAILURE);
}
val = strtol(argv[1], NULL, 10);
printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");
return 0;
}
Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.
e.g. I may have a Vehicle
class. A Car
would derive from a Vehicle
, as would a Motorbike
. I can ask each Vehicle
for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars
and Motorbikes
.
In my code I can often just deal with Vehicles
via common methods go()
, stop()
etc. When I add a new Vehicle type later (e.g. Scooter
) the majority of my code would remain oblivious to this fact, and the implementation of Scooter
alone worries about Scooter
particularities.
Consider DirectoryScanner from Apache Ant:
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
You'll need to reference ant.jar (~ 1.3 MB for ant 1.7.1).
There is another error with the forwars=d slash.
if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']
What about a helper function like this:
function makeDir($path)
{
$ret = mkdir($path); // use @mkdir if you want to suppress warnings/errors
return $ret === true || is_dir($path);
}
It will return true
if the directory was successfully created or already exists, and false
if the directory couldn't be created.
A better alternative is this (shouldn't give any warnings):
function makeDir($path)
{
return is_dir($path) || mkdir($path);
}
You should catch a HttpStatusCodeException
exception:
try {
restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
int statusCode = exception.getStatusCode().value();
...
}
I had the same problem, and non of the answers here helped my case. So after several hours of searching I found the solution for me and I hope it'll help somebody else.
This is a solution for anyone who gets the "Server Tomcat v7.0 Server at localhost failed to start." error after configuring the tomcat server in eclipse and trying to run a project on it.
After configuring the tomcat server in eclipse you need to copy the "WEB-INF" directory from your tomcat. C:\ ... %TOMCAT_HOME%\webapps\ROOT and their you will find the "WEB-INF" just copy and paste it in your WebContent folder in you eclipse project (overwrite the web.xml file).
Hope this helps.
Have you tried the __name__
attribute of the class? ie type(x).__name__
will give you the name of the class, which I think is what you want.
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:
x.__class__.__name__
You could use SQL.js which is the SQLlite lib compiled to JavaScript and store the database in the local storage introduced in HTML5.
Although a bit late, but a more compact version may be the following:
/**
* @param {string} quickCriteria Any string value to search for in the object properties.
* @param {any[]} objectArray The array of objects as the search domain
* @return {any[]} the search result
*/
onQuickSearchChangeHandler(quickCriteria, objectArray){
let quickResult = objectArray.filter(obj => Object.values(obj).some(val => val?val.toString().toLowerCase().includes(quickCriteria):false));
return quickResult;
}
It can handle falsy values like false, undefined, null and all the data types that define .toString()
method like number, boolean
etc.
I needed a more general solution to account for the possibility of multiple dictionaries in the list having the key value, and a straightforward implementation using list comprehension:
dict_indices = [i for i, d in enumerate(dict_list) if d[dict_key] == key_value]
Ok uninstall the app, but we admit that the data not must be lost? This can be resolve, upgrading versionCode and versionName and try the application in "Release" mode.
For example, this is important when we want to try the migration of our Database. We can compare the our application on play store with actual application not release yet.
If you have a form as such:
<form id="myform">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$('#myform').submit(function() {
// DO STUFF...
return true; // return false to cancel form action
});
At the moment, referencing the Google Android Map API v2 you can't run Google Maps v2 on the Android emulator; you must use a device for your tests.
nobody mentioned this
$(function() {
// place your code
});
which is a shorthand function of
$(document).ready(function() { .. });
Try using an Object, not an Array:
var test = new Object(); test[2300] = 'Some string';
This works for me!
$("#your_textarea").on('keydown', function(e){
if(e.keyCode === 13 && !e.shiftKey)
{
$('form').submit();
}
});
mklink
permissionsgit config --global core.symlinks true
Switching branches will force the recreation of missing symlinks.
Be careful, support for Symlinks in git on Windows is relatively new.
There are some bugs that still affect some git clients.
Notably, symlinks with relative (..
) paths are mangled in some programs because of a fixed regression in libgit2.
GitKraken is affected by this, for instance.
For xpath
you can use the above commands like this :
WebElement element = driver.findElement(By.xpath("enter xpath of source element here"));
WebElement target = driver.findElement(By.xpath("enter xpath of target here"));
(new Actions(driver)).dragAndDrop(element, target).perform();
For anyone who is looking a way to watch a specific file to exist in VBS:
Function bIsFileDownloaded(strPath, timeout)
Dim FSO, fileIsDownloaded
set FSO = CreateObject("Scripting.FileSystemObject")
fileIsDownloaded = false
limit = DateAdd("s", timeout, Now)
Do While Now < limit
If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
WScript.Sleep 1000
Loop
Set FSO = Nothing
bIsFileDownloaded = fileIsDownloaded
End Function
Usage:
FileName = "C:\test.txt"
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds
If fileIsDownloaded Then
WScript.Echo Now & " File is Downloaded: " & FileName
Else
WScript.Echo Now & " Timeout, file not found: " & FileName
End If
Just to review, REST
has certain properties that a developer should follow in order to make it RESTful
:
According to wikipedia:
The REST architectural style describes the following six constraints applied to the architecture, while leaving the implementation of the individual components free to design:
- Client–server: Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable.
- Stateless: The client–server communication is further constrained by no client context being stored on the server between requests.
- Cacheable: Responses must, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests.
- Layered system: A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches.
- Code on demand (optional): Servers can temporarily extend or customize the functionality of a client by the transfer of executable code.
- Uniform interface: The uniform interface between clients and servers, discussed below, simplifies and decouples the architecture, which enables each part to evolve independently. (i.e. HTTP GET, POST, PUT, PATCH, DELETE)
SO user Daniel Vasallo did a good job of laying out the responsibilities of these methods in the question Understanding REST: Verbs, error codes, and authentication:
When dealing with a Collection URI like: http://example.com/resources/
GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.
PUT: Meaning defined as "replace the entire collection with another collection".
POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.
DELETE: Meaning defined as "delete the entire collection".
Is it right to say that I can use it with a POST query? ...
Are these two queries the same? Can I use the second variant in any case or the documentation should explicitly say that I can use both GET and POST queries?
If you were writing a plain old RPC API call, they could technically interchangeable as long as the processing server side were no different between both calls. However, in order for the call to be RESTful, calling the endpoint via the GET
method should have a distinct functionality (which is to get resource(s)) from the POST
method (which is to create new resources).
Side note: there is some debate out there about whether or not POST
should also be allowed to be used to update resources... though i'm not commenting on that, I'm just telling you some people have an issue with that point.
you need to execute two queries:
One - to add the default value to the column required
ALTER TABLE 'Table_Name` ADD DEFAULT 'value' FOR 'Column_Name'
i want add default value to Column IsDeleted as below:
Example: ALTER TABLE [dbo].[Employees] ADD Default 0 for IsDeleted
Two - to alter the column value nullable to not null
ALTER TABLE 'table_name' ALTER COLUMN 'column_name' 'data_type' NOT NULL
i want to make the column IsDeleted as not null
ALTER TABLE [dbo].[Employees] Alter Column IsDeleted BIT NOT NULL
For React Native, React, and For Node project, below one is working
yarn add query-string
import queryString from 'query-string';
const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");
console.log(parsed.offset) will display 10
If you have a single column in datatable than it's simple to change datatable
to string
.
DataTable results = MyMethod.GetResults();
if(results != null && results.Rows.Count > 0) // Check datatable is null or not
{
List<string> lstring = new List<string>();
foreach(DataRow dataRow in dt.Rows)
{
lstring.Add(Convert.ToString(dataRow["ColumnName"]));
}
string mainresult = string.Join(",", lstring.ToArray()); // You can Use comma(,) or anything which you want. who connect the two string. You may leave space also.
}
Console.WriteLine (mainresult);
ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...
If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...
HTH
As Ponies says in a comment, you cannot mix OLAP functions with aggregate functions.
Perhaps it's easier to get the last completion date for each employee, and join that to a dataset containing the last completion date for each of the three targeted courses.
This is an untested idea that should hopefully put you down the right path:
SELECT employee_number,
course_code,
MAX(course_completion_date) AS max_date,
lcc.LAST_COURSE_COMPLETED
FROM employee_course_completion ecc
LEFT JOIN (
SELECT employee_number,
MAX(course_completion_date) AS LAST_COURSE_COMPLETED
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
) lcc
ON lcc.employee_number = ecc.employee_number
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code, lcc.LAST_COURSE_COMPLETED
Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:
var some_function = function(username, password)
{
return new Promise(function(resolve, reject)
{
/*stuff using username, password*/
if ( /* everything turned out fine */ )
{
resolve("Stuff worked!");
}
else
{
reject(Error("It broke"));
}
});
}
Then, use it:
some_module.some_function(username, password).then(function(uid)
{
// stuff
})
ES6:
const some_function = (username, password) =>
{
return new Promise((resolve, reject) =>
{
/*stuff using username, password*/
if ( /* everything turned out fine */ )
{
resolve("Stuff worked!");
}
else
{
reject(Error("It broke"));
}
});
};
Use:
some_module.some_function(username, password).then(uid =>
{
// stuff
});
As has already been said: figure
will create a new figure for your next plots. While calling figure
you can also configure it. Example:
figHandle = figure('Name', 'Name of Figure', 'OuterPosition',[1, 1, scrsz(3), scrsz(4)]);
The example sets the name for the window and the outer size of it in relation to the used screen.
Here figHandle
is the handle to the resulting figure and can be used later to change appearance and content. Examples:
Dot notation:
figHandle.PaperOrientation = 'portrait';
figHandle.PaperUnits = 'centimeters';
Old Style:
set(figHandle, 'PaperOrientation', 'portrait', 'PaperUnits', 'centimeters');
Using the handle with dot notation or set
, options for printing are configured here.
By keeping the handles for the figures with distinc names you can interact with multiple active figures. To set a existing figure as your active, call figure(figHandle)
. New plots will go there now.
in my case the copyright notice in the footer of a wordpress web site needed updating.
thought simple, but involved a step or more thann anticipated.
Open footer.php
in your theme's folder.
Locate copyright text, expected this to be all hard coded but found:
<div id="copyright">
<?php the_field('copyright_disclaimer', 'options'); ?>
</div>
Now we know the year is written somewhere in WordPress admin so locate that to delete the year written text. In WP-Admin, go to Options
on the left main admin menu:
Then on next page go to the tab Disclaimers
:
and near the top you will find Copyright year:
DELETE the © symbol + year + the empty space following the year, then save your page with Update
button at top-right of page.
With text version of year now delete, we can go and add our year that updates automatically with PHP. Go back to chunk of code in STEP 2 found in footer.php
and update that to this:
<div id="copyright">
©<?php echo date("Y"); ?> <?php the_field('copyright_disclaimer', 'options'); ?>
</div>
Done! Just need to test to ensure changes have taken effect as expected.
this might not be the same case for many, however we've come across this pattern among quite a number of our client sites and thought it would be best to document here.
The other answers are Ok, but a while loop seems more appropriate:
function setAll(array, value) {
var i = array.length;
while (i--) {
array[i] = value;
}
}
A more creative version:
function replaceAll(array, value) {
var re = new RegExp(value, 'g');
return new Array(++array.length).toString().replace(/,/g, value).match(re);
}
May not work everywhere though. :-)
max-height
.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}
.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}
The syntax is as follows :
import urllib3
urllib3.request.urlencode({"user" : "john" })
By default the RestTemplate relies on standard JDK facilities to establish HTTP connections. You can switch to use a different HTTP library such as Apache HttpComponents
@Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { RestTemplate restTemplate = builder.build(); return restTemplate; }
application.yml
logging: level: org.springframework.web.client.RestTemplate: DEBUG
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
public final class BufferingClientHttpResponseWrapper implements ClientHttpResponse {
private final ClientHttpResponse response;
private byte[] body;
BufferingClientHttpResponseWrapper(ClientHttpResponse response) {
this.response = response;
}
public HttpStatus getStatusCode() throws IOException {
return this.response.getStatusCode();
}
public int getRawStatusCode() throws IOException {
return this.response.getRawStatusCode();
}
public String getStatusText() throws IOException {
return this.response.getStatusText();
}
public HttpHeaders getHeaders() {
return this.response.getHeaders();
}
public InputStream getBody() throws IOException {
if (this.body == null) {
this.body = StreamUtils.copyToByteArray(this.response.getBody());
}
return new ByteArrayInputStream(this.body);
}
public void close() {
this.response.close();
}
}
package com.example.logging;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
public class LoggingRestTemplate implements ClientHttpRequestInterceptor {
private final static Logger LOGGER = LoggerFactory.getLogger(LoggingRestTemplate.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
return traceResponse(response);
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
if (!LOGGER.isDebugEnabled()) {
return;
}
LOGGER.debug(
"==========================request begin==============================================");
LOGGER.debug("URI : {}", request.getURI());
LOGGER.debug("Method : {}", request.getMethod());
LOGGER.debug("Headers : {}", request.getHeaders());
LOGGER.debug("Request body: {}", new String(body, "UTF-8"));
LOGGER.debug(
"==========================request end================================================");
}
private ClientHttpResponse traceResponse(ClientHttpResponse response) throws IOException {
if (!LOGGER.isDebugEnabled()) {
return response;
}
final ClientHttpResponse responseWrapper = new BufferingClientHttpResponseWrapper(response);
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(responseWrapper.getBody(), "UTF-8"));
String line = bufferedReader.readLine();
while (line != null) {
inputStringBuilder.append(line);
inputStringBuilder.append('\n');
line = bufferedReader.readLine();
}
LOGGER.debug(
"==========================response begin=============================================");
LOGGER.debug("Status code : {}", responseWrapper.getStatusCode());
LOGGER.debug("Status text : {}", responseWrapper.getStatusText());
LOGGER.debug("Headers : {}", responseWrapper.getHeaders());
LOGGER.debug("Response body: {}", inputStringBuilder.toString());
LOGGER.debug(
"==========================response end===============================================");
return responseWrapper;
}
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
RestTemplate restTemplate = builder.build();
restTemplate.setInterceptors(Collections.singletonList(new LoggingRestTemplate()));
return restTemplate;
}
Check the package of LoggingRestTemplate, for example in application.yml
:
logging: level: com.example.logging: DEBUG
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
RestTemplate restTemplate = builder.build();
restTemplate.setRequestFactory(new HttpComponentsAsyncClientHttpRequestFactory());
return restTemplate;
}
Check the package of LoggingRestTemplate, for example in application.yml
:
logging: level: org.apache.http: DEBUG
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
Just bind the datepicker to a class rather than binding it to the id . Remove the class when you want to revoke the datepicker...
$("#ddlSearchType").change(function () {
if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
$("#txtSearch").addClass("mydate");
$(".mydate").datepicker()
} else {
$("#txtSearch").removeClass("mydate");
}
});
I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me. I hope this helps someone.
import webbrowser
new = 2 # open in a new tab, if possible
# open a public URL, in this case, the webbrowser docs
url = "http://docs.python.org/library/webbrowser.html"
webbrowser.get(using='google-chrome').open(url,new=new)
you can use any other browser by changing the parameter 'using' as given in a link
In more recent browsers code like below may be enough.
<object data="https://www.w3.org/TR/PNG/iso_8859-1.txt" width="300" height="200">_x000D_
Not supported_x000D_
</object>
_x000D_
For me, the solution is:
Check Overwrite the existing database(WITH REPLACE) in optoins tab at left hand side.
Uncheck all other options.
Select source and destination database.
Click ok.
That's it.
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
I work primarily with Windows development machines and servers.
I just wanted to point out (at least for NET.Core 2.0 and above) the only thing needed is to execute dotnet --info
in a command prompt to get information about the latest version installed. If .NET Core is installed you will get some response.
On my development machine (Windows 10) the result is as follows. SDK is 2.1.2 and runtime is 2.0.3.
.NET Command Line Tools (2.1.2)
Product Information:
Version: 2.1.2
Commit SHA-1 hash: 5695315371
Runtime Environment:
OS Name: Windows
OS Version: 10.0.15063
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\2.1.2\
Microsoft .NET Core Shared Framework Host
Version : 2.0.3
Build : a9190d4a75f4a982ae4b4fa8d1a24526566c69df
On one of my servers running Windows Server 2016 with Windows Server Hosting pack (no SDK) result is as follows. No SDK, runtime is 2.0.3.
Microsoft .NET Core Shared Framework Host
Version : 2.0.3
Build : a9190d4a75f4a982ae4b4fa8d1a24526566c69df
Cheers !
I think you are looking for instance_of?
. is_a?
and kind_of?
will return true for instances from derived classes.
class X < String
end
foo = X.new
foo.is_a? String # true
foo.kind_of? String # true
foo.instance_of? String # false
foo.instance_of? X # true
struct Base {
virtual void f() {}
virtual ~Base() {}
};
struct Derived : Base {
void f() override {}
~Derived() override {}
};
Base* base = new Derived;
base->f(); // calls Derived::f
base->~Base(); // calls Derived::~Derived
Virtual destructor call is no different from any other virtual function call.
For base->f()
, the call will be dispatched to Derived::f()
, and it's the same for base->~Base()
- its overriding function - the Derived::~Derived()
will be called.
Same happens when destructor is being called indirectly, e.g. delete base;
. The delete
statement will call base->~Base()
which will be dispatched to Derived::~Derived()
.
If you are not going to delete object through a pointer to its base class - then there is no need to have a virtual destructor. Just make it protected
so that it won't be called accidentally:
// library.hpp
struct Base {
virtual void f() = 0;
protected:
~Base() = default;
};
void CallsF(Base& base);
// CallsF is not going to own "base" (i.e. call "delete &base;").
// It will only call Base::f() so it doesn't need to access Base::~Base.
//-------------------
// application.cpp
struct Derived : Base {
void f() override { ... }
};
int main() {
Derived derived;
CallsF(derived);
// No need for virtual destructor here as well.
}
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
If you already have all dependencies in your pom, try:
1. Remove all downloaded jars form your maven repository folder for 'org->springframework'
2. Make a maven clean build.
No there isn't, files are not line-addressable.
There is no constant-time way to find the start of line n in a text file. You must stream through the file and count newlines.
Use the simplest/fastest tool you have to do the job. To me, using head
makes much more sense than grep
, since the latter is way more complicated. I'm not saying "grep
is slow", it really isn't, but I would be surprised if it's faster than head
for this case. That'd be a bug in head
, basically.
If the user supplies invalid data, it should definitely be a 400 Bad Request
(The request contains bad syntax or cannot be fulfilled.)
From what I can see, none of the above can handle normal parameters and array parameters. Here's one that does.
function removeURLParameter(param, url) {
url = decodeURI(url).split("?");
path = url.length == 1 ? "" : url[1];
path = path.replace(new RegExp("&?"+param+"\\[\\d*\\]=[\\w]+", "g"), "");
path = path.replace(new RegExp("&?"+param+"=[\\w]+", "g"), "");
path = path.replace(/^&/, "");
return url[0] + (path.length
? "?" + path
: "");
}
function addURLParameter(param, val, url) {
if(typeof val === "object") {
// recursively add in array structure
if(val.length) {
return addURLParameter(
param + "[]",
val.splice(-1, 1)[0],
addURLParameter(param, val, url)
)
} else {
return url;
}
} else {
url = decodeURI(url).split("?");
path = url.length == 1 ? "" : url[1];
path += path.length
? "&"
: "";
path += decodeURI(param + "=" + val);
return url[0] + "?" + path;
}
}
How to use it:
url = location.href;
-> http://example.com/?tags[]=single&tags[]=promo&sold=1
url = removeURLParameter("sold", url)
-> http://example.com/?tags[]=single&tags[]=promo
url = removeURLParameter("tags", url)
-> http://example.com/
url = addURLParameter("tags", ["single", "promo"], url)
-> http://example.com/?tags[]=single&tags[]=promo
url = addURLParameter("sold", 1, url)
-> http://example.com/?tags[]=single&tags[]=promo&sold=1
Of course, to update a parameter, just remove then add. Feel free to make a dummy function for it.
First, the SSL certificates need to be installed. Instructions (based on https://stackoverflow.com/a/4454754/278488):
pushd /usr/ssl/certs
curl http://curl.haxx.se/ca/cacert.pem | awk 'split_after==1{n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1} {print > "cert" n ".pem"}'
c_rehash
The above is enough to fix curl
, but wget
requires an extra symlink:
ln -sT /usr/ssl /etc/ssl
For me the solution was totally different.
In my case I had an objectsource which required a datetimestamp parameter. Even though that ODS parameter ConvertEmptyStringToNull was true 1/1/0001 was being passed to SelectMethod. That in turn caused a sql datetime overflow exception when that datetime was passed to the sql server.
Added an additional check for datetime.year != 0001 and that solved it for me.
Weird that it would throw a transport level error and not a datetime overflow error. Anyways..
BYTE*
is probably a typedef for unsigned char*
, but I can't say for sure. It would help if you tell us what BYTE
is.
If BYTE* is unsigned char*, you can convert it to an std::string using the std::string range constructor, which will take two generic Iterators.
const BYTE* str1 = reinterpret_cast<const BYTE*> ("Hello World");
int len = strlen(reinterpret_cast<const char*>(str1));
std::string str2(str1, str1 + len);
That being said, are you sure this is a good idea? If BYTE
is unsigned char
it may contain non-ASCII characters, which can include NULLs. This will make strlen
give an incorrect length.
All of the current answers are wrong in some cases as they do not consider that timezones change their offset relative to UTC. So in some cases adding 24h is different from adding a calendar day.
The following solution works for Samoa and keeps the local time constant.
def add_day(today):
"""
Add a day to the current day.
This takes care of historic offset changes and DST.
Parameters
----------
today : timezone-aware datetime object
Returns
-------
tomorrow : timezone-aware datetime object
"""
today_utc = today.astimezone(datetime.timezone.utc)
tz = today.tzinfo
tomorrow_utc = today_utc + datetime.timedelta(days=1)
tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
minute=today.minute,
second=today.second)
return tomorrow_utc_tz
# core modules
import datetime
# 3rd party modules
import pytz
# add_day methods
def add_day(today):
"""
Add a day to the current day.
This takes care of historic offset changes and DST.
Parameters
----------
today : timezone-aware datetime object
Returns
-------
tomorrow : timezone-aware datetime object
"""
today_utc = today.astimezone(datetime.timezone.utc)
tz = today.tzinfo
tomorrow_utc = today_utc + datetime.timedelta(days=1)
tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
minute=today.minute,
second=today.second)
return tomorrow_utc_tz
def add_day_datetime_timedelta_conversion(today):
# Correct for Samoa, but dst shift
today_utc = today.astimezone(datetime.timezone.utc)
tz = today.tzinfo
tomorrow_utc = today_utc + datetime.timedelta(days=1)
tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
return tomorrow_utc_tz
def add_day_dateutil_relativedelta(today):
# WRONG!
from dateutil.relativedelta import relativedelta
return today + relativedelta(days=1)
def add_day_datetime_timedelta(today):
# WRONG!
return today + datetime.timedelta(days=1)
# Test cases
def test_samoa(add_day):
"""
Test if add_day properly increases the calendar day for Samoa.
Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
local time.
See https://stackoverflow.com/q/52084423/562769
A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
happened in Samoa.
"""
tz = pytz.timezone('Pacific/Apia')
today_utc = datetime.datetime(2011, 12, 30, 9, 59,
tzinfo=datetime.timezone.utc)
today_tz = today_utc.astimezone(tz) # 2011-12-29T23:59:00-10:00
tomorrow = add_day(today_tz)
return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'
def test_dst(add_day):
"""Test if add_day properly increases the calendar day if DST happens."""
tz = pytz.timezone('Europe/Berlin')
today_utc = datetime.datetime(2018, 3, 25, 0, 59,
tzinfo=datetime.timezone.utc)
today_tz = today_utc.astimezone(tz) # 2018-03-25T01:59:00+01:00
tomorrow = add_day(today_tz)
return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'
to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
(add_day_datetime_timedelta, 'timedelta'),
(add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
(add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
print('{:<25}: {:>5} {:>5}'
.format(name,
test_samoa(method),
test_dst(method)))
Method : Samoa DST
relativedelta : 0 0
timedelta : 0 0
timedelta+conversion : 1 0
timedelta+conversion+dst : 1 1
In java you can use setFetchSource like this :
client.prepareSearch(index).setTypes(type)
.setFetchSource(new String[] { "field1", "field2" }, null)
string result = System.Text.Encoding.UTF8.GetString(fs.ToArray());
Additionally, if you have the NDK installed, you can also find the listing in ${ndk_path}platforms\android-${api}\${architecture}\usr\include\android\keycodes.h
.
I'm only mentioning it because I've found it simpler to navigate and read than the KeyEvent class or docs.
You should be able to do this with existing bootstrap classes and a little custom styling.
<form>
<div class="input-prepend">
<span class="add-on">
<i class="icon-user"></i>
</span>
<input class="span2" id="prependedInput" type="text" placeholder="Username" style="background-color: #eeeeee;border-left: #eeeeee;">
</div>
Edit The icon is referenced via the icon-user
class. This answer was written at the time of Bootstrap version 2. You can see the reference on the following page: http://getbootstrap.com/2.3.2/base-css.html#images
Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.
Sub PasswordBreaker()
'Breaks worksheet password protection.
Dim i As Integer, j As Integer, k As Integer
Dim l As Integer, m As Integer, n As Integer
Dim i1 As Integer, i2 As Integer, i3 As Integer
Dim i4 As Integer, i5 As Integer, i6 As Integer
On Error Resume Next
For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
If ThisWorkbook.ProtectStructure = False Then
MsgBox "One usable password is " & Chr(i) & Chr(j) & _
Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
Exit Sub
End If
Next: Next: Next: Next: Next: Next
Next: Next: Next: Next: Next: Next
End Sub
Try to add type of configuration in dependency line. For example:
implementation project(path: ':some_module', **configuration: 'default'**)`
At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".
In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.
So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.
I wrote this and placed it in a test/utils
module in my project. For cases when its not a class, just plan ol' dict, this will traverse both objects and ensure
Its big... its not sexy... but oh boi does it work!
def assertObjectsEqual(obj_a, obj_b):
def _assert(a, b):
if a == b:
return
raise AssertionError(f'{a} !== {b} inside assertObjectsEqual')
def _check(a, b):
if a is None or b is None:
_assert(a, b)
for k,v in a.items():
if isinstance(v, dict):
assertObjectsEqual(v, b[k])
else:
_assert(v, b[k])
# Asserting both directions is more work
# but it ensures no dangling values on
# on either object
_check(obj_a, obj_b)
_check(obj_b, obj_a)
You can clean it up a little by removing the _assert
and just using plain ol' assert
but then the message you get when it fails is very unhelpful.
Since Spring 3.0 you can use @Primary
annotation. As per documentation:
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the element's primary attribute in Spring XML.
You should use it on Bean definition like this:
@Bean
@Primary
public ExampleBean exampleBean(@Autowired EntityManager em) {
return new ExampleBeanImpl(em);
}
or like this:
@Primary
@Service
public class ExampleService implements BaseServive {
}
You should create a method within your fragment that accepts the type of object you wish to pass into it. In this case i named it "setObject" (creative huh? :) ) That method can then perform whatever action you need with that object.
MyFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
fragment = new MyFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, detailsFragment)
.commit();
} else {
fragment = (MyFragment) getSupportFragmentManager().findFragmentById(
android.R.id.content);
}
fragment.setObject(yourObject); //create a method like this in your class "MyFragment"
}
Note that i'm using the support library and calls to getSupportFragmentManager() might be just getFragmentManager() for you depending on what you're working with
That’s probably everyone’s first thought. But it’s a little bit more difficult. See Chris Shiflett’s article SERVER_NAME
Versus HTTP_HOST
.
It seems that there is no silver bullet. Only when you force Apache to use the canonical name you will always get the right server name with SERVER_NAME
.
So you either go with that or you check the host name against a white list:
$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
exit;
}
Try this working for Firefox:
driver.manage().window.maximize();
Refer below :-
let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */
Also consider java.text.MessageFormat
, which uses a related syntax having numeric argument indexes. For example,
String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);
results in string
containing the following:
A string of ponies.
More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart
label formatting is described here; the class RCInfo
formats a game's status pane.
The minimal permissions that worked for me when running HeadObject
on any object in mybucket
:
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::mybucket/*",
"arn:aws:s3:::mybucket"
]
}
The easiest way I've found to place objects on the left is using FlowLayout.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
adding a component normally to this panel will place it on the left
Add a unique id to all your instances, i.e.
public interface Idable {
int id();
}
public class IdGenerator {
private static int id = 0;
public static synchronized int generate() { return id++; }
}
public abstract class AbstractSomething implements Idable {
private int id;
public AbstractSomething () {
this.id = IdGenerator.generate();
}
public int id() { return id; }
}
Extend from AbstractSomething and query this property. Will be safe inside a single vm (assuming no game playing with classloaders to get around statics).
It is recommended to read and write files asynchronously! and it's so easy to do in pure Swift,
here is the protocol:
protocol FileRepository {
func read(from path: String) throws -> String
func readAsync(from path: String, completion: @escaping (Result<String, Error>) -> Void)
func write(_ string: String, to path: String) throws
func writeAsync(_ string: String, to path: String, completion: @escaping (Result<Void, Error>) -> Void)
}
As you can see it allows you to read and write files synchronously or asynchronously.
Here is my implementation in Swift 5:
class DefaultFileRepository {
// MARK: Properties
let queue: DispatchQueue = .global()
let fileManager: FileManager = .default
lazy var baseURL: URL = {
try! fileManager
.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("MyFiles")
}()
// MARK: Private functions
private func doRead(from path: String) throws -> String {
let url = baseURL.appendingPathComponent(path)
var isDir: ObjCBool = false
guard fileManager.fileExists(atPath: url.path, isDirectory: &isDir) && !isDir.boolValue else {
throw ReadWriteError.doesNotExist
}
let string: String
do {
string = try String(contentsOf: url)
} catch {
throw ReadWriteError.readFailed(error)
}
return string
}
private func doWrite(_ string: String, to path: String) throws {
let url = baseURL.appendingPathComponent(path)
let folderURL = url.deletingLastPathComponent()
var isFolderDir: ObjCBool = false
if fileManager.fileExists(atPath: folderURL.path, isDirectory: &isFolderDir) {
if !isFolderDir.boolValue {
throw ReadWriteError.canNotCreateFolder
}
} else {
do {
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
} catch {
throw ReadWriteError.canNotCreateFolder
}
}
var isDir: ObjCBool = false
guard !fileManager.fileExists(atPath: url.path, isDirectory: &isDir) || !isDir.boolValue else {
throw ReadWriteError.canNotCreateFile
}
guard let data = string.data(using: .utf8) else {
throw ReadWriteError.encodingFailed
}
do {
try data.write(to: url)
} catch {
throw ReadWriteError.writeFailed(error)
}
}
}
extension DefaultFileRepository: FileRepository {
func read(from path: String) throws -> String {
try queue.sync { try self.doRead(from: path) }
}
func readAsync(from path: String, completion: @escaping (Result<String, Error>) -> Void) {
queue.async {
do {
let result = try self.doRead(from: path)
completion(.success(result))
} catch {
completion(.failure(error))
}
}
}
func write(_ string: String, to path: String) throws {
try queue.sync { try self.doWrite(string, to: path) }
}
func writeAsync(_ string: String, to path: String, completion: @escaping (Result<Void, Error>) -> Void) {
queue.async {
do {
try self.doWrite(string, to: path)
completion(.success(Void()))
} catch {
completion(.failure(error))
}
}
}
}
enum ReadWriteError: LocalizedError {
// MARK: Cases
case doesNotExist
case readFailed(Error)
case canNotCreateFolder
case canNotCreateFile
case encodingFailed
case writeFailed(Error)
}
Use getpass.getpass()
:
from getpass import getpass
password = getpass()
An optional prompt can be passed as parameter; the default is "Password: "
.
Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.
That syntax isn't valid in Oracle. You can do this:
UPDATE table1 SET table1.value = (SELECT table2.CODE
FROM table2
WHERE table1.value = table2.DESC)
WHERE table1.UPDATETYPE='blah'
AND EXISTS (SELECT table2.CODE
FROM table2
WHERE table1.value = table2.DESC);
Or you might be able to do this:
UPDATE
(SELECT table1.value as OLD, table2.CODE as NEW
FROM table1
INNER JOIN table2
ON table1.value = table2.DESC
WHERE table1.UPDATETYPE='blah'
) t
SET t.OLD = t.NEW
It depends if the inline view is considered updateable by Oracle ( To be updatable for the second statement depends on some rules listed here ).
Quite late to this party, today I had the same problem.
The right answer on macOs I think is use jenv
brew install jenv openjdk@11
jenv add /usr/local/opt/openjdk@11
And then add into Intellij IDEA as new SDK the following path:
~/.jenv/versions/11/libexec/openjdk.jdk/Contents/Home/
Need an edge-to-edge design? Drop the parent
.container
or.container-fluid
.
Still if you need to remove padding from .row
and immediate child columns you have to add the class .no-gutters
with the code from @Brian above to your own CSS file, actually it's Not 'right out of the box', check here for official details on the final Bootstrap 4 release: https://getbootstrap.com/docs/4.0/layout/grid/#no-gutters
The following worked well for me
try {
asdf
} catch {
$string_err = $_ | Out-String
}
write-host $string_err
The result of this is the following as a string instead of an ErrorRecord object
asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+ asdf
+ ~~~~
+ CategoryInfo : ObjectNotFound: (asdf:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I believe this would be most correct.
printf("%p", (void *)emp1);
printf("%p", (void *)*emp1);
printf()
is a variadic function and must be passed arguments of the right types. The standard says %p
takes void *
.
TextField( minLines: 1, maxLines: 5, maxLengthEnforced: true)
try:
git fetch origin master
git merge origin master
After to wrote this code I received other error: (non-fast-forward)
I write this code:
git fetch origin master:tmp
git rebase tmp
git push origin HEAD:master
git branch -D tmp
And resolved my problem
String a ="dgfa";
char [] c = a.toCharArray();
Arrays.sort(c);
return new String(c);
Note that this will not work as expected if it is a mixed case String (It'll put uppercase before lowercase). You can pass a comparator to the Sort method to change that.
Try this command:
git ls-files
This lists all of the files in the repository, including those that are only staged but not yet committed.
http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html
this function takes the number and precision and returns the rounded off number
float roundoff(float num,int precision)
{
int temp=(int )(num*pow(10,precision));
int num1=num*pow(10,precision+1);
temp*=10;
temp+=5;
if(num1>=temp)
num1+=10;
num1/=10;
num1*=10;
num=num1/pow(10,precision+1);
return num;
}
it converts the floating point number into int by left shifting the point and checking for the greater than five condition.
Material icons provided by google can be found here: https://design.google.com/icons/
You can download them as PNG
or SVG
in light and dark theme.
Code that is built into shared libraries should normally be position-independent code, so that the shared library can readily be loaded at (more or less) any address in memory. The -fPIC
option ensures that GCC produces such code.
Mysqli isn't installed on the new server. Run phpinfo() to confirm.
<?php
phpinfo();
The key is the margin: 0 auto; on the inner div. A proof-of-concept example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body>
<div style="background-color: blue; width: 100%;">
<div style="background-color: yellow; width: 940px; margin: 0 auto;">
Test
</div>
</div>
</body>
</html>
Using Google Closure compiler goog.require('goog.userAgent.flash') library I created this 2 functions.
boolean hasFlash()
Returns if browser has flash.
function hasFlash(){
var b = !1;
function c(a) {if (a = a.match(/[\d]+/g)) {a.length = 3;}}
(function() {
if (navigator.plugins && navigator.plugins.length) {
var a = navigator.plugins["Shockwave Flash"];
if (a && (b = !0, a.description)) {c(a.description);return;}
if (navigator.plugins["Shockwave Flash 2.0"]) {b = !0;return;}
}
if (navigator.mimeTypes && navigator.mimeTypes.length && (a = navigator.mimeTypes["application/x-shockwave-flash"], b = !(!a || !a.enabledPlugin))) {c(a.enabledPlugin.description);return;}
if ("undefined" != typeof ActiveXObject) {
try {
var d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");b = !0;c(d.GetVariable("$version"));return;
} catch (e) {}
try {
d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");b = !0;
return;
} catch (e) {}
try {
d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"), b = !0, c(d.GetVariable("$version"));
} catch (e) {}
}
})();
return b;
}
boolean isFlashVersion(version)
Returns if the flash version is greater than provided version
function isFlashVersion(version) {
var e = String.prototype.trim ? function(a) {return a.trim()} : function(a) {return /^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(a)[1]};
function f(a, b) {return a < b ? -1 : a > b ? 1 : 0};
var h = !1,l = "";
function m(a) {a = a.match(/[\d]+/g);if (!a) {return ""}a.length = 3;return a.join(".")}
(function() {
if (navigator.plugins && navigator.plugins.length) {
var a = navigator.plugins["Shockwave Flash"];
if (a && (h = !0, a.description)) {l = m(a.description);return}
if (navigator.plugins["Shockwave Flash 2.0"]) {h = !0;l = "2.0.0.11";return}
}
if (navigator.mimeTypes && navigator.mimeTypes.length && (a = navigator.mimeTypes["application/x-shockwave-flash"], h = !(!a || !a.enabledPlugin))) {l = m(a.enabledPlugin.description);return}
if ("undefined" != typeof ActiveXObject) {
try {
var b = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");h = !0;l = m(b.GetVariable("$version"));return
} catch (g) {}
try {
b = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");h = !0;l = "6.0.21";return
} catch (g) {}
try {
b = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"), h = !0, l = m(b.GetVariable("$version"))
} catch (g) {}
}
})();
var n = l;
return (function(a) {
var b = 0,g = e(String(n)).split(".");
a = e(String(a)).split(".");
for (var p = Math.max(g.length, a.length), k = 0; 0 == b && k < p; k++) {
var c = g[k] || "",d = a[k] || "";
do {
c = /(\d*)(\D*)(.*)/.exec(c) || ["", "", "", ""];d = /(\d*)(\D*)(.*)/.exec(d) || ["", "", "", ""];
if (0 == c[0].length && 0 == d[0].length) {break}
b = f(0 == c[1].length ? 0 : parseInt(c[1], 10), 0 == d[1].length ? 0 : parseInt(d[1], 10)) || f(0 == c[2].length, 0 == d[2].length) || f(c[2], d[2]);c = c[3];d = d[3]
} while (0 == b);
}
return 0 <= b
})(version)
}
From ggplot 2.2.0
labels can easily be stacked by using position = position_stack(vjust = 0.5)
in geom_text
.
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
Also note that "position_stack()
and position_fill()
now stack values in the reverse order of the grouping, which makes the default stack order match the legend."
Answer valid for older versions of ggplot
:
Here is one approach, which calculates the midpoints of the bars.
library(ggplot2)
library(plyr)
# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year),
transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)
# library(dplyr) ## If using dplyr...
# Data <- group_by(Data,Year) %>%
# mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
geom_bar(aes(fill = Category), stat="identity") +
geom_text(aes(label = Frequency, y = pos), size = 3)
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);