Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.
My finally working solution:
$(function () {
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
}
});
You have to include before:
@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")
You can install moment.js using:
Install-Package Moment.js
I have had the same error. And after I have already thought my mind is broken, because I had rename almost all my models properties the solution was delete one reference on All Syncfusion Controls and add references to the individual controls of this controls. (From Nuget)
How about something like this?
bool isChecked = false;
if (Boolean.TryParse(Request.Form.GetValues(”chkHuman”)[0], out isChecked) == false)
ModelState.AddModelError(”chkHuman”, “Nice try.”);
Solution for PostgreSQL:
final PreparedStatement statement = connection.prepareStatement(
"SELECT my_column FROM my_table where search_column = ANY (?)"
);
final String[] values = getValues();
statement.setArray(1, connection.createArrayOf("text", values));
try (ResultSet rs = statement.executeQuery()) {
while(rs.next()) {
// do some...
}
}
or
final PreparedStatement statement = connection.prepareStatement(
"SELECT my_column FROM my_table " +
"where search_column IN (SELECT * FROM unnest(?))"
);
final String[] values = getValues();
statement.setArray(1, connection.createArrayOf("text", values));
try (ResultSet rs = statement.executeQuery()) {
while(rs.next()) {
// do some...
}
}
As requested, I have transfered my comment to an answer so people can upvote it:
This works 90% of the time for iOS 13:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover, user-scalable=no, shrink-to-fit=no" />
and
<meta name="HandheldFriendly" content="true">
I had the same issue. I using the standard command for execution. It was calling the X64 ro run against X86 tests. I needed to specify the X86 and not the X64 version of the nunit-runner.
_Bool
is a keyword in C99: it specifies a type, just like int
or double
.
6.5.2
2 An object declared as type _Bool is large enough to store the values 0 and 1.
<span class="btn-pTool">
<a class="btn-pToolName" href="#"></a>
</span>
That's empty. Try adding a non breaking space to give the link and span some contents:
<span class="btn-pTool">
<a class="btn-pToolName" href="#"> </a>
</span>
It's also worth noting that the CSS spec says that you can't give a span a background image because spans are not block elements. Put the background image code in the div's class style, or use <p> instead of <span>
. Some browsers might let you put a background in a span, but not all will (perhaps older versions of IE).
Here to show equivalent implementation of a flatMap using subscribes.
Without flatMap:
this.searchField.valueChanges.debounceTime(400)
.subscribe(
term => this.searchService.search(term)
.subscribe( results => {
console.log(results);
this.result = results;
}
);
);
With flatMap:
this.searchField.valueChanges.debounceTime(400)
.flatMap(term => this.searchService.search(term))
.subscribe(results => {
console.log(results);
this.result = results;
});
http://plnkr.co/edit/BHGmEcdS5eQGX703eRRE?p=preview
Hope it could help.
Olivier.
I normally do this when working with associative arrays:
foreach ($assoc_array as $key => $value) {
//do something
}
This will work fine with non-associative arrays too. $key will be the index value. If you prefer, you can do this too:
foreach ($array as $indx => $value) {
//do something
}
In could able to resolve this issue with giving username and password in below url.
Please replace username and password with your Github credentials:
git remote set-url origin https://<username>:<password>@github.com/<username>/FirstRepository.git
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
function toCamelCase(str) {
// Lower cases the string
return str.toLowerCase()
// Replaces any - or _ characters with a space
.replace( /[-_]+/g, ' ')
// Removes any non alphanumeric characters
.replace( /[^\w\s]/g, '')
// Uppercases the first character in each group immediately following a space
// (delimited by spaces)
.replace( / (.)/g, function($1) { return $1.toUpperCase(); })
// Removes spaces
.replace( / /g, '' );
}
I was trying to find a JavaScript function to camelCase
a string, and wanted to make sure special characters would be removed (and I had trouble understanding what some of the answers above were doing). This is based on c c young's answer, with added comments and the removal of $peci&l characters.
Make simple:
@GetMapping("/health")
public ResponseEntity<String> healthCheck() {
LOG.info("REST request health check");
return new ResponseEntity<>("{\"status\" : \"UP\"}", HttpStatus.OK);
}
A slight generalization to Alexander's answer - np.reshape can take -1 as an argument, meaning "total array size divided by product of all other listed dimensions":
e.g. to flatten all but the last dimension:
>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
As above. Previous posts got me on the right track. This is how I've done it. The idea is to have an image next to every row in the table (generated by PHP script from database). When an image is clicked, the user would get redirected to the URL, and as a result, the appropriate record would be deleted from the database while showing some data related to the clicked record within jQuery UI Dialog.
The JavaScript code:
$(document).ready(function () {
$("#confirmDelete").dialog({
modal: true,
bgiframe: true,
autoOpen: false
});
});
function confirmDelete(username, id) {
var delUrl = "/users/delete/" + id;
$('#confirmDelete').html("Are you sure you want to delete user: '" + username + "'");
$('#confirmDelete').dialog('option', 'buttons', {
"No": function () {
$(this).dialog("close");
},
"Yes": function () {
window.location.href = delUrl;
}
});
$('#confirmDelete').dialog('open');
}
Dialog div:
<div id="confirmDelete" title="Delete User?"></div>
Image link:
<img src="img/delete.png" alt="Delete User" onclick="confirmDelete('<?=$username;?>','<?=$id;?>');"/>
This way you can pass over the PHP loop values into the dialog box. The only downside is using GET method to actually perform the action.
I have faced the same problem once too. I have solved it by creating on empty link with a ref to it like so:
linkRef = React.createRef();
render() {
return (
<a ref={this.linkRef}/>
);
}
and in my fetch function i have done something like this:
fetch(/*your params*/)
}).then(res => {
return res.blob();
}).then(blob => {
const href = window.URL.createObjectURL(blob);
const a = this.linkRef.current;
a.download = 'Lebenslauf.pdf';
a.href = href;
a.click();
a.href = '';
}).catch(err => console.error(err));
basically i have assigned the blobs url(href) to the link, set the download attribute and enforce one click on the link. As far as i understand this is the "basic" idea of the answer provided by @Nate. I dont know if this is a good idea to do it this way... I did.
For Laravel 3
Just a heads up on @giannis christofakis answer; for anyone using Laravel 3 replace
return Redirect::back()->withErrors(['msg', 'The Message']);
with:
return Redirect::back()->with_errors(['msg', 'The Message']);
This is working fine, try out this.
var ob = $("#myListBox");
for (var i = 0; i < buildings.length; i++) {
var val = buildings[i];
var text = buildings[i];
ob.prepend("<option value="+ val +">" + text + "</option>");
}
This message will also appear if you use .m files in your project which are not added in the build phase "compiles source"
Best Practice - use singular. You have a list of items that make up an Enum. Using an item in the list sounds strange when you say Versions.1_0
. It makes more sense to say Version.1_0
since there is only one 1_0 Version.
I am using SmartGit with msysgit on Windows 8.1 and noticed that there can be three different locations for the gitconfig
file:
%USERPROFILE%\.gitconfig
C:\Program Files (x86)\Git\etc\gitconfig
C:\Program Files (x86)\SmartGitHg\git\etc\gitconfig
But the one that is used is the one from %USERPROFILE%\.gitconfig
.
Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get
>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160
There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.
If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).
profilage bas� sur l'analyse de l'esprit
(french)
should be translated as:
profilage basé sur l'analyse de l'esprit
so, in this case �
= é
Bringing my answer from another question.
From the C specification, section 6.7.2:
— unsigned, or unsigned int
Meaning that unsigned
, when not specified the type, shall default to unsigned int
. So writing unsigned a
is the same as unsigned int a
.
From array of objects
function getSum(array, column)
let values = array.map((item) => parseInt(item[column]) || 0)
return values.reduce((a, b) => a + b)
}
foo = [
{ a: 1, b: "" },
{ a: null, b: 2 },
{ a: 1, b: 2 },
{ a: 1, b: 2 },
]
getSum(foo, a) == 3
getSum(foo, b) == 6
There's AppUpdater library. How to include:
allprojects { repositories { jcenter() maven { url "https://jitpack.io" } } }
dependencies { compile 'com.github.javiersantos:AppUpdater:2.6.4' }
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
AppUpdater appUpdater = new AppUpdater(this); appUpdater.start();
Try this:
ls -l | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'
NR is an AWK builtin variable to count the no. of records
There is no such thing as the "empty character" ''
.
If you need a space character, that can be represented as a space: c[i] = ' '
or as its ASCII octal equivalent: c[i] = '\040'
. If you need a NUL character that's c[i] = '\0'
.
With a simple call of clear() it appears in the DOM that the corresponding input/textarea component still has its old value, so any following changes on that component (e.g. filling the component with a new value) will not be processed in time.
If you take a look in the selenium source code you'll find that the clear()-method is documented with the following comment:
/** If this element is a text entry element, this will clear the value. Has no effect on other elements. Text entry elements are INPUT and TEXTAREA elements. Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events. If you want to ensure keyboard events are fired, consider using something like {@link #sendKeys(CharSequence...)} with the backspace key. To ensure you get a change event, consider following with a call to {@link #sendKeys(CharSequence...)} with the tab key. */
So using this helpful hint to clear an input/textarea (component that already has a value) AND assign a new value to it, you'll get some code like the following:
public void waitAndClearFollowedByKeys(By by, CharSequence keys) {
LOG.debug("clearing element");
wait(by, true).clear();
sendKeys(by, Keys.BACK_SPACE.toString() + keys);
}
public void sendKeys(By by, CharSequence keysToSend) {
WebElement webElement = wait(by, true);
LOG.info("sending keys '{}' to {}", escapeProperly(keysToSend), by);
webElement.sendKeys(keysToSend);
LOG.info("keys sent");
}
private String escapeProperly(CharSequence keysToSend) {
String result = "" + keysToSend;
result = result.replace(Keys.TAB, "\\t");
result = result.replace(Keys.ENTER, "\\n");
result = result.replace(Keys.RETURN, "\\r");
return result;
}
Sorry for this code being Java and not Python. Also, I had to skip out an additional "waitUntilPageIsReady()-method that would make this post way too long.
Hope this helps you on your journey with Selenium!
Advantages of RecyclerView over listview :
Contains ViewHolder by default.
Easy animations.
Supports horizontal , grid and staggered layouts
Advantages of listView over recyclerView :
Easy to add divider.
Can use inbuilt arrayAdapter for simple plain lists
Supports Header and footer .
Supports OnItemClickListner .
Example fetch with authorization header:
fetch('URL_GOES_HERE', {
method: 'post',
headers: new Headers({
'Authorization': 'Basic '+btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: 'A=1&B=2'
});
Better you can use the Webclient class to simplify your task:
using System.Net;
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString("http://somesite.com/default.html");
}
It's just the incorrect lines of code you were trying to execute..
hope it help..
You can also use
clone()
Method to copy all elements from one hashmap to another hashmap
Program for copy all elements from one hashmap to another
import java.util.HashMap;
public class CloneHashMap {
public static void main(String a[]) {
HashMap hashMap = new HashMap();
HashMap hashMap1 = new HashMap();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("Original HashMap : " + hashMap);
hashMap1 = (HashMap) hashMap.clone();
System.out.println("Copied HashMap : " + hashMap1);
}
}
I commonly like to use a slight variant on the standard for loop. I often use this to run a command on a series of remote hosts. I take advantage of bash's brace expansion to create for loops that allow me to create non-numerical for-loops.
Example:
I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:
% for host in {frontend{1..5},backend{1..3}}.mycompany.com
do ssh $host "echo -n $host; uptime"
done
I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z etc.). However, the double period syntax is a new feature of bash 3.0; earlier versions will not support this.
You can use column indices (letters) like this:
import pandas as pd
import numpy as np
file_loc = "path.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")
print(df)
[Corresponding documentation][1]:
usecolsint, str, list-like, or callable default None
- If None, then parse all columns.
- If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.
- If list of int, then indicates list of column numbers to be parsed.
If list of string, then indicates list of column names to be parsed.
New in version 0.24.0.
If callable, then evaluate each column name against it and parse the column if the callable returns True.
Returns a subset of the columns according to behavior above.
New in version 0.24.0.
When you fire a shell script, it runs a new instance of that shell (/bin/bash
). Thus, your script just fires up a shell, changes the directory and exits. Put another way, cd
(and other such commands) within a shell script do not affect nor have access to the shell from which they were launched.
string.isNullOrWhiteSpace(text) should be used in most cases as it also includes a blank string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
var str = "";
Console.WriteLine(string.IsNullOrWhiteSpace(str));
}
}
}
It returns True!
I'm no vim guru, but what I use in this circumstance is "visual mode". In command mode, type V
(capital). Then move up/down to highlight the block you want deleted (all the usual movement commands work). Then remove it with x
or d
.
There is PEP 8, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.
I also banged my head around this problem for some time and wished to solve this in an elegant but quick way.
Here are my 20 cents:
The answer using labels as mentioned here won't work if you are updating labels. But would work if you always add labels. More details here.
The answer mentioned here is the most elegant way to do this quickly according to me but had the problem of handling deletes. I am adding on to this answer:
I am doing this in one of the Kubernetes Operator where only a single task is performed in one reconcilation loop.
v2
.cm-v2
having labels: version: v2
and product: prime
if it does not exist and RETURN. If it exists GO BELOW.product: prime
but do not have version: v2
, If such deployments are found, DELETE them and RETURN. ELSE GO BELOW.product: prime
but does not have version: v2
ELSE GO BELOW.deployment-v2
with labels product: prime
and version: v2
and having config map attached as cm-v2
and RETURN, ELSE Do nothing.That's it! It looks long, but this could be the fastest implementation and is in principle with treating infrastructure as Cattle (immutability).
Also, the above solution works when your Kubernetes Deployment has Recreate update strategy. Logic may require little tweaks for other scenarios.
Faced the same problem, although I am using yarn.
The following worked for me:
yarn install
yarn start
We can use the following regex explained with the help of sed system command. The similar regex can be used in other languages and platforms.
Add the text into some file say test
manjeet-laptop:Desktop manjeet$ cat test
"The dog has a long tail, and it is RED!"
We can use the following regex to replace all white spaces with single space
manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"
Hope this serves the purpose
I think what you may be thinking of is expressions
or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:
width:expression(document.body.clientWidth > 800? "800px": "auto" );
This code makes IE emulate the max-width
property it doesn't support.
All things considered, however, avoid using these. They are a bad, bad thing.
Untested....but should work.
Dim lastrow as long
lastrow = range("D65000").end(xlup).Row
ActiveCell.FormulaR1C1 = _
"=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
Selection.AutoFill Destination:=Range("E2:E" & lastrow)
'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
Range("E2:E1344").Select
Only exception being are you sure your Autofill code is perfect...
You should use
<tbody>
<tr>
first page content here
</tr>
<tr>
..
</tr>
</tbody>
<tbody>
next page content...
</tbody>
And CSS:
tbody { display: block; page-break-before: avoid; }
tbody { display: block; page-break-after: always; }
I solved this on 12.10 by installing libssl-dev.
sudo apt-get install libssl-dev
Just execute, to clean gems obsolete and remove print warningns after bundle.
bundle clean --force
_x000D_
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
attachKeyboardListeners();
....
yourEditText1.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
yourEditText2.setVisibility(View.GONE);
yourEditText3.setVisibility(View.GONE);
yourEditText4.setVisibility(View.GONE);
yourEditText5.setVisibility(View.GONE);
} else {
yourEditText2.setVisibility(View.VISIBLE);
yourEditText3.setVisibility(View.VISIBLE);
yourEditText4.setVisibility(View.VISIBLE);
yourEditText5.setVisibility(VISIBLE);
}
}
});
}
}
I am not new to stackoverflow, just never had an account and usually came here for answers. I can't comment or vote up an answer yet. BUT wanted to say that the code from Michael Bacon above works really well. I am new to Python but not to programming. I have been reading Python Crash Course and there are a few things I wanted to do to break up the reading cover to cover approach. One utility that has uses from an ETL or even data quality perspective would be to capture the row count of a file independently from any ETL. The file has X number of rows, you import into SQL or Hadoop and you end up with X number of rows. You can validate at the lowest level the row count of a raw data file.
I have been playing with his code and doing some testing and this code is very efficient so far. I have created several different CSV files, various sizes, and row counts. You can see my code below and my comments provide the times and details. The code Michael Bacon above provided runs about 6 times faster than the normal Python method of just looping the lines.
Hope this helps someone.
import time
from itertools import (takewhile,repeat)
def readfilesimple(myfile):
# watch me whip
linecounter = 0
with open(myfile,'r') as file_object:
# watch me nae nae
for lines in file_object:
linecounter += 1
return linecounter
def readfileadvanced(myfile):
# watch me whip
f = open(myfile, 'rb')
# watch me nae nae
bufgen = takewhile(lambda x: x, (f.raw.read(1024 * 1024) for _ in repeat(None)))
return sum(buf.count(b'\n') for buf in bufgen if buf)
#return linecounter
# ************************************
# Main
# ************************************
#start the clock
start_time = time.time()
# 6.7 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfilesimple("c:/junk/book1.csv")
# 0.67 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfileadvanced("c:/junk/book1.csv")
# 25.9 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")
# 5.7 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")
# 292.92 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")
# 57 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")
#stop the clock
elapsed_time = time.time() - start_time
print("\nCode Execution: " + str(elapsed_time) + " seconds\n")
print("File contains: " + str(mycount) + " lines of text.")
Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.
1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
2. $ git branch <new_branch> (creates new branch)
3. $ git checkout new_branch
4. $ git add . (After making changes in the current branch)
5. $ git commit -m "type commit msg here"
6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
7. $ git merge new_branch (starts merging)
8. $ git push origin master (push to the remote server)
I referred this blog and I found it to be a cleaner approach.
You should look at the documentation for the Action method; it's explained well. For your case, this should work:
@Html.Action("GetOptions", new { pk="00", rk="00" });
The controllerName
parameter will default to the controller from which Html.Action
is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:
@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });
There's no way to evaluate multiple values in one 'case'. You could either use an if statement (as others have suggested) or call a method which evaluates the range that the integer belongs to and returns a value which represents that range (such as "minor", "adult", etc.), then evaluate this returned value in the switch statement. Of course, you'd probably still be using an if statement in the custom method.
Ctrl + F11 and Ctrl + F12 both work.
Well, it's this my DRY installation:
[Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache
)*.gems
files" to a computer without gems in own gem cache place (by default the same patron path of first step: [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache
)[Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache
) and fire the gem install anygemwithdependencieshere
(by example cucumber-2.99.0
)It's DRY because after install any gem, by default rubygems put the gem file in the cache gem directory and not make sense duplicate thats files, it's more easy if you want both computer has the same versions (or bloqued by paranoic security rules :v)
Edit: In some versions of ruby or rubygems, it don't work and fire alerts or error, you can put gems in other place but not get DRY, other alternative is using launch integrated command
gem server
and add the localhost url in gem sources, more information in: https://guides.rubygems.org/run-your-own-gem-server/
You should try something like this, I am doing this for my project, its a fallback system
//function to get the remote data
function url_get_contents ($url) {
if (function_exists('curl_exec')){
$conn = curl_init($url);
curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($conn, CURLOPT_FRESH_CONNECT, true);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1);
$url_get_contents_data = (curl_exec($conn));
curl_close($conn);
}elseif(function_exists('file_get_contents')){
$url_get_contents_data = file_get_contents($url);
}elseif(function_exists('fopen') && function_exists('stream_get_contents')){
$handle = fopen ($url, "r");
$url_get_contents_data = stream_get_contents($handle);
}else{
$url_get_contents_data = false;
}
return $url_get_contents_data;
}
then later you can do like this
$data = url_get_contents("http://www.google.com");
if($data){
//Do Something....
}
This approach is easier for me.
Suppose on a personal iMac where you are an admin, under the default directory when a command window is opened, /Users/jdoe, this will be the directory to go to: /Users/jdoe/Desktop/Mongo/db.3.2.1/bin.
These are the steps that can have the job done:
cd /Users/jdoe/Desktop/Mongo/db.3.2.1/bin
as the first line.chmod 755 mongobin
source mongobin
pwd
Voila!
You can also do npm install visionmedia/express
to install from Github
or
npm install visionmedia/express#branch
There is also support for installing directly from a Gist, Bitbucket, Gitlab, and a number of other specialized formats. Look at the npm install
documentation for them all.
Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.
In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.
The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new
keyword, and the context within that function (the this
keyword) will refer to the actual object instance where you call it.
Consider this example:
// constructor function
function MyClass () {
var privateVariable; // private member only available within the constructor fn
this.privilegedMethod = function () { // it can access private members
//..
};
}
// A 'static method', it's just like a normal function
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};
MyClass.prototype.publicMethod = function () {
// the 'this' keyword refers to the object instance
// you can access only 'privileged' and 'public' members
};
var myObj = new MyClass(); // new object instance
myObj.publicMethod();
MyClass.staticMethod();
To view database roles assigned to users, you can use sys.database_role_members
The following query returns the members of the database roles.
SELECT DP1.name AS DatabaseRoleName,
isnull (DP2.name, 'No members') AS DatabaseUserName
FROM sys.database_role_members AS DRM
RIGHT OUTER JOIN sys.database_principals AS DP1
ON DRM.role_principal_id = DP1.principal_id
LEFT OUTER JOIN sys.database_principals AS DP2
ON DRM.member_principal_id = DP2.principal_id
WHERE DP1.type = 'R'
ORDER BY DP1.name;
it defaults to submitting a form, easiest way is to add "return false"
<button type="cancel" onclick="window.location='http://stackoverflow.com';return false;">Cancel</button>
Postman 4.0.5 has a feature named Manage Cookies located below the Send button which manages the cookies separately from Chrome it seems.
Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
CSS
li {
display: inline-block;
}
Works for me also.
In my case, it's because of apache server is running somehow. So I stop apache then restart nginx. Work like a charm!
sudo /etc/init.d/apache2 stop
sudo systemctl restart nginx
You have to call DataReader.Read
to fetch the result:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read())
{
// read data for first record here
}
DataReader.Read()
returns a bool
indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:
while (dr.Read())
{
// read data for each record here
}
Put .gitignore in the working directory. It doesn't work if you put it in the .git (repository) directory.
$ ls -1d .git*
.git
.gitignore
Assuming doc
is your instance of org.w3c.dom.Document
:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
In recent Visual Studio Code versions you can find settings here:
Menu File → Preference → Settings → Text Editor → Files → (scroll down a bit) Trim Trailing Whitespace
This is for trimming whitespace when saving a file.
Or you can search "Trim Trailing Whitespace" in the top search bar.
By default, you can access your databases at http:// localhost/phpmyadmin using user: root and a blank password.
Once logged in PHPmyAdmin, click on the Privileges tab. and on the Add a new user link located under the User Overview table
Assuming you're on local branch master
, which is tracking origin/master
:
git diff --stat origin/master..
To expand on what Peter said: Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.
Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.
If you want to consider null values equality too, try the following
select column1, column2,
case
when column1 is NULL and column2 is NULL then 'true'
when column1=column2 then 'true'
else 'false'
end
from table;
Considering the performance of dictionary key lookups and deletes since they are hash operations, and considering the wording of the question was best way, I think that below is a perfectly valid approach, and the others are a bit over-complicated, IMHO.
public static void MergeOverwrite<T1, T2>(this IDictionary<T1, T2> dictionary, IDictionary<T1, T2> newElements)
{
if (newElements == null) return;
foreach (var e in newElements)
{
dictionary.Remove(e.Key); //or if you don't want to overwrite do (if !.Contains()
dictionary.Add(e);
}
}
OR if you're working in a multithreaded application and your dictionary needs to be thread safe anyway, you should be doing this:
public static void MergeOverwrite<T1, T2>(this ConcurrentDictionary<T1, T2> dictionary, IDictionary<T1, T2> newElements)
{
if (newElements == null || newElements.Count == 0) return;
foreach (var ne in newElements)
{
dictionary.AddOrUpdate(ne.Key, ne.Value, (key, value) => value);
}
}
You could then wrap this to make it handle an enumeration of dictionaries. Regardless, you're looking at about ~O(3n) (all conditions being perfect), since the .Add()
will do an additional, unnecessary but practically free, Contains()
behind the scenes. I don't think it gets much better.
If you wanted to limit extra operations on large collections, you should sum up the Count
of each dictionary you're about to merge and set the capacity of the the target dictionary to that, which avoids the later cost of resizing. So, end product is something like this...
public static IDictionary<T1, T2> MergeAllOverwrite<T1, T2>(IList<IDictionary<T1, T2>> allDictionaries)
{
var initSize = allDictionaries.Sum(d => d.Count);
var resultDictionary = new Dictionary<T1, T2>(initSize);
allDictionaries.ForEach(resultDictionary.MergeOverwrite);
return resultDictionary;
}
Note that I took in an IList<T>
to this method... mostly because if you take in an IEnumerable<T>
, you've opened yourself up to multiple enumerations of the same set, which can be very costly if you got your collection of dictionaries from a deferred LINQ statement.
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
We made a vertical SeekBar by using android:rotation="270"
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/camera_sv_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:id="@+id/camera_lv_expose"
android:layout_width="32dp"
android:layout_height="200dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
android:orientation="vertical">
<TextView
android:id="@+id/camera_tv_expose"
android:layout_width="32dp"
android:layout_height="20dp"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:gravity="center"/>
<FrameLayout
android:layout_width="32dp"
android:layout_height="180dp"
android:orientation="vertical">
<SeekBar
android:id="@+id/camera_sb_expose"
android:layout_width="180dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:rotation="270"/>
</FrameLayout>
</LinearLayout>
<TextView
android:id="@+id/camera_tv_help"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:text="@string/camera_tv"
android:textColor="#FFFFFF" />
</RelativeLayout>
Screenshot for camera exposure compensation:
I know the purists will hate this method, but you can cat
the file.
NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
echo "$NAME"
done
You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:
There is another library with much cleaner API and type-safe data. https://github.com/kodart/Httpzoid
Here is a simple usage example
Http http = HttpFactory.create(context);
http.post("http://example.com/users")
.data(new User("John"))
.execute();
Or more complex with callbacks
Http http = HttpFactory.create(context);
http.post("http://example.com/users")
.data(new User("John"))
.handler(new ResponseHandler<Void>() {
@Override
public void success(Void ignore, HttpResponse response) {
}
@Override
public void error(String message, HttpResponse response) {
}
@Override
public void failure(NetworkError error) {
}
@Override
public void complete() {
}
}).execute();
It is fresh new, but looks very promising.
You can use sed. But if you know perl, that might be easier, and more useful to know in the long run:
perl -n '/(\d+\.\d+\.\d+\.\d+)/ && print "$1\n"' < file
This particular NuGet package has a habit of losing its references in one of our projects. From time to time I will need to run the following command in the Package Manager Console to restore the references and everything is OK again
Update-Package Microsoft.AspNet.Webpages -reinstall
I know this is a bit old, but i thought i would contribute. Basing myself on the answer by @Sophy, this is what I did to add a .xxs breakpoint. I have not taken care of visible-inline, table.visible, etc classes.
/*========== Mobile First Method ==========*/
.col-xxs-12, .col-xxs-11, .col-xxs-10, .col-xxs-9, .col-xxs-8, .col-xxs-7, .col-xxs-6, .col-xxs-5, .col-xxs-4, .col-xxs-3, .col-xxs-2, .col-xxs-1 {
position: relative;
min-height: 1px;
padding-left: 15px;
padding-right: 15px;
float: left;
}
.visible-xxs {
display:none !important;
}
/* Custom, iPhone Retina */
@media only screen and (min-width : 320px) and (max-width:479px) {
.visible-xxs {
display: block !important;
}
.visible-xs {
display:none !important;
}
.hidden-xs {
display:block !important;
}
.hidden-xxs {
display:none !important;
}
.col-xxs-12 {
width: 100%;
}
.col-xxs-11 {
width: 91.66666667%;
}
.col-xxs-10 {
width: 83.33333333%;
}
.col-xxs-9 {
width: 75%;
}
.col-xxs-8 {
width: 66.66666667%;
}
.col-xxs-7 {
width: 58.33333333%;
}
.col-xxs-6 {
width: 50%;
}
.col-xxs-5 {
width: 41.66666667%;
}
.col-xxs-4 {
width: 33.33333333%;
}
.col-xxs-3 {
width: 25%;
}
.col-xxs-2 {
width: 16.66666667%;
}
.col-xxs-1 {
width: 8.33333333%;
}
.col-xxs-pull-12 {
right: 100%;
}
.col-xxs-pull-11 {
right: 91.66666667%;
}
.col-xxs-pull-10 {
right: 83.33333333%;
}
.col-xxs-pull-9 {
right: 75%;
}
.col-xxs-pull-8 {
right: 66.66666667%;
}
.col-xxs-pull-7 {
right: 58.33333333%;
}
.col-xxs-pull-6 {
right: 50%;
}
.col-xxs-pull-5 {
right: 41.66666667%;
}
.col-xxs-pull-4 {
right: 33.33333333%;
}
.col-xxs-pull-3 {
right: 25%;
}
.col-xxs-pull-2 {
right: 16.66666667%;
}
.col-xxs-pull-1 {
right: 8.33333333%;
}
.col-xxs-pull-0 {
right: auto;
}
.col-xxs-push-12 {
left: 100%;
}
.col-xxs-push-11 {
left: 91.66666667%;
}
.col-xxs-push-10 {
left: 83.33333333%;
}
.col-xxs-push-9 {
left: 75%;
}
.col-xxs-push-8 {
left: 66.66666667%;
}
.col-xxs-push-7 {
left: 58.33333333%;
}
.col-xxs-push-6 {
left: 50%;
}
.col-xxs-push-5 {
left: 41.66666667%;
}
.col-xxs-push-4 {
left: 33.33333333%;
}
.col-xxs-push-3 {
left: 25%;
}
.col-xxs-push-2 {
left: 16.66666667%;
}
.col-xxs-push-1 {
left: 8.33333333%;
}
.col-xxs-push-0 {
left: auto;
}
.col-xxs-offset-12 {
margin-left: 100%;
}
.col-xxs-offset-11 {
margin-left: 91.66666667%;
}
.col-xxs-offset-10 {
margin-left: 83.33333333%;
}
.col-xxs-offset-9 {
margin-left: 75%;
}
.col-xxs-offset-8 {
margin-left: 66.66666667%;
}
.col-xxs-offset-7 {
margin-left: 58.33333333%;
}
.col-xxs-offset-6 {
margin-left: 50%;
}
.col-xxs-offset-5 {
margin-left: 41.66666667%;
}
.col-xxs-offset-4 {
margin-left: 33.33333333%;
}
.col-xxs-offset-3 {
margin-left: 25%;
}
.col-xxs-offset-2 {
margin-left: 16.66666667%;
}
.col-xxs-offset-1 {
margin-left: 8.33333333%;
}
.col-xxs-offset-0 {
margin-left: 0%;
}
}
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px) {
.visible-xs {
display:block !important;
}
}
/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {
.visible-xs {
display:none !important;
}
}
/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {
}
/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {
}
AFAIK you cannot change the button text, it is hard coded in the browsers.
But there are several workarounds to put a button with diferent text/image on a form:
you have to float
your image container as follows:
HTML
<div id="container">
<div id="floated">...some other random text</div>
...
some random text
...
</div>
CSS
#container{
width: 400px;
background: yellow;
}
#floated{
float: left;
width: 150px;
background: red;
}
FIDDLE
first of all, give set an ID for your Fragment layout e.g:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
**android:id="@+id/cameraFragment"**
tools:context=".CameraFragment">
and use that ID to replace the view with another fragment.java file. e.g
ivGallary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UploadDoc uploadDoc= new UploadDoc();
(getActivity()).getSupportFragmentManager().beginTransaction()
.replace(**R.id.cameraFragment**, uploadDoc, "findThisFragment")
.addToBackStack(null)
.commit();
}
});
Another useful tool for this from the command line interface, is the pager command.
eg
pager grep -v Sleep | more; show full processlist;
Then you can page through the results.
You can also look for certain users, IPs or queries with grep or sed in this way.
The pager command is persistent per session.
Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...)
. Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.
Pass float to sleep, like sleep 0.1
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).
By default, imshow
sets the aspect of the plot to 1, as this is often what people want for image data.
In your case, you can do something like:
import matplotlib.pyplot as plt
import numpy as np
grid = np.random.random((10,10))
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))
ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')
ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')
ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')
plt.tight_layout()
plt.show()
SELECT LAST(row_name) FROM table_name
I just whipped this up for CBV. Not used in production but generates a PDF for me. Probably needs work for the error reporting side of things but does the trick so far.
import StringIO
from cgi import escape
from xhtml2pdf import pisa
from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import TemplateView
class PDFTemplateResponse(TemplateResponse):
def generate_pdf(self, retval):
html = self.content
result = StringIO.StringIO()
rendering = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if rendering.err:
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
else:
self.content = result.getvalue()
def __init__(self, *args, **kwargs):
super(PDFTemplateResponse, self).__init__(*args, mimetype='application/pdf', **kwargs)
self.add_post_render_callback(self.generate_pdf)
class PDFTemplateView(TemplateView):
response_class = PDFTemplateResponse
Used like:
class MyPdfView(PDFTemplateView):
template_name = 'things/pdf.html'
Simple Solution: Rather then cloning via https, clone it via ssh.
For example:
git clone https://github.com/vaibhavjain2/xxx.git - Avoid
git clone [email protected]:vaibhavjain2/xxx.git - Correct
Try something like grep -r -n -i --include="*.html *.php *.js" searchstrinhere .
the -i
makes it case insensitlve
the .
at the end means you want to start from your current directory, this could be substituted with any directory.
the -r
means do this recursively, right down the directory tree
the -n
prints the line number for matches.
the --include
lets you add file names, extensions. Wildcards accepted
For more info see: http://www.gnu.org/software/grep/
I know this is a very old question but it may be that you need to set the request headers. This solved it for me.
For example 'user-agent', 'accept' etc. here is an example with user-agent:
url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)
The problem is the linker is looking for libmagic.so
but you only have libmagic.so.1
A quick hack is to symlink libmagic.so.1
to libmagic.so
Under linux Ungzip your file using gunzip Edit your unzip sql file using
vi unzipsqlfile.sql
Remove the first binary line with esc dd go to the bottom of the file with esc shift g remove the last binary line with dd save the file esc x: Then reimport to mysql with :
mysql -u username -p new_database < unzipsqlfile.sql
I performed that with a 20go sql file from a jetbackup cpanel mysql backup. Be patient to wait vi doing the job for big files
Since you have the manual user input loop, after the scanner has read your first input it will pass the carriage/return into the next line which will also be read; of course, that is not what you wanted.
You can try this
try {
// ...
} catch (InputMismatchException e) {
reader.next();
}
or alternatively, you can consume that carriage return before reading your next double input by calling
reader.next()
If value is 9999.988 and Precision 4, scale 2 then it means 9999(it represents precision).99(scale is 2 so .988 is rounded to .99)
If value is 9999.9887 and precision is 4, scale is 2 then it means 9999.99
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
itemgetter
(see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.get
wins. And it does not require an extra import
.
>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
... k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)
Note that alternatively you can set d.__getitem__
as key
function which may provide a small performance boost over d.get
.
After reinstalling Android Studio, Is working without adb kill-server
There is an interesting alternative to the proposed solutions, that works with a single Dockerfile, require only a single call to docker build per conditional build and avoids bash.
Solution:
The following Dockerfile
solves that problem. Copy-paste it and try it yourself.
ARG my_arg
FROM centos:7 AS base
RUN echo "do stuff with the centos image"
FROM base AS branch-version-1
RUN echo "this is the stage that sets VAR=TRUE"
ENV VAR=TRUE
FROM base AS branch-version-2
RUN echo "this is the stage that sets VAR=FALSE"
ENV VAR=FALSE
FROM branch-version-${my_arg} AS final
RUN echo "VAR is equal to ${VAR}"
Explanation of Dockerfile:
We first get a base
image (centos:7
in your case) and put it into its own stage. The base
stage should contain things that you want to do before the condition. After that, we have two more stages, representing the branches of our condition: branch-version-1
and branch-version-2
. We build both of them. The final
stage than chooses one of these stages, based on my_arg
. Conditional Dockerfile. There you go.
Output when running:
(I abbreviated this a little...)
my_arg==2
docker build --build-arg my_arg=2 .
Step 1/12 : ARG my_arg
Step 2/12 : ARG ENV
Step 3/12 : FROM centos:7 AS base
Step 4/12 : RUN echo "do stuff with the centos image"
do stuff with the centos image
Step 5/12 : FROM base AS branch-version-1
Step 6/12 : RUN echo "this is the stage that sets VAR=TRUE"
this is the stage that sets VAR=TRUE
Step 7/12 : ENV VAR=TRUE
Step 8/12 : FROM base AS branch-version-2
Step 9/12 : RUN echo "this is the stage that sets VAR=FALSE"
this is the stage that sets VAR=FALSE
Step 10/12 : ENV VAR=FALSE
Step 11/12 : FROM branch-version-${my_arg}
Step 12/12 : RUN echo "VAR is equal to ${VAR}"
VAR is equal to FALSE
my_arg==1
docker build --build-arg my_arg=1 .
...
Step 11/12 : FROM branch-version-${my_arg}
Step 12/12 : RUN echo "VAR is equal to ${VAR}"
VAR is equal to TRUE
<ion-row *ngIf="cat === 1;else second"></ion-row>_x000D_
<ng-template #second>_x000D_
<ion-row *ngIf="cat === 2;else third"></ion-row>_x000D_
</ng-template>_x000D_
<ng-template #third>_x000D_
_x000D_
</ng-template>
_x000D_
Angular is already using ng-template under the hood in many of the structural directives that we use all the time: ngIf, ngFor and ngSwitch.
> What is ng-template in Angular
https://www.angularjswiki.com/angular/what-is-ng-template-in-angular/
Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)
if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.
You can try adding the border on an other element:
DOM:
<div><img src="#" /></div>
CSS:
div {
border: 1px solid black;
}
img {
filter: blur(5px);
}
The best method I've ever come across to update the content size of a UIScrollView
based on its contained subviews:
Objective-C
CGRect contentRect = CGRectZero;
for (UIView *view in self.scrollView.subviews) {
contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;
Swift
let contentRect: CGRect = scrollView.subviews.reduce(into: .zero) { rect, view in
rect = rect.union(view.frame)
}
scrollView.contentSize = contentRect.size
I have checked how ADB installs apps.
- It copies the APK to /data/local/tmp
- it runs 'shell:pm install /data/local/tmp/app.apk'
I have tried to replicate this behaviour by doing: (on pc, using usb-cable)
adb push app.apk /sdcard/app.apk
adb shell
$ pm install /sdcard/app.apk
This works. The app is installed.
I made an application (named AppInstall) which should install the other app.
(installed normally, non-rooted device)
It does:
Runtime.getRuntime().exec("pm install /sdcard/app.apk").waitFor();
But this gives the error:
java.lang.SecurityException: Neither user 10019 nor current process has android.permission.INSTALL_PACKAGES.
It seems like the error is thrown by pm, not by AppInstall.
Because the SecurityException is not catched by AppInstall and the app does not crash.
I've tried the same thing on a rooted device (same app and AppInstall) and it worked like a charm.
(Also normally installed, not in /system or anything)
AppInstall didn't even ask root-permission.
But thats because the shell is always #
instead of $
on that device.
Btw, you need root to install an app in /system, correct?
I tried adb remount on the non-rooted device and got:
remount failed: Operation not permitted.
That's why I could not try the /system thing on the non-rooted device.
Conclusion: you should use a rooted device
Hope this helps :)
Make sure the config file at .git is correct...Check URL & Make sure your using the correct protocol for your keys ...ProjectWorkspace/.git/config
~Wrong url for git@bitbucket
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = gitbucket.org:Prezyack/project-one-hello.git
fetch = +refs/heads/*:refs/remotes/origin/*
~Wrong URL for SSH...
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = https://[email protected]/emmap1/bitbucketspacestation.git
[branch "master"]
remote = origin
merge = refs/heads/master
We are looking at the URL... e.g: For bitbucket, expect [email protected] its gitbucket.org. make the necessary changes.. SAVE Try pushing again.
As I was saying in this question, I'd suggest you avoid redirecting all HTTP requests to their HTTPS equivalent blindly, as it may cause you a false impression of security. Instead, you should probably redirect the "root" of your HTTP site to the root of your HTTPS site and link from there, only to HTTPS.
The problem is that if some link or form on the HTTPS site makes the client send a request to the HTTP site, its content will be visible, before the redirection.
For example, if one of your pages served over HTTPS has a form that says <form action="http://example.com/doSomething">
and sends some data that shouldn't be sent in clear, the browser will first send the full request (including entity, if it's a POST) to the HTTP site first. The redirection will be sent immediately to the browser and, since a large number of users disable or ignore the warnings, it's likely to be ignored.
Of course, the mistake of providing the links that should be to the HTTPS site but that end up being for the HTTP site may cause problems as soon as you get something listening on the HTTP port on the same IP address as your HTTPS site. However, I think keeping the two sites as a "mirror" only increases the chances of making mistakes, as you may tend to make the assumption that it will auto-correct itself by redirecting the user to HTTPS, whereas it's often too late. (There were similar discussions in this question.)
AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/check" //check.xml
android:background="@null"/>
check.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
You can remove separator of empty rows by just adding minor height of footer
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
I solved a similar problem I had with scrollbar this way:
First disable vertical scrollbar by setting it's:
overflow-y: hidden;
Then make a div with fixed position with a height equal to the screen height and make it's width thin to look like scrollbar. This div should be vertically scroll-able. Now inside this div make another div with the height of your document (with all it's contents). Now all you need to do is to add an onScroll function to the container div and scroll body as the div scrolls. Here's the code:
HTML:
<div onscroll="OnScroll(this);" style="width:18px; height:100%; overflow-y: auto; position: fixed; top: 0; right: 0;">
<div id="ScrollDiv" style="width:28px; height:100%; overflow-y: auto;">
</div>
</div>
Then in your page load event add this:
JS:
$( document ).ready(function() {
var body = document.body;
var html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
document.getElementById('ScrollDiv').style.height = height + 'px';
});
function OnScroll(Div) {
document.body.scrollTop = Div.scrollTop;
}
Now scrolling the div works just like scrolling the body while body has no scrollbar.
If you're using the public API, the best way to do it is using if
statements.
If the video is public or unlisted, you set the thumbnail using the URL method. If the video is private you use the API to get the thumbnail.
<?php
if($video_status == 'unlisted'){
$video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
$video_status = '<i class="fa fa-lock"></i> Unlisted';
}
elseif($video_status == 'public'){
$video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
$video_status = '<i class="fa fa-eye"></i> Public';
}
elseif($video_status == 'private'){
$video_thumbnail = $playlistItem['snippet']['thumbnails']['maxres']['url'];
$video_status = '<i class="fa fa-lock"></i> Private';
}
ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)
EDIT: Browse all controls etc, here: http://www.sencha.com/products/js/
As of C++17 there's also std::from_chars. The following function takes a string of hex characters and returns a vector of T:
#include <charconv>
template<typename T>
std::vector<T> hexstr_to_vec(const std::string& str, unsigned char chars_per_num = 2)
{
std::vector<T> out(str.size() / chars_per_num, 0);
T value;
for (int i = 0; i < str.size() / chars_per_num; i++) {
std::from_chars<T>(
str.data() + (i * chars_per_num),
str.data() + (i * chars_per_num) + chars_per_num,
value,
16
);
out[i] = value;
}
return out;
}
As far as I read manual pages, scanf says that 'l' length modifier indicates (in case of floating points) that the argument is of type double rather than of type float, so you can have 'lf, le, lg'.
As for printing, officially, the manual says that 'l' applies only to integer types. So it might be not supported on some systems or by some standards. For instance, I get the following error message when compiling with gcc -Wall -Wextra -pedantic
a.c:6:1: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]
So you may want to doublecheck if your standard supports the syntax.
To conclude, I would say that you read with '%lf' and you print with '%f'.
use this method from everywhere with a context
private static String getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
while (cursor.moveToNext()) {
String phNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
}
cursor.close();
return stringBuffer.toString();
}
Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:
.text
.globl __start
__start:
la $a0,str1 #Load and print string asking for string
li $v0,4
syscall
li $v0,8 #take in input
la $a0, buffer #load byte space into address
li $a1, 20 # allot the byte space for string
move $t0,$a0 #save string to t0
syscall
la $a0,str2 #load and print "you wrote" string
li $v0,4
syscall
la $a0, buffer #reload byte space to primary address
move $a0,$t0 # primary address = t0 address (load pointer)
li $v0,4 # print string
syscall
li $v0,10 #end program
syscall
.data
buffer: .space 20
str1: .asciiz "Enter string(max 20 chars): "
str2: .asciiz "You wrote:\n"
###############################
#Output:
#Enter string(max 20 chars): qwerty 123
#You wrote:
#qwerty 123
#Enter string(max 20 chars): new world oreddeYou wrote:
# new world oredde //lol special character
###############################
After searching around a bit, the best solution in my opinion makes use of hudson.model.EnvironmentContributingAction.
import hudson.model.EnvironmentContributingAction
import hudson.model.AbstractBuild
import hudson.EnvVars
class BuildVariableInjector {
def build
def out
def BuildVariableInjector(build, out) {
this.build = build
this.out = out
}
def addBuildEnvironmentVariable(key, value) {
def action = new VariableInjectionAction(key, value)
build.addAction(action)
//Must call this for action to be added
build.getEnvironment()
}
class VariableInjectionAction implements EnvironmentContributingAction {
private String key
private String value
public VariableInjectionAction(String key, String value) {
this.key = key
this.value = value
}
public void buildEnvVars(AbstractBuild build, EnvVars envVars) {
if (envVars != null && key != null && value != null) {
envVars.put(key, value);
}
}
public String getDisplayName() {
return "VariableInjectionAction";
}
public String getIconFileName() {
return null;
}
public String getUrlName() {
return null;
}
}
}
I use this class in a system groovy script (using the groovy plugin) within a job.
import hudson.model.*
import java.io.File;
import jenkins.model.Jenkins;
def jenkinsRootDir = build.getEnvVars()["JENKINS_HOME"];
def parent = getClass().getClassLoader()
def loader = new GroovyClassLoader(parent)
def buildVariableInjector = loader.parseClass(new File(jenkinsRootDir + "/userContent/GroovyScripts/BuildVariableInjector.groovy")).newInstance(build, getBinding().out)
def projectBranchDependencies = []
//Some logic to set projectBranchDependencies variable
buildVariableInjector.addBuildEnvironmentVariable("projectBranchDependencies", projectBranchDependencies.join(","));
You can then access the projectBranchDependencies variable at any other point in your build, in my case, from an ANT script.
Note: I borrowed / modified the ideas for parts of this implementation from a blog post, but at the time of this posting I was unable to locate the original source in order to give due credit.
Use this:
android:gravity="top"
or
android:gravity="top|left"
For normal form you can do
class MyModelForm(forms.ModelForm):
slug = forms.CharField(widget=forms.HiddenInput())
If you have model form you can do the following
class MyModelForm(forms.ModelForm):
class Meta:
model = TagStatus
fields = ('slug', 'ext')
widgets = {'slug': forms.HiddenInput()}
You can also override __init__
method
class Myform(forms.Form):
def __init__(self, *args, **kwargs):
super(Myform, self).__init__(*args, **kwargs)
self.fields['slug'].widget = forms.HiddenInput()
Click the line number, and then copy and paste the link from the address bar. To select a range, click the number, and then shift click the later number.
Alternatively, the links are a relatively simple format, just append #L<number>
to the end for that specific line number, using the link to the file. Here's a link to the third line of the git
repository's README
:
You do not need to insert the current timestamp manually as MySQL
provides this facility to store it automatically. When the MySQL
table is created, simply do this:
TIMESTAMP
as your column type Default
value to CURRENT_TIMESTAMP
insert
any rows into the table without inserting any values for the time
columnYou'll see the current timestamp
is automatically inserted when you insert a row. Please see the attached picture.
I tried to create a byte array like this
byte[] bytes = new byte[Integer.MAX_VALUE-x];
System.out.println(bytes.length);
With this run configuration:
-Xms4G -Xmx4G
And java version:
Openjdk version "1.8.0_141"
OpenJDK Runtime Environment (build 1.8.0_141-b16)
OpenJDK 64-Bit Server VM (build 25.141-b16, mixed mode)
It only works for x >= 2 which means the maximum size of an array is Integer.MAX_VALUE-2
Values above that give
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit at Main.main(Main.java:6)
ByteArrayInputStream ins = new ByteArrayInputStream("Hello".getBytes());
System.out.println("ins.available() at begining:: " + ins.available());
ins.mark(0);
// Read input stream for some operations
System.out.println("ins.available() after reading :: " + ins.available());
ins.reset();
System.out.println("ins.available() after resetting :: " + ins.available());
// ins is ready for reading once again.
Normally I would recommend floating but from your 3 requirements I would suggest this:
position: absolute;
right: 10px;
top: 5px;
Don't forget position: relative;
on the parent div
Memoization is basically saving the results of past operations done with recursive algorithms in order to reduce the need to traverse the recursion tree if the same calculation is required at a later stage.
see http://scriptbucket.wordpress.com/2012/12/11/introduction-to-memoization/
Fibonacci Memoization example in Python:
fibcache = {}
def fib(num):
if num in fibcache:
return fibcache[num]
else:
fibcache[num] = num if num < 2 else fib(num-1) + fib(num-2)
return fibcache[num]
Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:
s = "something about cupcakes"
print(f"L{s}LL")
Select
p.Name,
p.SS,
f.fear
From
Persons p
left join
Person_Fear pf
inner join
Fears f
on
pf.fearID = f.fearID
on
p.personID = pf.PersonID
Here's the beginnings of a parser class to get you started. This ended up being my solution to a similar problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace XML
{
public class Parser
{
private string _FilePath = string.Empty;
private XDocument _XML_Doc = null;
public Parser(string filePath)
{
_FilePath = filePath;
_XML_Doc = XDocument.Load(_FilePath);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
/// </summary>
/// <param name="attributeName"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string attributeName, string newValue)
{
ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
{
ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) and value (oldValue)
/// with the specified new value (newValue) in elements with a given name (elementName).
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
{
ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues),
/// with the specified new value (newValue) in elements with a given name (elementName).
/// If oldValues is empty then oldValues will be ignored.
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="oldValues"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
{
List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();
foreach (XElement element in elements)
{
if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
{
if (element.Attribute(attributeName) != null)
{
if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
{ element.Attribute(attributeName).Value = newValue; }
}
}
}
}
public void SaveChangesToFile()
{
_XML_Doc.Save(_FilePath);
}
}
}
I had to stopPropigation
and preventDefault
in order to prevent a button expanding an accordion item that it sat above.
So...
@Component({
template: `
<button (click)="doSomething($event); false">Test</button>
`
})
export class MyComponent {
doSomething(e) {
e.stopPropagation();
// do other stuff...
}
}
Just pad with zeroes to the same length:
int maxlen = sizes.Max(x => x.Length);
var result = sizes.OrderBy(x => x.PadLeft(maxlen, '0'));
Using javascript you can style the scroll bars. Which works fine in IE as well as FF.
Check the below links
From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques
A Swift translation of the @dupuis2387 answer. Worked out the syntax to set the UIAlertController
title's color and font via KVC using the attributedTitle
key.
let message = "Some message goes here."
let alertController = UIAlertController(
title: "", // This gets overridden below.
message: message,
preferredStyle: .Alert
)
let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ -> Void in
}
alertController.addAction(okAction)
let fontAwesomeHeart = "\u{f004}"
let fontAwesomeFont = UIFont(name: "FontAwesome", size: 17)!
let customTitle:NSString = "I \(fontAwesomeHeart) Swift" // Use NSString, which lets you call rangeOfString()
let systemBoldAttributes:[String : AnyObject] = [
// setting the attributed title wipes out the default bold font,
// so we need to reconstruct it.
NSFontAttributeName : UIFont.boldSystemFontOfSize(17)
]
let attributedString = NSMutableAttributedString(string: customTitle as String, attributes:systemBoldAttributes)
let fontAwesomeAttributes = [
NSFontAttributeName: fontAwesomeFont,
NSForegroundColorAttributeName : UIColor.redColor()
]
let matchRange = customTitle.rangeOfString(fontAwesomeHeart)
attributedString.addAttributes(fontAwesomeAttributes, range: matchRange)
alertController.setValue(attributedString, forKey: "attributedTitle")
self.presentViewController(alertController, animated: true, completion: nil)
They are lists because you type them as lists in the dictionary:
bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}
You should use the bike-class instead:
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100),
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165)
}
This will allow you to get the cost of the bikes with bike.cost as you were trying to.
for bike in bikes.values():
profit = bike.cost * margin
print(bike.name + " : " + str(profit))
This will now print:
Kruzer : 33.0
Trike : 20.0
Here's a snippet of the HTML escape characters taken from a cached page on archive.org:
< | < less than sign
@ | @ at sign
] | ] right bracket
{ | { left curly brace
} | } right curly brace
… | … ellipsis
‡ | ‡ double dagger
’ | ’ right single quote
” | ” right double quote
– | – short dash
™ | ™ trademark
¢ | ¢ cent sign
¥ | ¥ yen sign
© | © copyright sign
¬ | ¬ logical not sign
° | ° degree sign
² | ² superscript 2
¹ | ¹ superscript 1
¼ | ¼ fraction 1/4
¾ | ¾ fraction 3/4
÷ | ÷ division sign
” | ” right double quote
> | > greater than sign
[ | [ left bracket
` | ` back apostrophe
| | | vertical bar
~ | ~ tilde
† | † dagger
‘ | ‘ left single quote
“ | “ left double quote
• | • bullet
— | — longer dash
¡ | ¡ inverted exclamation point
£ | £ pound sign
¦ | ¦ broken vertical bar
« | « double left than sign
® | ® registered trademark sign
± | ± plus or minus sign
³ | ³ superscript 3
» | » double greater-than sign
½ | ½ fraction 1/2
¿ | ¿ inverted question mark
“ | “ left double quote
— | — dash
This is the C ternary operator (Objective-C is a superset of C):
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
is semantically equivalent to
if(inPseudoEditMode) {
label.frame = kLabelIndentedRect;
} else {
label.frame = kLabelRect;
}
The ternary with no first element (e.g. variable ?: anotherVariable
) means the same as (valOrVar != 0) ? valOrVar : anotherValOrVar
As per John Gruber (Daring Fireball):
Regex:
(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))
using in preg_match():
preg_match("/(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/", $url)
Here is the extended regex pattern (with comments):
(?xi)
\b
( # Capture 1: entire matched URL
(?:
https?:// # http or https protocol
| # or
www\d{0,3}[.] # "www.", "www1.", "www2." … "www999."
| # or
[a-z0-9.\-]+[.][a-z]{2,4}/ # looks like domain name followed by a slash
)
(?: # One or more:
[^\s()<>]+ # Run of non-space, non-()<>
| # or
\(([^\s()<>]+|(\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels
)+
(?: # End with:
\(([^\s()<>]+|(\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels
| # or
[^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct chars
)
)
For more details please look at: http://daringfireball.net/2010/07/improved_regex_for_matching_urls
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
declare @data as varchar(50)
set @data='ciao335'
--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ---->>ciao
--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ---->>335
Ok, here is the JS code:
var data = JSON.parse('{"c":{"a":{"name":"cable - black","value":2}}}')
for (var event in data) {
var dataCopy = data[event];
for (data in dataCopy) {
var mainData = dataCopy[data];
for (key in mainData) {
if (key.match(/name|value/)) {
alert('key : ' + key + ':: value : ' + mainData[key])
}
}
}
}?
Persistence Context is an environment or cache where entity instances(which are capable of holding data and thereby having the ability to be persisted in a database) are managed by Entity Manager.It syncs the entity with database.All objects having @Entity annotation are capable of being persisted. @Entity is nothing but a class which helps us create objects in order to communicate with the database.And the way the objects communicate is using methods.And who supplies those methods is the Entity Manager.
You use RAISE_APPLICATION_ERROR
in order to create an Oracle style exception/error that is specific to your code/needs. Good use of these help to produce code that is clearer, more maintainable, and easier to debug.
For example, if I have an application calling a stored procedure that adds a user and that user already exists, you'll usually get back an error like:
ORA-00001: unique constraint (USERS.PK_USER_KEY) violated
Obviously this error and associated message are not unique to the task you were trying to do. Creating your own Oracle application errors allow you to be clearer on the intent of the action and the cause of the issue.
raise_application_error(-20101, 'User ' || in_user || ' already exists!');
Now your application code can write an exception handler in order to process this specific error condition. Think of it as a way to make Oracle communicate error conditions that your application expects in a "language" (for lack of a better term) that you have defined and is more meaningful to your application's problem domain.
Note that user defined errors must be in the range between -20000 and -20999.
The following link provides lots of good information on this topic and Oracle exceptions in general.
Take a look at this: slide ExpandableListView at DrawerLayout form right to left
I assume you have the ActionBarDrawerToggle implemented, the trick is to override the onOptionsItemSelected(MenuItem item)
method inside the ActionBarDrawerToggle object with this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (mDrawer.isDrawerOpen(Gravity.RIGHT)) {
mDrawer.closeDrawer(Gravity.RIGHT);
} else {
mDrawer.openDrawer(Gravity.RIGHT);
}
return true;
}
return false;
}
make sure and call this from onOptionsItemSelected(MenuItem item)
in the Activity:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
This will allow you to use the the home button functionality. To move the button to the right side of the action bar you will have to implement a custom action item, and maybe some other stuff to get it to work like you want.
Python idiom to return first item or None?
The most Pythonic approach is what the most upvoted answer demonstrated, and it was the first thing to come to my mind when I read the question. Here's how to use it, first if the possibly empty list is passed into a function:
def get_first(l):
return l[0] if l else None
And if the list is returned from a get_list
function:
l = get_list()
return l[0] if l else None
for
When I began trying to think of clever ways to do this, this is the second thing I thought of:
for item in get_list():
return item
This presumes the function ends here, implicitly returning None
if get_list
returns an empty list. The below explicit code is exactly equivalent:
for item in get_list():
return item
return None
if some_list
The following was also proposed (I corrected the incorrect variable name) which also uses the implicit None
. This would be preferable to the above, as it uses the logical check instead of an iteration that may not happen. This should be easier to understand immediately what is happening. But if we're writing for readability and maintainability, we should also add the explicit return None
at the end:
some_list = get_list()
if some_list:
return some_list[0]
or [None]
and select zeroth indexThis one is also in the most up-voted answer:
return (get_list()[:1] or [None])[0]
The slice is unnecessary, and creates an extra one-item list in memory. The following should be more performant. To explain, or
returns the second element if the first is False
in a boolean context, so if get_list
returns an empty list, the expression contained in the parentheses will return a list with 'None', which will then be accessed by the 0
index:
return (get_list() or [None])[0]
The next one uses the fact that and returns the second item if the first is True
in a boolean context, and since it references my_list twice, it is no better than the ternary expression (and technically not a one-liner):
my_list = get_list()
return (my_list and my_list[0]) or None
next
Then we have the following clever use of the builtin next
and iter
return next(iter(get_list()), None)
To explain, iter
returns an iterator with a .next
method. (.__next__
in Python 3.) Then the builtin next
calls that .next
method, and if the iterator is exhausted, returns the default we give, None
.
a if b else c
) and circling backThe below was proposed, but the inverse would be preferable, as logic is usually better understood in the positive instead of the negative. Since get_list
is called twice, unless the result is memoized in some way, this would perform poorly:
return None if not get_list() else get_list()[0]
The better inverse:
return get_list()[0] if get_list() else None
Even better, use a local variable so that get_list
is only called one time, and you have the recommended Pythonic solution first discussed:
l = get_list()
return l[0] if l else None
If you changed my.ini
and restarted mysql
and you still get this error please check your file path and replace "\"
to "/"
.
I solved my proplem after replacing.
editTransactionRow.pay_id is Null so in fact you are doing: null.ToString() and it cannot be executed. You need to check editTransactionRow.pay_id and not editTransactionRow.pay_id.ToString();
You code should be (IF pay_id is a string):
If String.IsNullOrEmpty(editTransactionRow.pay_id) = False Then
stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If
If pay_id is an Integer than you can just check if it's null normally without String... Edit to show you if it's not a String:
If editTransactionRow.pay_id IsNot Nothing Then
stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If
If it's from a database you can use IsDBNull but if not, do not use it.
When using literal strings (start with @") this might be easier
char tab = '\u0009';
string A = "Apple";
string B = "Bob";
string myStr = String.Format(@"{0}:{1}{2}", A, tab, B);
Would result in Apple:<tab>Bob
If you don't care about loading the file into memory, as of Go 1.16, you can use the os.ReadFile
and bytes.Count
functions.
package main
import (
"log"
"os"
"bytes"
)
func main() {
data, err := os.ReadFile("input.txt")
if err != nil {
log.Fatal(err)
}
n := bytes.Count(data, []byte{'\n'})
fmt.Printf("input.txt has %d lines\n", n)
}
Here's an article that explains how to approach doing this in 2020: https://www.robertcooper.me/table-row-links
The article explains 3 possible solutions:
<div>
elements instead of native HTML table elements in order to have tables rows as <a>
elements.The article goes into depth on how to implement each solution (with links to CodePens) and also considers edge cases, such as how to approach a situation where you want to add links inside you table cells (having nested <a>
elements is not valid HTML, so you need to workaround that).
As @gameliela pointed out, it may also be worth trying to find an approach where you don't make your entire row a link, since it will simplify a lot of things. I do, however, think that it can be a good user experience to have an entire table row clickable as a link since it is convenient for the user to be able to click anywhere on a table to navigate to the corresponding page.
Disable package-lock.json globally
type the following in your terminal:
npm config set package-lock false
this really work for me like magic
Why not just use the option Find and Replace. (every code editor has it)?
For example Visual Studio Code (under Edit option):
You just type in old name and new name and replace everyhting in the project with one click.
NOTE: This renames only file content, NOT file and folder names. Do not forget renaming folders, eg. templates/my_app_name/
rename it to templates/my_app_new_name/
I had the same issue, and the answer was in the dmenu source code: the stest utility made for that purpose. You can compile the 'stest.c' and 'arg.h' files and it should work. There is a man page for the usage, that I put there for convenience:
STEST(1) General Commands Manual STEST(1)
NAME
stest - filter a list of files by properties
SYNOPSIS
stest [-abcdefghlpqrsuwx] [-n file] [-o file]
[file...]
DESCRIPTION
stest takes a list of files and filters by the
files' properties, analogous to test(1). Files
which pass all tests are printed to stdout. If no
files are given, stest reads files from stdin.
OPTIONS
-a Test hidden files.
-b Test that files are block specials.
-c Test that files are character specials.
-d Test that files are directories.
-e Test that files exist.
-f Test that files are regular files.
-g Test that files have their set-group-ID
flag set.
-h Test that files are symbolic links.
-l Test the contents of a directory given as
an argument.
-n file
Test that files are newer than file.
-o file
Test that files are older than file.
-p Test that files are named pipes.
-q No files are printed, only the exit status
is returned.
-r Test that files are readable.
-s Test that files are not empty.
-u Test that files have their set-user-ID flag
set.
-v Invert the sense of tests, only failing
files pass.
-w Test that files are writable.
-x Test that files are executable.
EXIT STATUS
0 At least one file passed all tests.
1 No files passed all tests.
2 An error occurred.
SEE ALSO
dmenu(1), test(1)
dmenu-4.6 STEST(1)
I try in this example to show you a complete example to personalize your OrderBy sorts
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.data.domain.Sort;
/**
* Spring Data repository for the User entity.
*/
@SuppressWarnings("unused")
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List <User> findAllWithCustomOrderBy(Sort sort);
}
you will use this example : A method for build dynamically a object that instance of Sort :
import org.springframework.data.domain.Sort;
public class SampleOrderBySpring{
Sort dynamicOrderBySort = createSort();
public static void main( String[] args )
{
System.out.println("default sort \"firstName\",\"name\",\"age\",\"size\" ");
Sort defaultSort = createStaticSort();
System.out.println(userRepository.findAllWithCustomOrderBy(defaultSort ));
String[] orderBySortedArray = {"name", "firstName"};
System.out.println("default sort ,\"name\",\"firstName\" ");
Sort dynamicSort = createDynamicSort(orderBySortedArray );
System.out.println(userRepository.findAllWithCustomOrderBy(dynamicSort ));
}
public Sort createDynamicSort(String[] arrayOrdre) {
return Sort.by(arrayOrdre);
}
public Sort createStaticSort() {
String[] arrayOrdre ={"firstName","name","age","size");
return Sort.by(arrayOrdre);
}
}
I was having the same exception with node v12.13.1,
Downgraded node to v10.15.3 and it works fine now.
There are a couple of parallization bugs in SQL server with abnormal input. OPTION(MAXDOP 1) will sidestep them.
EDIT: Old. My testing was done largely on SQL 2005. Most of these seem to not exist anymore, but every once in awhile we question the assumption when SQL 2014 does something dumb and we go back to the old way and it works. We never managed to demonstrate that it wasn't just a bad plan generation on more recent cases though since SQL server can be relied on to get the old way right in newer versions. Since all cases were IO bound queries MAXDOP 1 doesn't hurt.
The absolute limitation on TCP packet size is 64K (65535 bytes), but in practicality this is far larger than the size of any packet you will see, because the lower layers (e.g. ethernet) have lower packet sizes.
The MTU (Maximum Transmission Unit) for Ethernet, for instance, is 1500 bytes. Some types of networks (like Token Ring) have larger MTUs, and some types have smaller MTUs, but the values are fixed for each physical technology.
These are the necersary imports:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
I know this has an accepted answer, but in reading the replies on the answer, I see some things that I can clear up that might help other people having issues with events not triggering after a value change.
This will select the value in the drop-down:
$("#gate").val("gateway_2")
If this select element is using JQueryUI or other JQuery wrapper, use the refresh method of the wrapper to update the UI to show that the value has been selected. The below example is for JQueryUI, but you will have to look at the documentation for the wrapper you are using to determine the correct method for the refresh:
$("#gate").selectmenu("refresh");
If there is an event that needs to be triggered such as a change event, you will have to trigger that manually as changing the value does not fire the event. The event you need to fire depends on how the event was created:
If the event was created with JQuery i.e. $("#gate").on("change",function(){}) then trigger the event using the below method:
$("#gate").change();
If the event was created using a standard JavaScript event i.e. then trigger the event using the below method:
var JSElem = $("#gate")[0];
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
JSElem.dispatchEvent(evt);
} else {
JSElem.fireEvent("onchange");
}
When the form is processed, you redirect to another page:
... process complete....
header('Location: thankyou.php');
you can also redirect to the same page.
if you are doing something like comments and you want the user to stay on the same page, you can use Ajax to handle the form submission
Use document.title
:
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
First please follow the two lines of codes to update the action bar items before that you should set a condition in oncreateOptionMenu(). For example:
Boolean mISQuizItemSelected = false;
/**
* Called to inflate the action bar menus
*
* @param menu
* the menu
*
* @return true, if successful
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
inflater.inflate(R.menu.menu_demo, menu);
//condition to hide the menus
if (mISQuizItemSelected) {
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setVisible(false);
}
}
return super.onCreateOptionsMenu(menu);
}
/**
* Called when the item on the action bar being selected.
*
* @param item
* menuitem being selected
*
* @return true if the menuitem id being selected is matched
* false if none of the menuitems id are matched
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getId() == R.id.action_quiz) {
//to navigate based on the usertype either learner or leo
mISQuizItemSelected = true;
ActionBar actionBar = getActionBar();
invalidateOptionMenu();
}
}
Another way is to use reflection:
protected T GetObject<T>(Type[] signature, object[] args)
{
return (T)typeof(T).GetConstructor(signature).Invoke(args);
}
It is possible using ConfigTransform
build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/
All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.
The same applies to "app.*.config" transform files in non-web projects.
and then adding the following target to your *.csproj
.
<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
<TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>
Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.
Different case but may help someone,
In my case Window firewall was enabled on Server,
Two thinks can be done,
1) Disable windows firewall (your on risk but it will get thing work)
2) Add port in inbound rule.
Thanks .
There is a significant difference between <blockquote><pre>...
and <pre>{@code....
The former will omit the type declarations in generics but the latter will keep it.
E.g.:
List<MyClass> myObject = null;
displays as List myObject = null;
with the firts and as List<MyClass> myObject = null;
with the second
In the Laravel 4 manual - it talks about doing raw commands like this:
DB::select(DB::raw('RENAME TABLE photos TO images'));
edit: I just found this in the Laravel 4 documentation which is probably better:
DB::statement('drop table users');
Update: In Laravel 4.1 (maybe 4.0 - I'm not sure) - you can also do this for a raw Where query:
$users = User::whereRaw('age > ? and votes = 100', array(25))->get();
Further Update If you are specifically looking to do a table rename - there is a schema command for that - see Mike's answer below for that.
Something like this should do it:
.column-left{ float: left; width: 33.333%; }
.column-right{ float: right; width: 33.333%; }
.column-center{ display: inline-block; width: 33.333%; }
EDIT
To do this with a larger number of columns you could build a very simple grid system. For example, something like this should work for a five column layout:
.column {_x000D_
float: left;_x000D_
position: relative;_x000D_
width: 20%;_x000D_
_x000D_
/*for demo purposes only */_x000D_
background: #f2f2f2;_x000D_
border: 1px solid #e6e6e6;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.column-offset-1 {_x000D_
left: 20%;_x000D_
}_x000D_
.column-offset-2 {_x000D_
left: 40%;_x000D_
}_x000D_
.column-offset-3 {_x000D_
left: 60%;_x000D_
}_x000D_
.column-offset-4 {_x000D_
left: 80%;_x000D_
}_x000D_
_x000D_
.column-inset-1 {_x000D_
left: -20%;_x000D_
}_x000D_
.column-inset-2 {_x000D_
left: -40%;_x000D_
}_x000D_
.column-inset-3 {_x000D_
left: -60%;_x000D_
}_x000D_
.column-inset-4 {_x000D_
left: -80%;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="column column-one column-offset-2">Column one</div>_x000D_
<div class="column column-two column-inset-1">Column two</div>_x000D_
<div class="column column-three column-offset-1">Column three</div>_x000D_
<div class="column column-four column-inset-2">Column four</div>_x000D_
<div class="column column-five">Column five</div>_x000D_
</div>
_x000D_
Or, if you are lucky enough to be able to support only modern browsers, you can use flexible boxes:
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.column {_x000D_
flex: 1;_x000D_
_x000D_
/*for demo purposes only */_x000D_
background: #f2f2f2;_x000D_
border: 1px solid #e6e6e6;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.column-one {_x000D_
order: 3;_x000D_
}_x000D_
.column-two {_x000D_
order: 1;_x000D_
}_x000D_
.column-three {_x000D_
order: 4;_x000D_
}_x000D_
.column-four {_x000D_
order: 2;_x000D_
}_x000D_
.column-five {_x000D_
order: 5;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="column column-one">Column one</div>_x000D_
<div class="column column-two">Column two</div>_x000D_
<div class="column column-three">Column three</div>_x000D_
<div class="column column-four">Column four</div>_x000D_
<div class="column column-five">Column five</div>_x000D_
</div>
_x000D_
Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:
xx <- reshape(df, idvar=c("skew","version","color"),
v.names="price", timevar="product", direction="wide")
xx will have columns price.p1, ... price.p4, so:
ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
geom_point(shape=19, size=5)
ggp + facet_grid(color~version)
gives the result from your image.
$('input[name=test]').click(function () {
if (this.id == "watch-me") {
$("#show-me").show('slow');
} else {
$("#show-me").hide('slow');
}
});
The line
base64String = Base64.encode(byteArray);
converts the full array (102400 bytes) to Base64, not just the number of bytes you have read. You need to pass it the numbers of bytes.
Router Link
routerLink with brackets and none - simple explanation.
The difference between routerLink= and [routerLink] is mostly like relative and absolute path.
Similar to a href you may want to navigate to ./about.html or https://your-site.com/about.html.
When you use without brackets then you navigate relative and without params;
my-app.com/dashboard/client
"jumping" from my-app.com/dashboard to my-app.com/dashboard/client
<a routerLink="client/{{ client.id }}" .... rest the same
When you use routerLink with brackets then you execute app to navigate absolute and you can add params how is the puzzle of your new link
first of all it will not include the "jump" from dashboard/ to dashboard/client/client-id and bring you data of client/client-id which is more helpful for EDIT CLIENT
<a [routerLink]="['/client', client.id]" ... rest the same
The absolute way or brackets routerLink require additional set up of you components and app.routing.module.ts
The code without error will "tell you more/what is the purpose of []" when you make the test. Just check this with or without []. Than you may experiments with selectors which - as mention above - helps with dynamics routing.
See whats the routerLink construct
Back to the original question:
xcopy "bin\development\whee.config.example" "TestConnectionExternal\bin\Debug\whee.config"
could be done with two commands eg:
mkdir "c:\mybackup\TestConnectionExternal\bin\Debug\whee.config\.."
xcopy "bin\development\whee.config.example" "c:\mybackup\TestConnectionExternal\bin\Debug\whee.config\"
By simply appending "\.." to the path of the destination file the destination directory is created if it not already exists. In this case
"c:\mybackup\TestConnectionExternal\bin\Debug\"
which is the parent directory of the non-existing directory
"c:\mybackup\TestConnectionExternal\bin\Debug\whee.config\.."
At least for WIN7 mkdir does not care if the directory
"c:\mybackup\TestConnectionExternal\bin\Debug\whee.config\"
really exists.
Query string parameters can be accepted simply by using an argument on the action - i.e.
public ActionResult Foo(string someValue, int someOtherValue) {...}
which will accept a query like .../someroute?someValue=abc&someOtherValue=123
Other than that, you can look at the request directly for more control.
I think the variable should be in the same block:
@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
if (isUserConnected)
{ // meaning that the viewing user has not been saved
<div>
<div> click to join us </div>
<a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
</div>
}
}
You can try command to clear the untracked files from the local
Git 2.11 and newer versions:
git clean -d -f .
Older versions of Git:
git clean -d -f ""
Where -d
can be replaced with the following:
-x
ignored files are also removed as well as files unknown to Git.
-d
remove untracked directories in addition to untracked files.
-f
is required to force it to run.
Here is the link that can be helpful as well.
there is a simple trick you can work here but it need preparation before you print, you have to put what ever you wants to print in a variable and then print so you will know the length to remove the string.here is an example.
#include <iostream>
#include <string> //actually this thing is not nessasory in tdm-gcc
using namespace std;
int main(){
//create string variable
string str="Starting count";
//loop for printing numbers
for(int i =0;i<=50000;i++){
//get previous string length and clear it from screen with backspace charactor
cout << string(str.length(),'\b');
//create string line
str="Starting count " +to_string(i);
//print the new line in same spot
cout <<str ;
}
}
Try to execute the procedure like this,
var c refcursor;
execute pkg_name.get_user('14232', '15', 'TDWL', 'SA', 1, :c);
print c;
I assume this is *nix?
Use "here document":
sqlplus -s user/pass <<+EOF
select 1 from dual;
+EOF
EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):
$ echo 'select 1 from dual;'|sqlplus -s user/pw
1
----------
1
$
In Log4j2, the "extras" lib is not mandatory any more. Also the configuration format has changed.
An example is provided in the Apache documentation
property.filename = /foo/bar/test.log
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = /foo/bar/rolling/test1-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 2
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=100MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 5
logger.rolling.name = com.example.my.class
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile
I know I'm WAY late to this question, but figured I'd throw my snippets up here. A lot of the answers here are OK, and, as one points out, it's generally best to use feature detection
rather than rely on the userAgent
string. However, if you are going to go that route, I've written a complete snippet, as well as an alternate jQuery implementation to replace the depricated $.browser
.
My first snippet simply adds four properties to the navigator
object: browser
, version
, mobile
, & webkit
.
/** navigator [extended]
* Simply extends Browsers navigator Object to include browser name, version number, and mobile type (if available).
*
* @property {String} browser The name of the browser.
* @property {Double} version The current Browser version number.
* @property {String|Boolean} mobile Will be `false` if is not found to be mobile device. Else, will be best guess Name of Mobile Device (not to be confused with browser name)
* @property {Boolean} webkit If is webkit or not.
*/
;(function(){function c(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return"MSIE";case /Chrome/.test(navigator.userAgent):return"Chrome";case /Opera/.test(navigator.userAgent):return"Opera";case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):return/Silk/i.test(navigator.userAgent)?"Silk":"Kindle";case /BlackBerry/.test(navigator.userAgent):return"BlackBerry";case /PlayBook/.test(navigator.userAgent):return"PlayBook";case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):return"Blackberry";
case /Android/.test(navigator.userAgent):return"Android";case /Safari/.test(navigator.userAgent):return"Safari";case /Firefox/.test(navigator.userAgent):return"Mozilla";case /Nokia/.test(navigator.userAgent):return"Nokia"}}catch(a){console.debug("ERROR:setBrowser\t",a)}}function d(){try{switch(!0){case /Sony[^ ]*/i.test(navigator.userAgent):return"Sony";case /RIM Tablet/i.test(navigator.userAgent):return"RIM Tablet";case /BlackBerry/i.test(navigator.userAgent):return"BlackBerry";case /iPhone/i.test(navigator.userAgent):return"iPhone";
case /iPad/i.test(navigator.userAgent):return"iPad";case /iPod/i.test(navigator.userAgent):return"iPod";case /Opera Mini/i.test(navigator.userAgent):return"Opera Mini";case /IEMobile/i.test(navigator.userAgent):return"IEMobile";case /BB[0-9]{1,}; Touch/i.test(navigator.userAgent):return"BlackBerry";case /Nokia/i.test(navigator.userAgent):return"Nokia";case /Android/i.test(navigator.userAgent):return"Android"}}catch(a){console.debug("ERROR:setMobile\t",a)}return!1}function e(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return/Trident/i.test(navigator.userAgent)&&
/rv:([0-9]{1,}[\.0-9]{0,})/.test(navigator.userAgent)?parseFloat(navigator.userAgent.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")):/MSIE/i.test(navigator.userAgent)&&0<parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge";case /Chrome/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Opera/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].replace(/[^0-9\.]/g,
""));case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):if(/Silk/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));if(/Kindle/i.test(navigator.userAgent)&&/Version/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /BlackBerry/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("/")[1].replace(/[^0-9\.]/g,
""));case /PlayBook/.test(navigator.userAgent):case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):case /Safari/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Firefox/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split(/Firefox\//i)[1].replace(/[^0-9\.]/g,""));case /Android/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,
""));case /Nokia/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Browser")[1].replace(/[^0-9\.]/g,""))}}catch(a){console.debug("ERROR:setVersion\t",a)}}a:{try{if(navigator&&navigator.userAgent){navigator.browser=c();navigator.mobile=d();navigator.version=e();var b;b:{try{b=/WebKit/i.test(navigator.userAgent);break b}catch(a){console.debug("ERROR:setWebkit\t",a)}b=void 0}navigator.webkit=b;break a}}catch(a){}throw Error("Browser does not support `navigator` Object |OR| has undefined `userAgent` property.");
}})();
/* simple c & p of above */
Before to do anything check for css rules with:
{ position:absolute }
Remove if exist and don't need them.
I had to use:
table, tbody {
width: 100%;
}
The table
alone wasn't enough, the tbody
was also needed for it to work for me.
Use a closure, it result in a clean solution:
<th onClick={this.handleSort(column)} >{column}</th>
handleSort function will return a function that have the value column already set.
handleSort: function(value) {
return () => {
console.log(value);
}
}
The anonymous function will be called with the correct value when the user click on the th.
Example: https://stackblitz.com/edit/react-pass-parameters-example
I also got the problem. This is what I did:
Now, go to nodeJS site, and install again. Select 2nd option in installation option (ie npm package). Install it. You problem must be solved by now.
All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long
is at least 32 bits, so %lu
together with (unsigned long)k
is always correct:
uint32_t k;
printf("%lu\n", (unsigned long)k);
size_t
is trickier, which is why %zu
was added in C99. If you can't use that, then treat it just like k
(long
is the biggest type in C89, size_t
is very unlikely to be larger).
size_t sz;
printf("%zu\n", sz); /* C99 version */
printf("%lu\n", (unsigned long)sz); /* common C89 version */
If you don't get the format specifiers correct for the type you are passing, then printf
will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.
JSON.parse
expects valid notation inside a string, whether that be object {}
, array []
, string ""
or number types (int, float, doubles).
If there is potential for what is parsing to be an empty string then the developer should check for it.
If it was built into the function it would add extra cycles, since built in functions are expected to be extremely performant, it makes sense to not program them for the race case.
You can use the function MROUND(<reference cell>, <round to multiple of digit needed>)
.
Example:
For a value A1 = 21
round to multiple of 10 it would be written as
=MROUND(A1,10)
for which Result = 20
For a value Z4 = 55.1
round to multiple of 10 it would be written as
=MROUND(Z4,10)
for which Result = 60
As I see it, there are two problems that need addressing when needing a default value.
Here is my solution:
# the reader providers a default if nil
# but this wont work when saved
def status
read_attribute(:status) || "P"
end
# so, define a before_validation callback
before_validation :set_defaults
protected
def set_defaults
# if a non-default status has been assigned, it will remain
# if no value has been assigned, the reader will return the default and assign it
# this keeps the default logic DRY
status = status
end
I'd love to know why people think of this approach.
The best, quickest and easiest way to resolve the comma in data issue is to use Excel to save a comma separated file after having set Windows' list separator setting to something other than a comma (such as a pipe). This will then generate a pipe (or whatever) separated file for you that you can then import. This is described here.
Have a look at: Greybox
It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.
You will find many information on how to use Greybox and also some great examples. Cheers Kara
I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size. You have to use an ArrayList or a Vector or any other dynamic structure.
ShellEd is a good plugin for Eclipse.
This link helped me to install it: http://mattnorris.me/blog/install-eclipse-shelled-plugin/
Steps:
Download ShellEd: http://sourceforge.net/projects/shelled/files/latest/download - The file is a zipped archive named something like net.sourceforge.shelled-site-2.0.x.zip.
Then click Help > Install New Software...
Edit: (after the code change)
There is no way for us to tell you whether you need or not to call your parent's __init__
(or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your __init__
is done in parent class, you can just skip child-class __init__
altogether.
consider the following example:
>>> class A:
def __init__(self, val):
self.a = val
>>> class B(A):
pass
>>> class C(A):
def __init__(self, val):
A.__init__(self, val)
self.a += val
>>> A(4).a
4
>>> B(5).a
5
>>> C(6).a
12
@user812954's answer was quite helpful, except I had to do this this in two steps:
sudo su
cd directory
Then, to exit out of "super user" mode, just type exit
.
To understand the difference between these you must understand the Gradient Descent Algorithm and its Variants.
Before I start with the actual answer, I would like to build some background.
A batch is the complete dataset. Its size is the total number of training examples in the available dataset.
Mini-batch size is the number of examples the learning algorithm processes in a single pass (forward and backward).
A Mini-batch is a small part of the dataset of given mini-batch size.
Iterations is the number of batches of data the algorithm has seen (or simply the number of passes the algorithm has done on the dataset).
Epochs is the number of times a learning algorithm sees the complete dataset. Now, this may not be equal to the number of iterations, as the dataset can also be processed in mini-batches, in essence, a single pass may process only a part of the dataset. In such cases, the number of iterations is not equal to the number of epochs.
In the case of Batch gradient descent, the whole batch is processed on each training pass. Therefore, the gradient descent optimizer results in smoother convergence than Mini-batch gradient descent, but it takes more time. The batch gradient descent is guaranteed to find an optimum if it exists.
Stochastic gradient descent is a special case of mini-batch gradient descent in which the mini-batch size is 1.
I've just been banging my head against a wall trying to solve a bug because I read this page and concluded there was no meaningful difference when in practice there is so I'll post this link here in case anyone else finds they get different results out of == and equals.
Object == equality fails, but .Equals succeeds. Does this make sense?
string a = "x";
string b = new String(new []{'x'});
Console.WriteLine("x == x " + (a == b));//True
Console.WriteLine("object x == x " + ((object)a == (object)b));//False
Console.WriteLine("x equals x " + (a.Equals(b)));//True
Console.WriteLine("object x equals x " + (((object)a).Equals((object)b)));//True
If you don't want to use any libraries and you have reoccurrences in your data, you can use which
with sapply
as well.
new_order <- sapply(target, function(x,df){which(df$name == x)}, df=df)
df <- df[new_order,]
In my case there were some vstest processes running (with various names but all containing the string vstest). I had to terminate them in taskmgr.