Depending on the encoding you wish to use:
var str = System.Text.Encoding.Default.GetString(result);
public bool SaveBase64(string Dir, string FileName, string FileType, string Base64ImageString)
{
try
{
string folder = System.Web.HttpContext.Current.Server.MapPath("~/") + Dir;
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string filePath = folder + "/" + FileName + "." + FileType;
File.WriteAllBytes(filePath, Convert.FromBase64String(Base64ImageString));
return true;
}
catch
{
return false;
}
}
The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:
http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/
try:
parent.childNodes[1].style.color = "rgb(155, 102, 102)";
Or
parent.childNodes[1].style.color = "#"+(155).toString(16)+(102).toString(16)+(102).toString(16);
I think AddRange is better implemented like so:
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection) Items.Add(i);
OnCollectionChanged(
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
It saves you a list copy. Also if you want to micro-optimise you could do adds for up to N items and if more than N items where added do a reset.
If you want to execute each command only if the previous one succeeded, then combine them using the &&
operator:
cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install
If one of the commands fails, then all other commands following it won't be executed.
If you want to execute all commands regardless of whether the previous ones failed or not, separate them with semicolons:
cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install
In your case, I think you want the first case where execution of the next command depends on the success of the previous one.
You can also put all commands in a script and execute that instead:
#! /bin/sh
cd /my_folder \
&& rm *.jar \
&& svn co path to repo \
&& mvn compile package install
(The backslashes at the end of the line are there to prevent the shell from thinking that the next line is a new command; if you omit the backslashes, you would need to write the whole command in a single line.)
Save that to a file, for example myscript
, and make it executable:
chmod +x myscript
You can now execute that script like other programs on the machine. But if you don't place it inside a directory listed in your PATH
environment variable (for example /usr/local/bin
, or on some Linux distributions ~/bin
), then you will need to specify the path to that script. If it's in the current directory, you execute it with:
./myscript
The commands in the script work the same way as the commands in the first example; the next command only executes if the previous one succeeded. For unconditional execution of all commands, simply list each command on its own line:
#! /bin/sh
cd /my_folder
rm *.jar
svn co path to repo
mvn compile package install
For me, removing WebDAV from my server caused the application to return a 503 Service Unavailable
Error message when using PUT
or DELETE
, so I re-installed it back again. I also tried completely removing .NET Framework 4.5 and reinstalling it and also tried re-registering as suggested but to no avail.
I was able to fix this by disabling WebDAV for the individual application pool, this stopped the 'bad module' error when using PUT
or DELETE
.
WebDAV Authoring Tools
in the listDisable WebDAV
in the top right.Ta daaaa!
I still left the remove items in my web.config
file.
<system.webServer>
<modules>
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
<system.webServer>
This link is where I found the instructions but it's not very clear.
Note that you may need to do something like ./gradlew <module_directory>:<module_name>:dependencies
if the module has extra directory before reach its build.gradle. When in doubt, do ./gradlew tasks --all
to check the name.
I had the same problem. I restarted my computer and the issue was resolved.
Both works. Instead of ==
you can write eq
I found the answer in the official website
$ vi ~/.profile
# add the following line
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
And now restart the terminal or type source !$
(equivalent to source ~/.profile
)
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
You can use HttpEntity to read both Body and Headers.
@RequestMapping(value = "/restURL")
public String serveRest(HttpEntity<String> httpEntity){
MultiValueMap<String, String> headers =
httpEntity.getHeaders();
Iterator<Map.Entry<String, List<String>>> s =
headers.entrySet().iterator();
while(s.hasNext()) {
Map.Entry<String, List<String>> obj = s.next();
String key = obj.getKey();
List<String> value = obj.getValue();
}
String body = httpEntity.getBody();
}
Here is the jsFillde link for the same, http://jsfiddle.net/techno2mahi/Lfw96ja6/.
This uses the directive which is available for download at http://vitalets.github.io/checklist-model/.
This is the good to have directive as your application will need this functionality much often.
The code is below:
<div class="container">
<div class="ng-scope" ng-app="app" ng-controller="Ctrl1">
<div class="col-xs-12 col-sm-6">
<h3>Multi Checkbox List Demo</h3>
<div class="well"> <!-- ngRepeat: role in roles -->
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
</label>
</div>
<br>
<button ng-click="checkAll()">check all</button>
<button ng-click="uncheckAll()">uncheck all</button>
<button ng-click="checkFirst()">check first</button>
<div>
<h3>Selected User Roles </h3>
<pre class="ng-binding">{{user.roles|json}}</pre>
</div>
<br>
<div><b/>Provided by techno2Mahi</b></div>
</div>
var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl1', function($scope) {
$scope.roles = [
'guest',
'user',
'customer',
'admin'
];
$scope.user = {
roles: ['user']
};
$scope.checkAll = function() {
$scope.user.roles = angular.copy($scope.roles);
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push('guest');
};
});
I got this error when making a request using http to a url that required https. I guess the ajax call is not handling the redirection. This is the case even with the crossDomain ajax option set to true (on JQuery 1.5.2).
How is main called?
When you are using the console application template the code will be compiled requiring a method called Main in the startup object as Main is market as entry point to the application.
By default no startup object is specified in the project propery settings and the Program class will be used by default. You can change this in the project property under the "Build" tab if you wish.
Keep in mind that which ever object you assign to be the startup object must have a method named Main in it.
How are args passed to main method
The accepted format is MyConsoleApp.exe value01 value02 etc...
The application assigns each value after each space into a separate element of the parameter array.
Thus, MyConsoleApp.exe value01 value02 will mean your args paramter has 2 elements:
[0] = "value01"
[1] = "value02"
How you parse the input values and use them is up to you.
Hope this helped.
Additional Reading:
Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send
System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:
Here is what the trace log looked like on the machine where the client certificate failed.
System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.
Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL
Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)
After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.
From the Sonatype doc:
The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.
I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.
Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!
Use the builtin function zip()
:
In Python 3:
z = list(zip(x,y))
In Python 2:
z = zip(x,y)
Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:
function showMe(e) {
// i am spammy!
alert(e.value);
}
....
<input type="text" id="foo" value="bar" onkeyup="showMe(this)" />
You should have a look on the -regextype
argument of find
, see manpage:
-regextype type
Changes the regular expression syntax understood by -regex and -iregex
tests which occur later on the command line. Currently-implemented
types are emacs (this is the default), posix-awk, posix-basic,
posix-egrep and posix-extended.
I guess the emacs
type doesn't support the [[:digit:]]
construct. I tried it with posix-extended
and it worked as expected:
find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'
This is common, you will need to do the following steps:
1- Right click on the project
2- Build path
3- Configure Build Path
4- Remove jars/projects that had moved from their old path
5- clean the project
6- build the project "if not automatically built"
7- Add the jars/projects using their new locations
Run and that is it!
The code you posted does not produce the error messages you quoted. You should provide a (small) example that actually exhibits the problem.
Number(((Math.random() * 100) + 1).toFixed(2))
this will return a random number from 1 to 100 rounded to 2 decimal places.
Here's an updated version (Swift 3.0.1) from Ben Packard's answer.
import UIKit
@IBDesignable class BorderedButton: UIButton {
@IBInspectable var borderColor: UIColor? {
didSet {
if let bColor = borderColor {
self.layer.borderColor = bColor.cgColor
}
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
override var isHighlighted: Bool {
didSet {
guard let currentBorderColor = borderColor else {
return
}
let fadedColor = currentBorderColor.withAlphaComponent(0.2).cgColor
if isHighlighted {
layer.borderColor = fadedColor
} else {
self.layer.borderColor = currentBorderColor.cgColor
let animation = CABasicAnimation(keyPath: "borderColor")
animation.fromValue = fadedColor
animation.toValue = currentBorderColor.cgColor
animation.duration = 0.4
self.layer.add(animation, forKey: "")
}
}
}
}
The resulting button can be used inside your StoryBoard thanks to the @IBDesignable
and @IBInspectable
tags.
Also the two properties defined, allow you to set the border width and color directly on interface builder and preview the result.
Other properties could be added in a similar fashion, for border radius and highlight fading time.
I used the following for a drawable image with a circular background.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@color/colorAccent"/>
</shape>
</item>
<item
android:drawable="@drawable/ic_select"
android:bottom="20dp"
android:left="20dp"
android:right="20dp"
android:top="20dp"/>
</layer-list>
Here is what it looks like
Hope that helps someone out.
You must declare the reportfile as variable for console.
Problem is all the Dokumentations you can find are not running so .. I was give 1 day of my live to find the right way ....
Example: for batch/console
cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\test.log':level=32 && C:\ffmpeg\bin\ffmpeg.exe -loglevel warning -report -i inputfile f outputfile
Exemple Javascript:
var reortlogfile = "cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\" + filename + ".log':level=32 && C:\ffmpeg\bin\ffmpeg.exe" .......;
You can change the dir and filename how ever you want.
Frank from Berlin
In order to find an iframe id ending with "iFrame" within a page containing many iframes.
jQuery(document).ready(function (){
jQuery("iframe").each(function(){
if( jQuery(this).attr('id').match(/_iFrame/) ) {
alert(jQuery(this).attr('id'));
}
});
});
Go to My computer -> right click -> system properties -> environmental variables -> Path -> add you jdk/bin to this path
C:\Program Files\Java\jdk1.8.0_211\bin
*if this not work then
In cmd set the path by using the below command
set PATH=C:\Program Files\Java\jdk1.8.0_211\bin
now the path is set now you can use the keytool
no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length
if ( $('#someDiv').length ){
}
1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.
You can specify the color
option as a list directly to the plot
function.
from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np # I find np.random.randint to be better
# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)
# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))
# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)
To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.
my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.
The last example yields the follow simple gradient of colors for me:
I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.
In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.
You can also use pd.concat
, which is particularly helpful when you are joining more than two dataframes:
bigdata = pd.concat([data1, data2], ignore_index=True, sort=False)
Right now I'm using:
TO_IGNORE=(
E201 # Whitespace after '('
E301 # Expected N blank lines, found M
E303 # Too many blank lines (pep8 gets confused by comments)
)
ARGS="--ignore `echo ${TO_IGNORE[@]} | tr ' ' ','`"
Which works, but (in the general case) will break horribly if array elements have a space in them.
(For those interested, this is a wrapper script around pep8.py)
Run the following commands:
$ git checkout mobiledevice
$ git pull origin master
This would merge all the latest commits to your branch. If the merge results in some conflicts, you'll need to fix them.
I don't know if this is the best practice but works for me.
One of other differences is kmalloc will return logical address (else you specify GPF_HIGHMEM). Logical addresses are placed in "low memory" (in the first gigabyte of physical memory) and are mapped directly to physical addresses (use __pa macro to convert it). This property implies kmalloced memory is continuous memory.
In other hand, Vmalloc is able to return virtual addresses from "high memory". These addresses cannot be converted in physical addresses in a direct fashion (you have to use virt_to_page function).
It's not enough to have just compile project("xy")
dependency.
You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).
Create a settings.gradle file in the root of your project and add this:
include ':progressfragment'
to that file. Then sync Gradle and it should work.
Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.
Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.
i.e.
var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
inventory = inventoryId
});
You could just add a toString()
method to MyClass, per http://developer.android.com/reference/android/widget/ArrayAdapter.html:
However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.
class MyClass {
@Override
public String toString() {
return "Hello, world.";
}
}
Yet another approach.
The following is now possible thanks to the recent PHP 7 version.
$theStdClass = (object) [
'a' => 'Alpha',
'b' => 'Bravo',
'c' => 'Charlie',
'd' => 'Delta',
];
$foo = new class($theStdClass) {
public function __construct($data) {
if (!is_array($data)) {
$data = (array) $data;
}
foreach ($data as $prop => $value) {
$this->{$prop} = $value;
}
}
public function word4Letter($letter) {
return $this->{$letter};
}
};
print $foo->word4Letter('a') . PHP_EOL; // Alpha
print $foo->word4Letter('b') . PHP_EOL; // Bravo
print $foo->word4Letter('c') . PHP_EOL; // Charlie
print $foo->word4Letter('d') . PHP_EOL; // Delta
print $foo->word4Letter('e') . PHP_EOL; // PHP Notice: Undefined property
In this example, $foo is being initialized as an anonymous class that takes one array or stdClass as only parameter for the constructor.
Eventually, we loop through the each items contained in the passed object and dynamically assign then to an object's property.
To make this approch event more generic, you can write an interface or a Trait that you will implement in any class where you want to be able to cast an stdClass.
Just remove css from your js fiddle, ng-show will controll it. AngularJS sets the display style to none (using an !important flag). And remove this class when it must be shown.
You could host password in a repository and then just hide the page behind hidden address, that is derived from that password. This is not a very secure way, but it is simple.
http://en.wikipedia.org/wiki/Euclidean_distance
If you have the coordinates, use the formula to calculate the distance:
var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );
If your platform supports the **
operator, you can instead use that:
const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
Here's a possible partial answer, because it only allows selecting the test scripts, not individual tests within those scripts.
And it also limited by my using legacy compatibility mode vs unittest
scripts, so not guaranteeing it would work with native pytest.
Here goes:
subset_tests_directory
.ln -s tests_directory/foo.py
ln -s tests_directory/bar.py
be careful about imports which implicitly assume files are in test_directory
. I had to fix several of those by running python foo.py
, from within subset_tests_directory
and correcting as needed.
Once the test scripts execute correctly, just cd subset_tests_directory
and pytest
there. Pytest will only pick up the scripts it sees.
Another possibility is symlinking within your current test directory, say as ln -s foo.py subset_foo.py
then pytest subset*.py
. That would avoid needing to adjust your imports, but it would clutter things up until you removed the symlinks. Worked for me as well.
I found this good article about zval in PHP, which mentioned COW too:
Copy On Write (abbreviated as ‘COW’) is a trick designed to save memory. It is used more generally in software engineering. It means that PHP will copy the memory (or allocate new memory region) when you write to a symbol, if this one was already pointing to a zval.
Invoking an empty time.Time
struct literal will return Go's zero date. Thus, for the following print statement:
fmt.Println(time.Time{})
The output is:
0001-01-01 00:00:00 +0000 UTC
For the sake of completeness, the official documentation explicitly states:
The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.
Here's a one line solution without a while loop.
The order is preserved in the resulting list.
The potential downsides are
let re = /\s*([^[:]+):\"([^"]+)"/g
let str = '[description:"aoeu" uuid:"123sth"]'
(str.match(re) || []).map(e => RegExp(re.source, re.flags).exec(e))
[ [ 'description:"aoeu"',
'description',
'aoeu',
index: 0,
input: 'description:"aoeu"',
groups: undefined ],
[ ' uuid:"123sth"',
'uuid',
'123sth',
index: 0,
input: ' uuid:"123sth"',
groups: undefined ] ]
express.bodyParser() needs to be told what type of content it is that it's parsing. Therefore, you need to make sure that when you're executing a POST request, that you're including the "Content-Type" header. Otherwise, bodyParser may not know what to do with the body of your POST request.
If you're using curl to execute a POST request containing some JSON object in the body, it would look something like this:
curl -X POST -H "Content-Type: application/json" -d @your_json_file http://localhost:xxxx/someRoute
If using another method, just be sure to set that header field using whatever convention is appropriate.
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
I found a solution:
Objective-C:
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
Swift 3+:
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
Please use below code
package com.myjava.string;
import java.util.StringTokenizer;
public class MyStrRemoveMultSpaces {
public static void main(String a[]){
String str = "String With Multiple Spaces";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}
}
To get the behavior you want you need to wait for the process to finish before you exit Main()
. To be able to tell when your process is done you need to return a Task
instead of a void
from your function, you should never return void
from a async
function unless you are working with events.
A re-written version of your program that works correctly would be
class Program { static void Main(string[] args) { Debug.WriteLine("Calling DoDownload"); var downloadTask = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); downloadTask.Wait(); //Waits for the background task to complete before finishing. } private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); } }
Because you can not await
in Main()
I had to do the Wait()
function instead. If this was a application that had a SynchronizationContext I would do await downloadTask;
instead and make the function this was being called from async
.
Another option
min.getTime() <= d.getTime() && d.getTime() <= max.getTime()
The title
attribute works on most HTML tags and is widely supported by modern browsers.
The EOF flag is only set after a read operation attempts to read past the end of the file. get()
is returning the symbolic constant traits::eof()
(which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof()
be true. If you want to check for this condition, you can do something like the following:
int ch;
while ((ch = inf.get()) != EOF) {
std::cout << static_cast<char>(ch) << "\n";
}
I found this nugget at the link following. It worked perfect for me and only took 5 seconds.
As of VirtualBox 4 they added support for expansion.
VBoxManage modifyhd filename.vdi --resize 46080
That will resize a virtual disk image to 45GB.
https://superuser.com/questions/172651/increasing-disk-space-on-virtualbox
For me, the issue was that I was using the pkg library to turn my app into an executable binary. In that case, the accepted solutions didn't work. However, using the following code solved my problem:
const NODE_ENV = (<any>process).pkg ? 'production' : process.env.NODE_ENV;
I found this solution here on GitHub.
Use geom_text
, with aes
label. You can play with hjust, vjust
to adjust text position.
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +
geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)
I think we can answer it much more succinctly. I answered a related question, and copying my answer from there
But first, an NP-hard problem is a problem for which we cannot prove that a polynomial time solution exists. NP-hardness of some "problem-P" is usually proven by converting an already proven NP-hard problem to the "problem-P" in polynomial time.
To answer the rest of question, you first need to understand which NP-hard problems are also NP-complete. If an NP-hard problem belongs to set NP, then it is NP-complete. To belong to set NP, a problem needs to be
(i) a decision problem,
(ii) the number of solutions to the problem should be finite and each solution should be of polynomial length, and
(iii) given a polynomial length solution, we should be able to say whether the answer to the problem is yes/noNow, it is easy to see that there could be many NP-hard problems that do not belong to set NP and are harder to solve. As an intuitive example, the optimization-version of traveling salesman where we need to find an actual schedule is harder than the decision-version of traveling salesman where we just need to determine whether a schedule with length <= k exists or not.
My favorite smtp server is hMailServer.
It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.
It can proxy through your gmail/yahoo/etc account or send email directly.
Once it is installed, email in xampp just works with no config changes.
MESSAGELENGHT = 39
"A normal function call using if elif and else."
if MESSAGELENGHT == 16:
Datapacket = "word"
elif MESSAGELENGHT == 8:
Datapacket = 'byte'
else:
Datapacket = 'bit'
#similarly for a oneliner expresion:
Datapacket = "word" if MESSAGELENGHT == 16 else 'byte' if MESSAGELENGHT == 8 else 'bit'
print(Datapacket)
Thanks
I'm very late to the party, but since element.lastChild.nextSibling === null
, the following seems like the most straightforward option to me:
for(var child=element.firstChild; child!==null; child=child.nextSibling) {
console.log(child);
}
I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:
/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload
If you need to do this often, you may want to use an alias. I use the following:
alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'
The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.
You can use "restart" instead of "reload" if you really want to restart the server.
First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....
Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.
PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name")
remove(int index) method of arraylist removes the element at the specified position(index) in the list. After removing arraylist items shifts any subsequent elements to the left.
Means if a arraylist contains {20,15,30,40}
I have called the method: arraylist.remove(1)
then the data 15 will be deleted and 30 & 40 these two items will be left shifted by 1.
For this reason you have to delete higher index item of arraylist first.
So..for your given situation..the code will be..
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");
int i[] = {1,3,5};
for (int j = i.length-1; j >= 0; j--) {
list.remove(i[j]);
}
Above answers are pretty sufficient. Additional to the onChange
, if you upload a file using drag and drop events, you can get the file in drop
event by accessing eventArgs.dataTransfer.files
.
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
We can do this using several ways.
int main()
{
priority_queue<int, vector<int>, greater<int> > pq;
pq.push(40);
pq.push(320);
pq.push(42);
pq.push(65);
pq.push(12);
cout<<pq.top()<<endl;
return 0;
}
struct comp
{
bool operator () (int lhs, int rhs)
{
return lhs > rhs;
}
};
int main()
{
priority_queue<int, vector<int>, comp> pq;
pq.push(40);
pq.push(320);
pq.push(42);
pq.push(65);
pq.push(12);
cout<<pq.top()<<endl;
return 0;
}
<select>
<option value="" style="display:none;"></option>
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>
There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.
Here is an example using Posh-SSH:
# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'
# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'
# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath
Some additional notes:
That should give you a decent starting point.
Note: this no longer works due to https://github.com/Homebrew/brew/pull/612
I had the same problem today. I uninstalled (unbrewed??) openssl 1.0.2 and installed 1.0.1 also with homebrew. Dotnet new/restore/run then worked fine.
Install openssl 101:
brew install homebrew/versions/openssl101
Linking:
brew link --force homebrew/versions/openssl101
You neglected to say which version of C you are concerned about. Let's assume it's this one:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
As you can see by reading the specification, the standard definitions of true
and false
are 1 and 0, yes.
If your question is about a different version of C, or about non-standard definitions for true
and false
, then ask a more specific question.
Mr. Curious was curious about this as well. In addition to the #>> '{}'
operator, in 9.6+ one can get the value of a jsonb string with the ->>
operator:
select to_jsonb('Some "text"'::TEXT)->>0;
?column?
-------------
Some "text"
(1 row)
If one has a json value, then the solution is to cast into jsonb first:
select to_json('Some "text"'::TEXT)::jsonb->>0;
?column?
-------------
Some "text"
(1 row)
As mentioned before, you can't use inline elements for styling pseudo classes. Before and after pseudo classes are states of elements, not actual elements. You could only possibly use JavaScript for this.
A HashSet
has an internal structure (hash), where items can be searched and identified quickly. The downside is that iterating through a HashSet
(or getting an item by index) is rather slow.
So why would someone want be able to know if an entry already exists in a set?
One situation where a HashSet
is useful is in getting distinct values from a list where duplicates may exist. Once an item is added to the HashSet
it is quick to determine if the item exists (Contains
operator).
Other advantages of the HashSet
are the Set operations: IntersectWith
, IsSubsetOf
, IsSupersetOf
, Overlaps
, SymmetricExceptWith
, UnionWith
.
If you are familiar with the object constraint language then you will identify these set operations. You will also see that it is one step closer to an implementation of executable UML.
The "-r" option is invalid on my systems. I had to use a different syntax for the "From" field.
-a "From: Foo Bar <[email protected]>"
Try this:
counter=0
while true; do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
break
elif [[ "$counter" -gt 20 ]]; then
echo "Counter limit reached, exit script."
exit 1
else
let counter++
echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
Explanation
break
- if files are present, it will break and allow the script to process the files.[[ "$counter" -gt 20 ]]
- if the counter variable is greater than 20, the script will exit.let counter++
- increments the counter by 1 at each pass.From Java 11 turn to a big change
Oracle will change its historical “BCL” license with a combination of an open source and commercial license
Update : 25-Aug-2019
for more details oracle-vs-openjdk
hsb.s = max != 0 ? 255 * delta / max : 0;
?
is a ternary operator. It works like an if
in conjunction with the :
!=
means not equals
So, the long form of this line would be
if (max != 0) { //if max is not zero
hsb.s = 255 * delta / max;
} else {
hsb.s = 0;
}
If you're not using gradle (creating a project from an APK, for instance), this can be done through the Android Studio UI (as of version 3.3.2):
Open Module Settings
+ Add Content Root
button (center right)OK
In my experience (with native code), as long as your .so
's are built with debug symbols and from the same absolute paths, breakpoints added in source files will be automatically recognized.
The other answers weren't working for me. Here's what I found at w3schools, assuming the div
has a height
and/or width
set.
All you need is height
and width
to exclude padding.
var height = document.getElementById('myDiv').style.height;
var width = document.getElementById('myDiv').style.width;
You downvoters: This answer has helped at least 5 people, judging by the upvotes I've received. If you don't like it, tell me why so I can fix it. That's my biggest pet peeve with downvotes; you rarely tell me why you downvote it.
You can do it in a beginners style by using control statements and loops..
#include <iostream>
using namespace std;
int main(){
int arr[] = {10,20,30,40,50}, toFind= 10, notFound = -1;
for(int i = 0; i<=sizeof(arr); i++){
if(arr[i] == toFind){
cout<< "Element is found at " <<i <<" index" <<endl;
return 0;
}
}
cout<<notFound<<endl;
}
Well, I would store instead a string concatenation of Locale.getISO3Language()
, getISO3Country()
and getVariant() as key, which would allow me to latter call Locale(String language, String country, String variant)
constructor.
indeed, relying of displayLanguage implies using the langage of locale to display it, which make it locale dependant, contrary to iso language code.
As an example, en locale key would be storable as
en_EN
en_US
and so on ...
I have answered this question here..Covariant virtual functions return type problem
See if it helps for some one.
Recursion as it applies to programming is basically calling a function from inside its own definition (inside itself), with different parameters so as to accomplish a task.
Apart from using AsyncTask you can put the operation in runnable-
Runnable r=new Runnable()
{
public void run()
{
///-------network operation code
}
};
//--------call r in this way--
Thread t=new Thread(r);`enter code here`
t.start();
Also put the UI work in a haldler..such as updating a textview etc..
I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.
map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });
<div id="map_canvas2" style="width: 850px; height: 600px">
</div>
Replacement for Apple's Reachability re-written in Swift with closures, inspired by tonymillion: https://github.com/ashleymills/Reachability.swift
Drop the file Reachability.swift
into your project. Alternatively, use CocoaPods or Carthage - See the Installation section of the project's README.
Get notifications about network connectivity:
//declare this property where it won't go out of scope relative to your listener
let reachability = Reachability()!
reachability.whenReachable = { reachability in
if reachability.isReachableViaWiFi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
reachability.whenUnreachable = { _ in
print("Not reachable")
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
and for stopping notifications
reachability.stopNotifier()
I had a similar problem but using IntelliJ IDEA rather than Eclipse. I already had the ARM EABI installed, but I still got the error.
For IntelliJ IDEA, it appears you also have to create an AVB first before running the emulator, so to do this you must just go into Android SDK Manager and create a new AVB. This should solve your problem... Please make sure you have followed the above answer to include the ARM before following these steps.
Checkbox image was overlapping when I used my own drawables from selector, I have solve this using below code :
CheckBox cb = new CheckBox(mActivity);
cb.setText("Hi");
cb.setButtonDrawable(R.drawable.check_box_selector);
cb.setChecked(true);
cb.setPadding(cb.getPaddingLeft(), padding, padding, padding);
Thanks to Alex Semeniuk
I always use Gliffy works perfectly and does lots of things including class diagrams.
Run PowerShell and type:
gci -Path "C:\Program Files*\Microsoft SQL Server" -Recurse -Include "Ssms.exe" | Select -ExpandProperty FullName
You need to change source to viewmodel object:
myBinding.Source = viewModelObject;
Originally we used no-cache many years ago and did run into some problems with stale content with certain browsers... Don't remember the specifics unfortunately.
We had since settled on JUST the use of no-store. Have never looked back or had a single issue with stale content by any browser or intermediaries since.
This space is certainly dominated by reality of implementations vs what happens to have been written in various RFCs. Many proxies in particular tend to think they do a better job of "improving performance" by replacing the policy they are supposed to be following with their own.
For some reason @Alejandro Gracia answer starts working only after a few second.
I found a solution that blocks the RecyclerView instantaneously:
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return true;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
This is implementation dependent:
Standard 23.1.2.8:
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
Maybe you could try this -- this is standard conforming:
for (auto it = numbers.begin(); it != numbers.end(); ) {
if (*it % 2 == 0) {
numbers.erase(it++);
}
else {
++it;
}
}
Note that it++ is postfix, hence it passes the old position to erase, but first jumps to a newer one due to the operator.
2015.10.27 update:
C++11 has resolved the defect. iterator erase (const_iterator position);
return an iterator to the element that follows the last element removed (or set::end
, if the last element was removed). So C++11 style is:
for (auto it = numbers.begin(); it != numbers.end(); ) {
if (*it % 2 == 0) {
it = numbers.erase(it);
}
else {
++it;
}
}
Yes. By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\
, but after that, if it doesn't find the view, it checks in \Views\Shared
.
The shared directory is there specifically to share Views across multiple controllers. Just add your View to the Shared subdirectory and you're good to go.
If you do return View("~/Views/Wherever/SomeDir/MyView.aspx")
You can return any View you'd like.
I have recently done something similar to this using the "Haversine Formula" on WGS-84 data, which is a derivative of the "Law of Haversines" with very satisfying results.
Yes, WGS-84 assumes the Earth is an ellipsoid, but I believe you only get about a 0.5% average error using an approach like the "Haversine Formula", which may be an acceptable amount of error in your case. You will always have some amount of error unless you're talking about a distance of a few feet and even then there is theoretically curvature of the Earth... If you require a more rigidly WGS-84 compatible approach checkout the "Vincenty Formula."
I understand where starblue is coming from, but good software engineering is often about trade-offs, so it all depends on the accuracy you require for what you are doing. For example, the result calculated from "Manhattan Distance Formula" versus the result from the "Distance Formula" can be better for certain situations as it is computationally less expensive. Think "which point is closest?" scenarios where you don't need a precise distance measurement.
Regarding, the "Haversine Formula" it is easy to implement and is nice because it is using "Spherical Trigonometry" instead of a "Law of Cosines" based approach which is based on two-dimensional trigonometry, therefore you get a nice balance of accuracy over complexity.
A gentleman by the name of Chris Veness has a great website that explains some of the concepts you are interested in and demonstrates various programmatic implementations; this should answer your x/y conversion question as well.
This seems to work for me:
>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True
One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
There are two problems with your xpath - first you need to remove the child selector from after Data
like phihag mentioned. Also you forgot to include root
in your xpath. Here is what you want to do:
select="/root/DataSet/Data[@Value1='2']/@Value2"
Simply difference between Forward
(ServletRequest request, ServletResponse response) and sendRedirect
(String url) is
forward():
forward()
method is executed in the server side.forward ()
method is provided by the servlet container.sendRedirect()
method.RequestDispatcher
interface.sendRedirect():
sendRedirect()
method is executed in the client side.sendRedirect()
method is provided under HTTP
so it can be used only with HTTP
clients.sendRedirect()
method is slower because when new request is created old request object is lost.HttpServletResponse
.Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.
Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103)
Using array_walk
$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");
$r=array();
array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));
echo implode(', ', $r);
I use to use the Do, Loop a lot but I have started using a Sub or a Function that I could exit out of instead. It just seemed cleaner to me. If any variables you need are not global you will need to pass them to the Sub also.
For i=1 to N
DoWork i
Next
Sub DoWork(i)
[Code]
If Condition1 Then
Exit Sub
End If
[MoreCode]
If Condition2 Then
Exit Sub
End If
[MoreCode]
If Condition2 Then
Exit Sub
End If
[...]
End Sub
SELECT * FROM table
where Date(col) = 'date'
If I'm setting a value and I know it will always be one line of code to do so, I typically use the ternary (conditional) operator. If there's a chance my code and logic will change in the future, I use an if/else as it's more clear to other programmers.
Of further interest to you may be the ?? operator.
If you would like to monitor the changes each time there is a keystroke on the keyboard.
const textarea = document.querySelector(`#string`)
textarea.addEventListener("keydown", (e) =>{
console.log('test')
})
I had a similar problem using android 5.0 with a bad parent activity name
<activity
android:name=".DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
I removed the com.example.myfirstapp from the parent activity name and it worked properly
On top of the already provided answers there is a very nice pattern in Python that allows you to enumerate both keys and values of a dictionary.
The normal case you enumerate the keys of the dictionary:
example_dict = {1:'a', 2:'b', 3:'c', 4:'d'}
for i, k in enumerate(example_dict):
print(i, k)
Which outputs:
0 1
1 2
2 3
3 4
But if you want to enumerate through both keys and values this is the way:
for i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
Which outputs:
0 1 a
1 2 b
2 3 c
3 4 d
In Python 3, map
returns an iterable object of type map
, and not a subscriptible list, which would allow you to write map[i]
. To force a list result, write
payIntList = list(map(int,payList))
However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:
payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
print(pi)
Do you mean something like history.go(-1);
? It will go back to the previous page.
These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
You can use PSCP to copy files from Windows to Linux.
Type command pscp source_file user@host:destination_file
pscp sample.txt [email protected]:/mydata/sample.txt
If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html
If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.
The simplest Hello World example...
$hello = "Hello World"
$hello | Out-File c:\debug.txt
Try using asapp:
npm install --save asapp
https://www.npmjs.com/package/asapp
var { controller, helper, middleware, route, schema, model, APP, ROOT } = require('asapp')
controller('home')
instead require('../../controllers/home)
In Python/Spark we can do:
def quiet_logs( sc ):
logger = sc._jvm.org.apache.log4j
logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR )
logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR )
The after defining Sparkcontaxt 'sc' call this function by : quiet_logs( sc )
You can also do it like this:
var tt="88,9827";
tt=tt.replace(",", ".");
alert(tt);
Well, its true that we can use Vb Script for what you intended to do. We can open an application through the code like Internet Explorer. We can navigate to site you intend for. Later we can check the element names of Text Boxes which require username and password; can set then and then Login. It works fine all of using code.
No manual interaction with the website. And eventually you will end up signing in by just double clicking the file.
To get you started :
Set objIE = CreateObject("InternetExplorer.Application")
Call objIE.Navigate("https://gmail.com")
This will open an instance of internet explore and navigate to gmail. Rest you can learn and apply.
You can use the next code:
JS
function showname () {
var name = document.getElementById('fileInput');
alert('Selected file: ' + name.files.item(0).name);
alert('Selected file: ' + name.files.item(0).size);
alert('Selected file: ' + name.files.item(0).type);
};
HTML
<body>
<p>
<input type="file" id="fileInput" multiple onchange="showname()"/>
</p>
</body>
You really should try to use screen
. It is a bit more complicated than just doing nohup long_running &
, but understanding screen once you never come back again.
Start your screen session at first:
user@host:~$ screen
Run anything you want:
wget http://mirror.yandex.ru/centos/4.6/isos/i386/CentOS-4.6-i386-binDVD.iso
Press ctrl+A and then d. Done. Your session keeps going on in background.
You can list all sessions by screen -ls
, and attach to some by screen -r 20673.pts-0.srv
command, where 0673.pts-0.srv is an entry list.
By default Vagrant uses a generated private key to login, you can try this:
ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1
Thanks to hobs for his comment on Alex's answer. Indeed update({'k1': 1}, {'k1': {'k2': 2}})
will cause TypeError: 'int' object does not support item assignment.
We should check the types of the input values at the beginning of the function. So, I suggest the following function, which should solve this (and other) problem.
Python 3:
from collections.abc import Mapping
def deep_update(d1, d2):
if all((isinstance(d, Mapping) for d in (d1, d2))):
for k, v in d2.items():
d1[k] = deep_update(d1.get(k), v)
return d1
return d2
The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.
If you are supposed to get a JSON Object you can just put:
JSONObject myObject = new JSONObject(result);
I would suggest keeping a reference within the activity to the Menu object you receive in onCreateOptionsMenu and then using that to retrieve the MenuItem that requires the change as and when you need it. For example, you could do something along the lines of the following:
public class YourActivity extends Activity {
private Menu menu;
private String inBedMenuTitle = "Set to 'In bed'";
private String outOfBedMenuTitle = "Set to 'Out of bed'";
private boolean inBed = false;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Create your menu...
this.menu = menu;
return true;
}
private void updateMenuTitles() {
MenuItem bedMenuItem = menu.findItem(R.id.bedSwitch);
if (inBed) {
bedMenuItem.setTitle(outOfBedMenuTitle);
} else {
bedMenuItem.setTitle(inBedMenuTitle);
}
}
}
Alternatively, you can override onPrepareOptionsMenu to update the menu items each time the menu is displayed.
//This will sort your array
function SortByName(a, b){
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
array.sort(SortByName);
function trimRegex(str, regex){
return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}
let test = '||ab||cd||';
trimRegex(test, /[^|]/);
console.log(test); //output: ab||cd
or
function trimChar(str, trim, req){
let regex = new RegExp('[^'+trim+']');
return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}
let test = '||ab||cd||';
trimChar(test, '|');
console.log(test); //output: ab||cd
I restarted my phone after uninstalling the app and it worked
You can either loop through the rows with a cursor and append to a field in a temp table, or you could use the COALESCE function to concatenate the fields.
select * from table limit 5 offset (select count(*) from table) - 5;
It is ok for sure. With just few hundred of entries, it will be fast.
You can add an unique id as as primary key (int autoincrement) ans set your coupon_code as unique. So if you need to do request in other tables it's better to use int than varchar
Here is an example on how to center an object vertically with jQuery:
var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2 + 'px');
But you could easily change that to whatever your needs are.
How about Netbeans, here is an article how to set it up with NB7:
http://netbeanside61.blogspot.com/2011/06/downloading-openjdk7-binary-for-mac-os.html
Maybe similar steps for Eclipse.
You're looking for Enumerable#select (also called find_all
):
@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
# { "age" => 50, "father" => "Batman" } ]
Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers
] for which block is not false."
In normal situations the following should work:
var can = CanvasElement.getContext('2d'); //get context
var lineHeight = /[0-9]+(?=pt|px)/.exec(can.font); //get height from font variable
The best I've seen so far is HtmlCleaner:
HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.
With HtmlCleaner you can locate any element using XPath.
For other html parsers see this SO question.
I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:
public void LogEmployees (IEnumerable<dynamic> list)
{
foreach (dynamic item in list)
{
string name = item.Name;
int id = item.Id;
}
}
Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.
This is because you are adding your <tbody>
tag before <td>
in table you cannot print any data without <td>
.
So for that you have to make a <div>
say #header
with position: fixed;
header
{
position: fixed;
}
make another <div>
which will act as <tbody>
tbody
{
overflow:scroll;
}
Now your header is fixed and the body will scroll. And the header will remain there.
<html>
<head>
<meta charset="utf-8">
<title>Best Login Page design in html and css</title>
<style type="text/css">
body {
background-color: #f4f4f4;
color: #5a5656;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
font-size: 16px;
line-height: 1.5em;
}
a { text-decoration: none; }
h1 { font-size: 1em; }
h1, p {
margin-bottom: 10px;
}
strong {
font-weight: bold;
}
.uppercase { text-transform: uppercase; }
/* ---------- LOGIN ---------- */
#login {
margin: 50px auto;
width: 300px;
}
form fieldset input[type="text"], input[type="password"] {
background-color: #e5e5e5;
border: none;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
color: #5a5656;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
font-size: 14px;
height: 50px;
outline: none;
padding: 0px 10px;
width: 280px;
-webkit-appearance:none;
}
form fieldset input[type="submit"] {
background-color: #008dde;
border: none;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
color: #f4f4f4;
cursor: pointer;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
height: 50px;
text-transform: uppercase;
width: 300px;
-webkit-appearance:none;
}
form fieldset a {
color: #5a5656;
font-size: 10px;
}
form fieldset a:hover { text-decoration: underline; }
.btn-round {
background-color: #5a5656;
border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
color: #f4f4f4;
display: block;
font-size: 12px;
height: 50px;
line-height: 50px;
margin: 30px 125px;
text-align: center;
text-transform: uppercase;
width: 50px;
}
.facebook-before {
background-color: #0064ab;
border-radius: 3px 0px 0px 3px;
-moz-border-radius: 3px 0px 0px 3px;
-webkit-border-radius: 3px 0px 0px 3px;
color: #f4f4f4;
display: block;
float: left;
height: 50px;
line-height: 50px;
text-align: center;
width: 50px;
}
.facebook {
background-color: #0079ce;
border: none;
border-radius: 0px 3px 3px 0px;
-moz-border-radius: 0px 3px 3px 0px;
-webkit-border-radius: 0px 3px 3px 0px;
color: #f4f4f4;
cursor: pointer;
height: 50px;
text-transform: uppercase;
width: 250px;
}
.twitter-before {
background-color: #189bcb;
border-radius: 3px 0px 0px 3px;
-moz-border-radius: 3px 0px 0px 3px;
-webkit-border-radius: 3px 0px 0px 3px;
color: #f4f4f4;
display: block;
float: left;
height: 50px;
line-height: 50px;
text-align: center;
width: 50px;
}
.twitter {
background-color: #1bb2e9;
border: none;
border-radius: 0px 3px 3px 0px;
-moz-border-radius: 0px 3px 3px 0px;
-webkit-border-radius: 0px 3px 3px 0px;
color: #f4f4f4;
cursor: pointer;
height: 50px;
text-transform: uppercase;
width: 250px;
}
</style>
</head>
<body>
<div id="login">
<h1><strong>Welcome.</strong> Please login.</h1>
<form action="javascript:void(0);" method="get">
<fieldset>
<p><input type="text" required value="Username" onBlur="if(this.value=='')this.value='Username'" onFocus="if(this.value=='Username')this.value='' "></p>
<p><input type="password" required value="Password" onBlur="if(this.value=='')this.value='Password'" onFocus="if(this.value=='Password')this.value='' "></p>
<p><a href="#">Forgot Password?</a></p>
<p><input type="submit" value="Login"></p>
</fieldset>
</form>
<p><span class="btn-round">or</span></p>
<p>
<a class="facebook-before"></a>
<button class="facebook">Login Using Facbook</button>
</p>
<p>
<a class="twitter-before"></a>
<button class="twitter">Login Using Twitter</button>
</p>
</div> <!-- end login -->
</body>
</html>
For instance if you want random access to noncontiguous data.
p -> [p0, p1, p2, ...]
p0 -> data1
p1 -> data2
-- in C
T ** p = (T **) malloc(sizeof(T*) * n);
p[0] = (T*) malloc(sizeof(T));
p[1] = (T*) malloc(sizeof(T));
You store a pointer p
that points to an array of pointers. Each pointer points to a piece of data.
If sizeof(T)
is big it may not be possible to allocate a contiguous block (ie using malloc) of sizeof(T) * n
bytes.
Mini snippet:
var speedtest = {};
function speedTest_start(name) { speedtest[name]= +new Date(); }
function speedTest_stop(name) { return +new Date() - speedtest[name] + (delete
speedtest[name]?0:0); }
use like:
speedTest_start("test1");
// ... some code
speedTest_stop("test1");
// returns the time duration in ms
Also more tests possible:
speedTest_start("whole");
// ... some code
speedTest_start("part");
// ... some code
speedTest_stop("part");
// returns the time duration in ms of "part"
// ... some code
speedTest_stop("whole");
// returns the time duration in ms of "whole"
In case someone stumbles upon this, in Django 2.0.2
you can use this
Thousand separator. Be sure to read format localization as well.
If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:
(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),
You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:
(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),
This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
I would do it something along these lines:
class Foo{
...
};
int main(){
Foo* arrayOfFoo[100]; //[1]
arrayOfFoo[0] = new Foo; //[2]
}
[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.
[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.
There's also the PHP UML tool available from pear.
PHP_UML:
Install it on the command line via:
$ pear install pear/php_uml
(This used to be $ pear install pear/php_uml-alpha
but the package has since gone stable.)
Generate your xmi:
$ phpuml -o project.xmi
Using the Random Class
public static void randomizeArray(int[] arr) {
Random rGenerator = new Random(); // Create an instance of the random class
for (int i =0; i< arr.length;i++ ) {
//Swap the positions...
int rPosition = rGenerator.nextInt(arr.length); // Generates an integer within the range (Any number from 0 - arr.length)
int temp = arr[i]; // variable temp saves the value of the current array index;
arr[i] = arr[rPosition]; // array at the current position (i) get the value of the random generated
arr[rPosition] = temp; // the array at the position of random generated gets the value of temp
}
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i]); //Prints out the array
}
}
Only stopped containers can be listed using:
docker ps --filter "status=exited"
or
docker ps -f "status=exited"
Run clean command:
# Remove all untracked files and directories. (`-f` is `force`, `-d` is `remove directories`)
git clean -fd
Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket
Try numpy.clip
:
>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
You can clip only the bottom half with clip(0)
.
>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])
You can clip only the top half with clip(max=n)
. (This is much better than my previous suggestion, which involved passing NaN
to the first parameter and using out
to coerce the type.):
>>> a.clip(max=2)
array([ 1, 2, 2, -4, 2])
Another interesting approach is to use where
:
>>> numpy.where(a <= 2, a, 2)
array([ 1, 2, 2, -4, 2])
Finally, consider aix's answer. I prefer clip
for simple operations because it's self-documenting, but his answer is preferable for more complex operations.
If you just want to throw away everything in your working folder (eg the results of a failed or aborted merge) and revert to a clean previous commit, do a git reset --hard
.
C does not have its own String data type like Java.
Only we can declare String datatype in C using character array or character pointer For example :
char message[10];
or
char *message;
But you need to declare at least:
char message[14];
to copy "Hello, world!" into message variable.
Simply use
sp_restoredb 'Your Database Name' ,'Location From you want to restore'
Example: sp_restoredb 'omDB','D:\abc.bak'
Step1. $ cd [your working path of code]
Step2. $ svn commit [your server path ] -m 'Add commit message'
For help use $ svn help commit
Use this :
private string GetAlbumRSS(SyndicationItem album)
{
string url = "";
foreach (SyndicationElementExtension ext in album.ElementExtensions)
if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
return (url);
}
protected void Page_Load(object sender, EventArgs e)
{
string albumRSS;
string url = "http://www.SomeSite.com/rss?";
XmlReader r = XmlReader.Create(url);
SyndicationFeed albums = SyndicationFeed.Load(r);
r.Close();
foreach (SyndicationItem album in albums.Items)
{
cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
albumRSS = GetAlbumRSS(album);
}
}
$enter_string = '<textarea style="color:#FF0000;" name="message">EXAMPLE</textarea>';
echo('Echo as HTML' . htmlspecialchars((string)$enter_string));
On the basis of the question's title, "Resolve promises one after another (i.e. in sequence)?", we might understand that the OP is more interested in the sequential handling of promises on settlement than sequential calls per se.
This answer is offered :
If concurrent calls are genuinely not wanted then see Benjamin Gruenbaum's answer which covers sequential calls (etc) comprehensively.
If however, you are interested (for improved performance) in patterns which allow concurrent calls followed by sequential handling of responses, then please read on.
It's tempting to think you have to use Promise.all(arr.map(fn)).then(fn)
(as I have done many times) or a Promise lib's fancy sugar (notably Bluebird's), however (with credit to this article) an arr.map(fn).reduce(fn)
pattern will do the job, with the advantages that it :
.then()
is used.Here it is, written for Q
.
var readFiles = function(files) {
return files.map(readFile) //Make calls in parallel.
.reduce(function(sequence, filePromise) {
return sequence.then(function() {
return filePromise;
}).then(function(file) {
//Do stuff with file ... in the correct sequence!
}, function(error) {
console.log(error); //optional
return sequence;//skip-over-error. To stop-on-error, `return error` (jQuery), or `throw error` (Promises/A+).
});
}, Q()).then(function() {
// all done.
});
};
Note: only that one fragment, Q()
, is specific to Q. For jQuery you need to ensure that readFile() returns a jQuery promise. With A+ libs, foreign promises will be assimilated.
The key here is the reduction's sequence
promise, which sequences the handling of the readFile
promises but not their creation.
And once you have absorbed that, it's maybe slightly mind-blowing when you realise that the .map()
stage isn't actually necessary! The whole job, parallel calls plus serial handling in the correct order, can be achieved with reduce()
alone, plus the added advantage of further flexibility to :
Here it is, for Q
again.
var readFiles = function(files) {
return files.reduce(function(sequence, f) {
var filePromise = readFile(f);//Make calls in parallel. To call sequentially, move this line down one.
return sequence.then(function() {
return filePromise;
}).then(function(file) {
//Do stuff with file ... in the correct sequence!
}, function(error) {
console.log(error); //optional
return sequence;//Skip over any errors. To stop-on-error, `return error` (jQuery), or `throw error` (Promises/A+).
});
}, Q()).then(function() {
// all done.
});
};
That's the basic pattern. If you wanted also to deliver data (eg the files or some transform of them) to the caller, you would need a mild variant.
I suggest this ugly method but it works:
length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)
I came here to find a lighter solution than this one!
Adding this to your code android:focusableInTouchMode="true"
will make sure that your keypad doesn't appear on startup for your edittext box. You want to add this line to your linear layout that contains the EditTextBox. You should be able to play with this to solve both your problems. I have tested this. Simple solution.
ie: In your app_list_view.xml file
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:focusableInTouchMode="true">
<EditText
android:id="@+id/filter_edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="@id/android:list"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:layout_width="fill_parent"
android:focusable="true"
android:descendantFocusability="beforeDescendants"/>
</LinearLayout>
------------------ EDIT: To Make keyboard appear on startup -----------------------
This is to make they Keyboard appear on the username edittextbox on startup. All I've done is added an empty Scrollview to the bottom of the .xml file, this puts the first edittext into focus and pops up the keyboard. I admit this is a hack, but I am assuming you just want this to work. I've tested it, and it works fine.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="20dip"
android:paddingRight="20dip">
<EditText
android:id="@+id/userName"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
/>
<EditText
android:id="@+id/password"
android:password="true"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Password" />
<ScrollView
android:id="@+id/ScrollView01"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</ScrollView>
</LinearLayout>
If you are looking for a more eloquent solution, I've found this question which might help you out, it is not as simple as the solution above but probably a better solution. I haven't tested it but it apparently works. I think it is similar to the solution you've tried which didn't work for you though.
Hope this is what you are looking for.
Cheers!
I had the same problem. This problem is easily solved if you issue the Cleanup command from AnkhSVN.
The dateTime.AddDays(-1)
does not subtract that one day from the dateTime
reference. It will return a new instance, with that one day subtracted from the original reference.
DateTime dateTime = DateTime.Now;
DateTime otherDateTime = dateTime.AddDays(-1);
For anyone else reading this looking to disable this via GPO for all users, this is the setting:
Computer Configuration/Administrative Templates/Windows Components/Internet Explorer/Compatibility View/Turn on Internet Explorer Standards Mode for Local Intranet
although the web.config edit fixed it for me.
If you want to select only one of two nodes with union operator, you can use this solution:
(//bookstore/book/title | //bookstore/city/zipcode/title)[1]
var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);
var first = month.AddMonths(-1);
var last = month.AddDays(-1);
In-line them if you really need one or two lines.
//return timestamp, use to format month, year as per requirement
function getMonthYear($beforeMonth = '') {
if($beforeMonth !="" && $beforeMonth >= 1) {
$date = date('Y')."-".date('m')."-15";
$timestamp_before = strtotime( $date . ' -'.$beforeMonth.' month' );
return $timestamp_before;
} else {
$time= time();
return $time;
}
}
//call function
$month_year = date("Y-m",getMonthYear(1));// last month before current month
$month_year = date("Y-m",getMonthYear(2)); // second last month before current month
Having trouble with a button onclick event in jsfiddle?
If so see Onclick event not firing on jsfiddle.net
if you want to change only the colour of the flag on hover
use this:
.fa-flag:hover {_x000D_
color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
Try this code. it worked for me.
function getInvoiceID(url, invoiceId) {
return $.ajax({
type: 'POST',
url: url,
data: { invoiceId: invoiceId },
async: false,
});
}
function isInvoiceIdExists(url, invoiceId) {
$.when(getInvoiceID(url, invoiceId)).done(function (data) {
if (!data) {
}
});
}
Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory
bean declaration in the following part:
<property name="packagesToScan" value="com.mblog.model"></property>
sometimes you need to set Padding, not Margin to make space between items smaller than default
Activity has six states
Activity lifecycle has seven methods
onCreate()
onStart()
onResume()
onPause()
onStop()
onRestart()
onDestroy()
Situations
When open the app
onCreate() --> onStart() --> onResume()
When back button pressed and exit the app
onPaused() -- > onStop() --> onDestory()
When home button pressed
onPaused() --> onStop()
After pressed home button when again open app from recent task list or clicked on icon
onRestart() --> onStart() --> onResume()
When open app another app from notification bar or open settings
onPaused() --> onStop()
Back button pressed from another app or settings then used can see our app
onRestart() --> onStart() --> onResume()
When any dialog open on screen
onPause()
After dismiss the dialog or back button from dialog
onResume()
Any phone is ringing and user in the app
onPause() --> onResume()
When user pressed phone's answer button
onPause()
After call end
onResume()
When phone screen off
onPaused() --> onStop()
When screen is turned back on
onRestart() --> onStart() --> onResume()
This works fine:
struct node *addNode(node *head, int value) {
node *newNode = (node *) malloc(sizeof(node));
newNode->value = value;
newNode->next = NULL;
if (head == NULL) {
// Add at the beginning
head = newNode;
} else {
node *current = head;
while (current->next != NULL) {
current = current->next;
};
// Add at the end
current->next = newNode;
}
return head;
}
Example usage:
struct node *head = NULL;
for (int currentIndex = 1; currentIndex < 10; currentIndex++) {
head = addNode(head, currentIndex);
}
Add below commend on your project,
npm install
npm i react-native-orientation-locker
then you use manifest class like, React_Native (Your Project Folder)/ android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
Thank You!
Others have answered the different syntaxes, but please note, when you are doing your couts
, you are only using ->
:
int main()
{
Kwadrat* kwadrat = new Kwadrat(1,2,3);
cout<<kwadrat->val1<<endl;
cout<<kwadrat->val2<<endl;
cout<<kwadrat->val3<<endl;
return 0;
}
Thanks for the above script. One little modification to add in the file ending correctly. Try this ...
$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**
Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat
SSLSocketFactory does not expose its X509TrustManager, which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call sslSocketFactory(SSLSocketFactory, X509TrustManager), which avoids such reflection.
Source: OkHttp documentation
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslContext.getSocketFactory(),
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
});
In Express 4.x
I used the following to load ejs
:
var path = require('path');
// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// The views/index.ejs exists in the app directory
app.get('/hello', function (req, res) {
res.render('index', {title: 'title'});
});
Then you just need two files to make it work - views/index.ejs
:
<%- include partials/navigation.ejs %>
And the views/partials/navigation.ejs
:
<ul><li class="active">...</li>...</ul>
You can also tell Express to use ejs
for html templates:
var path = require('path');
var EJS = require('ejs');
app.engine('html', EJS.renderFile);
// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
res.render('index.html', {title: 'title'});
});
Finally you can also use the ejs
layout module:
var EJSLayout = require('express-ejs-layouts');
app.use(EJSLayout);
This will use the views/layout.ejs
as your layout.
1.
if(1 == @$manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
2.
if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
3.
if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}
Preferred way to change the appearance/whatever of row views once the ListView is drawn is to change something in the data ListView draws from (the array of objects that is passed into your Adapter) and make sure to account for that in your getView() function, then redraw the ListView by calling
notifyDataSetChanged();
EDIT: while there is a way to do this, if you need to do this chances are doing something wrong. While are few edge cases I can think about, generally using notifyDataSetChanged()
and other built in mechanisms is a way to go.
EDIT 2: One of the common mistakes people make is trying to come up with their own way to respond to user clicking/selecting a row in the ListView, as in one of the comments to this post. There is an existing way to do this. Here's how:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/* Parameters
parent: The AdapterView where the click happened.
view: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position: The position of the view in the adapter.
id: The row id of the item that was clicked. */
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//your code here
}
});
ListView has a lot of build-in functionality and there is no need to reinvent the wheel for simpler cases. Since ListView extends AdapterView, you can set the same Listeners, such as OnItemClickListener as in the example above.
Possibilities:
Use String.equals()
:
if (some_string.equals("john") ||
some_string.equals("mary") ||
some_string.equals("peter"))
{
}
Use a regular expression:
if (some_string.matches("john|mary|peter"))
{
}
Store a list of strings to be matched against in a Collection and search the collection:
Set<String> names = new HashSet<String>();
names.add("john");
names.add("mary");
names.add("peter");
if (names.contains(some_string))
{
}
I know this question is already solved.. but there is a very easy way to crop. you can just do it in one line-
Mat cropedImage = fullImage(Rect(X,Y,Width,Height));
The Date
constructor (click the link!) accepts the time as long
in milliseconds, not seconds. You need to multiply it by 1000 and make sure that you supply it as long
.
Date d = new Date(1220227200L * 1000);
This shows here
Sun Aug 31 20:00:00 GMT-04:00 2008
scroll at particular position
and this helped me alot.
by click listener you can get the position in your adapter
layoutmanager.scrollToPosition(int position);
I think you should move the variable declaration to top of block. I.e.
{
foo();
int i = 0;
bar();
}
to
{
int i = 0;
foo();
bar();
}
If I could, I would vote for the answer by Paulo. I tested it and understood the concept. I can confirm it works.
The find
command can output many parameters.
For example, add the following to the --printf
clause:
%a for attributes in the octal format
%n for the file name including a complete path
Example:
find Desktop/ -exec stat \{} --printf="%y %n\n" \; | sort -n -r | head -1
2011-02-14 22:57:39.000000000 +0100 Desktop/new file
Let me raise this question as well: Does the author of this question want to solve his problem using Bash or PHP? That should be specified.
I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).
This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.
Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.
Then under Tfvc: Location you can paste the location of the executable.
For 2017 it'll be
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
Or for 2019 (Preview)
C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.
After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone
pasted my repo:
Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen
Then chose the new method of authentication
Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).
Click Continue
Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.
Cheers!
I did
git branch -f new_local_branch_name origin/remote_branch_name
Instead of
git branch -f new_local_branch_name upstream/remote_branch_name
As suggested by @innaM.
When I used the upstream version, it said 'fatal: Not a valid object name: 'upstream/remote_branch_name''. I did not do git fetch origin
as a comment suggested, but instead simply replaced upstream
with origin
. I guess they are equivalent.
I use Ctrl-b + q which makes it flash number for each pane, redrawing them on the way.
I got the same error because of a simple typo in vhost.conf. Remember to make sure you don't have any errors in the config files.
apachectl configtest
You can do navigation between view controllers using code with the help of storyboard and storyboardId of the view controller. This code is for Swift 3:
let signUpVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUp")
self.navigationController?.pushViewController(signUpVC, animated: true)
Rather than using the jQuery .parents
function (as suggested in the accepted answer), it's better to use .closest
for this purpose. As explained in the jQuery api docs, .closest
checks the element passed and all its parents, whereas .parents
just checks the parents.
Consequently, this works:
$(function() {
$("body").click(function(e) {
if ($(e.target).closest("#myDiv").length) {
alert("Clicked inside #myDiv");
} else {
alert("Clicked outside #myDiv");
}
});
})
some great answers here, but they do not tackle how to use super()
in the case where different classes in the hierarchy have different signatures ... especially in the case of __init__
to answer that part and to be able to effectively use super()
i'd suggest reading my answer super() and changing the signature of cooperative methods.
here's just the solution to this scenario:
- the top-level classes in your hierarchy must inherit from a custom class like
SuperObject
:- if classes can take differing arguments, always pass all arguments you received on to the super function as keyword arguments, and, always accept
**kwargs
.
class SuperObject:
def __init__(self, **kwargs):
print('SuperObject')
mro = type(self).__mro__
assert mro[-1] is object
if mro[-2] is not SuperObject:
raise TypeError(
'all top-level classes in this hierarchy must inherit from SuperObject',
'the last class in the MRO should be SuperObject',
f'mro={[cls.__name__ for cls in mro]}'
)
# super().__init__ is guaranteed to be object.__init__
init = super().__init__
init()
example usage:
class A(SuperObject):
def __init__(self, **kwargs):
print("A")
super(A, self).__init__(**kwargs)
class B(SuperObject):
def __init__(self, **kwargs):
print("B")
super(B, self).__init__(**kwargs)
class C(A):
def __init__(self, age, **kwargs):
print("C",f"age={age}")
super(C, self).__init__(age=age, **kwargs)
class D(B):
def __init__(self, name, **kwargs):
print("D", f"name={name}")
super(D, self).__init__(name=name, **kwargs)
class E(C,D):
def __init__(self, name, age, *args, **kwargs):
print( "E", f"name={name}", f"age={age}")
super(E, self).__init__(name=name, age=age, *args, **kwargs)
E(name='python', age=28)
output:
E name=python age=28
C age=28
A
D name=python
B
SuperObject
The documentation makes the calloc
look like malloc
, which just does zero-initialize the memory; this is not the primary difference! The idea of calloc
is to abstract copy-on-write semantics for memory allocation. When you allocate memory with calloc
it all maps to same physical page which is initialized to zero. When any of the pages of the allocated memory is written into a physical page is allocated. This is often used to make HUGE hash tables, for example since the parts of hash which are empty aren't backed by any extra memory (pages); they happily point to the single zero-initialized page, which can be even shared between processes.
Any write to virtual address is mapped to a page, if that page is the zero-page, another physical page is allocated, the zero page is copied there and the control flow is returned to the client process. This works same way memory mapped files, virtual memory, etc. work.. it uses paging.
Here is one optimization story about the topic: http://blogs.fau.de/hager/2007/05/08/benchmarking-fun-with-calloc-and-zero-pages/
cellEndEditTimer.Start();
this line makes the datagridview update the list of checked boxes
Thank you.