time.time()
will do the job.
import time
start = time.time()
# run your code
end = time.time()
elapsed = end - start
You may want to look at this question, but I don't think it will be necessary.
How about making the input a list. Then you may use standard list operations.
a=list(input("Enter the numbers"))
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
resp.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resp.write(data);
resp.end();
});
}
Uncomment this line (in /conf/logging.properties
)
org.apache.jasper.compiler.TldLocationsCache.level = FINE
Work's for me in tomcat 7.0.53!
All of the answers above are correct; attr_reader
and attr_writer
are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.
Sometimes we may not have access to a Jenkins machine to copy a folder directly into another Jenkins instance. So I wrote a menu driven utility which uses Jenkins REST API calls to install plugins and jobs from one Jenkins instance to another.
For plugin migration:
{SOURCE_JENKINS_SERVER}/pluginManager/api/json?depth=1
will get you the list of plugins installed with their version.You can send a POST request with the following parameters to install these plugins.
final_url=`{DESTINATION_JENKINS_SERVER}/pluginManager/installNecessaryPlugins`
data=`<jenkins><install plugin="{PLUGIN_NAME}@latest"/></jenkins>` (where, latest will fetch the latest version of the plugin_name)
auth=`(destination_jenkins_username, destination_jenkins_password)`
header=`{crumb_field:crumb_value,"Content-Type":"application/xml”}` (where crumb_field=Jenkins-Crumb and get crumb value using API call {DESTINATION_JENKINS_SERVER}/crumbIssuer/api/json
For job migration:
{SOURCE_JENKINS_URL}/view/All/api/json
{SOURCE_JENKINS_URL}/job/{JOB_NAME}
.I have created a menu-driven utility in Python which asks the user to start plugin or Jenkins migration and uses Jenkins REST API calls to do it.
You can refer the JenkinsMigration.docx from this URL jenkinsjenkinsmigrationjenkinsrestapi
Place the body of your loop after the while
and before the test. The actual body of the while
loop should be a no-op.
while
check_if_file_present
#do other stuff
(( current_time <= cutoff ))
do
:
done
Instead of the colon, you can use continue
if you find that more readable. You can also insert a command that will only run between iterations (not before first or after last), such as echo "Retrying in five seconds"; sleep 5
. Or print delimiters between values:
i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'
I changed the test to use double parentheses since you appear to be comparing integers. Inside double square brackets, comparison operators such as <=
are lexical and will give the wrong result when comparing 2 and 10, for example. Those operators don't work inside single square brackets.
You can simply use the jQuery Validate plugin as follows.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
DEMO: http://jsfiddle.net/xs5vrrso/
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js
file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension
For anyone who wants to pass in arbitrary strings which are exact matches (And not worry about escaping regex special characters), git log takes a --fixed-strings option
git log --fixed-strings --grep "$SEARCH_TERM"
your dependency based on data is trying to find their respective entities which one has not been created, comments the dependencies based on data and runs the app again.
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter-data-jpa</artifactId> -->
<!-- </dependency> -->
For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent described here on MDN and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link...
var theEvent = document.createEvent("MouseEvent");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var element = document.getElementById('link');
element.dispatchEvent(theEvent);
while (element)
{
if (element.tagName == "A" && element.href != "")
{
if (element.target == "_blank") { window.open(element.href, element.target); }
else { document.location = element.href; }
element = null;
}
else
{
element = element.parentElement;
}
}
The same thing happened to me and i found that i forgot to put the " at the end of the
#import "CPDConstants.h
so instead
#import "CPDConstants.h"
You can use assign
(doc) to change the value of perf.a1:
> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5
This is probably the simplest way of doing it:
sed -r 's/\s+//g' filename > output
mv ouput filename
simple code add for file .php then your folder which number of file to count its
$directory = "images/icons";
$files = scandir($directory);
for($i = 0 ; $i < count($files) ; $i++){
if($files[$i] !='.' && $files[$i] !='..')
{ echo $files[$i]; echo "<br>";
$file_new[] = $files[$i];
}
}
echo $num_files = count($file_new);
simple add its done ....
use this
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class dynamic_spinner_main extends Activity {
private Spinner m_myDynamicSpinner;
private EditText m_addItemText;
private ArrayAdapter<CharSequence> m_adapterForSpinner;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_spinner);
///////////////////////////////////////////////////////////////
//grab our UI elements so we can manipulate them (in the case of the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
////////////////////////////////////////////////////////////////
//create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
m_adapterForSpinner.add("gr");
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
startActivity(mIntent);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
addButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
clearButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
private void addNewSpinnerItem() {
CharSequence textHolder = "" + m_addItemText.getText();
m_adapterForSpinner.add(textHolder);
}
private void clearSpinnerItems() {
m_adapterForSpinner.clear();
m_adapterForSpinner.add("dummy item");
}
}
main_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_height="wrap_content"
android:layout_margin="4px"
android:id="@+id/newSpinnerItemText"
android:layout_width="fill_parent"></EditText>
<Button android:layout_height="wrap_content"
android:id="@+id/AddBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Add To Spinner"></Button>
<Button android:layout_height="wrap_content"
android:id="@+id/ClearBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Clear Spinner Items"></Button>
<Spinner android:layout_height="wrap_content"
android:id="@+id/dynamicSpinner"
android:layout_margin="4px"
android:layout_width="fill_parent"></Spinner>
</LinearLayout>
1) No, a NumberFormatException is an unchecked Exception. Even though you caught it (you aren't required to) because it's unchecked. This is because it is a subclass of IllegalArgumentException
which is a subclass of RuntimeException
.
2) RuntimeException
is the root of all unchecked Exceptions. Every subclass of RuntimeException
is unchecked. All other Exceptions and Throwable
are checked except for Errors ( Which comes under Throwable
).
3/4) You could alert the user that they picked a non-existent file and ask for a new one. Or just quit informing the user that they entered something invalid.
5) Throwing and catching 'Exception'
is bad practice. But more generally, you might throw other exceptions so the caller can decide how to deal with it. For example, if you wrote a library to handle reading some file input and your method was passed a non-existent file, you have no idea how to handle that. Does the caller want to ask again or quit? So you throw the Exception up the chain back to the caller.
In many cases, an unchecked Exception
occurs because the programmer did not verify inputs (in the case of NumberFormatException
in your first question). That's why its optional to catch them, because there are more elegant ways to avoid generating those exceptions.
Just so that we have some other options: reset($arr);
good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:
$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.
The way to do this without changing the pointer:
$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));
The benefit of $arr[reset(array_keys($arr))];
is that it raises an warning if the array is actually empty.
$last = count($arr_nav) - 1;
foreach ($arr_nav as $i => $row)
{
$isFirst = ($i == 0);
$isLast = ($i == $last);
echo ... $row['name'] ... $row['url'] ...;
}
You could use a variable to make the calculation and use toFixed
when you set the #diskamountUnit
element value:
var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));
You can also do that in one step, in the val
method call but IMO the first way is more readable:
$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
You've started right - now you just need to fill the each student
structure in the array:
struct student
{
public int s_id;
public String s_name, c_name, dob;
}
class Program
{
static void Main(string[] args)
{
student[] arr = new student[4];
for(int i = 0; i < 4; i++)
{
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
arr[i].s_id = Int32.Parse(Console.ReadLine());
arr[i].s_name = Console.ReadLine();
arr[i].c_name = Console.ReadLine();
arr[i].s_dob = Console.ReadLine();
}
}
}
Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.
Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Demo {
public static final String PRIVATE_KEY="/home/user/private.der";
public static final String PUBLIC_KEY="/home/user/public.der";
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
//get the private key
File file = new File(PRIVATE_KEY);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) file.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
System.out.println("Exponent :" + privKey.getPrivateExponent());
System.out.println("Modulus" + privKey.getModulus());
//get the public key
File file1 = new File(PUBLIC_KEY);
FileInputStream fis1 = new FileInputStream(file1);
DataInputStream dis1 = new DataInputStream(fis1);
byte[] keyBytes1 = new byte[(int) file1.length()];
dis1.readFully(keyBytes1);
dis1.close();
X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
System.out.println("Exponent :" + pubKey.getPublicExponent());
System.out.println("Modulus" + pubKey.getModulus());
}
}
According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).
FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional
v_aux VARCHAR2(32000);
v_has_double_quotes BOOLEAN;
v_has_comma BOOLEAN;
v_has_newline BOOLEAN;
BEGIN
v_has_double_quotes := instr(str, '"') > 0;
v_has_comma := instr(str,',') > 0;
v_has_newline := instr(str, C_NEWLINE) > 0;
IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
IF v_has_double_quotes THEN
v_aux := replace(str,'"','""');
ELSE
v_aux := str;
END IF;
return '"'||v_aux||'"';
ELSE
return str;
END IF;
END;
Instead of setting the ng-model to item.size.code, how about setting it to size:
<select ng-options="size as size.name for size in sizes"
ng-model="item" ng-change="update()"></select>
Then in your update()
method, $scope.item
will be set to the currently selected item.
And whatever code needed item.size.code
, can get that property via $scope.item.code
.
Update based on more info in comments:
Use some other $scope property for your select ng-model then:
<select ng-options="size as size.name for size in sizes"
ng-model="selectedItem" ng-change="update()"></select>
Controller:
$scope.update = function() {
$scope.item.size.code = $scope.selectedItem.code
// use $scope.selectedItem.code and $scope.selectedItem.name here
// for other stuff ...
}
It's a bug in chrome for local dev. Try other browser. Then it'll work.
The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.
http://momentjs.com/ Moment.js
will display the time nicely.
You have to change the file from .html to .php.
and add this following line
header('Content-Type: text/html; charset=utf-8');
I know this question is pretty old now, but I thought you might have an easier time with ElementTree
from xml.etree import ElementTree as ET
import datetime
f = ET.XML(data)
for element in f:
if element.tag == "currentTime":
# Handle time data was pulled
currentTime = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
if element.tag == "cachedUntil":
# Handle time until next allowed update
cachedUntil = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
if element.tag == "result":
# Process list of skills
pass
I know that's not super specific, but I just discovered it, and so far it's a lot easier to get my head around than the minidom (since so many nodes are essentially white space).
For instance, you have the tag name and the actual text together, just as you'd probably expect:
>>> element[0]
<Element currentTime at 40984d0>
>>> element[0].tag
'currentTime'
>>> element[0].text
'2010-04-12 02:45:45'e
If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.
Instead, you want to compile with link-time-optimization
clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o
and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm
clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program
This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing
clang program.bc -o program
although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.
Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option
-B/home/jeremy/fakebin
to any linking steps above.
You can see the differences b/w these two
import sys
for i in range(1,10 ):
sys.stdout.write(str(i))
sys.stdout.flush()
for i in range(1,10 ):
print i
If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html
If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.
$ git checkout stash@{0} -- <filename>
Notes:
Make sure you put space after the "--" and the file name parameter
Replace zero(0) with your specific stash number. To get stash list, use:
git stash list
Based on Jakub Narebski's answer -- Shorter version
The solution of @Ashivad mostly fixed my problem, but I needed to make this one-line addition to prevent the input to be erased after the results dropdown is displayed:
in success
callback of the autocomplete added this line after triggering chosen:updated
:
$combosearchChosen.find('input').val(request.term);
Complete listing:
var $combosearch = $('[data-combosearch]');
if (!$combosearch.length) {
return;
}
var options = $combosearch.data('options');
console.log('combosearch', $combosearch, options);
$combosearch.chosen({
no_results_text: "Oops, nothing found!",
width: "60%"
});
// actual chosen container
var $combosearchChosen = $combosearch.next();
$combosearchChosen.find('input').autocomplete({
source: function( request, response ) {
$.ajax({
url: options.remote_source + "&query=" + request.term,
dataType: "json",
beforeSend: function(){
$('ul.chosen-results').empty();
},
success: function( data ) {
response( $.map( data, function( item, index ) {
$combosearch.append('<option value="' + item.id + '">' + item.label + '</option>');
}));
$combosearch.trigger('chosen:updated');
$combosearchChosen.find('input').val(request.term);
}
});
}
});
You have to add
<script>jQuery.noConflict();</script>
after
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
Turn on debug logging to get a better picture of what is going on.
You can tell if the session cookies are being set by using a browser-side debugger to look at the headers returned in HTTP responses. (There are other ways too.)
One possibility is that SpringSecurity is setting secure session cookies, and your next page requested has an "http" URL instead of an "https" URL. (The browser won't send a secure cookie for an "http" URL.)
Use two different patterns: [0-9]*
and [a-zA-Z]*
and split twice by each of them.
select *
from TABLE_NAME
where dbms_lob.instr(COLUMNNAME,'searchtext') > 0;
The terms resource and endpoint are often used synonymously. But in fact they do not mean the same thing.
The term endpoint is focused on the URL that is used to make a request.
The term resource is focused on the data set that is returned by a request.
Now, the same resource can often be accessed by multiple different endpoints.
Also the same endpoint can return different resources, depending on a query string.
Let us see some examples:
Have a look at the following examples of different endpoints:
/api/companies/5/employees/3
/api/v2/companies/5/employees/3
/api/employees/3
They obviously could all access the very same resource in a given API.
Also an existing API could be changed completely. This could lead to new endpoints that would access the same old resources using totally new and different URLs:
/api/employees/3
/new_api/staff/3
If your endpoint returns a collection, you could implement searching/filtering/sorting using query strings. As a result the following URLs all use the same endpoint (/api/companies
), but they can return different resources (or resource collections, which by definition are resources in themselves):
/api/companies
/api/companies?sort=name_asc
/api/companies?location=germany
/api/companies?search=siemens
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
Quick function based on responses.
loadCSS = function(href) {
var cssLink = $("<link>");
$("head").append(cssLink); //IE hack: append before setting href
cssLink.attr({
rel: "stylesheet",
type: "text/css",
href: href
});
};
Usage:
loadCSS("/css/file.css");
If you have Java 6 (You should have, btw) or higher, then simply do this :
Console console = System.console();
String str = console.readLine("Please enter the xxxx : ");
Please remember to do :
import java.io.Console;
Thats it!
Memoization is the when you store previous results of a function call (a real function always returns the same thing, given the same inputs). It doesn't make a difference for algorithmic complexity before the results are stored.
Recursion is the method of a function calling itself, usually with a smaller dataset. Since most recursive functions can be converted to similar iterative functions, this doesn't make a difference for algorithmic complexity either.
Dynamic programming is the process of solving easier-to-solve sub-problems and building up the answer from that. Most DP algorithms will be in the running times between a Greedy algorithm (if one exists) and an exponential (enumerate all possibilities and find the best one) algorithm.
just put #login-box
before <h2>Welcome</h2>
will be ok.
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
here is jsfiddle http://jsfiddle.net/SyjjW/4/
Check for padding attribute if the issue still exists after changing theme.
Padding Issue creating a white space on top of fragment window / app window
Once you remove the padding - top value automatically the white space is removed.
Nowadays, most HTTP connections are considered persistent unless declared otherwise. However, to save server ressources the connection is rarely kept open forever, the default connection timeout for many servers is rather short, for example 5 seconds for the Apache httpd 2.2 and above.
The org.apache.http.NoHttpResponseException
error comes most likely from one persistent connection that was closed by the server.
It's possible to set the maximum time to keep unused connections open in the Apache Http client pool, in milliseconds.
With Spring Boot, one way to achieve this:
public class RestTemplateCustomizers {
static public class MaxConnectionTimeCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
HttpClient httpClient = HttpClientBuilder
.create()
.setConnectionTimeToLive(1000, TimeUnit.MILLISECONDS)
.build();
restTemplate.setRequestFactory(
new HttpComponentsClientHttpRequestFactory(httpClient));
}
}
}
// In your service that uses a RestTemplate
public MyRestService(RestTemplateBuilder builder ) {
restTemplate = builder
.customizers(new RestTemplateCustomizers.MaxConnectionTimeCustomizer())
.build();
}
How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?
If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.
using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt");
}
You need to add references to:
For .NET Core targeting net46, you need to add dependencies for
Example project.json:
"dependencies": {
"System.IO.Compression": "4.1.0",
"System.IO.Compression.ZipFile": "4.0.1"
},
"frameworks": {
"net46": {}
}
For .NET Core 2.0, just adding a simple using statement is all that is needed:
I already tried all of the possible solutions on stackoverflow and didn't work What I tried:
But finally I found the solution, you have to disable Hyper-V from System Configuration:
Check System Information then Hyper-V is off now
Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.
fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"
you can create Extension function for any View
fun View.hideKeyboard() = this.let {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
Example use with Activity
window.decorView.hideKeyboard();
Example use with View
etUsername.hideKeyboard();
Happy Coding...
React events are actually Synthetic Events, not Native Events. As it is written here:
Event delegation: React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops.
Try to use Use Event.stopImmediatePropagation
:
upvote: (e) ->
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
The difference between HEAD (current branch or last committed state on current branch), index (aka. staging area) and working tree (the state of files in checkout) is described in "The Three States" section of the "1.3 Git Basics" chapter of Pro Git book by Scott Chacon (Creative Commons licensed).
Here is the image illustrating it from this chapter:
In the above image "working directory" is the same as "working tree", the "staging area" is an alternate name for git "index", and HEAD points to currently checked out branch, which tip points to last commit in the "git directory (repository)"
Note that git commit -a
would stage changes and commit in one step.
It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?
something like this:
$("#gender").trigger("pageinit");
I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.
#!/usr/bin/perl
use FindBin::libs;
use <your lib>;
When the JVM loads classes, or otherwise sees a literal string, or some code intern
s a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string. If another copy is added, the runtime arranges it so that all the literals refer to the same string object. This is called "interning". If you say something like
String s = "test";
return (s == "test");
it'll return true
, because the first and second "test" are actually the same object. Comparing interned strings this way can be much, much faster than String.equals
, as there's a single reference comparison rather than a bunch of char
comparisons.
You can add a string to the pool by calling String.intern()
, which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string). The pooled version (the string returned from intern
) will be equal to any identical literal. For example:
String s1 = "test";
String s2 = new String("test"); // "new String" guarantees a different object
System.out.println(s1 == s2); // should print "false"
s2 = s2.intern();
System.out.println(s1 == s2); // should print "true"
Good Solution is to get Nearest Round Number is
var=2.5
echo $var | awk '{print int($1+0.5)}'
Logic is simple if the var decimal value is less then .5 then closest value taken is integer value. Well if decimal value is more than .5 then next integer value gets added and since awk then takes only integer part. Issue solved
You could reference controls inside the master page this way:
void Page_Load()
{
ContentPlaceHolder cph;
Literal lit;
cph = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if (cph != null) {
lit = (Literal) cph.FindControl("Literal1");
if (lit != null) {
lit.Text = "Some <b>HTML</b>";
}
}
}
In this example you have to put a Literal control in your ContentPlaceholder.
A standard LEFT JOIN could resolve the problem and, if the fields on join are indexed,
should also be faster
SELECT *
FROM Table1 as t1 LEFT JOIN Table2 as t2
ON t1.FirstName = t2.FirstName AND t1.LastName=t2.LastName
WHERE t2.BirthDate Is Null
This method does not need to modify dtype or ravel your numpy array.
The core idea is: 1.initialize with one extra row. 2.change the list(which has one more row) to array 3.delete the extra row in the result array e.g.
>>> a = [np.zeros((10,224)), np.zeros((10,))]
>>> np.array(a)
# this will raise error,
ValueError: could not broadcast input array from shape (10,224) into shape (10)
# but below method works
>>> a = [np.zeros((11,224)), np.zeros((10,))]
>>> b = np.array(a)
>>> b[0] = np.delete(b[0],0,0)
>>> print(b.shape,b[0].shape,b[1].shape)
# print result:(2,) (10,224) (10,)
Indeed, it's not necessarily to add one more row, as long as you can escape from the gap stated in @aravk33 and @user707650 's answer and delete the extra item later, it will be fine.
While @jackofallcode answer is correct, it can be written in one line:
((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);
Here's a complete example of jHackTheRipper's answer for the TL;DR crowd. :-) In this case, I wanted to run g++-4.5 on an Ubuntu system that defaults to 4.6. As root
:
apt-get install g++-4.5
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 100
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.5 50
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 100
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.5 50
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.6 100
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.5 50
update-alternatives --set g++ /usr/bin/g++-4.5
update-alternatives --set gcc /usr/bin/gcc-4.5
update-alternatives --set cpp-bin /usr/bin/cpp-4.5
Here, 4.6 is still the default (aka "auto mode"), but I explicitly switch to 4.5 temporarily (manual mode). To go back to 4.6:
update-alternatives --auto g++
update-alternatives --auto gcc
update-alternatives --auto cpp-bin
(Note the use of cpp-bin
instead of just cpp
. Ubuntu already has a cpp
alternative with a master link of /lib/cpp
. Renaming that link would remove the /lib/cpp
link, which could break scripts.)
File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml
, .yaml
or indeed anything else.
The (rather sparse) YAML FAQ recommends that you use .yaml
in preference to .yml
, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml
instead.
So, what really matters is what is inside the file, rather than what its extension is.
Please change small "mm" month to capital "MM" it will work.for reference below is the sample code.
Date myDate = new Date();
SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);
Date dt = sm.parse(strDate);
System.out.println(strDate);
I know this is probably overkill, but here's my ObjectComparer class I use for this very purpose:
/// <summary>
/// Utility class for comparing objects.
/// </summary>
public static class ObjectComparer
{
/// <summary>
/// Compares the public properties of any 2 objects and determines if the properties of each
/// all contain the same value.
/// <para>
/// In cases where object1 and object2 are of different Types (both being derived from Type T)
/// we will cast both objects down to the base Type T to ensure the property comparison is only
/// completed on COMMON properties.
/// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
/// both objects will be cast to Foo for comparison)
/// </para>
/// </summary>
/// <typeparam name="T">Any class with public properties.</typeparam>
/// <param name="object1">Object to compare to object2.</param>
/// <param name="object2">Object to compare to object1.</param>
/// <param name="propertyInfoList">A List of <see cref="PropertyInfo"/> objects that contain data on the properties
/// from object1 that are not equal to the corresponding properties of object2.</param>
/// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
public static bool GetDifferentProperties<T> ( T object1 , T object2 , out List<PropertyInfo> propertyInfoList )
where T : class
{
return GetDifferentProperties<T>( object1 , object2 , null , out propertyInfoList );
}
/// <summary>
/// Compares the public properties of any 2 objects and determines if the properties of each
/// all contain the same value.
/// <para>
/// In cases where object1 and object2 are of different Types (both being derived from Type T)
/// we will cast both objects down to the base Type T to ensure the property comparison is only
/// completed on COMMON properties.
/// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
/// both objects will be cast to Foo for comparison)
/// </para>
/// </summary>
/// <typeparam name="T">Any class with public properties.</typeparam>
/// <param name="object1">Object to compare to object2.</param>
/// <param name="object2">Object to compare to object1.</param>
/// <param name="ignoredProperties">A list of <see cref="PropertyInfo"/> objects
/// to ignore when completing the comparison.</param>
/// <param name="propertyInfoList">A List of <see cref="PropertyInfo"/> objects that contain data on the properties
/// from object1 that are not equal to the corresponding properties of object2.</param>
/// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
public static bool GetDifferentProperties<T> ( T object1 , T object2 , List<PropertyInfo> ignoredProperties , out List<PropertyInfo> propertyInfoList )
where T : class
{
propertyInfoList = new List<PropertyInfo>();
// If either object is null, we can't compare anything
if ( object1 == null || object2 == null )
{
return false;
}
Type object1Type = object1.GetType();
Type object2Type = object2.GetType();
// In cases where object1 and object2 are of different Types (both being derived from Type T)
// we will cast both objects down to the base Type T to ensure the property comparison is only
// completed on COMMON properties.
// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
// both objects will be cast to Foo for comparison)
if ( object1Type != object2Type )
{
object1Type = typeof ( T );
object2Type = typeof ( T );
}
// Remove any properties to be ignored
List<PropertyInfo> comparisonProps =
RemoveProperties( object1Type.GetProperties() , ignoredProperties );
foreach ( PropertyInfo object1Prop in comparisonProps )
{
Type propertyType = null;
object object1PropValue = null;
object object2PropValue = null;
// Rule out an attempt to check against a property which requires
// an index, such as one accessed via this[]
if ( object1Prop.GetIndexParameters().GetLength( 0 ) == 0 )
{
// Get the value of each property
object1PropValue = object1Prop.GetValue( object1 , null );
object2PropValue = object2Type.GetProperty( object1Prop.Name ).GetValue( object2 , null );
// As we are comparing 2 objects of the same type we know
// that they both have the same properties, so grab the
// first non-null value
if ( object1PropValue != null )
propertyType = object1PropValue.GetType().GetInterface( "IComparable" );
if ( propertyType == null )
if ( object2PropValue != null )
propertyType = object2PropValue.GetType().GetInterface( "IComparable" );
}
// If both objects have null values or were indexed properties, don't continue
if ( propertyType != null )
{
// If one property value is null and the other is not null,
// they aren't equal; this is done here as a native CompareTo
// won't work with a null value as the target
if ( object1PropValue == null || object2PropValue == null )
{
propertyInfoList.Add( object1Prop );
}
else
{
// Use the native CompareTo method
MethodInfo nativeCompare = propertyType.GetMethod( "CompareTo" );
// Sanity Check:
// If we don't have a native CompareTo OR both values are null, we can't compare;
// hence, we can't confirm the values differ... just go to the next property
if ( nativeCompare != null )
{
// Return the native CompareTo result
bool equal = ( 0 == (int) ( nativeCompare.Invoke( object1PropValue , new object[] {object2PropValue} ) ) );
if ( !equal )
{
propertyInfoList.Add( object1Prop );
}
}
}
}
}
return propertyInfoList.Count == 0;
}
/// <summary>
/// Compares the public properties of any 2 objects and determines if the properties of each
/// all contain the same value.
/// <para>
/// In cases where object1 and object2 are of different Types (both being derived from Type T)
/// we will cast both objects down to the base Type T to ensure the property comparison is only
/// completed on COMMON properties.
/// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
/// both objects will be cast to Foo for comparison)
/// </para>
/// </summary>
/// <typeparam name="T">Any class with public properties.</typeparam>
/// <param name="object1">Object to compare to object2.</param>
/// <param name="object2">Object to compare to object1.</param>
/// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
public static bool HasSamePropertyValues<T> ( T object1 , T object2 )
where T : class
{
return HasSamePropertyValues<T>( object1 , object2 , null );
}
/// <summary>
/// Compares the public properties of any 2 objects and determines if the properties of each
/// all contain the same value.
/// <para>
/// In cases where object1 and object2 are of different Types (both being derived from Type T)
/// we will cast both objects down to the base Type T to ensure the property comparison is only
/// completed on COMMON properties.
/// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
/// both objects will be cast to Foo for comparison)
/// </para>
/// </summary>
/// <typeparam name="T">Any class with public properties.</typeparam>
/// <param name="object1">Object to compare to object2.</param>
/// <param name="object2">Object to compare to object1.</param>
/// <param name="ignoredProperties">A list of <see cref="PropertyInfo"/> objects
/// to ignore when completing the comparison.</param>
/// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
public static bool HasSamePropertyValues<T> ( T object1 , T object2 , List<PropertyInfo> ignoredProperties )
where T : class
{
// If either object is null, we can't compare anything
if ( object1 == null || object2 == null )
{
return false;
}
Type object1Type = object1.GetType();
Type object2Type = object2.GetType();
// In cases where object1 and object2 are of different Types (both being derived from Type T)
// we will cast both objects down to the base Type T to ensure the property comparison is only
// completed on COMMON properties.
// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
// both objects will be cast to Foo for comparison)
if ( object1Type != object2Type )
{
object1Type = typeof ( T );
object2Type = typeof ( T );
}
// Remove any properties to be ignored
List<PropertyInfo> comparisonProps =
RemoveProperties( object1Type.GetProperties() , ignoredProperties );
foreach ( PropertyInfo object1Prop in comparisonProps )
{
Type propertyType = null;
object object1PropValue = null;
object object2PropValue = null;
// Rule out an attempt to check against a property which requires
// an index, such as one accessed via this[]
if ( object1Prop.GetIndexParameters().GetLength( 0 ) == 0 )
{
// Get the value of each property
object1PropValue = object1Prop.GetValue( object1 , null );
object2PropValue = object2Type.GetProperty( object1Prop.Name ).GetValue( object2 , null );
// As we are comparing 2 objects of the same type we know
// that they both have the same properties, so grab the
// first non-null value
if ( object1PropValue != null )
propertyType = object1PropValue.GetType().GetInterface( "IComparable" );
if ( propertyType == null )
if ( object2PropValue != null )
propertyType = object2PropValue.GetType().GetInterface( "IComparable" );
}
// If both objects have null values or were indexed properties, don't continue
if ( propertyType != null )
{
// If one property value is null and the other is not null,
// they aren't equal; this is done here as a native CompareTo
// won't work with a null value as the target
if ( object1PropValue == null || object2PropValue == null )
{
return false;
}
// Use the native CompareTo method
MethodInfo nativeCompare = propertyType.GetMethod( "CompareTo" );
// Sanity Check:
// If we don't have a native CompareTo OR both values are null, we can't compare;
// hence, we can't confirm the values differ... just go to the next property
if ( nativeCompare != null )
{
// Return the native CompareTo result
bool equal = ( 0 == (int) ( nativeCompare.Invoke( object1PropValue , new object[] {object2PropValue} ) ) );
if ( !equal )
{
return false;
}
}
}
}
return true;
}
/// <summary>
/// Removes any <see cref="PropertyInfo"/> object in the supplied List of
/// properties from the supplied Array of properties.
/// </summary>
/// <param name="allProperties">Array containing master list of
/// <see cref="PropertyInfo"/> objects.</param>
/// <param name="propertiesToRemove">List of <see cref="PropertyInfo"/> objects to
/// remove from the supplied array of properties.</param>
/// <returns>A List of <see cref="PropertyInfo"/> objects.</returns>
private static List<PropertyInfo> RemoveProperties (
IEnumerable<PropertyInfo> allProperties , IEnumerable<PropertyInfo> propertiesToRemove )
{
List<PropertyInfo> innerPropertyList = new List<PropertyInfo>();
// Add all properties to a list for easy manipulation
foreach ( PropertyInfo prop in allProperties )
{
innerPropertyList.Add( prop );
}
// Sanity check
if ( propertiesToRemove != null )
{
// Iterate through the properties to ignore and remove them from the list of
// all properties, if they exist
foreach ( PropertyInfo ignoredProp in propertiesToRemove )
{
if ( innerPropertyList.Contains( ignoredProp ) )
{
innerPropertyList.Remove( ignoredProp );
}
}
}
return innerPropertyList;
}
}
/*-------- Bootstrap Modal Popup in Center of Screen --------------*/
/*---------------extra css------*/
.modal {
text-align: center;
padding: 0 !important;
}
.modal:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -4px;
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
/*----- Modal Popup -------*/
<div class="modal fade" role="dialog">
<div class="modal-dialog" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h5 class="modal-title">Header</h5>
</div>
<div class="modal-body">
body here
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Could there be any problem if i replace Method-1 by Method-2?
No, just use map[key] = value
. The two options are equivalent.
Regarding Dictionary<>
vs. Hashtable
: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false);
and the add
parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.
You want to join on condition 1 AND condition 2, so simply use the AND keyword as below
ON a.userid = b.sourceid AND a.listid = b.destinationid;
In as few words as possible:
Intent myIntent = new Intent(MainActivity.this, Katra_home.class);
startActivity(myIntent);
This Should the perfect one :)
Try the :lt selector: http://docs.jquery.com/Selectors/lt#index
$('a:lt(20)');
I found the following slightly altered range useful for parsing comment blocks out of a database, this means that you won't have to contend with tab and escape characters which would cause a CSV field to become upset.
parsememo = Regex.Replace(parsememo, @"[^\u001F-\u007F]", string.Empty);
If you want to avoid other special characters or particular punctuation check the ascii table
In my Windows 7 box I found netbeans.conf in <Drive>:\<Program Files folder>\<NetBeans installation folder>\etc
. Thanks all.
Well, I like MONEY
! It's a byte cheaper than DECIMAL
, and the computations perform quicker because (under the covers) addition and subtraction operations are essentially integer operations. @SQLMenace's example—which is a great warning for the unaware—could equally be applied to INT
egers, where the result would be zero. But that's no reason not to use integers—where appropriate.
So, it's perfectly 'safe' and appropriate to use MONEY
when what you are dealing with is MONEY
and use it according to mathematical rules that it follows (same as INT
eger).
Would it have been better if SQL Server promoted division and multiplication of MONEY
's into DECIMAL
s (or FLOAT
s?)—possibly, but they didn't choose to do this; nor did they choose to promote INT
egers to FLOAT
s when dividing them.
MONEY
has no precision issue; that DECIMAL
s get to have a larger intermediate type used during calculations is just a 'feature' of using that type (and I'm not actually sure how far that 'feature' extends).
To answer the specific question, a "compelling reason"? Well, if you want absolute maximum performance in a SUM(x)
where x
could be either DECIMAL
or MONEY
, then MONEY
will have an edge.
Also, don't forget it's smaller cousin, SMALLMONEY
—just 4 bytes, but it does max out at 214,748.3647
- which is pretty small for money—and so is not often a good fit.
To prove the point around using larger intermediate types, if you assign the intermediate explicitly to a variable, DECIMAL
suffers the same problem:
declare @a decimal(19,4)
declare @b decimal(19,4)
declare @c decimal(19,4)
declare @d decimal(19,4)
select @a = 100, @b = 339, @c = 10000
set @d = @a/@b
set @d = @d*@c
select @d
Produces 2950.0000
(okay, so at least DECIMAL
rounded rather than MONEY
truncated—same as an integer would.)
Consider this question asked at StackOverflow today:
A good test and a practical example is what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.
What's the problem with the code?
The code only works the first time the user clicks the button.
What's the solution?
Add the var
keyword before the variable name.
I'm using Spring Boot 2.0.4.RELEASE. Hikari is default connection pool and .hikari
is no longer necessary.
application.properties
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.jdbcUrl=jdbc:mysql://localhost:3306/myDB...
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.poolname=myPool
application.yml
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/myDB...
username: xxx
password: xxx
poolName: myPool
And configuration
does not need to extend HikariConfig
, and DataSourceBuilder
can be used as it was before.
@Configuration
public class DataSourceConfiguration {
@Bean(name="myDataSource")
@ConfigurationProperties("spring.datasource")
public DataSource myDataSource() {
return DataSourceBuilder.create().build();
}
}
Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...
# fooz.yml
foo:
bar: <%= $ENV[:some_var] %>
No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.
If you can use the template like that or the << >>
or the {{ }}
styles depending on your reader, after that you just ...
In another yml file ...
# boo.yml
development:
fooz: foo
Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.
Then just Select
:
var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();
(edit) Actually - the names could be inferred in this case, so you could use:
var list = source.Select(s=>new { s.ID, s.Name }).ToList();
which saves a few electrons...
This is how you can find the latitude and longitude of where we have click on map.
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1)
{
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
}
return false;
}
it works well.
To get the location's address we can use geocoder class.
I recently discovered an interesting trick that allows to "Split String With String As Delimiter", so I couldn't resist the temptation to post it here as a new answer. Note that "obviously the question wasn't accurate. Firstly, both string1 and string2 can contain spaces. Secondly, both string1 and string2 can contain ampersands ('&')". This method correctly works with the new specifications (posted as a comment below Stephan's answer).
@echo off
setlocal
set "str=string1&with spaces by string2&with spaces.txt"
set "string1=%str: by =" & set "string2=%"
set "string2=%string2:.txt=%"
echo "%string1%"
echo "%string2%"
For further details on the split method, see this post.
SQL Server 2012 above, I prefer use format() function, more simplify.
SELECT format(date,'MM.yyyy') AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY format(date,'MM.yyyy')
It occurs basically when _Layout.cshtml is without:
@RenderSection("scripts", required: false)
or with
@RenderSection("scripts")
WITHOUT
required: false
So, Just add @RenderSection("scripts", required: false) in _Layout.cshtml and it works specially for those developers who works with Kendoui genarated projects.
This Question was asked here: VBA Arrays - Check strict (not approximative) match
Sub test()
vars1 = Array("Examples")
vars2 = Array("Example")
If IsInArray(Range("A1").value, vars1) Then
x = 1
End If
If IsInArray(Range("A1").value, vars2) Then
x = 1
End If
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
-[NSString initWithData:encoding]
is your friend but only when you use a proper encoding.
This seems to be the cleanest way to do
if (foo === 1) {
} else if (bar === 99) {
} else if (foo === 2) {
} else {
}
in the template:
<ng-container *ngIf="foo === 1; else elseif1">foo === 1</ng-container>
<ng-template #elseif1>
<ng-container *ngIf="bar === 99; else elseif2">bar === 99</ng-container>
</ng-template>
<ng-template #elseif2>
<ng-container *ngIf="foo === 2; else else1">foo === 2</ng-container>
</ng-template>
<ng-template #else1>else</ng-template>
Notice that it works like a proper else if
statement should when the conditions involve different variables (only 1 case is true at a time). Some of the other answers don't work right in such a case.
aside: gosh angular, that's some really ugly else if
template code...
You can use gridspec to control the spacing between axes. There's more information here.
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure(figsize = (4,4))
gs1 = gridspec.GridSpec(4, 4)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes.
for i in range(16):
# i = i + 1 # grid spec indexes from 0
ax1 = plt.subplot(gs1[i])
plt.axis('on')
ax1.set_xticklabels([])
ax1.set_yticklabels([])
ax1.set_aspect('equal')
plt.show()
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.
Edit: I found this JQuery script which is doing what you are asking for, I didn't test it though.
From http://htmlexplorer.com/2015/01/assign-output-var_dump-print_r-php-variable.html:
var_dump and print_r functions can only output directly to browser. So the output of these functions can only retrieved by using output control functions of php. Below method may be useful to save the output.
function assignVarDumpValueToString($object) { ob_start(); var_dump($object); $result = ob_get_clean(); return $result; }
ob_get_clean() can only clear last data entered to internal buffer. So ob_get_contents method will be useful if you have multiple entries.
From the same source as above:
function varDumpToErrorLog( $var=null ){ ob_start(); // start reading the internal buffer var_dump( $var); $grabbed_information = ob_get_contents(); // assigning the internal buffer contents to variable ob_end_clean(); // clearing the internal buffer. error_log( $grabbed_information); // saving the information to error_log }
Even same issue I faced, in browser it was showing compiled code. I have made below changes in webpack config file and it is working fine now.
devtool: '#inline-source-map',
debug: true,
and in loaders I kept babel-loader as first option
loaders: [
{
loader: "babel-loader",
include: [path.resolve(__dirname, "src")]
},
{ test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel' },
{ test: /\.html$/, loader: 'raw' },
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{test: /\.less$/, loader: "style!css!less"},
{ test: /\.styl$/, loader: 'style!css!stylus' },
{ test: /\.css$/, loader: 'style!css' }
]
Another option, using list comprehension and join:
''.join([_str[i] for i in xrange(len(_str)) if i != 4])
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.
location / {
root /path/to/root/of/static/files;
try_files $uri $uri/ @apachesite;
expires max;
access_log off;
}
location @apachesite {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files
. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.
I have been searching for this for ages on my CM 11 android phone, running kitkat.
Well.. finally I found it. It's hidden in a totally unintuitive location:
Here you can choose between Media Device (MTP), Camera (PTP) and Mass storage (UMS). Turn them all off to get it to charge only.
Sadly, if the option is not there, it is not supported by the phone. This seems to be the case for my HTC One (M7).
I had a similar problem with a log4j.xml file for a unit test, did all of the above. But figured out it was because I was only re-running a failed test....if I re-run the entire test class the correct file is picked up. This is under Intelli-j 9.0.4
HISTTIMEFORMAT="%d/%m/%y %H:%M "
For any commands typed prior to this, it will not help since they will just get a default time of when you turned history on, but it will log the time of any further commands after this.
If you want it to log history for permanent, you should put the following
line in your ~/.bashrc
export HISTTIMEFORMAT="%d/%m/%y %H:%M "
Use the element.checked
property.
This is what I use:
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
Convert an integer directly to long by adding 'L' to the end of Integer.
Long i = 1234L;
They have one for free as a sample at http://www.xamltemplates.net/
While list(map(int, str(x)))
is the Pythonic approach, you can formulate logic to derive digits without any type conversion:
from math import log10
def digitize(x):
n = int(log10(x))
for i in range(n, -1, -1):
factor = 10**i
k = x // factor
yield k
x -= k * factor
res = list(digitize(5243))
[5, 2, 4, 3]
One benefit of a generator is you can feed seamlessly to set
, tuple
, next
, etc, without any additional logic.
The first things to check (or ask your host provider to check) are the values of max_execution_time
, upload_max_filesize
, memory_limit
and post_max_size
in the php.ini configuration file. All of these three settings limit the maximum size of data that can be submitted and handled by PHP.
Please note that post_max_size
needs to be larger than upload_max_filesize
.
If you want to print something = '@'
2 times in a line, you can write this:
print(something * 2)
If you want to print 4 lines of something, you can use a for loop:
for i in range(4):
print(something)
echo
produces a trailing newline character which is hashed too. Try:
/bin/echo -n foobar | sha256sum
//function a(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 1');_x000D_
}, 3000);_x000D_
// callback();_x000D_
//}_x000D_
_x000D_
//function b(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 2');_x000D_
}, 2000);_x000D_
// callback();_x000D_
//}_x000D_
_x000D_
_x000D_
_x000D_
//function c(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 3');_x000D_
}, 1000);_x000D_
// callback();_x000D_
_x000D_
//}_x000D_
_x000D_
_x000D_
/*function d(callback){_x000D_
a(function(){_x000D_
b(function(){_x000D_
_x000D_
c(callback);_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
}_x000D_
d();*/_x000D_
_x000D_
_x000D_
async function funa(){_x000D_
_x000D_
var pr1=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 1"),3000)_x000D_
_x000D_
})_x000D_
_x000D_
_x000D_
var pr2=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 2"),2000)_x000D_
_x000D_
})_x000D_
_x000D_
var pr3=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 3"),1000)_x000D_
_x000D_
})_x000D_
_x000D_
_x000D_
var res1 = await pr1;_x000D_
var res2 = await pr2;_x000D_
var res3 = await pr3;_x000D_
console.log(res1,res2,res3);_x000D_
console.log(res1);_x000D_
console.log(res2);_x000D_
console.log(res3);_x000D_
_x000D_
} _x000D_
funa();_x000D_
_x000D_
_x000D_
_x000D_
async function f1(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,3000))_x000D_
.then(()=>console.log('Hi3 I am order 1'))_x000D_
return 1; _x000D_
_x000D_
}_x000D_
_x000D_
async function f2(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,2000))_x000D_
.then(()=>console.log('Hi3 I am order 2'))_x000D_
return 2; _x000D_
_x000D_
}_x000D_
_x000D_
async function f3(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,1000))_x000D_
.then(()=>console.log('Hi3 I am order 3'))_x000D_
return 3; _x000D_
_x000D_
}_x000D_
_x000D_
async function finaloutput2(arr){_x000D_
_x000D_
return await Promise.all([f3(),f2(),f1()]);_x000D_
}_x000D_
_x000D_
//f1().then(f2().then(f3()));_x000D_
//f3().then(f2().then(f1()));_x000D_
_x000D_
//finaloutput2();_x000D_
_x000D_
//var pr1=new Promise(f3)_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
async function f(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 1');_x000D_
}, 3000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// f(); _x000D_
_x000D_
async function g(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 2');_x000D_
}, 2000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// g(); _x000D_
_x000D_
async function h(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 3');_x000D_
}, 1000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
async function finaloutput(arr){_x000D_
_x000D_
return await Promise.all([f(),g(),h()]);_x000D_
}_x000D_
_x000D_
//finaloutput();_x000D_
_x000D_
//h(); _x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
What you need is called attribute selector. An example, using your html structure, is the following:
div[class^="tocolor-"], div[class*=" tocolor-"] {
color:red
}
In the place of div
you can add any element or remove it altogether, and in the place of class
you can add any attribute of the specified element.
[class^="tocolor-"]
— starts with "tocolor-".
[class*=" tocolor-"]
— contains the substring "tocolor-" occurring directly after a space character.
Demo: http://jsfiddle.net/K3693/1/
More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs
Use a second ArrayList for the 3 strings, not a primitive array. Ie.
private List<List<String>> addresses = new ArrayList<List<String>>();
Then you can have:
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
addresses.add(singleAddress);
(I think some strange things can happen with type erasure here, but I don't think it should matter here)
If you're dead set on using a primitive array, only a minor change is required to get your example to work. As explained in other answers, the size of the array can not be included in the declaration. So changing:
private ArrayList<String[]> addresses = new ArrayList<String[3]>();
to
private ArrayList<String[]> addresses = new ArrayList<String[]>();
will work.
"How to attach url link to an image?"
You do it like this:
<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>
See it in action.
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
Here's a generic helper function with assumption checking:
func assumeNoError(value interface{}, err error) interface{} {
if err != nil {
panic("error encountered when none assumed:" + err.Error())
}
return value
}
Since this returns as an interface{}
, you'll generally need to cast it back to your function's return type.
For example, the OP's example called Get(1)
, which returns (Item, error)
.
item := assumeNoError(Get(1)).(Item)
The trick that makes this possible: Multi-values returned from one function call can be passed in as multi-variable arguments to another function.
As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order.
This answer borrows heavily from existing answers, but none had provided a simple, generic solution of this form.
In the .css try
.jumbotron {_x000D_
background-color:red !important; _x000D_
}
_x000D_
The few lines you posted from your script look okay to me. It's probably something a bit deeper.
You need to find which line is giving you this error. Add set -xv
to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.
BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash
on top, but your bash interpreter is located in /usr/bin/bash
, you'll see this error.
New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
Two ways:
You can use setState
inside componentDidUpdate
. The problem is that somehow you are creating an infinite loop because there's no break condition.
Based on the fact that you need values that are provided by the browser once the component is rendered, I think your approach about using componentDidUpdate
is correct, it just needs better handling of the condition that triggers the setState
.
Originally there was just 302
Response | What browsers should do |
---|---|
302 Found |
Redo request with new url |
The idea is that:
GET
at some location, you would redo your GET
to the new URLPOST
at some location, you would redo your POST
to the new URLPUT
at some location, you would redo your PUT
to the new URLDELETE
at some location, you would redo your DELETE
to the new URLUnfortunately every browser did it wrong. When getting a 302
, they would always switch to GET
at the new URL, rather than retrying the request with the same verb (e.g., POST
):
It became de-facto wrong.
All browsers got 302
wrong. So 303
and 307
were created.
Response | What browsers should do | What browsers actually do |
---|---|---|
302 Found |
Redo request with new url | GET with new url |
303 See Other |
GET with new url | GET with new url |
307 Temporary Redirect |
Redo request with new url | Redo request with new url |
The 5 different kinds of redirects:
+------------------------------------------------------------+
¦ ¦ Switch to GET? ¦
¦ ¦------------------------------------------------¦
¦ Temporary ¦ No ¦ Yes ¦
¦-----------+------------------------+-----------------------¦
¦ No ¦ 308 Permanent Redirect ¦ 301 Moved Permanently ¦
¦-----------+------------------------+-----------------------¦
¦ Yes ¦ 307 Temporary Redirect ¦ 303 See Other ¦
¦ ¦ 302 Found (intended) ¦ 302 Found (actual) ¦
+------------------------------------------------------------+
Alternatively:
Response | Switch to get? | Temporary? |
---|---|---|
301 Moved Permanently |
No | No |
302 Found (intended) |
No | Yes |
302 Found (actual) |
Yes | Yes |
303 See Other |
Yes | Yes |
307 Temporary Redirect |
No | Yes |
308 Permanent Redirect |
No | No |
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
You need Set with objects:
Set rng = Sheet8.Range("A12")
Sheet8 is fine.
Sheet1.[a1]
I made a simple to use utility, hope you enjoy.
If the generated INSERT statements are being truncated, check the limit text length of the results on the Management Studio Options: Tools > Options
, Query Results > SQL Server > Results to Grid
, "Non XML data" value under "Maximum Characters Retrieved".
-- Make sure you're on the correct database
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
DECLARE @Tables TABLE (
TableName varchar(50) NOT NULL,
Arguments varchar(1000) NULL
);
-- INSERT HERE THE TABLES AND CONDITIONS YOU WANT TO GENERATE THE INSERT STATEMENTS
INSERT INTO @Tables (TableName, Arguments) VALUES ('table1', 'WHERE field1 = 3101928464');
-- (ADD MORE LINES IF YOU LIKE) INSERT INTO @Tables (TableName, Arguments) VALUES ('table2', 'WHERE field2 IN (1, 3, 5)');
-- YOU DON'T NEED TO EDIT FROM NOW ON.
-- Generating the Script
DECLARE @TableName varchar(50),
@Arguments varchar(1000),
@ColumnName varchar(50),
@strSQL varchar(max),
@strSQL2 varchar(max),
@Lap int,
@Iden int,
@TypeOfData int;
DECLARE C1 CURSOR FOR
SELECT TableName, Arguments FROM @Tables
OPEN C1
FETCH NEXT FROM C1 INTO @TableName, @Arguments;
WHILE @@FETCH_STATUS = 0
BEGIN
-- If you want to delete the lines before inserting, uncomment the next line
-- PRINT 'DELETE FROM ' + @TableName + ' ' + @Arguments
SET @strSQL = 'INSERT INTO ' + @TableName + ' (';
-- List all the columns from the table (to the INSERT into columns...)
SET @Lap = 0;
DECLARE C2 CURSOR FOR
SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
OPEN C2
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
WHILE @@FETCH_STATUS = 0
BEGIN
IF(@Lap>0)
BEGIN
SET @strSQL = @strSQL + ', ';
END
SET @strSQL = @strSQL + @ColumnName;
SET @Lap = @Lap + 1;
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
END
CLOSE C2
DEALLOCATE C2
SET @strSQL = @strSQL + ')'
SET @strSQL2 = 'SELECT ''' + @strSQL + '
SELECT '' + ';
-- List all the columns from the table again (for the SELECT that will be the input to the INSERT INTO statement)
SET @Lap = 0;
DECLARE C2 CURSOR FOR
SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
OPEN C2
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
WHILE @@FETCH_STATUS = 0
BEGIN
IF(@Lap>0)
BEGIN
SET @strSQL2 = @strSQL2 + ' + '', '' + ';
END
-- For each data type, convert the data properly
IF(@TypeOfData IN (55, 106, 56, 108, 63, 38, 109, 50, 48, 52)) -- Numbers
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (62)) -- Float Numbers
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), CONVERT(decimal(18,5), ' + @ColumnName + ')), ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (61, 111)) -- Datetime
SET @strSQL2 = @strSQL2 + 'ISNULL( '''''''' + CONVERT(varchar(max),' + @ColumnName + ', 121) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (47, 39)) -- Texts
SET @strSQL2 = @strSQL2 + 'ISNULL('''''''' + RTRIM(LTRIM(' + @ColumnName + ')) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
ELSE -- Unknown data types
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '(INCORRECT TYPE ' + CONVERT(varchar(10), @TypeOfData) + ')''';
SET @Lap = @Lap + 1;
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
END
CLOSE C2
DEALLOCATE C2
SET @strSQL2 = @strSQL2 + ' as [-- ' + @TableName + ']
FROM ' + @TableName + ' WITH (NOLOCK) ' + @Arguments
SET @strSQL2 = @strSQL2 + ';
';
--PRINT @strSQL;
--PRINT @strSQL2;
EXEC(@strSQL2);
FETCH NEXT FROM C1 INTO @TableName, @Arguments;
END
CLOSE C1
DEALLOCATE C1
ROLLBACK
END TRY
BEGIN CATCH
ROLLBACK TRAN
SELECT 0 AS Situacao;
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage,
@strSQL As strSQL,
@strSQL2 as strSQL2;
END CATCH
You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink
Assuming you have foo.conf in sites-available
Try
cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l
Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf
Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.
If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.
ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf
Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:
lrwxrwxrwx 1 root root 26 Jun 24 21:06 000-default -> ../sites-available/default
See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).
Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.
you could add an sed script to your commandline:
ls /home/user/new/*.txt | sed -r 's/^.+\///'
I think it simple in mysql since mysql the inbuilt function called now() which gives current time(time of that insert).
So your query should look like similarly
CREATE TABLE defaultforTime(
`creation_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
`modification_time` DATETIME default now()
);
Thank you.
You can also switch environments in Anaconda Navigator, install Jupiter and run it.
Changing only what's after hash - old browsers
document.location.hash = 'lookAtMeNow';
Changing full URL. Chrome, Firefox, IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use
history.replaceState('data to be passed', 'Title of the page', '/test');
Try running these in the console now!
Add an END
at last before alias name.
CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
For example:
SELECT CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
FROM TableName
If you know that your Properties
object only contains <String, String>
entries, you can resort to a raw type:
Properties properties = new Properties();
Map<String, String> map = new HashMap<String, String>((Map) properties);
#!/bin/ksh
variable1=$(
echo "set feed off
set pages 0
select count(*) from table;
exit
" | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"
The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC
See http://play.golang.org/p/vTidOlmb9P
You can use Google Guava Table
Complete class to download a file while printing status to console.
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
class FileDownloader
{
private readonly string _url;
private readonly string _fullPathWhereToSave;
private bool _result = false;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);
public FileDownloader(string url, string fullPathWhereToSave)
{
if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
if (string.IsNullOrEmpty(fullPathWhereToSave)) throw new ArgumentNullException("fullPathWhereToSave");
this._url = url;
this._fullPathWhereToSave = fullPathWhereToSave;
}
public bool StartDownload(int timeout)
{
try
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWhereToSave));
if (File.Exists(_fullPathWhereToSave))
{
File.Delete(_fullPathWhereToSave);
}
using (WebClient client = new WebClient())
{
var ur = new Uri(_url);
// client.Credentials = new NetworkCredential("username", "password");
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadFileCompleted += WebClientDownloadCompleted;
Console.WriteLine(@"Downloading file:");
client.DownloadFileAsync(ur, _fullPathWhereToSave);
_semaphore.Wait(timeout);
return _result && File.Exists(_fullPathWhereToSave);
}
}
catch (Exception e)
{
Console.WriteLine("Was not able to download file!");
Console.Write(e);
return false;
}
finally
{
this._semaphore.Dispose();
}
}
private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.Write("\r --> {0}%.", e.ProgressPercentage);
}
private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
{
_result = !args.Cancelled;
if (!_result)
{
Console.Write(args.Error.ToString());
}
Console.WriteLine(Environment.NewLine + "Download finished!");
_semaphore.Release();
}
public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
{
return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
}
}
Usage:
static void Main(string[] args)
{
var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec);
Console.WriteLine("Done - success: " + success);
Console.ReadLine();
}
In your terminal run: docker exec -it container_name /bin/bash
Then: mysql
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
Can be read, "For all s such that s does not equal s[start]"
$ ps -fA | grep python
501 81211 12368 0 10:11PM ttys000 0:03.12
python -m SimpleHTTPServer
$ kill 81211
String text = String.copyValueOf(data);
or
String text = String.valueOf(data);
is arguably better (encapsulates the new String
call).
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:
void foo(char* str);
foo("hello");
However, if you want to keep your code warning-free as well then just make respective change in your code:
void foo(char* str);
foo((char *)"hello");
That is, simply cast the string
constant to (char *)
.
Here one big collection of debug constants that we use. Enjoy.
// Uncomment the defitions to show additional info.
// #define DEBUG
// #define DEBUGWHERE_SHOWFULLINFO
// #define DEBUG_SHOWLINES
// #define DEBUG_SHOWFULLPATH
// #define DEBUG_SHOWSEPARATORS
// #define DEBUG_SHOWFULLINFO
// Definition of DEBUG functions. Only work if DEBUG is defined.
#ifdef DEBUG
#define debug_separator() NSLog( @"----------------------------------------------------------------------------" );
#ifdef DEBUG_SHOWSEPARATORS
#define debug_showSeparators() debug_separator();
#else
#define debug_showSeparators()
#endif
/// /// /// ////// /////
#ifdef DEBUG_SHOWFULLPATH
#define debug_whereFull() debug_showSeparators(); NSLog(@"Line:%d : %s : %s", __LINE__,__FILE__,__FUNCTION__); debug_showSeparators();
#else
#define debug_whereFull() debug_showSeparators(); NSLog(@"Line:%d : %s : %s", __LINE__,[ [ [ [NSString alloc] initWithBytes:__FILE__ length:strlen(__FILE__) encoding:NSUTF8StringEncoding] lastPathComponent] UTF8String ] ,__FUNCTION__); debug_showSeparators();
#endif
/// /// /// ////// /////
#define debugExt(args,...) debug_separator(); debug_whereFull(); NSLog( args, ##__VA_ARGS__); debug_separator();
/// /// /// ////// ///// Debug Print Macros
#ifdef DEBUG_SHOWFULLINFO
#define debug(args,...) debugExt(args, ##__VA_ARGS__);
#else
#ifdef DEBUG_SHOWLINES
#define debug(args,...) debug_showSeparators(); NSLog([ NSString stringWithFormat:@"Line:%d : %@", __LINE__, args ], ##__VA_ARGS__); debug_showSeparators();
#else
#define debug(args,...) debug_showSeparators(); NSLog(args, ##__VA_ARGS__); debug_showSeparators();
#endif
#endif
/// /// /// ////// ///// Debug Specific Types
#define debug_object( arg ) debug( @"Object: %@", arg );
#define debug_int( arg ) debug( @"integer: %i", arg );
#define debug_float( arg ) debug( @"float: %f", arg );
#define debug_rect( arg ) debug( @"CGRect ( %f, %f, %f, %f)", arg.origin.x, arg.origin.y, arg.size.width, arg.size.height );
#define debug_point( arg ) debug( @"CGPoint ( %f, %f )", arg.x, arg.y );
#define debug_bool( arg ) debug( @"Boolean: %@", ( arg == YES ? @"YES" : @"NO" ) );
/// /// /// ////// ///// Debug Where Macros
#ifdef DEBUGWHERE_SHOWFULLINFO
#define debug_where() debug_whereFull();
#else
#define debug_where() debug(@"%s",__FUNCTION__);
#endif
#define debug_where_separators() debug_separator(); debug_where(); debug_separator();
/// /// /// ////// /////
#else
#define debug(args,...)
#define debug_separator()
#define debug_where()
#define debug_where_separators()
#define debug_whereFull()
#define debugExt(args,...)
#define debug_object( arg )
#define debug_int( arg )
#define debug_rect( arg )
#define debug_bool( arg )
#define debug_point( arg )
#define debug_float( arg )
#endif
Use element.closest()
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
See this example DOM:
<article>
<div id="div-01">Here is div-01
<div id="div-02">Here is div-02
<div id="div-03">Here is div-03</div>
</div>
</div>
</article>
This is how you would use element.closest:
var el = document.getElementById('div-03');
var r1 = el.closest("#div-02");
// returns the element with the id=div-02
var r2 = el.closest("div div");
// returns the closest ancestor which is a div in div, here is div-03 itself
var r3 = el.closest("article > div");
// returns the closest ancestor which is a div and has a parent article, here is div-01
var r4 = el.closest(":not(div)");
// returns the closest ancestor which is not a div, here is the outmost article
IF you have data you're waiting for the server to return (item.id) and have a construct like this:
ng-style="{'background-image':'url(https://www.myImageplusitsid/{{item.id}})'}"
Make sure you add something like ng-if="item.id"
Otherwise you'll either have two requests or one faulty.
Use the following code:
make -I/usr/lib/jvm/jdk*/include
where jdk* is the directory name of your jdk installation (e.g. jdk1.7.0).
And there wouldn't be a system-wide solution since the directory name would be different with different builds of JDK downloaded and installed. If you desire an automated solution, please include all commands in a single script and run the said script in Terminal.
You need to call the AddAddress
method once for every recipient. Like so:
$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..
Better yet, add them as Carbon Copy recipients.
$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..
To make things easy, you should loop through an array to do this.
$recipients = array(
'[email protected]' => 'Person One',
'[email protected]' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
As of the time of answering this, Eclipse Version: 2020-06 (4.16.0)
has a File --> Import --> Gradle --> Existing gradle project
menu option.You can use this option to import gradle project into Eclipse directly.
Personally I prefer making it in two seperate sections but within the same PHP like:
<?php
if (question1) { $variable_1 = somehtml; }
else { $variable_1 = someotherhtml; }
if (question2) {
$variable_2 = somehtml2;
}
else {
$variable_2 = someotherhtml2;
}
etc.
$output=<<<HERE
htmlhtmlhtml$variable1htmlhtmlhtml$varianble2htmletcetcetc
HERE;
echo $output;
?>
But maybe it is slower?
publish date: 06/26/2018
https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("anonymous",
"[email protected]");
// Copy the contents of the file to the request stream.
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader("testfile.txt"))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine($"Upload File Complete, status
{response.StatusDescription}");
}
}
}
}
Similar, but using WMIC command line to obtain the process ID and path:
WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid
This will create a text file with each process and its parameters. You can search in the file for your VM File Path, and get the correct Process ID to end task with.
Thanks to http://windowsxp.mvps.org/listproc.htm for the correct command line parameters.
To get the checked state of your checkbox the path would be:
this.refs.complete.state.checked
The alternative is to get it from the event passed into the handleChange
method:
event.target.checked
@JsonFormat only work for standard format supported by the jackson version that you are using.
Ex :- compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) for jackson 2.8.6
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
Because:
$ find /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home -name java*
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javac
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javadoc
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javafxpackager
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javah
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javap
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/javapackager
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/javafx-src.zip
/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/bin/java
There's two steps in that process:
a) Grant privileges. As root user execute with this substituting 'password'
with your current root password :
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';
b) bind to all addresses:
The easiest way is to comment out the line in your my.cnf
file:
#bind-address = 127.0.0.1
and restart mysql
service mysql restart
By default it binds only to localhost, but if you comment the line it binds to all interfaces it finds. Commenting out the line is equivalent to bind-address=*
.
To check where mysql service has binded execute as root:
netstat -tupan | grep mysql
Update For Ubuntu 16:
Config file is (now)
/etc/mysql/mysql.conf.d/mysqld.cnf
(at least on standard Ubuntu 16)
You add a
float: left;
to the style of the 3 elements and make sure the parent container has
overflow: hidden; position: relative;
this makes sure the floats take up actual space.
<html>
<head>
<title>Website Title </title>
</head>
<body>
<div id="the-whole-thing" style="position: relative; overflow: hidden;">
<div id="leftThing" style="position: relative; width: 25%; background-color: blue; float: left;">
Left Side Menu
</div>
<div id="content" style="position: relative; width: 50%; background-color: green; float: left;">
Random Content
</div>
<div id="rightThing" style="position: relative; width: 25%; background-color: yellow; float: left;">
Right Side Menu
</div>
</div>
</body>
</html>
Also please note that the width: 100% and height: 100% need to be removed from the container, otherwise the 3rd block will wrap to a 2nd line.
By default Jsonresult "Deny get"
Suppose if we have method like below
[HttpPost]
public JsonResult amc(){}
By default it "Deny Get".
In the below method
public JsonResult amc(){}
When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.
public JsonResult amc()
{
return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}
Changing this behaviour actually creates a far better user experience than the default behaviour implemented natively. Consider that the behaviour of the enter key is already inconsistent from the user's point of view, because in a single line input, enter tends to submit a form, while in a multi-line textarea, it simply adds a newline to the contents of the field.
I recently did it like this (uses jQuery):
$('input.enterastab, select.enterastab, textarea.enterastab').live('keydown', function(e) {
if (e.keyCode==13) {
var focusable = $('input,a,select,button,textarea').filter(':visible');
focusable.eq(focusable.index(this)+1).focus();
return false;
}
});
This is not terribly efficient, but works well enough and is reliable - just add the 'enterastab' class to any input element that should behave in this way.
The way I do it is practically a one-liner.
The function creates a Range object and then creates a DocumentFragment in the Range with the string as the child content.
Then it grabs the text of the fragment, removes any "invisible"/zero-width characters, and trims it of any leading/trailing white space.
I realize this question is old, I just thought my solution was unique and wanted to share. :)
function getTextFromString(htmlString) {
return document
.createRange()
// Creates a fragment and turns the supplied string into HTML nodes
.createContextualFragment(htmlString)
// Gets the text from the fragment
.textContent
// Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
.replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
// Trims off any extra space on either end of the string
.trim();
}
var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');
alert(cleanString);
Although I like fhucho's recommendation of
String.valueOf(i)
The irony is that this method actually calls
Integer.toString(i)
Thus, use String.valueOf(i)
if you like how it reads and you don't need radix, but also knowing that it is less efficient than Integer.toString(i)
.
Symbol You Want on Color You Want!
I was looking for this answer for days and here it is the right and easy way to create a custom marker:
'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=xxx%7c5680FC%7c000000&.png' where xxx is the text and 5680fc is the hexadecimal color code of the background and 000000 is the hexadecimal color code of the text.
Theses markers are totally dynamic and you can create whatever balloon icon you want. Just change the URL.
Use the StringUtils class, it also includes null check
StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
You're almost there, you just have to append:
-Dhttp.proxyUser=someUserName
-Dhttp.proxyPassword=somePassword
Public Class Item
Public ID As Guid
Public Text As String
Public Sub New(ByVal id As Guid, ByVal name As String)
Me.ID = id
Me.Text = name
End Sub
End Class
Public Sub Load(sender As Object, e As EventArgs) Handles Me.Load
Dim box As New ComboBox
Me.Controls.Add(box) 'Sorry I forgot this line the first time.'
Dim h As IntPtr = box.Handle 'Im not sure you need this but you might.'
Try
box.Items.Add(New Item(Guid.Empty, Nothing))
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
The output is "Attempted to read protected memory. This is an indication that other memory is corrupt."
If, like me, none of the above quite works, it might be worth also specifically trying a lower TLS version alone. I had tried both of the following, but didn't seem to solve my problem:
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls
In the end, it was only when I targetted TLS 1.0 (specifically remove 1.1 and 1.2 in the code) that it worked:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls
The local server (that this was being attempted on) is fine with TLS 1.2, although the remote server (which was previously "confirmed" as fine for TLS 1.2 by a 3rd party) seems not to be.
Hope this helps someone.
In my case I am using a CSS framework which adds box-shadow
, so I had to also add
box-shadow: none;
So the complete snippet is:
border: none;
border-width: 0;
box-shadow: none;
# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
iptables -A FORWARD -p all -d $ip -j REJECT
done
The options object can be added to the chart when the new Chart object is created.
var chart1 = new Chart(canvas, {
type: "pie",
data: data,
options: {
legend: {
display: false
},
tooltips: {
enabled: false
}
}
});
Just had to fix this myself. The above answers don't seem to take into account the
$mail->SMTPDebug = 0;
option. It may not have been available when the question was first asked.
If you got your code from the PHPMail site, the default will be
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
https://github.com/Synchro/PHPMailer/blob/master/examples/test_smtp_gmail_advanced.php
Set the value to 0 to suppress the errors and edit the 'catch' part of your code as explained above.
According to documentation of $viewContentLoaded, it supposed to work
Emitted every time the ngView content is reloaded.
$viewContentLoaded
event is emitted that means to receive this event you need a parent controller like
<div ng-controller="MainCtrl">
<div ng-view></div>
</div>
From MainCtrl
you can listen the event
$scope.$on('$viewContentLoaded', function(){
//Here your view content is fully loaded !!
});
Check the Demo
Try this
ImageView img
Bitmap bmp;
int width=100;
int height=100;
img=(ImageView)findViewById(R.id.imgView);
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.image);//image is your image
bmp=Bitmap.createScaledBitmap(bmp, width,height, true);
img.setImageBitmap(bmp);
Or If you want to load complete image size in memory then you can use
<ImageView
android:id="@+id/img"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/image"
android:scaleType="fitXY"/>
hello everyone I had the same issue and non of the above answers fixed so I went to the flutter official GitHub and found the answer there here is the link and you have to follow all these steps.
https://github.com/flutter/flutter/issues/67986
flutter upgrade
flutter config --android-studio-dir="C:\Program Files\Android\Android Studio"
for mac you can do the following as answered by Andrew
ln -s ~/Library/Application\ Support/Google/AndroidStudio4.1/plugins ~/Library/Application\ Support/AndroidStudio4.1
flutter doctor -v
then if the issue still persistes then just shift to the beta channel and the upgrade flutter then it will fix it.
flutter channel beta
flutter upgrade
you can enable flutter web as an optional steps
As per: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
9.2 OPTIONS
The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
Responses to this method are not cacheable.
If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body.
If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).
If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.
A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of "0".
The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a Max-Forwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.
9.4 HEAD
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.
First install a pod :-
pod 'SwiftGifOrigin'
and import in your class
import SwiftGifOrigin
then write this code in viewDidiload method
yourImageView.image = UIImage.gif(name: "imageName")
Note:- plz do not include the file extension in the gif file name. Ex:-
//Don't Do this
yourImageView.image = UIImage.gif(name: "imageName.gif")
See source: https://github.com/swiftgif/SwiftGif
Had such a problem (with https://github.com/PHPMailer/PHPMailer), just reload PHP and everything start worked
for Centos 6 and 7:
service php-fpm restart
A solution could be to use adapter functions like these to start using mysqli
instead of mysql
over your entire application:
if (!function_exists('mysql_connect')) {
function mysql_connect($host = '', $user = '', $password = '', $database = '', $port = 0, $socket = '') {
return mysqli_connect($host, $user, $password, $database, $port, $socket);
}
}
if (!function_exists('mysql_select_db')) {
function mysql_select_db($link, $dbname) {
mysqli_select_db($link, $dbname);
}
}
I could do this on Linux.
$ pip3 install --user 'requests[socks]'
$ https_proxy=socks5://<hostname or ip>:<port> python3 -c \
> 'import requests;print(requests.get("https://httpbin.org/ip").text)'
I think there is another elegant solution.
What you want to do is (safely) "pass" the type of the generic type parameter up from the concerete class to the superclass.
If you allow yourself to think of the class type as "metadata" on the class, that suggests the Java method for encoding metadata in at runtime: annotations.
First define a custom annotation along these lines:
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EntityAnnotation {
Class entityClass();
}
You can then have to add the annotation to your subclass.
@EntityAnnotation(entityClass = PassedGenericType.class)
public class Subclass<PassedGenericType> {...}
Then you can use this code to get the class type in your base class:
import org.springframework.core.annotation.AnnotationUtils;
.
.
.
private Class getGenericParameterType() {
final Class aClass = this.getClass();
EntityAnnotation ne =
AnnotationUtils.findAnnotation(aClass, EntityAnnotation.class);
return ne.entityClass();
}
Some limitations of this approach are:
PassedGenericType
) in TWO places rather than one which is non-DRY.Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.
HTML:
<h1>Hello world!</h1>
Javascript (jQuery):
$(document).ready(function(){
$('h1').css({ 'width':'100%', 'text-align':'center' });
var h1 = $('h1').height();
var h = h1/2;
var w1 = $(window).height();
var w = w1/2;
var m = w - h
$('h1').css("margin-top",m + "px")
});
This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top
of the h1. The beauty of this method is that it works on multiple-line h1
s.
EDIT: I modified it so that it centered it every time the window is resized.
assert_has_calls
is another approach to this problem.
From the docs:
assert_has_calls (calls, any_order=False)
assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.
If any_order is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.
If any_order is True then the calls can be in any order, but they must all appear in mock_calls.
Example:
>>> from unittest.mock import call, Mock
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
Source: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls
You can write your own extension method
public static class IntegerExtensions
{
public static int ParseInt(this string value, int defaultValue = 0)
{
int parsedValue;
if (int.TryParse(value, out parsedValue))
{
return parsedValue;
}
return defaultValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return value.ParseInt();
}
}
And wherever in code just call
int myNumber = someString.ParseInt(); // Returns value or 0
int age = someString.ParseInt(18); // With default value 18
int? userId = someString.ParseNullableInt(); // Returns value or null
In this concrete case
int yourValue = TextBoxD1.Text.ParseInt();
You might want to retain source order then you can just use this.
@import
'foo',
'bar';
I prefer this.
If you get the the text inside the element use
$(".element-classname").text();
In your code:
$('.HOEnZb').text();
if you want get all the data including html Tags use:
$(".element-classname").html();
In your code:
$('.HOEnZb').html();
Hope it helps:)
Use insert() to insert an element before a given position.
For instance, with
arr = ['A','B','C']
arr.insert(0,'D')
arr becomes ['D','A','B','C']
because D
is inserted before the element at index 0.
Now, for
arr = ['A','B','C']
arr.insert(4,'D')
arr becomes ['A','B','C','D']
because D
is inserted before the element at index 4 (which is 1 beyond the end of the array).
However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.
Here's some example code:
import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
print perm
will print out
('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
ORDER BY modify_date DESC
The type
for a function is FN
rather than P
for procedure. Or you can filter on the name column.
$date = new \DateTime("now", new \DateTimeZone('Asia/Calcutta') );
$day = $date->format('D');
$weekendnaame = weekedName();
$weekid =$weekendnaame[$day];
$dayname = 0;
$weekiarray = weekendArray($weekid);
foreach ($weekiarray as $key => $value) {
if (in_array($value, $request->get('week_id')))
{
$dayname = $key+1;
break;
}
}
weeknDate($dayname),
function weeked(){
$week = array("1"=>"Sunday", "2"=>"Monday", "3"=>"Tuesday", "4"=>"Wednesday", "5"=>"Thursday", "6"=>"Friday", "7"=>"Saturday");
return $week;
}
function weekendArray($day){
$favcolor = $day;
switch ($favcolor) {
case 1:
$array = array(2,3,4,5,6,7,1);
break;
case 2:
$array = array(3,4,5,6,7,1,2);
break;
case 3:
$array = array(4,5,6,7,1,2,3);
break;
case 4:
$array = array(5,6,7,1,2,3,4);
break;
case 5:
$array = array(6,7,1,2,3,4,5);
break;
case 6:
$array = array(7,1,2,3,4,5,6);
break;
case 7:
$array = array(1,2,3,4,5,6,7);
break;
default:
$array = array(1,2,3,4,5,6,7);
}
return $array;
}
function weekedName(){
$week = array("Sun"=>0,"Mun"=>1,"Tue"=>3,"Wed"=>4,"Thu"=>5,"Fri"=>6,"Sat"=>7);
return $week;
}
For C++, there are various type-safe enum techniques available, and some of those (such as the proposed-but-never-submitted Boost.Enum) include support for getting the size of a enum.
The simplest approach, which works in C as well as C++, is to adopt a convention of declaring a ...MAX value for each of your enum types:
enum Folders { FA, FB, FC, Folders_MAX = FC };
ContainerClass *m_containers[Folders_MAX + 1];
....
m_containers[FA] = ...; // etc.
Edit: Regarding { FA, FB, FC, Folders_MAX = FC}
versus {FA, FB, FC, Folders_MAX]
: I prefer setting the ...MAX value to the last legal value of the enum for a few reasons:
Folders_MAX
gives the maximum possible enum value).Folders_MAX = FC
stands out from other entries out a bit more (making it a bit harder to accidentally add enum values without updating the max value, a problem Martin York referenced).switch (folder) { case FA: ...; case FB: ...; // Oops, forgot FC! }
dirname(parent.frame(2)$ofile)
doesn't work for me either, but the following (as suggested in https://stackoverflow.com/a/35842176/992088) works for me in ubuntu 14.04
dirname(rstudioapi::getActiveDocumentContext()$path)
If you are not limiting yourself to the standard library, I like psutil for this.
For instance to find all "python" processes:
>>> import psutil
>>> [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'python' in p.info['name']]
[{'name': 'python3', 'pid': 21947},
{'name': 'python', 'pid': 23835}]
I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:
<select [(ngModel)]="simpleValue"> // value is a string or number
<option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>
If you want to match on the actual object, I'd do it like this:
<select [(ngModel)]="objValue"> // value is an object
<option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>
If you are using Python3.
then you can use Print Function :
your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data, file=open('D:\log.txt', 'w'))
For python2
this is the example of Python Print String To Text File
def my_func():
"""
this function return some value
:return:
"""
return 25.256
def write_file(data):
"""
this function write data to file
:param data:
:return:
"""
file_name = r'D:\log.txt'
with open(file_name, 'w') as x_file:
x_file.write('{} TotalAmount'.format(data))
def run():
data = my_func()
write_file(data)
run()
On macOS, the reason for using the --user
flag is to make sure we don't corrupt the libraries the OS relies on. A conservative approach for many macOS users is to avoid installing or updating pip with a command that requires sudo
. Thus, this includes installing to /usr/local/bin
...
Ref: Installing python for Neovim (https://github.com/zchee/deoplete-jedi/wiki/Setting-up-Python-for-Neovim)
I'm not all clear why installing into /usr/local/bin
is a risk on a Mac given the fact that the system only relies on python binaries in /Library/Frameworks/
and /usr/bin
. I suspect it's because as noted above, installing into /usr/local/bin
requires sudo
which opens the door to making a costly mistake with the system libraries. Thus, installing into ~/.local/bin
is a sure fire way to avoid this risk.
Ref: Using python on a Mac (https://docs.python.org/2/using/mac.html)
Finally, to the degree there is a benefit of installing packages into the /usr/local/bin
, I wonder if it makes sense to change the owner of the directory from root
to user
? This would avoid having to use sudo
while still protecting against making system-dependent changes.* Is this a security default a relic of how Unix systems were more often used in the past (as servers)? Or at minimum, just a good way to go for Mac users not hosting a server?
*Note: Mac's System Integrity Protection (SIP) feature also seems to protect the user from changing the system-dependent libraries.
- E
You can use the Counter
supplied in the collections
package which has a mode
-esque function
from collections import Counter
data = Counter(your_list_in_here)
data.most_common() # Returns all unique items and their counts
data.most_common(1) # Returns the highest occurring item
Note: Counter is new in python 2.7 and is not available in earlier versions.
1) The result of repr('foo')
is the string 'foo'
. In your Python shell, the result of the expression is expressed as a representation too, so you're essentially seeing repr(repr('foo'))
.
2) eval
calculates the result of an expression. The result is always a value (such as a number, a string, or an object). Multiple variables can refer to the same value, as in:
x = 'foo'
y = x
x and y now refer to the same value.
3) I have no idea what you meant here. Can you post an example, and what you'd like to see?
try this:
var result = from r in myDataTable.AsEnumerable()
where r.Field<string>("Name") != "n/a" &&
r.Field<string>("Name") != "" select r;
DataTable dtResult = result.CopyToDataTable();
If you are running it from command line, sometimes python interpreter is not aware of the path where to look for modules.
Below is the directory structure of my project:
/project/apps/..
/project/tests/..
I was running below command:
>> cd project
>> python tests/my_test.py
After running above command i got below error
no module named lib
lib was imported in my_test.py
i printed sys.path and figured out that path of project i am working on is not available in sys.path list
i added below code at the start of my script my_test.py
.
import sys
import os
module_path = os.path.abspath(os.getcwd())
if module_path not in sys.path:
sys.path.append(module_path)
I am not sure if it is a good way of solving it but yeah it did work for me.
The following answer applies to a Spark Streaming application.
By setting the "truncate" option to false, you can tell the output sink to display the full column.
val query = out.writeStream
.outputMode(OutputMode.Update())
.format("console")
.option("truncate", false)
.trigger(Trigger.ProcessingTime("5 seconds"))
.start()
There are a lot of complicated solutions above. For me? I used GIMP to save a copy of the original PNG file after changing the image size to 32 x 32 pixels.
Just be sure to save it as a *.ico file and use the
<link rel="shortcut icon" href="http://sstatic.net/stackoverflow/img/favicon.ico">
listed above
If you want to add a bounding box, use a rectangle:
ax = plt.gca()
r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
ax.add_artist(r)
I've learned to not try to outsmart the garbage collection. With that said, I just stick to using using
keyword when dealing with unmanaged resources like file I/O or database connections.
Clickatell is a popular SMS gateway. It works in 200+ countries.
Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.
The HTTP/S method is as simple as this:
http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here
The SMTP method consists of sending a plain-text e-mail to: [email protected]
, with the following body:
user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home
You can also test the gateway (incoming and outgoing) for free from your browser
Give a different alias
SELECT Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate
I know that is a little bit dated, but with basic commands, we can take the mac address of an interface:
ip link show eth0 | grep link/ether | awk '{print $2}'
Have a nice day!
You can set padding to your view by pro grammatically throughout below code -
view.setPadding(0,1,20,3);
And, also there are different type of padding available -
These, links will refer Android Developers site. Hope this helps you lot.
In this case you might want to use the functions np.hstack and np.vstack
arr = np.array([])
arr = np.hstack((arr, np.array([1,2,3])))
# arr is now [1,2,3]
arr = np.vstack((arr, np.array([4,5,6])))
# arr is now [[1,2,3],[4,5,6]]
You also can use the np.concatenate function.
Cheers
I just tested this and it works in Access 2010.
Say you have a SELECT query with parameters:
PARAMETERS startID Long, endID Long;
SELECT Members.*
FROM Members
WHERE (((Members.memberID) Between [startID] And [endID]));
You run that query interactively and it prompts you for [startID] and [endID]. That works, so you save that query as [MemberSubset].
Now you create an UPDATE query based on that query:
UPDATE Members SET Members.age = [age]+1
WHERE (((Members.memberID) In (SELECT memberID FROM [MemberSubset])));
You run that query interactively and again you are prompted for [startID] and [endID] and it works well, so you save it as [MemberSubsetUpdate].
You can run [MemberSubsetUpdate] from VBA code by specifying [startID] and [endID] values as parameters to [MemberSubsetUpdate], even though they are actually parameters of [MemberSubset]. Those parameter values "trickle down" to where they are needed, and the query does work without human intervention:
Sub paramTest()
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("MemberSubsetUpdate")
qdf!startID = 1 ' specify
qdf!endID = 2 ' parameters
qdf.Execute
Set qdf = Nothing
End Sub