I only installed the Oracle Data Provider for .NET 2.0 (11.1.0.6.20) and I did not install the Oracle Instant Client (11.1.0.6.0).
I just installed it and the error disappeared!
Now has a new nuget package, try use it: https://www.nuget.org/packages/Oracle.ManagedDataAccess.EntityFramework/
Ok, when you know for sure other applications that used the same process worked; on your new application make sure you have the data access reference and the three dll files...
I downloaded ODAC1120320Xcopy_32bit this from the Oracle site:
http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html
Reference: Oracle.DataAccess.dll (ODAC1120320Xcopy_32bit\odp.net4\odp.net\bin\4\Oracle.DataAccess.dll)
Include these 3 files within your project:
When I tried to create another application with the correct reference and files I would receive that error message.
The fix: Highlighted all three of the files and selected "Copy To Output" = Copy if newer. I did copy if newer since one of the dll's is above 100MB and any updates I do will not copy those files again.
I also ran into a registry error, this fixed it.
public void updateRegistryForOracleNLS()
{
RegistryKey oracle = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\ORACLE");
oracle.SetValue("NLS_LANG", "AMERICAN_AMERICA.WE8MSWIN1252");
}
For the Oracle nls_lang list, see this site: https://docs.oracle.com/html/B13804_02/gblsupp.htm
After that, everything worked smooth.
I hope it helps.
Check that there isn't a firewall that is ending the connection after certain period of time (this was the cause of a similar problem we had)
After having to tackle this issue myself, I would like to build upon user854301's answer.
Mongoose ^4.13.8 I was able to use a function called toConstructor()
which allowed me to avoid building the query multiple times when filters are applied. I know this function is available in older versions too but you'll have to check the Mongoose docs to confirm this.
The following uses Bluebird promises:
let schema = Query.find({ name: 'bloggs', age: { $gt: 30 } });
// save the query as a 'template'
let query = schema.toConstructor();
return Promise.join(
schema.count().exec(),
query().limit(limit).skip(skip).exec(),
function (total, data) {
return { data: data, total: total }
}
);
Now the count query will return the total records it matched and the data returned will be a subset of the total records.
Please note the () around query() which constructs the query.
You can do something like this
import React from 'react';
class Header extends React.Component {
constructor() {
super();
}
checkClick(e, notyId) {
alert(notyId);
}
render() {
return (
<PopupOver func ={this.checkClick } />
)
}
};
class PopupOver extends React.Component {
constructor(props) {
super(props);
this.props.func(this, 1234);
}
render() {
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default Header;
Using statics
var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});
MyComponent.customMethod('bar'); // true
I was facing this issue due to empty space at the end of the password(spring.rabbitmq.password=rabbit ) in spring boot application.properties got resolved on removing the empty space. Hope this checklist helps some one facing this issue.
easy!
$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
git pull <remote> master:dev
will fetch the remote/master
branch and merge it into your local/dev
branch.
git pull <remote> dev
will fetch the remote/dev
branch, and merge it into your current branch.
I think you said the conflicting commit is on remote/dev
, so that is the branch you probably intended to fetch and merge.
In that case, you weren't actually merging the conflict into your local branch, which is sort of weird since you said you saw the incorrect code in your working copy. You might want to check what is going on in remote/master
.
It is rather messy but you need to do something like the following:
START "do something window" dir
FOR /F "tokens=2" %I in ('TASKLIST /NH /FI "WINDOWTITLE eq do something window"' ) DO SET PID=%I
ECHO %PID%
TASKKILL /PID %PID%
Found this on this page.
(This kind of thing is much easier if you have a UNIX / LINUX system ... or if you run Cygwin or similar on Windows.)
You can use a a union for two main reasons:
1 Is really more of a C-style hack to short-cut writing code on the basis you know how the target system's memory architecture works. As already said you can normally get away with it if you don't actually target lots of different platforms. I believe some compilers might let you use packing directives also (I know they do on structs)?
A good example of 2. can be found in the VARIANT type used extensively in COM.
Try this:
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
...
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_launcher);
so your icon will be used for Home / back
or
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
...
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayShowHomeEnabled(true);
actionbar.setIcon(R.drawable.ic_launcher);
for static icon
You can create your own user defined functions in a module within Excel such as (from memory, so may need some debugging, and the syntax may vary among Excel versions as well):
Public Function ZeroToBlank (x As Integer) As String
If x = 0 then
ZeroToBlank = ""
Else
ZeroToBlank = CStr(x)
End If
End Function
You can then simply insert =ZeroToBlank (Index (a,b,c))
into your cell.
There's a nice tutorial on just this subject here.
The basic steps are:
Tools -> Macro -> Visual Basic Editor
.Insert -> Module
.=ZeroToBlank (<<whatever>>)
<<whatever>>
is the value you wish to use blank for if it's zero.Note that there may be minor variations depending on which version of Excel you have. My version of Excel is 2002 which admittedly is pretty old, but it still does everything I need of it.
Yes it's possible. Follow these steps:
#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)
What about summing both extremities? It would cut time in half. Like so:
1, 2, 3, 4, 5, 6, 7, 8; sum = 0
2, 3, 4, 5, 6, 7; sum = 10
3, 4, 5, 6; sum = 19
4, 5; sum = 28
sum = 37
One algorithm could be:
function sum_array(arr){
let sum = 0,
length = arr.length,
half = Math.floor(length/2)
for (i = 0; i < half; i++) {
sum += arr[i] + arr[length - 1 - i]
}
if (length%2){
sum += arr[half]
}
return sum
}
It performs faster when I test it on the browser with performance.now()
.
I think this is a better way. What do you guys think?
It's can be easily reached with:
<?php
$post = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);
You get this error if you have constrained T
to being a class
Scripting is inevitable.
This isn't provided because of the security risk. <input type='file' />
is closest, but not what you are looking for.
Checkout this example that uses Javascript to achieve what you want.
If the OS is windows, you can use VB scripts to access the core control files to browse for a folder.
when you add context:component-scan for the first time in an xml, the following needs to be added.
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
OFFSET is what you are looking for.
SELECT * FROM table LIMIT 10 OFFSET 10
scanf("%2000s %2000[^\n]", a, b);
It's a hex number and is 16 decimal.
I assume 0
means false
(which is the case in a lot of programming languages). That means true
is not 0
(some languages use -1
some others use 1
; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:
bool boolValue = intValue != 0;
At finally OAuth gives you back the access token to access the resource from resource server, OpenID gives you back meta data details about resources in JWT / encrypted token
How about suppressing errors on each line specific to each error?
Something like this: https://pylint.readthedocs.io/en/latest/user_guide/message-control.html
Error: [pylint] Class 'class_name' has no 'member_name' member It can be suppressed on that line by:
# pylint: disable=no-member
Base on @Jonik answer I have created fully functional extension to ArrayAdapter
class SpinnerArrayAdapter<T> : ArrayAdapter<T> {
private val selectText : String
private val resource: Int
private val fieldId : Int
private val inflater : LayoutInflater
constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(true)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(false)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getCount(): Int {
return super.getCount() + 1 // adjust for initial selection
}
private fun initialSelection(inDropDown: Boolean) : View {
// Just simple TextView as initial selection.
val view = TextView(context)
view.setText(selectText)
view.setPadding(8, 0, 8, 0)
if(inDropDown) {
// Hide when dropdown is open
view.height = 0
}
return view
}
private fun createViewFromResource(inflater: LayoutInflater, position: Int,
@Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
val view: View
val text: TextView?
if (convertView == null || (convertView is TextView)) {
view = inflater.inflate(resource, parent, false)
} else {
view = convertView
}
try {
if (fieldId === 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = view as TextView
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(fieldId)
if (text == null) {
throw RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(fieldId)
+ " in item layout")
}
}
} catch (e: ClassCastException) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e)
}
val item = getItem(position)
if (item is CharSequence) {
text.text = item
} else {
text.text = item!!.toString()
}
return view
}
Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.
All transaction must contain four properties that commonly known as ACID properties. i.e ACID are the group of properties of any transaction.
I use the following PowerShell cobbled together from a few places for our Octopus Deploy instances when TopShelf messes up or a service fails for some other reason.
$ServiceName = 'MyNaughtyService'
$ServiceName | Stop-Service -ErrorAction SilentlyContinue
# We tried nicely, now KILL!!!
$ServiceNamePID = Get-Service | Where { $_.Name -eq $ServiceName} # If it was hung($_.Status -eq 'StopPending' -or $_.Status -eq 'Stopping') -and
$ServicePID = (Get-WmiObject Win32_Service | Where {$_.Name -eq $ServiceNamePID.Name}).ProcessID
Stop-Process $ServicePID -Force
From go 1.13 onwards, if you had already configured your terminal with the git credentials and yet facing this issue, then you could try setting the GOPRIVATE
environment variable. Setting this environment variable solved this issue for me.
export GOPRIVATE=github.com/{organizationName/userName of the package}/*
I use @Thiho answer but i get this error:
'git' is not recognized as an internal or external command
For solving that i use this steps:
I add the following paths to PATH:
C:\Program Files\Git\bin\
C:\Program Files\Git\cmd\
In windows 7:
Finally close and re-open your console.
You didn't specify a GradientType
:
background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */
This is a typical scenario where subtype polymorphism helps. Do the following
interface I {
void do();
}
class A implements I { void do() { doA() } ... }
class B implements I { void do() { doB() } ... }
class C implements I { void do() { doC() } ... }
Then you can simply call do()
on this
.
If you are not free to change A
, B
, and C
, you could apply the visitor pattern to achieve the same.
MVP:
Advantages:
Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.
Disadvantages:
1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.
3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.
MVC:
Advanatages:
Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.
Disadvantagaes:
Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.
MVVM:
After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.
Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.
const stringInject = (str = '', obj = {}) => {
let newStr = str;
Object.keys(obj).forEach((key) => {
let placeHolder = `#${key}#`;
if(newStr.includes(placeHolder)) {
newStr = newStr.replace(placeHolder, obj[key] || " ");
}
});
return newStr;
}
Input: stringInject("Hi #name#, How are you?", {name: "Ram"});
Output: "Hi Ram, How are you?"
mkmf
is part of the ruby1.9.1-dev
package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev
package by doing:
sudo apt-get install ruby1.9.1-dev
Then you can install Rails as per normal.
Generally it's easier to just do:
sudo apt-get install ruby-dev
Tested with below sample snippet, tried with MapUtils, and Java8 Stream feature. It worked with both cases.
public static void main(String[] args) {
Map<String, String> test = new HashMap<String, String>();
test.put("a", "1");
test.put("d", "1");
test.put("b", "2");
test.put("c", "3");
test.put("d", "4");
test.put("d", "41");
System.out.println(test);
Map<String, String> test1 = MapUtils.invertMap(test);
System.out.println(test1);
Map<String, String> mapInversed =
test.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
System.out.println(mapInversed);
}
Output:
{a=1, b=2, c=3, d=41}
{1=a, 2=b, 3=c, 41=d}
{1=a, 2=b, 3=c, 41=d}
The unix 'date' command is surprisingly versatile.
date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"
Takes the output of date
, which will be in the format defined by -f, and then prints it out (-j says don't attempt to set the date) in the form +%s, seconds since epoch.
I had a similar issue but in my case, the solution was to dispatch the action as an async task in the main queue
DispatchQueue.main.async {
let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
self.present(vc, animated: true, completion: nil)
}
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
I assume the reason you don't want it to close in Debug mode, is because you want to look at the values of variables etc. So it's probably best to just insert a break-point on the closing "}" of the main function. If you don't need to debug, then Ctrl-F5 is the best option.
Here is a solution that works in IE, Firefox, and Chrome. The idea is to increase the font size of the br element from the body size of 14px to 18px, and lower the element by 4px so the extra size is below the text line. The result is 4px of extra whitespace below the br.
br
{
font-size: 18px;
vertical-align: -4px;
}
$('input[type=text],select', '.sys');
for looping:
$('input[type=text],select', '.sys').each(function() {
// code
});
I had a similar issue where I was getting the same error message for a user. I feel that by sharing my mistake, I can clear up the issue, answer the question, and prevent others from making the same mistake.
I wanted a user to have access to 4 particular views without having access to their underlying tables (or anything else in the DB for that matter).
Initially I gave them the database role membership of "db_denydatareader" thinking that this would prevent them from selecting anything from any table or view (which it did - as I thought), though I then granted "select" on these 4 views assuming that it would work as I intended - it did not.
The correct way to do it is to simply not grant them the db_datareader role and simply grant "select" on the items which you want the user to be able to access. The results of the above was that the user was able to access absolutely nothing outside these 4 views - the tables which these views area based on are also not available to this user.
Also You can use
$value = $("#txt").val();
if($value == "")
{
//Your Code Here
}
else
{
//Your code
}
Try it. It work.
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Implements means that it takes on the designated behavior that the interface specifies. Consider the following interface:
public interface ISpeak
{
public String talk();
}
public class Dog implements ISpeak
{
public String talk()
{
return "bark!";
}
}
public class Cat implements ISpeak
{
public String talk()
{
return "meow!";
}
}
Both the Cat
and Dog
class implement the ISpeak
interface.
What's great about interfaces is that we can now refer to instances of this class through the ISpeak
interface. Consider the following example:
Dog dog = new Dog();
Cat cat = new Cat();
List<ISpeak> animalsThatTalk = new ArrayList<ISpeak>();
animalsThatTalk.add(dog);
animalsThatTalk.add(cat);
for (ISpeak ispeak : animalsThatTalk)
{
System.out.println(ispeak.talk());
}
The output for this loop would be:
bark!
meow!
Interface provide a means to interact with classes in a generic way based upon the things they do without exposing what the implementing classes are.
One of the most common interfaces used in Java, for example, is Comparable
. If your object implements this interface, you can write an implementation that consumers can use to sort your objects.
For example:
public class Person implements Comparable<Person>
{
private String firstName;
private String lastName;
// Getters/Setters
public int compareTo(Person p)
{
return this.lastName.compareTo(p.getLastName());
}
}
Now consider this code:
// Some code in other class
List<Person> people = getPeopleList();
Collections.sort(people);
What this code did was provide a natural ordering to the Person
class. Because we implemented the Comparable
interface, we were able to leverage the Collections.sort()
method to sort our List
of Person
objects by its natural ordering, in this case, by last name.
I just had only getters , after adding setters too , problems resolved.
we have to give the controller name in lower cases in server side
$this->class = strtolower(__CLASS__);
Now, unless you're trying to write C++ code using Python syntax, what would you need overloading for?
I think it's exactly opposite. Overloading is only necessary to make strongly-typed languages act more like Python. In Python you have keyword argument, and you have *args
and **kwargs
.
See for example: What is a clean, Pythonic way to have multiple constructors in Python?
A minor improvement on d4nt's answer, as you probably want to check for errors and not have to change xcopy paths if you're working on a server and development machine:
public void CopyFolder(string source, string destination)
{
string xcopyPath = Environment.GetEnvironmentVariable("WINDIR") + @"\System32\xcopy.exe";
ProcessStartInfo info = new ProcessStartInfo(xcopyPath);
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.Arguments = string.Format("\"{0}\" \"{1}\" /E /I", source, destination);
Process process = Process.Start(info);
process.WaitForExit();
string result = process.StandardOutput.ReadToEnd();
if (process.ExitCode != 0)
{
// Or your own custom exception, or just return false if you prefer.
throw new InvalidOperationException(string.Format("Failed to copy {0} to {1}: {2}", source, destination, result));
}
}
sudo su
cd /var/log/mysql
and lastly type: > mysql-slow.log
This worked for me
There is no notion of a function in the JDK as of java 6.
Guava has a Function interface though and the
Collections2.transform(Collection<E>, Function<E,E2>)
method provides the functionality you require.
Example:
// example, converts a collection of integers to their
// hexadecimal string representations
final Collection<Integer> input = Arrays.asList(10, 20, 30, 40, 50);
final Collection<String> output =
Collections2.transform(input, new Function<Integer, String>(){
@Override
public String apply(final Integer input){
return Integer.toHexString(input.intValue());
}
});
System.out.println(output);
Output:
[a, 14, 1e, 28, 32]
These days, with Java 8, there is actually a map function, so I'd probably write the code in a more concise way:
Collection<String> hex = input.stream()
.map(Integer::toHexString)
.collect(Collectors::toList);
Note: For (PHP 7 >= 7.3.0) we can use array_key_last — Gets the last key of an array
array_key_last ( array $array ) : mixed
This snippet works fine, for sending the Bearer Token using Jersey Client.
WebTarget webTarget = client.target("endpoint");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
invocationBuilder.header("Authorization", "Bearer "+"Api Key");
Response response = invocationBuilder.get();
String responseData = response.readEntity(String.class);
System.out.println(response.getStatus());
System.out.println("responseData "+responseData);
My answer to this quesiton.
Modify file C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\vcvarsqueryregistry.bat
The content of :GetWin10SdkDir
From
@REM ---------------------------------------------------------------------------
:GetWin10SdkDir
@call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE > nul 2>&1
@if errorlevel 1 exit /B 1
@exit /B 0
to
@REM ---------------------------------------------------------------------------
:GetWin10SdkDir
@call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE > nul 2>&1
@if errorlevel 1 exit /B 1
@setlocal enableDelayedExpansion
set HostArch=x86
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" ( set "HostArch=x64" )
if "%PROCESSOR_ARCHITECTURE%"=="EM64T" ( set "HostArch=x64" )
if "%PROCESSOR_ARCHITECTURE%"=="ARM64" ( set "HostArch=arm64" )
if "%PROCESSOR_ARCHITECTURE%"=="arm" ( set "HostArch=arm" )
@endlocal & set PATH=%WindowsSdkDir%bin\%WindowsSDKVersion%%HostArch%;%PATH%
@exit /B 0
Modify this single place will enable the support for all Windows 10 sdk along with all build target of visual studio, including
They are all working.
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.
If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.
Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.
Things seem to have gotten better/easier since Android 5.0 (API level 21).
I think what you're looking for is something like this:
<style name="AppTheme" parent="AppBaseTheme">
<!-- Top-top notification/status bar color: -->
<!--<item name="colorPrimaryDark">#000000</item>-->
<!-- App bar color: -->
<item name="colorPrimary">#0000FF</item>
</style>
See here for reference:
https://developer.android.com/training/material/theme.html#ColorPalette
On my Mac r is installed in /usr/local/bin/r
, add line below in .bash_profile
solved the same problem:
alias r="LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 r"
You can use display:inline-block
instead of float
and vertical-align:middle
with this CSS:
.col-lg-4, .col-lg-8 {
float:none;
display:inline-block;
vertical-align:middle;
margin-right:-4px;
}
The demo http://bootply.com/94402
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
Let's face it: this one appears a lot when recording macros:
Range("X1").Select
Selection.Copy
Range("Y9).Select
Selection.Paste
While the only thing the person wants is:
Range("Y9").Value = Range("X1").Value
Therefore, instead of using copy-paste in VBA macros, I'd advise the following simple approach:
Destination_Range.Value = Source_Range.Value
Import by using the import
keyword:
import package.myclass;
But since it's the default package and same, you just create a new instance like:
elf ob = new elf(); //Instance of elf class
in my case it helped to remove the lines build.gradle
compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '8.2.0.jre11'
I don't know why this happens, but after adding the specified library, the compiled jar stops working
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
//Your stuff
});
Both awk
and sed
are plenty fast, but if you think it matters feel free to use one of the following:
If the characters that you want to delete are always at the end of the string
echo '1234567890 *' | tr -d ' *'
If they can appear anywhere within the string and you only want to delete those at the end
echo '1234567890 *' | rev | cut -c 4- | rev
The man pages of all the commands will explain what's going on.
I think you should use sed
, though.
However, I'm a bit confused as to why
__init__
is always called after__new__
.
Not much of a reason other than that it just is done that way. __new__
doesn't have the responsibility of initializing the class, some other method does (__call__
, possibly-- I don't know for sure).
I wasn't expecting this. Can anyone tell me why this is happening and how I implement this functionality otherwise? (apart from putting the implementation into the
__new__
which feels quite hacky).
You could have __init__
do nothing if it's already been initialized, or you could write a new metaclass with a new __call__
that only calls __init__
on new instances, and otherwise just returns __new__(...)
.
If you want to round the decimal, look at Math.Round()
For to use looping to get all arguments and in pure batch:
Obs: For using without: ?*&<>
@echo off && setlocal EnableDelayedExpansion
for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!")
:: write/test these arguments/parameters ::
for /l %%l in (1 1 !_cnt!)do echo/ The argument n:%%l is: !_arg_[%%l]!
goto :eof
Your code is ready to do something with the argument number where it needs, like...
@echo off && setlocal EnableDelayedExpansion
for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!"
echo= !_arg_[1]! !_arg_[2]! !_arg_[2]!> log.txt
DateTime dt;
TimeZoneInfo tzf;
tzf = TimeZoneInfo.FindSystemTimeZoneById("TimeZone String");
dt = TimeZoneInfo.ConvertTime(DateTime.Now, tzf);
lbltime.Text = dt.ToString();
This is naive, but I had to make it to be POSIX compliant. Requires permission to cd into the file's directory.
#!/bin/sh
if [ ${#} = 0 ]; then
echo "Error: 0 args. need 1" >&2
exit 1
fi
if [ -d ${1} ]; then
# Directory
base=$( cd ${1}; echo ${PWD##*/} )
dir=$( cd ${1}; echo ${PWD%${base}} )
if [ ${dir} = / ]; then
parentPath=${dir}
else
parentPath=${dir%/}
fi
if [ -z ${base} ] || [ -z ${parentPath} ]; then
if [ -n ${1} ]; then
fullPath=$( cd ${1}; echo ${PWD} )
else
echo "Error: unsupported scenario 1" >&2
exit 1
fi
fi
elif [ ${1%/*} = ${1} ]; then
if [ -f ./${1} ]; then
# File in current directory
base=$( echo ${1##*/} )
parentPath=$( echo ${PWD} )
else
echo "Error: unsupported scenario 2" >&2
exit 1
fi
elif [ -f ${1} ] && [ -d ${1%/*} ]; then
# File in directory
base=$( echo ${1##*/} )
parentPath=$( cd ${1%/*}; echo ${PWD} )
else
echo "Error: not file or directory" >&2
exit 1
fi
if [ ${parentPath} = / ]; then
fullPath=${fullPath:-${parentPath}${base}}
fi
fullPath=${fullPath:-${parentPath}/${base}}
if [ ! -e ${fullPath} ]; then
echo "Error: does not exist" >&2
exit 1
fi
echo ${fullPath}
In pgAdmin you can also use
SET search_path TO your_db_name;
You can use Bit
DataType in SQL Server to store boolean data.
FYI: it looks like you might have an infinite loop in your example...
if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
cnt
is greater than 0cnt
is greater than 0cnt
by 1The net result is that cnt
will always be greater than 0 and the loop will never exit.
You can use the following library:
https://github.com/pnowy/NativeCriteria
The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).
You can find the examples on github page, the library is available at Maven central of course.
NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));
I have a lib that uses trim. so solved it by using the following code.
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
For 2019, you don't need to install body-parser
.
You can use:
var express = require('express');
var app = express();
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
You can use ave
:
df$count <- ave(df$num, df[,c("name","type")], FUN=length)
The 1st one is default, when there is nothing special to return or write. 2nd and 3rd are basically the same where 3rd is a bit more expanded version of 2nd
grep "pattern" <(head -n 10 filename)
It must be here, because accepted answer from 2012
In 2018 and modern browsers you can send a custom event from iframe to parent window.
iframe:
var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)
parent:
window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
console.log(e.detail) // outputs: {foo: 'bar'}
}
PS: Of course, you can send events in opposite direction same way.
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
It can be done all on the client-side using the OnClientClick
[MSDN] event handler and window.open
[MDN]:
<asp:Button
runat="server"
OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
Open a new window!
</asp:Button>
If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.
Read the DOM with JavaScript in iframe and send it via postMessage to the top window.
More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
This problem is probably from your /etc/apt/sources.list as others mentioned but there is chance that the problem is with your hard disk. I solved the same issue by cleaning up some space.
When you don't have enough space on your hard disk, updating your machine won't occur until you delete some files.
Absolute positioning means that the element is taken completely out of the normal flow of the page layout. As far as the rest of the elements on the page are concerned, the absolutely positioned element simply doesn't exist. The element itself is then drawn separately, sort of "on top" of everything else, at the position you specify using the left, right, top and bottom
attributes.
Using the position you specify with these attributes, the element is then placed at that position within its last ancestor element which has a position attribute of anything other than static
(page elements default to static when no position attribute specified), or the document body (browser viewport) if no such ancestor exists.
For example, if I had this code:
<body>
<div style="position:absolute; left: 20px; top: 20px;"></div>
</body>
...the <div>
would be positioned 20px from the top of the browser viewport, and 20px from the left edge of same.
However, if I did something like this:
<div id="outer" style="position:relative">
<div id="inner" style="position:absolute; left: 20px; top: 20px;"></div>
</div>
...then the inner
div would be positioned 20px from the top of the outer
div, and 20px from the left edge of same, because the outer
div isn't positioned with position:static
because we've explicitly set it to use position:relative
.
Relative positioning, on the other hand, is just like stating no positioning at all, but the left, right, top and bottom
attributes "nudge" the element out of their normal layout. The rest of the elements on the page still get laid out as if the element was in its normal spot though.
For example, if I had this code:
<span>Span1</span>
<span>Span2</span>
<span>Span3</span>
...then all three <span>
elements would sit next to each other without overlapping.
If I set the second <span>
to use relative positioning, like this:
<span>Span1</span>
<span style="position: relative; left: -5px;">Span2</span>
<span>Span3</span>
...then Span2 would overlap the right side of Span1 by 5px. Span1 and Span3 would sit in exactly the same place as they did in the first example, leaving a 5px gap between the right side of Span2 and the left side of Span3.
Hope that clarifies things a bit.
wrap the table in a div with class="container"
div.container {
width: 100%;
overflow-x: auto;
}
then
#table_id tr td {
white-space:nowrap;
}
result
As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:
func makeTimestamp() int64 {
return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}
OneOfOne's answer works because time.Nanosecond
happens to be 1
, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.
See https://en.wikipedia.org/wiki/Dimensional_analysis
Another way of looking at this is that both time.Now().UnixNano()
and time.Millisecond
use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.
I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'. For those who came here like me, this is how to do it:
int num = 6;
num.ToString().ToCharArray()[0];
kieron's answer contains w3schools ref. to which nobody rely , bobince's answer gives link , which actually tells native implementation of IE ,
so here is the original documentation quoted to rightly understand what readystate represents :
The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:
UNSENT (numeric value 0)
The object has been constructed.OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.LOADING (numeric value 3)
The response entity body is being received.DONE (numeric value 4)
The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).
Please Read here : W3C Explaination Of ReadyState
You can just use a simple loop: -
>>> mylist = ['10', '12', '14']
>>> for elem in mylist:
print elem
10
12
14
I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:
curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"
The basic idea is that each part (split by string in boundary
with --
) has it's own headers (Content-Type
in the second part, for example.) The FormData
object manages all this for you, so it's a better way to accomplish our goals.
This translates to fetch API like this:
const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')
fetch('http://localhost:5001/api/v0/add', {
method: 'POST',
body: formData
})
.then(r => r.json())
.then(data => {
console.log(data)
})
public boolean isAlertPresent()
{
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
} // catch
} // isAlertPresent()
check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY
In Python 2.7, it goes like:
>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}
Zip them!
Use this to display the Unix numerical permission values (octal values) and file name.
stat -c '%a %n' *
Use this to display the Unix numerical permission values (octal values) and the folder's sgid and sticky bit, user name of the owner, group name, total size in bytes and file name.
stat -c '%a %A %U %G %s %n' *
Add %y
if you need time of last modification in human-readable format. For more options see stat.
Better version using an Alias
Using an alias is a more efficient way to accomplish what you need and it also includes color. The following displays your results organized by group directories first, display in color, print sizes in human readable format (e.g., 1K 234M 2G) edit your ~/.bashrc
and add an alias for your account or globally by editing /etc/profile.d/custom.sh
Typing cls
displays your new LS command results.
alias cls="ls -lha --color=always -F --group-directories-first |awk '{k=0;s=0;for(i=0;i<=8;i++){;k+=((substr(\$1,i+2,1)~/[rwxst]/)*2^(8-i));};j=4;for(i=4;i<=10;i+=3){;s+=((substr(\$1,i,1)~/[stST]/)*j);j/=2;};if(k){;printf(\"%0o%0o \",s,k);};print;}'"
Folder Tree
While you are editing your bashrc or custom.sh include the following alias to see a graphical representation where typing lstree
will display your current folder tree structure
alias lstree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'"
It would display:
|-scripts
|--mod_cache_disk
|--mod_cache_d
|---logs
|-run_win
|-scripts.tar.gz
Building from Michael Baylon's answer, I needed a list which also included schema information and this is how I modified his query.
SELECT TABLE_SCHEMA + '.' + TABLE_NAME as 'Schema.Table'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG = 'dbName'
ORDER BY TABLE_SCHEMA, TABLE_NAME
$str = 'abcdef';
echo $str[0]; // a
PRAGMA table_info([tablename]);
Although I've used Eclipse for years, this "answer" is only conjecture (which I'm going to try tonight). If it gets down-voted out of existence, then obviously I'm wrong.
Oracle relies on CMake to generate a Visual Studio "Solution" for their MySQL Connector C source code. Within the Solution are "Projects" that can be compiled individually or collectively (by the Solution). Each Project has its own makefile, compiling its portion of the Solution with settings that are different than the other Projects.
Similarly, I'm hoping an Eclipse Workspace can hold my related makefile Projects (Eclipse), with a master Project whose dependencies compile the various unique-makefile Projects as pre-requesites to building its "Solution". (My folder structure would be as @Rafael describes).
So I'm hoping a good way to use Workspaces is to emulate Visual Studio's ability to combine dissimilar Projects into a Solution.
You can always use strtotime to minus the number of days from the current date:
$users = Users::where('status_id', 'active')
->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
->get();
You can also use update ... from
syntax and use a mapping table. If you want to update more than one column, it's much more generalizable:
update test as t set
column_a = c.column_a
from (values
('123', 1),
('345', 2)
) as c(column_b, column_a)
where c.column_b = t.column_b;
You can add as many columns as you like:
update test as t set
column_a = c.column_a,
column_c = c.column_c
from (values
('123', 1, '---'),
('345', 2, '+++')
) as c(column_b, column_a, column_c)
where c.column_b = t.column_b;
It boils down to adding android:stretchColumns="*"
to your TableLayout
root and setting android:layout_width="0dp"
to all the children in your TableRow
s.
<TableLayout
android:stretchColumns="*" // Optionally use numbered list "0,1,2,3,..."
>
<TableRow
android:layout_width="0dp"
>
if (month == 4 || month == 6 || month == 9 || month == 11)
daysInMonth = 30;
else
if (month == 2)
daysInMonth = (leapYear) ? 29 : 28;
else
daysInMonth = 31;
you could try
$('*').not('#div').bind('touchmove', false);
add this if necessary
$('#div').bind('touchmove');
note that everything is fixed except #div
If you are just using interfaces for types, leave out the export
keyword and ts can pick up on the types without needing to import. They key is you cannot use import
/export
anywhere.
export interface Person {
name: string;
age: number;
}
into
interface Person {
name: string;
age: number;
}
you can include @ in a 'scriptBlock' like this:
@(
echo don't echoed
hostname
)
echo echoed
and especially do not do that :)
for %%a in ("@") do %%~aecho %%~a
It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.
I presume SELECT user FROM dual;
should give you the current user
and SELECT sys_context('userenv','instance_name') FROM dual;
the name of the instance
I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL;
If you are using Android Studio 3.2 & above,then issue will be solved by adding google() & jcenter() to build.gradle of the project:
repositories {
google()
jcenter()
}
I had the same issue on iOS and the cause for me was that my index.ios.js was incorrect (because I copy-pasted one of the examples without looking at its contents), it was ending with a module export declaration
exports.title = ...
exports.description = ...
module.exports = MyRootComponent;
Instead of the expected
AppRegistry.registerComponent('MyAppName', () => MyRootComponent);
You could have the same issue on android with the index.android.js I guess.
In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged()
in RunOnUiThread()
.
private void updateData() {
List<Data> newData = getYourNewData();
mAdapter.setList(yourNewList);
runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
If you mean you want to fetch everything from the beginning up to a particular point, Charles Bailey's answer is perfect. If you want to do the reverse and retrieve a subset of the history going back from the current date, you can use git clone --depth [N]
where N is the number of revs of history you want. However:
--depth
Create a shallow clone with a history truncated to the specified number of revisions. A shallow repository has a number of limitations (you cannot clone or fetch from it, nor push from nor into it), but is adequate if you are only interested in the recent history of a large project with a long history, and would want to send in fixes as patches.
After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use $this
operator to work on class functions. So I couldn't find a difference in them yet. :(
you can also use vertice :
private static final int verticesColors[] = {
Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, 0xFF000000, 0xFF000000, 0xFF000000
};
float verts[] = {
point1.x, point1.y, point2.x, point2.y, point3.x, point3.y
};
canvas.drawVertices(Canvas.VertexMode.TRIANGLES, verts.length, verts, 0, null, 0, verticesColors, 0, null, 0, 0, new Paint());
Requires Newtonsoft Json.Net
A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:
public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
JObject attributesAsJObject = dynamicToGetPropertiesFor;
Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
List<string> toReturn = new List<string>();
foreach (string key in values.Keys)
{
toReturn.Add(key);
}
return toReturn;
}
Then you simply foreach like this:
foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
// And
dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}
Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.
Try this
DateTime startTime = varValue
DateTime endTime = varTime
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );
Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.
The built-in webserver is hardwired to use Default.aspx as the default page.
The project must have atleast an empty Default.aspx
file to overcome the Directory Listing problem for Global.asax
.
:)
Once you add that empty file all requests can be handled in one location.
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
this.Response.Write("hi@ " + this.Request.Path + "?" + this.Request.QueryString);
this.Response.StatusCode = 200;
this.Response.ContentType = "text/plain";
this.Response.End();
}
}
You may set the default file association of ps1
files to be powershell.exe
which will allow you to execute a powershell script by double clicking on it.
In Windows 10,
ps1
fileOpen with
Choose another app
More apps
Look for another app on this PC
. C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
. That will change the file association and ps1
files will execute by double-clicking them. You may change it back to its default behavior by setting notepad.exe
to the default app.
You can do "redundant styling" and that should fix the issue. You use the same styling you have on the but add it to a that is within the .
Example:
<td width="110" align="center" valign="top" style="color:#000000;">
<a href="https://example.com" target="_blank"
style="color:#000000; text-decoration:none;"><span style="color:#000000; text-decoration:none;">BOOK NOW</span></a>
</td>
Previous answers have covered the use of git rebase -i
to edit the commit that you want to split, and committing it in parts.
This works well when splitting the files into different commits, but if you want to break apart changes to the individual files, there's more you need to know.
Having got to the commit you want to split, using rebase -i
and marking it for edit
, you have two options.
After using git reset HEAD~
, go through the patches individually using git add -p
to select the ones you want in each commit
Edit the working copy to remove the changes you do not want; commit that interim state; and then pull back the full commit for the next round.
Option 2 is useful if you're splitting a large commit, as it lets you check that the interim versions build and run properly as part of the merge. This proceeds as follows.
After using rebase -i
and edit
ing the commit, use
git reset --soft HEAD~
to undo the commit, but leave the committed files in the index. You can also do a mixed reset by omitting --soft, depending on how close to the final result your initial commit is going to be. The only difference is whether you start with all the changes staged or with them all unstaged.
Now go in and edit the code. You can remove changes, delete added files, and do whatever you want to construct the first commit of the series you're looking for. You can also build it, run it, and confirm that you have a consistent set of source.
Once you're happy, stage/unstage the files as needed (I like to use git gui
for this), and commit the changes through the UI or the command line
git commit
That's the first commit done. Now you want to restore your working copy to the state it had after the commit you are splitting, so that you can take more of the changes for your next commit. To find the sha1 of the commit you're editing, use git status
. In the first few lines of the status you'll see the rebase command that is currently executing, in which you can find the sha1 of your original commit:
$ git status
interactive rebase in progress; onto be83b41
Last commands done (3 commands done):
pick 4847406 US135756: add debugging to the file download code
e 65dfb6a US135756: write data and download from remote
(see more in file .git/rebase-merge/done)
...
In this case, the commit I'm editing has sha1 65dfb6a
. Knowing that, I can check out the content of that commit over my working directory using the form of git checkout
which takes both a commit and a file location. Here I use .
as the file location to replace the whole working copy:
git checkout 65dfb6a .
Don't miss the dot on the end!
This will check out, and stage, the files as they were after the commit you're editing, but relative to the previous commit you made, so any changes you already committed won't be part of the commit.
You can either go ahead now and commit it as-is to finish the split, or go around again, deleting some parts of the commit before making another interim commit.
If you want to reuse the original commit message for one or more commits, you can use it straight from the rebase's working files:
git commit --file .git/rebase-merge/message
Finally, once you've committed all the changes,
git rebase --continue
will carry on and complete the rebase operation.
org.springframework.util.CollectionUtils
boolean containsAny(java.util.Collection<?> source, java.util.Collection<?> candidates)
Return true if any element in 'candidates' is contained in 'source'; otherwise returns false
In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%'
there
are position
(reversed order of args) and strpos
.
SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0
Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain %
and especially _
(single char wildcard), to give no false positives.
There might be a more elegant way to do this but here is my solution. With Jquery
fileEle.value = "";
var parEle = $(fileEle).parent();
var newEle = $(fileEle).clone()
$(fileEle).remove();
parEle.append(newEle);
Basically you cleat the value of the input. Clone it and put the clone in place of the old one.
$ipaddress = '';
if ($_SERVER['HTTP_CLIENT_IP'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if ($_SERVER['HTTP_X_FORWARDED_FOR'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if ($_SERVER['HTTP_X_FORWARDED'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if ($_SERVER['HTTP_FORWARDED_FOR'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if ($_SERVER['HTTP_FORWARDED'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1')
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
copy *.csv new.csv
No need for /b as csv isn't a binary file type.
just Add:
<button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
FYI, sender
and e
are not specific to ASP.NET or to C#. See Events (C# Programming Guide) and Events in Visual Basic.
You can do this without modifying the html. http://jsfiddle.net/8JwhZ/1085/
<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>
.title span:nth-of-type(1) { float:right }
.title span:nth-of-type(2) { float:left }
Here's an Add to Calendar service to serve the purpose for adding an event on
The "Add to Calendar" button for events on websites and calendars is easy to install, language independent, time zone and DST compatible. It works perfectly in all modern browsers, tablets and mobile devices, and with Apple Calendar, Google Calendar, Outlook, Outlook.com and Yahoo Calendar.
<div title="Add to Calendar" class="addeventatc">
Add to Calendar
<span class="start">03/01/2018 08:00 AM</span>
<span class="end">03/01/2018 10:00 AM</span>
<span class="timezone">America/Los_Angeles</span>
<span class="title">Summary of the event</span>
<span class="description">Description of the event</span>
<span class="location">Location of the event</span>
</div>
Before pushing, do a git pull with rebase option. This will get the changes that you made online (in your origin) and apply them locally, then add your local changes on top of it.
git pull --rebase
Now, you can push to remote
git push
For more information take a look at Git rebase explained and Chapter 3.6 Git Branching - Rebasing.
SELECT * FROM table ORDER BY id DESC,datechat desc LIMIT 50
If you have a date field that is storing the date(and time) on which the chat was sent or any field that is filled with incrementally(order by DESC) or desinscrementally( order by ASC) data per row put it as second column on which the data should be order.
That's what worked for me!!!! hope it will help!!!!
Guess you are looking for .focusout()
Usually the application that misses the .dll indicates what version you need – if one does not work, simply download the Microsoft visual C++ 2010 x86 or x64 from this link:
For 32 bit OS:Here
For 64 bit OS:Here
Fast solution:
SELECT * FROM TABLE1
MINUS
SELECT * FROM TABLE2
No records should show...
A cleaner alternative would be the following:
Due to the fact that every async function is technically a promise
You can add catches to functions when calling them with await
async function a(){
let error;
// log the error on the parent
await b().catch((err)=>console.log('b.failed'))
// change an error variable
await c().catch((err)=>{error=true; console.log(err)})
// return whatever you want
return error ? d() : null;
}
a().catch(()=>console.log('main program failed'))
No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!
Lets say you are working with mongodb, if there is an error you might prefer to handle it in the function calling it than making wrappers, or using try catches.
I replaced the "localhost" with IP Address (Database server's public IP Address) in the jdbc Url then it worked.
jdbcUrl = "jdbc:oracle:thin:<user>@//localhost:1521/<Service Name>";
??
jdbcUrl = "jdbc:oracle:thin:<user>@//<Public IP Address>:1521/<Service Name>";
I think that in this question is missing one important information.
How many records will you insert?
You can do this with this library. https://github.com/itmor/events-js
const events = new Events();
events.add({
blockIsHidden: () => {
if ($('div').css('display') === 'none') return true;
}
});
function printText () {
console.log('The block has become hidden!');
}
events.on('blockIsHidden', printText);
Suppose you want to create a vector x whose length is zero. Now let v be any vector.
> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0
ng g c --dry-run so you can see what you are about to do before you actually do it will save some frustration. Just shows you what it is going to do without actually doing it.
As the question and user3490026's answer are a top search hit, I have made a reproducible example and a brief illustration of the suggestions made so far, together with a solution that explicitly addresses the OP's question.
One of the things that ggplot2
does and which can be confusing is that it automatically blends certain legends when they are associated with the same variable. For instance, factor(gear)
appears twice, once for linetype
and once for fill
, resulting in a combined legend. By contrast, gear
has its own legend entry as it is not treated as the same as factor(gear)
. The solutions offered so far usually work well. But occasionally, you may need to override the guides. See my last example at the bottom.
# reproducible example:
library(ggplot2)
p <- ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs)) +
geom_point(aes(shape = factor(cyl))) +
geom_line(aes(linetype = factor(gear))) +
geom_smooth(aes(fill = factor(gear), color = gear)) +
theme_bw()
Remove all legends: @user3490026
p + theme(legend.position = "none")
Remove all legends: @duhaime
p + guides(fill = FALSE, color = FALSE, linetype = FALSE, shape = FALSE)
Turn off legends: @Tjebo
ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs), show.legend = FALSE) +
geom_point(aes(shape = factor(cyl)), show.legend = FALSE) +
geom_line(aes(linetype = factor(gear)), show.legend = FALSE) +
geom_smooth(aes(fill = factor(gear), color = gear), show.legend = FALSE) +
theme_bw()
Remove fill so that linetype becomes visible
p + guides(fill = FALSE)
Same as above via the scale_fill_ function:
p + scale_fill_discrete(guide = FALSE)
And now one possible answer to the OP's request
"to keep the legend of one layer (smooth) and remove the legend of the other (point)"
Turn some on some off ad-hoc post-hoc
p + guides(fill = guide_legend(override.aes = list(color = NA)),
color = FALSE,
shape = FALSE)
Set your Rgui preferences for a large number of lines, then timestamp and save as file at suitable intervals.
window.navigator.onLine
is what you looking for, but few things here to add, first, if it's something on your app which you want to keep checking (like to see if the user suddenly go offline, which correct in this case most of the time, then you need to listen to change also), for that you add event listener to window to detect any change, for checking if the user goes offline, you can do:
window.addEventListener("offline",
()=> console.log("No Internet")
);
and for checking if online:
window.addEventListener("online",
()=> console.log("Connected Internet")
);
check it useing loop for each index in comboxlist.Items[i]
bool CheckedOrUnchecked= comboxlist.CheckedItems.Contains(comboxlist.Items[0]);
I think it solve your purpose
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
Use:
((Long) userService.getAttendanceList(currentUser)).intValue();
instead.
The .intValue()
method is defined in class Number
, which Long
extends.
You need to add the following line:
using FootballLeagueSystem;
into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login
.
At the moment the compiler can't find the Login
class.
Unintentional zooming tends to happen when:
To prevent the double tap behaviour I have found two very simple workarounds:
<button onclick='event.preventDefault()'>Prevent Default</button>
<button style='touch-action: manipulation'>Touch Action Manipulation</button>
Both of these prevent Safari (iOS 10.3.2) from zooming in on the button. As you can see one is JavaScript only, the other is CSS only. Use appropriately.
Here is a demo: https://codepen.io/lukejacksonn/pen/QMELXQ
I have not attempted to prevent the pinch behaviour (yet), primarily because I tend not to create multi touch interfaces for the web and secondly I have come round to the idea that perhaps all interfaces including native app UI should be "pinch to zoom"-able in places. I'd still design to avoid the user having to do this to make your UI accessible to them, at all costs.
Right click on Project -> Add FrameWork Support -> Maven
One other way, using the splat operator:
*a, last = [1, 3, 4, 5]
STDOUT:
a: [1, 3, 4]
last: 5
No, since the other option is modifying the Zend engine, and one would be hard-pressed to call that a "better way".
Edit:
If you really wanted to, you could use an array:
$boolarray = Array(false => 'false', true => 'true');
echo $boolarray[false];
For anyone wondering about the difference between -1.#IND00
and -1.#IND
(which the question specifically asked, and none of the answers address):
-1.#IND00
This specifically means a non-zero number divided by zero, e.g. 3.14 / 0
(source)
-1.#IND
(a synonym for NaN
)
This means one of four things (see wiki from source):
1) sqrt
or log
of a negative number
2) operations where both variables are 0 or infinity, e.g. 0 / 0
3) operations where at least one variable is already NaN
, e.g. NaN * 5
4) out of range trig, e.g. arcsin(2)
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
From angular's documentation,
ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit
onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude
The major difference between them is when used with ng-include.
<div ng-include="partialViewUrl" onload="myFunction()"></div>
In this case, myFunction is called everytime the partial view is loaded.
<div ng-include="partialViewUrl" ng-init="myFunction()"></div>
Whereas, in this case, myFunction is called only once when the parent view is loaded.
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
Well, you can use the CASE statement:
SELECT
CASE
WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
ELSE Date1
END AS MostRecentDate
[For Microsoft SQL Server 2008 and above, you may consider Sven's simpler answer below.]
If your question was prompted by using JAXB and wanting to choose the correct XMLAccessType
, I had the same question. The JAXB Javadoc says that a "field" is a non-static, non-transient instance variable. A "property" has a getter/setter pair (so it should be a private variable). A "public member" is public, and therefore is probably a constant. Also in JAXB, an "attribute" refers to part of an XML element, as in <myElement myAttribute="first">hello world</myElement>
.
It seems that a Java "property," in general, can be defined as a field with at least a getter or some other public method that allows you to get its value. Some people also say that a property needs to have a setter. For definitions like this, context is everything.
The best one I have used and researched on it is $request->merge([])
(Check My Piece of Code):
public function index(Request $request) {
not_permissions_redirect(have_premission(2));
$filters = (!empty($request->all())) ? true : false;
$request->merge(['type' => 'admin']);
$users = $this->service->getAllUsers($request->all());
$roles = $this->roles->getAllAdminRoles();
return view('users.list', compact(['users', 'roles', 'filters']));
}
Check line # 3 inside the index function.
state={
name:"",
email:""
}
handalSubmit = () => {
after api call
let resetFrom = {}
fetch('url')
.then(function(response) {
if(response.success){
resetFrom{
name:"",
email:""
}
}
})
this.setState({...resetFrom})
}
Look at the internals of the Date class and you will see that you can extract all the bits (date, month, year, hour, etc).
http://www.w3schools.com/jsref/jsref_obj_date.asp
For something like Fri 23:00 1 Feb 2013
the code is like:
date = new Date();_x000D_
_x000D_
weekdayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];_x000D_
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];_x000D_
var dateString = weekdayNames[date.getDay()] + " " _x000D_
+ date.getHours() + ":" + ("00" + date.getMinutes()).slice(-2) + " " _x000D_
+ date.getDate() + " " + monthNames[date.getMonth()] + " " + date.getFullYear();_x000D_
_x000D_
console.log(dateString);
_x000D_
**** Modified 2019-05-29 to keep 3 downvoters happy
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
//output
a: 1
b: 2
Use this, one function solve all problems of comma and quote:
public static DataTable CsvToDataTable(string strFilePath)
{
if (File.Exists(strFilePath))
{
string[] Lines;
string CSVFilePathName = strFilePath;
Lines = File.ReadAllLines(CSVFilePathName);
while (Lines[0].EndsWith(","))
{
Lines[0] = Lines[0].Remove(Lines[0].Length - 1);
}
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names; force lower case to ensure matching later on.
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i], typeof(string));
DataRow Row;
int rowcount = 0;
try
{
string[] ToBeContinued = new string[]{};
bool lineToBeContinued = false;
for (int i = 1; i < Lines.GetLength(0); i++)
{
if (!Lines[i].Equals(""))
{
Fields = Lines[i].Split(new char[] { ',' });
string temp0 = string.Join("", Fields).Replace("\"\"", "");
int quaotCount0 = temp0.Count(c => c == '"');
if (Fields.GetLength(0) < Cols || lineToBeContinued || quaotCount0 % 2 != 0)
{
if (ToBeContinued.GetLength(0) > 0)
{
ToBeContinued[ToBeContinued.Length - 1] += "\n" + Fields[0];
Fields = Fields.Skip(1).ToArray();
}
string[] newArray = new string[ToBeContinued.Length + Fields.Length];
Array.Copy(ToBeContinued, newArray, ToBeContinued.Length);
Array.Copy(Fields, 0, newArray, ToBeContinued.Length, Fields.Length);
ToBeContinued = newArray;
string temp = string.Join("", ToBeContinued).Replace("\"\"", "");
int quaotCount = temp.Count(c => c == '"');
if (ToBeContinued.GetLength(0) >= Cols && quaotCount % 2 == 0 )
{
Fields = ToBeContinued;
ToBeContinued = new string[] { };
lineToBeContinued = false;
}
else
{
lineToBeContinued = true;
continue;
}
}
//modified by Teemo @2016 09 13
//handle ',' and '"'
//Deserialize CSV following Excel's rule:
// 1: If there is commas in a field, quote the field.
// 2: Two consecutive quotes indicate a user's quote.
List<int> singleLeftquota = new List<int>();
List<int> singleRightquota = new List<int>();
//combine fileds if number of commas match
if (Fields.GetLength(0) > Cols)
{
bool lastSingleQuoteIsLeft = true;
for (int j = 0; j < Fields.GetLength(0); j++)
{
bool leftOddquota = false;
bool rightOddquota = false;
if (Fields[j].StartsWith("\""))
{
int numberOfConsecutiveQuotes = 0;
foreach (char c in Fields[j]) //start with how many "
{
if (c == '"')
{
numberOfConsecutiveQuotes++;
}
else
{
break;
}
}
if (numberOfConsecutiveQuotes % 2 == 1)//start with odd number of quotes indicate system quote
{
leftOddquota = true;
}
}
if (Fields[j].EndsWith("\""))
{
int numberOfConsecutiveQuotes = 0;
for (int jj = Fields[j].Length - 1; jj >= 0; jj--)
{
if (Fields[j].Substring(jj,1) == "\"") // end with how many "
{
numberOfConsecutiveQuotes++;
}
else
{
break;
}
}
if (numberOfConsecutiveQuotes % 2 == 1)//end with odd number of quotes indicate system quote
{
rightOddquota = true;
}
}
if (leftOddquota && !rightOddquota)
{
singleLeftquota.Add(j);
lastSingleQuoteIsLeft = true;
}
else if (!leftOddquota && rightOddquota)
{
singleRightquota.Add(j);
lastSingleQuoteIsLeft = false;
}
else if (Fields[j] == "\"") //only one quota in a field
{
if (lastSingleQuoteIsLeft)
{
singleRightquota.Add(j);
}
else
{
singleLeftquota.Add(j);
}
}
}
if (singleLeftquota.Count == singleRightquota.Count)
{
int insideCommas = 0;
for (int indexN = 0; indexN < singleLeftquota.Count; indexN++)
{
insideCommas += singleRightquota[indexN] - singleLeftquota[indexN];
}
if (Fields.GetLength(0) - Cols >= insideCommas) //probabaly matched
{
int validFildsCount = insideCommas + Cols; //(Fields.GetLength(0) - insideCommas) may be exceed the Cols
String[] temp = new String[validFildsCount];
int totalOffSet = 0;
for (int iii = 0; iii < validFildsCount - totalOffSet; iii++)
{
bool combine = false;
int storedIndex = 0;
for (int iInLeft = 0; iInLeft < singleLeftquota.Count; iInLeft++)
{
if (iii + totalOffSet == singleLeftquota[iInLeft])
{
combine = true;
storedIndex = iInLeft;
break;
}
}
if (combine)
{
int offset = singleRightquota[storedIndex] - singleLeftquota[storedIndex];
for (int combineI = 0; combineI <= offset; combineI++)
{
temp[iii] += Fields[iii + totalOffSet + combineI] + ",";
}
temp[iii] = temp[iii].Remove(temp[iii].Length - 1, 1);
totalOffSet += offset;
}
else
{
temp[iii] = Fields[iii + totalOffSet];
}
}
Fields = temp;
}
}
}
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
{
Fields[f] = Fields[f].Replace("\"\"", "\""); //Two consecutive quotes indicate a user's quote
if (Fields[f].StartsWith("\""))
{
if (Fields[f].EndsWith("\""))
{
Fields[f] = Fields[f].Remove(0, 1);
if (Fields[f].Length > 0)
{
Fields[f] = Fields[f].Remove(Fields[f].Length - 1, 1);
}
}
}
Row[f] = Fields[f];
}
dt.Rows.Add(Row);
rowcount++;
}
}
}
catch (Exception ex)
{
throw new Exception( "row: " + (rowcount+2) + ", " + ex.Message);
}
//OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", FilePath + FileName));
//OleDbCommand command = new OleDbCommand("SELECT * FROM " + FileName, connection);
//OleDbDataAdapter adapter = new OleDbDataAdapter(command);
//DataTable dt = new DataTable();
//adapter.Fill(dt);
//adapter.Dispose();
return dt;
}
else
return null;
//OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", strFilePath));
//OleDbCommand command = new OleDbCommand("SELECT * FROM " + strFileName, connection);
//OleDbDataAdapter adapter = new OleDbDataAdapter(command);
//DataTable dt = new DataTable();
//adapter.Fill(dt);
//return dt;
}
Is this what you are trying?
Option Explicit
Public Sub SaveWorksheetsAsCsv()
Dim WS As Worksheet
Dim SaveToDirectory As String, newName As String
SaveToDirectory = "H:\test\"
For Each WS In ThisWorkbook.Worksheets
newName = GetBookName(ThisWorkbook.Name) & "_" & WS.Name
WS.Copy
ActiveWorkbook.SaveAs SaveToDirectory & newName, xlCSV
ActiveWorkbook.Close Savechanges:=False
Next
End Sub
Function GetBookName(strwb As String) As String
GetBookName = Left(strwb, (InStrRev(strwb, ".", -1, vbTextCompare) - 1))
End Function
Normally it's not possible to download just one file from git
without downloading the whole repository as suggested in the first answer.
It's because Git doesn't store files as you think (as CVS/SVN do), but it generates them based on the entire history of the project.
But there are some workarounds for specific cases. Examples below with placeholders for user
, project
, branch
, filename
.
GitHub
wget https://raw.githubusercontent.com/user/project/branch/filename
GitLab
wget https://gitlab.com/user/project/raw/branch/filename
GitWeb
If you're using Git on the Server - GitWeb, then you may try in example (change it into the right path):
wget "http://example.com/gitweb/?p=example;a=blob_plain;f=README.txt;hb=HEAD"
GitWeb at drupalcode.org
Example:
wget "http://drupalcode.org/project/ads.git/blob_plain/refs/heads/master:/README.md"
googlesource.com
There is an undocumented feature that allows you to download base64-encoded versions of raw files:
curl "https://chromium.googlesource.com/chromium/src/net/+/master/http/transport_security_state_static.json?format=TEXT" | base64 --decode
In other cases check if your Git repository is using any web interfaces.
If it's not using any web interface, you may consider to push your code to external services such as GitHub, Bitbucket, etc. and use it as a mirror.
If you don't have wget
installed, try curl -O (url)
alternatively.
select distinct a.FirstName, a.LastName, v.District from AddTbl a inner join ValTbl v on a.LastName = v.LastName order by a.FirstName;
hope this helps
It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:
This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.
In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.
You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.
Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)
Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:
public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
if (uiElement == null)
{
throw new ArgumentNullException("uiElement");
}
if (uiElement.InvokeRequired)
{
if (forceSynchronous)
{
uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
}
else
{
uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
}
}
else
{
if (uiElement.IsDisposed)
{
throw new ObjectDisposedException("Control is already disposed.");
}
updater();
}
}
Consider the case where we're calling SafeInvoke
from the non-gui thread for a control whose handle has not been created.
uiElement
is not null, so we check uiElement.InvokeRequired
. Per the MSDN docs (bolded) InvokeRequired
will return false
because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else
condition where we check IsDisposed
or immediately proceed to call the submitted action... from the background thread!
At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?
All good answers, but I did not saw a reference to java.util.Collections which uses tons of static inner class for their static factor methods. So adding the same.
Adding an example from java.util.Collections which has multiple static inner class. Inner classes are useful to group code which needs to be accessed via outer class.
/**
* @serial include
*/
static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
implements Set<E>, Serializable {
private static final long serialVersionUID = -9215047833775013803L;
UnmodifiableSet(Set<? extends E> s) {super(s);}
public boolean equals(Object o) {return o == this || c.equals(o);}
public int hashCode() {return c.hashCode();}
}
Here is the static factor method in the java.util.Collections class
public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
return new UnmodifiableSet<>(s);
}
In Java 9 you have the even more elegant solution of using immutable lists via the new convenience factory method List.of
:
List<String> immutableList = List.of("one","two","three");
(shamelessly copied from here )
In the Blade Template : define a variable like this
@extends('app',['title' => 'Your Title Goes Here'])
@section('content')
And in the app.blade.php or any other of your choice ( I'm just following default Laravel 5 setup )
<title>{{ $title or 'Default title Information if not set explicitly' }}</title>
This is my first answer here. Hope it works.Good luck!
@Html.TextBoxFor(model => model.IssueDate, new { @class = "form-control", name = "inv_issue_date", id = "inv_issue_date", title = "Select Invoice Issue Date", placeholder = "dd/mm/yyyy", style = "text-align:center;" })
I prefer ANSI timestamp literals:
insert into the_table
(the_timestamp_column)
values
(timestamp '2017-10-12 21:22:23');
More details in the manual: https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF51062
char[] ch = ?
new String(ch).getBytes();
or
new String(ch).getBytes("UTF-8");
to get non-default charset.
Update: Since Java 7: new String(ch).getBytes(StandardCharsets.UTF_8);
There is a comprehensive list of tools on the PostgreSQL Wiki:
https://wiki.postgresql.org/wiki/PostgreSQL_Clients
And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.
Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:
For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.
Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)
import os
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
self.var1 = os.environ["VAR1"]
self.var2 = os.environ["VAR2"]
def test_01(self):
print("var1: {}, var2: {}".format(self.var1, self.var2))
Then from the command line (tested on Linux)
$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
When using NOT IN you should ensure that none of the values are NULL:
SELECT mac, creation_date
FROM logs
WHERE logs_type_id=11
AND mac NOT IN (
SELECT mac
FROM consols
WHERE mac IS NOT NULL -- add this
)
You need to do a lot more work than 1. click export 2. Open file.
I think that when the Excel CSV documentation talks about OS and regional settings being interpreted, that means that Excel will do that when it opens the file (which is in their "special" csv format). See this article, "Excel formatting and features are not transferred to other file formats"
Also, Excel is actually storing a number, and converting to a date string only for display. When it exports to CSV, it is converting it to a different date string. If you want that date string to be non-default, you will need to convert your Excel cells to strings before performing your export.
Alternately, you could convert your dates to the number value that Excel is saving. Since that is a time code, it actually will obey OS and regional settings, assuming you import it properly. Notepad will only show you the 10-digit number, though.
You're way off track here.
You already have a nice, big error message. Why on Earth would you want to write code that checks $?
explicitly after every single command? This is enormously cumbersome and error prone. The correct solution is stop checking $?
.
Instead, use PowerShell's built in mechanism to blow up for you. You enable it by setting the error preference to the highest level:
$ErrorActionPreference = 'Stop'
I put this at the top of every single script I ever write, and now I don't have to check $?
. This makes my code vastly simpler and more reliable.
If you run into situations where you really need to disable this behavior, you can either catch
the error or pass a setting to a particular function using the common -ErrorAction
. In your case, you probably want your process to stop on the first error, catch the error, and then log it.
Do note that this doesn't handle the case when external executables fail (exit code nonzero, conventionally), so you do still need to check $LASTEXITCODE
if you invoke any. Despite this limitation, the setting still saves a lot of code and effort.
You might also want to consider using strict mode:
Set-StrictMode -Version Latest
This prevents PowerShell from silently proceeding when you use a non-existent variable and in other weird situations. (See the -Version
parameter for details about what it restricts.)
Combining these two settings makes PowerShell much more of fail-fast language, which makes programming in it vastly easier.
Here is the simple explanation of Redux over Flux. Redux does not have a dispatcher.It relies on pure functions called reducers. It does not need a dispatcher. Each actions are handled by one or more reducers to update the single store. Since data is immutable, reducers returns a new updated state that updates the store
For more information Flux vs Redux
Checkout this thread, it has some useful information about exiting and tracebacks.
If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
break
interacts solely with the closest enclosing loop or switch, whether it be a for
, while
or do .. while
type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:
for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:
while (B) D; // Simply doesn't have A or C
do { D; } while (B); // Omits initial goto test
continue; // goto iter;
break; // goto end;
The difference is, continue
and break
interact with virtual labels automatically placed by the compiler. This is similar to what return
does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.
The programming error the notice refers to is misunderstanding break
as interacting with an enclosing block rather than an enclosing loop. Consider:
for (A; B; C) {
D;
if (E) {
F;
if (G) break; // Incorrectly assumed to break if(E), breaks for()
H;
}
I;
}
J;
Someone thought, given such a piece of code, that G
would cause a jump to I
, but it jumps to J
. The intended function would use if (!G) H;
instead.
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
Since Bash 4.2 you can use printf
's %(datefmt)T
format:
$ printf '%(%c)T\n' 1267619929
Wed 03 Mar 2010 01:38:49 PM CET
That's nice, because it's a shell builtin. The format for datefmt is a string accepted by strftime(3)
(see man 3 strftime
). Here %c
is:
%c
The preferred date and time representation for the current locale.
Now if you want a script that accepts an argument and, if none is provided, reads stdin, you can proceed as:
#!/bin/bash
if (($#)); then
printf '%(%c)T\n' "$@"
else
while read -r line; do
printf '%(%c)T\n' "$line"
done
fi
Strings:
>>> n = '4'
>>> print(n.zfill(3))
004
And for numbers:
>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n)) # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n)) # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n)) # python >= 2.7 + python3
004
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
Just to top this up to the new Java 8 API:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));
A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.
In my case there was a conflict in the namespaces , I have:
using System.Web.Mvc;
and
using System.Collections.Generic;
I explicitly want to use the Mvc one so I declared it as :
new System.Web.Mvc.SelectList(...)
I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.
I have done the following using OpenCV 3.0.0 and python:
import cv2
#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img)
#-----Converting image to LAB Color model-----------------------------------
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)
#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)
#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)
#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)
#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)
#_____END_____#
You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.
1) Go to Xcode Preferences
2) Locate the location tab
3) Set the Xcode verdion in Given Command Line Tools
Now, it ll successfully work.
In addition to all answers above:
If updating the cacerts file in JRE directory doesn't help, try to update it in JDK.
C:\Program Files\Java\jdk1.8.0_192\jre\lib\security
In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.
Thanx @krd, I am using your error catch process, but had to update the print and except statements. I am using Python 2.7.6 on Linux Mint 17.2.
Also, it was unclear where the output string was coming from. My update:
import subprocess
# Output returned in error handler
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "1.1.1.1"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
# Output returned normally
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "8.8.8.8"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
I see an output like this:
Ping stdout output on error:
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
--- 1.1.1.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms
Ping stdout output on success:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=37.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=59 time=38.8 ms
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 37.840/38.321/38.802/0.481 ms
Html Code:-
<a href="#" id="playerID">Play</a>
<iframe src="https://www.youtube.com/embed/videoID" class="embed-responsive-item" data-play="0" id="VdoID" ></iframe>
Jquery Code:-
$('#playerID').click(function(){
var videoURL = $('#VdoID').attr('src'),
dataplay = $('#VdoID').attr('data-play');
//for check autoplay
//if not set autoplay=1
if(dataplay == 0 ){
$('#VdoID').attr('src',videoURL+'?autoplay=1');
$('#VdoID').attr('data-play',1);
}
else{
var videoURL = $('#VdoID').attr('src');
videoURL = videoURL.replace("?autoplay=1", "");
$('#VdoID').prop('src','');
$('#VdoID').prop('src',videoURL);
$('#VdoID').attr('data-play',0);
}
});
Thats It!
To add to Matt wilson's answer I had a bunch of code-first entity classes but no database as I hadn't taken a backup. So I did the following on my Entity Framework project:
Open Package Manager console in Visual Studio and type the following:
Enable-Migrations
Add-Migration
Give your migration a name such as 'Initial' and then create the migration. Finally type the following:
Update-Database
Update-Database -Script -SourceMigration:0
The final command will create your database tables from your entity classes (provided your entity classes are well formed).
I found this sample script here that seems to be working pretty well:
SELECT r.session_id,r.command,CONVERT(NUMERIC(6,2),r.percent_complete)
AS [Percent Complete],CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time],
CONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min],
CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) AS [ETA Min],
CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours],
CONVERT(VARCHAR(1000),(SELECT SUBSTRING(text,r.statement_start_offset/2,
CASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END)
FROM sys.dm_exec_sql_text(sql_handle))) AS [SQL]
FROM sys.dm_exec_requests r WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')
here is vertical menu base on Bootstrap http://www.okvee.net/articles/okvee-bootstrap-sidebar-menu it is also support responsive design.
add this function in static class in project like utility class:
utility.cs content:
public static class Utility
{
public static string GetBaseUrl()
{
var request = HttpContext.Current.Request;
var urlHelper = new UrlHelper(request.RequestContext);
var baseUrl = $"{request.Url.Scheme}://{request.Url.Authority}{urlHelper.Content("~")}";
return baseUrl;
}
}
use this code any where and enjoy it:
var baseUrl = Utility.GetBaseUrl();
Well then: welcome to the R world ;-)
Here you go
urls <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz",
"xxxxx"
)
readUrl <- function(url) {
out <- tryCatch(
{
# Just to highlight: if you want to use more than one
# R expression in the "try" part then you'll have to
# use curly brackets.
# 'tryCatch()' will return the last evaluated expression
# in case the "try" part was completed successfully
message("This is the 'try' part")
readLines(con=url, warn=FALSE)
# The return value of `readLines()` is the actual value
# that will be returned in case there is no condition
# (e.g. warning or error).
# You don't need to state the return value via `return()` as code
# in the "try" part is not wrapped inside a function (unlike that
# for the condition handlers for warnings and error below)
},
error=function(cond) {
message(paste("URL does not seem to exist:", url))
message("Here's the original error message:")
message(cond)
# Choose a return value in case of error
return(NA)
},
warning=function(cond) {
message(paste("URL caused a warning:", url))
message("Here's the original warning message:")
message(cond)
# Choose a return value in case of warning
return(NULL)
},
finally={
# NOTE:
# Here goes everything that should be executed at the end,
# regardless of success or error.
# If you want more than one expression to be executed, then you
# need to wrap them in curly brackets ({...}); otherwise you could
# just have written 'finally=<expression>'
message(paste("Processed URL:", url))
message("Some other message at the end")
}
)
return(out)
}
> y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory
> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"
[5] "</head><body>"
[6] ""
> length(y)
[1] 3
> y[[3]]
[1] NA
tryCatch
tryCatch
returns the value associated to executing expr
unless there's an error or a warning. In this case, specific return values (see return(NA)
above) can be specified by supplying a respective handler function (see arguments error
and warning
in ?tryCatch
). These can be functions that already exist, but you can also define them within tryCatch()
(as I did above).
The implications of choosing specific return values of the handler functions
As we've specified that NA
should be returned in case of error, the third element in y
is NA
. If we'd have chosen NULL
to be the return value, the length of y
would just have been 2
instead of 3
as lapply()
will simply "ignore" return values that are NULL
. Also note that if you don't specify an explicit return value via return()
, the handler functions will return NULL
(i.e. in case of an error or a warning condition).
"Undesired" warning message
As warn=FALSE
doesn't seem to have any effect, an alternative way to suppress the warning (which in this case isn't really of interest) is to use
suppressWarnings(readLines(con=url))
instead of
readLines(con=url, warn=FALSE)
Multiple expressions
Note that you can also place multiple expressions in the "actual expressions part" (argument expr
of tryCatch()
) if you wrap them in curly brackets (just like I illustrated in the finally
part).
The first method
if (isset($arr['1']))
will not work on an associative array.
For example, the following code displays "Nope, not more than one."
$arr = array(
'a' => 'apple',
'b' => 'banana',
);
if (isset($arr['1'])) {
echo "Yup, more than one.";
} else {
echo "Nope, not more than one.";
}
Using onBackPressed()
method:
@Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
}
or use the finish()
method, I have something like
//Password Error, I call function
Quit();
protected void Quit() {
super.finish();
}
With super.finish() you close the super class's activity.
Here is how I got it going specifically for the admob sdk jar file:
jar
file into the libs folder.jar
file and select Add Library
now the jar file is a library lets add it to the compile pathbuild.gradle
file (note there are two build.gradle
files at least, don't use the root one use the one in your project scope).Find the dependencies section (for me i was trying to the admob -GoogleAdMobAdsSdk jar file) e.g.
dependencies {
compile files('libs/android-support-v4.jar','libs/GoogleAdMobAdsSdk-6.3.1.jar')
}
Last go into settings.gradle
and ensure it looks something like this:
include ':yourproject', ':yourproject:libs:GoogleAdMobAdsSdk-6.3.1'