Why not pass an object to v-bind:class to dynamically toggle the class:
<div v-bind:class="{ disabled: order.cancelled_at }"></div>
This is what is recommended by the Vue docs.
According to the docs:
"If the onPressed callback is null, then the button will be disabled and by default will resemble a flat button in the disabledColor."
https://docs.flutter.io/flutter/material/RaisedButton-class.html
So, you might do something like this:
RaisedButton(
onPressed: calculateWhetherDisabledReturnsBool() ? null : () => whatToDoOnPressed,
child: Text('Button text')
);
Do this:
function changeHeight() { document.getElementById('chartdiv').style.height = "200px" } <button type="button" onClick="changeHeight();"> Click Me!</button>
Your way is optimized, in my opinion. But you will end up with reordered keys. Newly created key will be appended at the end. I know you should never rely on key order, but if you need to preserve it, you will need to go through all keys and construct new object one by one, replacing the key in question during that process.
Like this:
var new_o={};
for (var i in o)
{
if (i==old_key) new_o[new_key]=o[old_key];
else new_o[i]=o[i];
}
o=new_o;
ListView was intended for simple use cases like the same static view for all row items.
Since you have to create ViewHolders and make significant use of getItemViewType()
, and dynamically show different row item layout xml's, you should try doing that using the RecyclerView, which is available in Android API 22. It offers better support and structure for multiple view types.
Check out this tutorial on how to use the RecyclerView to do what you are looking for.
private void button1_Click(object sender, EventArgs e)
{
TimeSpan timespan;
timespan = dateTimePicker2.Value - dateTimePicker1.Value;
int timeDifference = timespan.Days;
MessageBox.Show(timeDifference.ToString());
}
Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:
SELECT employee_number,
MAX(MAX(course_completion_date))
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
And as Teradata allows re-using an alias this also works:
SELECT employee_number,
MAX(max_date)
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
/*
* Code Prepared by **Muhammad Mubashir**.
* Analyst Software Engineer.
Email Id : [email protected]
Skype Id : muhammad.mubashir.ansari
Code: **August, 2011.**
Description: **Get Updates(means New .Apk File) from IIS Server and Download it on Device SD Card,
and Uninstall Previous (means OLD .apk) and Install New One.
and also get Installed App Version Code & Version Name.**
All Rights Reserved.
*/
package com.SelfInstall01;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.SelfInstall01.SelfInstall01Activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SelfInstall01Activity extends Activity
{
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
//private Drawable icon;
/*private void prettyPrint() {
//Log.v(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
}*/
}
public int VersionCode;
public String VersionName="";
public String ApkName ;
public String AppName ;
public String BuildVersionPath="";
public String urlpath ;
public String PackageName;
public String InstallAppPackageName;
public String Text="";
TextView tvApkStatus;
Button btnCheckUpdates;
TextView tvInstallVersion;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Text= "Old".toString();
Text= "New".toString();
ApkName = "SelfInstall01.apk";//"Test1.apk";// //"DownLoadOnSDcard_01.apk"; //
AppName = "SelfInstall01";//"Test1"; //
BuildVersionPath = "http://10.0.2.2:82/Version.txt".toString();
PackageName = "package:com.SelfInstall01".toString(); //"package:com.Test1".toString();
urlpath = "http://10.0.2.2:82/"+ Text.toString()+"_Apk/" + ApkName.toString();
tvApkStatus =(TextView)findViewById(R.id.tvApkStatus);
tvApkStatus.setText(Text+" Apk Download.".toString());
tvInstallVersion = (TextView)findViewById(R.id.tvInstallVersion);
String temp = getInstallPackageVersionInfo(AppName.toString());
tvInstallVersion.setText("" +temp.toString());
btnCheckUpdates =(Button)findViewById(R.id.btnCheckUpdates);
btnCheckUpdates.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
GetVersionFromServer(BuildVersionPath);
if(checkInstalledApp(AppName.toString()) == true)
{
Toast.makeText(getApplicationContext(), "Application Found " + AppName.toString(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Application Not Found. "+ AppName.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}// On Create END.
private Boolean checkInstalledApp(String appName){
return getPackages(appName);
}
// Get Information about Only Specific application which is Install on Device.
public String getInstallPackageVersionInfo(String appName)
{
String InstallVersion = "";
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++)
{
//apps.get(i).prettyPrint();
if(apps.get(i).appname.toString().equals(appName.toString()))
{
InstallVersion = "Install Version Code: "+ apps.get(i).versionCode+
" Version Name: "+ apps.get(i).versionName.toString();
break;
}
}
return InstallVersion.toString();
}
private Boolean getPackages(String appName)
{
Boolean isInstalled = false;
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++)
{
//apps.get(i).prettyPrint();
if(apps.get(i).appname.toString().equals(appName.toString()))
{
/*if(apps.get(i).versionName.toString().contains(VersionName.toString()) == true &&
VersionCode == apps.get(i).versionCode)
{
isInstalled = true;
Toast.makeText(getApplicationContext(),
"Code Match", Toast.LENGTH_SHORT).show();
openMyDialog();
}*/
if(VersionCode <= apps.get(i).versionCode)
{
isInstalled = true;
/*Toast.makeText(getApplicationContext(),
"Install Code is Less.!", Toast.LENGTH_SHORT).show();*/
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
//SelfInstall01Activity.this.finish(); Close The App.
DownloadOnSDcard();
InstallApplication();
UnInstallApplication(PackageName.toString());
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("New Apk Available..").setPositiveButton("Yes Proceed", dialogClickListener)
.setNegativeButton("No.", dialogClickListener).show();
}
if(VersionCode > apps.get(i).versionCode)
{
isInstalled = true;
/*Toast.makeText(getApplicationContext(),
"Install Code is better.!", Toast.LENGTH_SHORT).show();*/
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
//SelfInstall01Activity.this.finish(); Close The App.
DownloadOnSDcard();
InstallApplication();
UnInstallApplication(PackageName.toString());
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("NO need to Install.").setPositiveButton("Install Forcely", dialogClickListener)
.setNegativeButton("Cancel.", dialogClickListener).show();
}
}
}
return isInstalled;
}
private ArrayList<PInfo> getInstalledApps(boolean getSysPackages)
{
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++)
{
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
//newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
return res;
}
public void UnInstallApplication(String packageName)// Specific package Name Uninstall.
{
//Uri packageURI = Uri.parse("package:com.CheckInstallApp");
Uri packageURI = Uri.parse(packageName.toString());
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);
}
public void InstallApplication()
{
Uri packageURI = Uri.parse(PackageName.toString());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);
// Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.setFlags(Intent.ACTION_PACKAGE_REPLACED);
//intent.setAction(Settings. ACTION_APPLICATION_SETTINGS);
intent.setDataAndType
(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + ApkName.toString())),
"application/vnd.android.package-archive");
// Not open this Below Line Because...
////intent.setClass(this, Project02Activity.class); // This Line Call Activity Recursively its dangerous.
startActivity(intent);
}
public void GetVersionFromServer(String BuildVersionPath)
{
//this is the file you want to download from the remote server
//path ="http://10.0.2.2:82/Version.txt";
//this is the name of the local file you will create
// version.txt contain Version Code = 2; \n Version name = 2.1;
URL u;
try {
u = new URL(BuildVersionPath.toString());
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
//Toast.makeText(getApplicationContext(), "HttpURLConnection Complete.!", Toast.LENGTH_SHORT).show();
InputStream in = c.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; //that stops the reading after 1024 chars..
//in.read(buffer); // Read from Buffer.
//baos.write(buffer); // Write Into Buffer.
int len1 = 0;
while ( (len1 = in.read(buffer)) != -1 )
{
baos.write(buffer,0, len1); // Write Into ByteArrayOutputStream Buffer.
}
String temp = "";
String s = baos.toString();// baos.toString(); contain Version Code = 2; \n Version name = 2.1;
for (int i = 0; i < s.length(); i++)
{
i = s.indexOf("=") + 1;
while (s.charAt(i) == ' ') // Skip Spaces
{
i++; // Move to Next.
}
while (s.charAt(i) != ';'&& (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.'))
{
temp = temp.toString().concat(Character.toString(s.charAt(i))) ;
i++;
}
//
s = s.substring(i); // Move to Next to Process.!
temp = temp + " "; // Separate w.r.t Space Version Code and Version Name.
}
String[] fields = temp.split(" ");// Make Array for Version Code and Version Name.
VersionCode = Integer.parseInt(fields[0].toString());// .ToString() Return String Value.
VersionName = fields[1].toString();
baos.close();
}
catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
}
//return true;
}// Method End.
// Download On My Mobile SDCard or Emulator.
public void DownloadOnSDcard()
{
try{
URL url = new URL(urlpath.toString()); // Your given URL.
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect(); // Connection Complete here.!
//Toast.makeText(getApplicationContext(), "HttpURLConnection complete.", Toast.LENGTH_SHORT).show();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH); // PATH = /mnt/sdcard/download/
if (!file.exists()) {
file.mkdirs();
}
File outputFile = new File(file, ApkName.toString());
FileOutputStream fos = new FileOutputStream(outputFile);
// Toast.makeText(getApplicationContext(), "SD Card Path: " + outputFile.toString(), Toast.LENGTH_SHORT).show();
InputStream is = c.getInputStream(); // Get from Server and Catch In Input Stream Object.
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1); // Write In FileOutputStream.
}
fos.close();
is.close();//till here, it works fine - .apk is download to my sdcard in download file.
// So please Check in DDMS tab and Select your Emulator.
//Toast.makeText(getApplicationContext(), "Download Complete on SD Card.!", Toast.LENGTH_SHORT).show();
//download the APK to sdcard then fire the Intent.
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(), "Error! " +
e.toString(), Toast.LENGTH_LONG).show();
}
}
}
If you were to use the C library then this could be done:
time_t t;
struct tm * timeinfo;
time (&t);
timeinfo = localtime (&t);
NSLog(@"Hour: %d Minutes: %d", timeinfo->tm_hour, timeinfo->tm_min);
And using Swift:
var t = time_t()
time(&t)
let x = localtime(&t)
println("Hour: \(x.memory.tm_hour) Minutes: \(x.memory.tm_min)")
For further guidance see: http://www.cplusplus.com/reference/ctime/localtime/
The simple solution would be:
while True:
age = int(input("Please enter your age: "))
if (age<=0) or (age>120):
print('Sorry, I did not understand that.Please try again')
continue
else:
if age>=18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
break
Explanation of above code: In order for a valid age,it should be positive and should not be more than normal physical age,say for example maximum age is 120.
Then we can ask user for age and if age input is negative or more than 120,we consider it invalid input and ask the user to try again.
Once the valid input is entered, we perform a check (using nested if-else statement) whether the age is >=18 or vice versa and print a message whether the user is eligible to vote
You should be able to install m2e (maven project for eclipse) using the Help -> Install New Software dialog. On that dialog open the Juno site (http://download.eclipse.org/releases/juno) and expand the Collaboration group (or type m2e into the filter). Select the two m2e options and follow the installation dialog
You can do so starting with Postgres 9.1:
with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows
In the meanwhile, if you're only interested in the id, you can do so with a trigger:
create function t1_ins_into_t2()
returns trigger
as $$
begin
insert into table2 (val) values (new.id);
return new;
end;
$$ language plpgsql;
create trigger t1_ins_into_t2
after insert on table1
for each row
execute procedure t1_ins_into_t2();
you can try this
class select_choice():
return x, y
a, b = test()
I would try to connect to the phone with ddms on its own without Eclipse. You might be running an emulator inside eclipse that you dont see or have some other problems with Eclipse.
Just run ddms from a command prompt and see if the device appears and you can connect to it.
You can also see if appears when you run adb devices
and see that your phone is listed (and maybve something else..)
Well, on Windows I happily run diff
and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.
So, my answer is that the Windows equivalent of diff
, is none other than diff
itself!
Another way in .Net 2.0
static void Main(string[] args)
{
List<string> alpha = new List<string>();
for(char a = 'a'; a <= 'd'; a++)
{
alpha.Add(a.ToString());
alpha.Add(a.ToString());
}
Console.WriteLine("Data :");
alpha.ForEach(delegate(string t) { Console.WriteLine(t); });
alpha.ForEach(delegate (string v)
{
if (alpha.FindAll(delegate(string t) { return t == v; }).Count > 1)
alpha.Remove(v);
});
Console.WriteLine("Unique Result :");
alpha.ForEach(delegate(string t) { Console.WriteLine(t);});
Console.ReadKey();
}
Here is a Javascript solution (for folks like me who were looking for an answer to the title):
function SaveToDisk(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html
Unfortunately the working for me with IE11, which is not accepting new MouseEvent. I use the following in that case:
//...
try {
var evt = new MouseEvent(...);
} catch (e) {
window.open(fileURL, fileName);
}
//...
Just noting that the reason actually is that the size of the enum is not yet known after forward declaration. Well, you use forward declaration of a struct to be able to pass a pointer around or refer to an object from a place that's refered to in the forward declared struct definition itself too.
Forward declaring an enum would not be too useful, because one would wish to be able to pass around the enum by-value. You couldn't even have a pointer to it, because i recently got told some platforms use pointers of different size for char than for int or long. So it all depends on the content of the enum.
The current C++ Standard explicitly disallows doing something like
enum X;
(in 7.1.5.3/1
). But the next C++ Standard due to next year allows the following, which convinced me the problem actually has to do with the underlying type:
enum X : int;
It's known as a "opaque" enum declaration. You can even use X by value in the following code. And its enumerators can later be defined in a later redeclaration of the enumeration. See 7.2
in the current working draft.
As far as the best algorithm goes you probably have it right. I would recommend that you unravel the recursive function and use a stack of your own (remember a stack overflow is the end of the world in a .Net 2.0+ app, the exception can not be caught IIRC).
The most important thing is that if you are using it in any form of a UI put it on a worker thread that signals the UI thread with updates.
Ctrl+0 or empty the value and hit enter.
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
If your method doesn't have to return html and has to do something else then you can use a lambda instead of helper method in Razor
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
Func<int,int,int> Sum = (a, b) => a + b;
}
<h2>Index</h2>
@Sum(3,4)
This is done using the REPLACE function
To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:
SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn] FROM [SomeTable]
To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"
UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')
You should be using a class
for multiple elements as an id
is meant to be only a single element. To answer your question on the .each()
syntax though, this is what it would look like:
$('#myID').each(function() {
$(this).remove();
});
Official JQuery documentation here.
The difference between an operating system and a kernel:
The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:
If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.
var globalObject = {
name:"a",
age:20
}
function() {
let localObject = {
name:'a',
age:21
}
this.globalObject = localObject;
}
Hope you dont mind Xml.Linq and .net3.5+
XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);
Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects
In NetBeans 7.0 (may be lower too) you could declare the the return type "array with Text objects " just as @return Text
and the code hinting will work:
Edit: updated the example with @Bob Fanger suggestion
/**
* get all Tests
*
* @return Test|Array $tests
*/
public function getAllTexts(){
return array(new Test(), new Test());
}
and just use it:
$tests = $controller->getAllTests();
//$tests-> //codehinting works!
//$tests[0]-> //codehinting works!
foreach($tests as $text){
//$test-> //codehinting works!
}
It is not perfect but it is better then just to leave it just "mixed", which brings no value.
CONS is you are allowed to tread the array as Text Object which will throw errors.
I was facing same issue, used below query to resolve it.
While creating DB you can use utf-8 encoding
eg. create database my_db character set utf8 collate utf8mb4;
EDIT: (Considering suggestions from comments) Changed utf8_bin to utf8mb4
That's:
SELECT * FROM Header
WHERE (userID LIKE '%''%')
Here's the code:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
DataRow _ravi = dt.NewRow();
_ravi["Name"] = "ravi";
_ravi["Marks"] = "500";
dt.Rows.Add(_ravi);
To see the structure, or rather I'd rephrase it as schema, you can export it to an XML file by doing the following.
To export only the schema/structure, do:
dt.WriteXMLSchema("dtSchemaOrStructure.xml");
Additionally, you can also export your data:
dt.WriteXML("dtDataxml");
i faced the same issue, issue was i tried to push my code with a xml
file (used as a data set) which has size of 1.3gb , so i add these file into .gitignore
and then problem solved
Collation means assigning some order to the characters in an Alphabet, say, ASCII or Unicode etc.
Suppose you have 3 characters in your alphabet - {A,B,C}. You can define some example collations for it by assigning integral values to the characters
As a matter of fact, you can define n! collations on an Alphabet of size n. Given such an order, different sorting routines likes LSD/MSD string sorts make use of it for sorting strings.
Also i have found another useful link. It is a background hack used like this
.selector { background-size: cover; -ms-behavior: url(/backgroundsize.min.htc); }
If anyone, fails to load because hes script violates the script-src "Content Security Policy" or "because unsafe-eval' is not an allowed", I will advice using my pretty-small module-injector as a dev-tools snippet, then you'll be able to load like this:
imports('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js')_x000D_
.then(()=>alert(`today is ${moment().format('dddd')}`));
_x000D_
<script src="https://raw.githack.com/shmuelf/PowerJS/master/src/power-moduleInjector.js"></script>
_x000D_
this solution works because:
Maybe you are out of inodes. Try df -i
2591792 136322 2455470 6% /home
/dev/sdb1 1887488 1887488 0 100% /data
Disk used 6% but inode table full.
Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:
For Columns:
For Rows:
Hope this helps...
Maybe
if (inventory.contains("bread") && !inventory.contains("water"))
Or
if (inventory.contains("bread")) {
if (!inventory.contains("water")) {
// do something here
}
}
"Cloud computing" is more of an operating-system-level concept than a language concept.
Let's say you want to host an application on Amazon's EC2 cloud computing service -- you can develop it in any language you like, on any operating system supported by EC2 (several flavors of Linux, Solaris, and Windows), then install and run it "in the cloud" on one or more virtual machines, much as you would do on a dedicated physical server.
For Windows:
You may find the need to check the status of your domains DNS records, or check the Name Servers to see which records the servers are pulling.
Launch Windows Command Prompt by navigating to Start > Command Prompt or via Run > CMD.
Type NSLOOKUP and hit Enter. The default Server is set to your local DNS, the Address will be your local IP.
Set the DNS Record type you wish to lookup by typing set type=##
where ## is the record type, then hit Enter. You may use ANY, A, AAAA, A+AAAA, CNAME, MX, NS, PTR, SOA, or SRV as the record type.
Now enter the domain name you wish to query then hit Enter.. In this example, we will use Managed.com.
NSLOOKUP will now return the record entries for the domain you entered.
You can also change the Name Servers which you are querying. This is useful if you are checking the records before DNS has fully propagated. To change the Name Server type server [name server]. Replace [name server] with the Name Servers you wish to use. In this example, we will set these as NSA.managed.com.
Once changed, change the query type (Step 3) if needed then enter new a new domain (Step 4.)
For Linux:
1) Check DNS Records Using Dig Command Dig stands for domain information groper is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality than dig.
2) Check DNS Records Using NSlookup Command Nslookup is a program to query Internet domain name servers. Nslookup has two modes interactive and non-interactive.
Interactive mode allows the user to query name servers for information about various hosts and domains or to print a list of hosts in a domain.
Non-interactive mode is used to print just the name and requested information for a host or domain. It’s network administration tool which will help them to check and troubleshoot DNS related issues.
3) Check DNS Records Using Host Command host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host prints a short summary of its command line arguments and options.
Following is the method in C# to get the enum value by string
///
/// Method to get enumeration value from string value.
///
///
///
public T GetEnumValue<T>(string str) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new Exception("T must be an Enumeration type.");
}
T val = ((T[])Enum.GetValues(typeof(T)))[0];
if (!string.IsNullOrEmpty(str))
{
foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
{
if (enumValue.ToString().ToUpper().Equals(str.ToUpper()))
{
val = enumValue;
break;
}
}
}
return val;
}
Following is the method in C# to get the enum value by int.
///
/// Method to get enumeration value from int value.
///
///
///
public T GetEnumValue<T>(int intValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new Exception("T must be an Enumeration type.");
}
T val = ((T[])Enum.GetValues(typeof(T)))[0];
foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
{
if (Convert.ToInt32(enumValue).Equals(intValue))
{
val = enumValue;
break;
}
}
return val;
}
If I have an enum as follows:
public enum TestEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 3
}
then I can make use of above methods as
TestEnum reqValue = GetEnumValue<TestEnum>("Value1"); // Output: Value1
TestEnum reqValue2 = GetEnumValue<TestEnum>(2); // OutPut: Value2
Hope this will help.
Use margin instead of padding in the parent div: http://blog.vjeux.com/2012/css/css-absolute-position-taking-into-account-padding.html
Another way of converting between pretty much any data format using R is with the rio package.
rio
package using install.packages("rio")
Load the rio library, then use the convert()
function:
library("rio")
convert("my_file.dta", "my_file.csv")
This method allows you to convert between many formats (e.g., Stata, SPSS, SAS, CSV, etc.). It uses the file extension to infer format and load using the appropriate importing package. More info can be found on the R-project rio page.
From Python 2.5 onwards you can do:
value = b if a > 10 else c
Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:
value = [c, b][a > 10]
There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.
for example if you want change package from com.example.a to com.example.b
1)change project style folder from android to package (in project side)
2)right click top of folder and click replace in path
3)select in project button
4)in first input write com.example.a
5)in second input write com.example.b
6)when you see warning select replace all to replace value
after finish replace you can see your package name is com.example.b
This expands the ternary option into if/else which minified is equivalent to the ternary option but doesn't sacrifice readability.
const clamp = (value, min, max) => {
if (value < min) return min;
if (value > max) return max;
return value;
}
Minifies to 35b (or 43b if using function
):
const clamp=(c,a,l)=>c<a?a:c>l?l:c;
Also, depending on what perf tooling or browser you use you get various outcomes of whether the Math based implementation or ternary based implementation is faster. In the case of roughly the same performance, I would opt for readability.
If boost is available on your system (I think it's standard on most Linux distros these days), it has a Tokenizer class you can use.
If not, then a quick Google turns up a hand-rolled tokenizer for std::string that you can probably just copy and paste. It's very short.
And, if you don't like either of those, then here's a split() function I wrote to make my life easier. It'll break a string into pieces using any of the chars in "delim" as separators. Pieces are appended to the "parts" vector:
void split(const string& str, const string& delim, vector<string>& parts) {
size_t start, end = 0;
while (end < str.size()) {
start = end;
while (start < str.size() && (delim.find(str[start]) != string::npos)) {
start++; // skip initial whitespace
}
end = start;
while (end < str.size() && (delim.find(str[end]) == string::npos)) {
end++; // skip to end of word
}
if (end-start != 0) { // just ignore zero-length strings.
parts.push_back(string(str, start, end-start));
}
}
}
style="column-width:300px;white-space: normal;"
In case you have a library that relies on requests
and you cannot modify the verify path (like with pyvmomi
) then you'll have to find the cacert.pem
bundled with requests and append your CA there. Here's a generic approach to find the cacert.pem
location:
windows
C:\>python -c "import requests; print requests.certs.where()"
c:\Python27\lib\site-packages\requests-2.8.1-py2.7.egg\requests\cacert.pem
linux
# (py2.7.5,requests 2.7.0, verify not enforced)
root@host:~/# python -c "import requests; print requests.certs.where()"
/usr/lib/python2.7/dist-packages/certifi/cacert.pem
# (py2.7.10, verify enforced)
root@host:~/# python -c "import requests; print requests.certs.where()"
/usr/local/lib/python2.7/dist-packages/requests/cacert.pem
btw. @requests-devs, bundling your own cacerts with request is really, really annoying... especially the fact that you do not seem to use the system ca store first and this is not documented anywhere.
update
in situations, where you're using a library and have no control over the ca-bundle location you could also explicitly set the ca-bundle location to be your host-wide ca-bundle:
REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-bundle.crt python -c "import requests; requests.get('https://somesite.com';)"
I find myself forgetting how to do this every time as well so I just wrap the two one-liners that I need in a little class:
public class Utility
{
/// <summary>
/// Takes the full name of a resource and loads it in to a stream.
/// </summary>
/// <param name="resourceName">Assuming an embedded resource is a file
/// called info.png and is located in a folder called Resources, it
/// will be compiled in to the assembly with this fully qualified
/// name: Full.Assembly.Name.Resources.info.png. That is the string
/// that you should pass to this method.</param>
/// <returns></returns>
public static Stream GetEmbeddedResourceStream(string resourceName)
{
return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
}
/// <summary>
/// Get the list of all emdedded resources in the assembly.
/// </summary>
/// <returns>An array of fully qualified resource names</returns>
public static string[] GetEmbeddedResourceNames()
{
return Assembly.GetExecutingAssembly().GetManifestResourceNames();
}
}
There is a Bootstrap3 native solution: http://getbootstrap.com/components/#responsive-embed
since Bootstrap 3.2.0!
If you are using Bootstrap < v3.2.0 so look into "responsive-embed.less" file of v3.2.0 - possibly you can use/copy this code in your case (it works for me in v3.1.1).
I am hosting my EC2 and S3 bucket in us-west-2 (Oregon) region. When I was calling $s3client->listBuckets()
to list existing buckets in my php, I was getting exception - "Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings...".
I made below changes to make it work. Sharing these details in case someone is facing similar issue and any of above answers have not helped.
ntpstat
command. If you get error, this link helps you to know what is going wrong.date.timezone
was not set to any value and also it was commented by default. I un-commented by removing ';' before this line and set its value to "UTC"
and saved the file.sudo service httpd restart
and sudo service ntpd restart
commands.After this I am able to list buckets successfully without any exception. Hope this helps.
The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.
If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.
You can use std::cin.get()
from iostream
:
#include <iostream> // std::cout, std::cin
using namespace std;
int main() {
do {
cout << '\n' << "Press the Enter key to continue.";
} while (cin.get() != '\n');
return 0;
}
Besides, system('pause')
is slow, and includes a file you probably don't need: stdlib.h
. It is platform-dependent, and actually calls up a 'virtual' OS.
If you want to do this the C++ way, do it like this:
#include <fstream>
#include <iterator>
#include <algorithm>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
std::ofstream output( "C:\\myfile.gif", std::ios::binary );
std::copy(
std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>( ),
std::ostreambuf_iterator<char>(output));
}
If you need that data in a buffer to modify it or something, do this:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
// copies all data into buffer
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
}
Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
}
with:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
}
}
or if you also wish a counter for each subcategory, replace with this:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
}
}
Try This.
Controller:
List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");
One reason why you might prefer to use a JOIN
rather than NOT IN
is that if the Values in the NOT IN
clause contain any NULL
s you will always get back no results. If you do use NOT IN
remember to always consider whether the sub query might bring back a NULL value!
RE: Question in Comments
'x' NOT IN (NULL,'a','b')
= 'x' <> NULL and 'x' <> 'a' and 'x' <> 'b'
= Unknown and True and True
= Unknown
The AT command would do that but that's what the Scheduled Tasks gui is for. Enter "help at" in a cmd window for details.
I was able to get this to work by using the Invoke-Expression
cmdlet.
Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
You need to Override equals
and hashCode
.
equals
will compare the objects for equality according to the properties you need and hashCode
is mandatory in order for your objects to be used correctly in Collections
and Maps
For me the dialogue appears more than one if I click the dpFlightDate edit text more than one time same for the timmer dialog . how can I avoid this dialog to appear only once and if the user click's 2nd time the dialog must not appear again ie if dialog is on the screen ?
// perform click event on edit text
dpFlightDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(frmFlightDetails.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
dpFlightDate.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
tpFlightTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog
timePickerDialog = new TimePickerDialog(frmFlightDetails.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
tpFlightTime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
}
});
If you read the docs.
$('#mydialog').dialog('isOpen')
This method returns a Boolean (true or false), not a jQuery object.
If you have a complex form with multiple files and other inputs here is a solution that plays nice with ngModel
.
It consists of a file input component that wraps a simple file input and implements the ControlValueAccessor
interface to make it consumable by ngModel
. The component exposes the FileList
object to ngModel
.
This solution is based on this article.
The component is used like this:
<file-input name="file" inputId="file" [(ngModel)]="user.photo"></file-input>
<label for="file"> Select file </label>
Here's the component code:
import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => FileInputComponent),
multi: true
};
@Component({
selector: 'file-input',
templateUrl: './file-input.component.html',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class FileInputComponent {
@Input()
public name:string;
@Input()
public inputId:string;
private innerValue:any;
constructor() { }
get value(): FileList {
return this.innerValue;
};
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: FileList) => void = noop;
set value(v: FileList) {
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
onBlur() {
this.onTouchedCallback();
}
writeValue(value: FileList) {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
changeFile(event) {
this.value = event.target.files;
}
}
And here's the component template:
<input type="file" name="{{ name }}" id="{{ inputId }}" multiple="multiple" (change)="changeFile($event)"/>
The window.showModalDialog is deprecated (Intent to Remove: window.showModalDialog(), Removing showModalDialog from the Web platform). [...]The latest plan is to land the showModalDialog removal in Chromium 37. This means the feature will be gone in Opera 24 and Chrome 37, both of which should be released in September.[...]
Its a good idea to stay away from parseInt and use Number and Math.round unless you need hex or octal. Both can use strings. Why stay away from it?
parseInt(0.001, 10)
0
parseInt(-0.0000000001, 10)
-1
parseInt(0.0000000001, 10)
1
parseInt(4000000000000000000000, 10)
4
It completly butchers really large or really small numbers. Oddly enough it works normally if these inputs are a string.
parseInt("-0.0000000001", 10)
0
parseInt("0.0000000001", 10)
0
parseInt("4000000000000000000000", 10)
4e+21
Instead of risking hard to find bugs with this and the other gotchas people mentioned, I would just avoid parseInt unless you need to parse something other than base 10. Number, Math.round, Math.foor, and .toFixed(0) can all do the same things parseInt can be used for without having these types of bugs.
If you really want or need to use parseInt for some of it's other qualities, never use it to convert floats to ints.
The other scenario you mush verify is that the file you're trying to unpack is not empty and is valid.
In my case I wasn't downloading the file correctly, after double check and I made sure I had the right file I could unpack it without any issues.
As basZero mentioned, X-Forwarded-For should be checked for comma. (Look at : http://en.wikipedia.org/wiki/X-Forwarded-For). The general format of the field is: X-Forwarded-For: clientIP, proxy1, proxy2... and so on. So we will be seeing something like this : X-FORWARDED-FOR: 129.77.168.62, 129.77.63.62.
Kotlin version with update for deprication of RequestBody.create
:
Retrofit interface
@Multipart
@POST("uploadPhoto")
fun uploadFile(@Part file: MultipartBody.Part): Call<FileResponse>
and to Upload
fun uploadFile(fileUrl: String){
val file = File(fileUrl)
val fileUploadService = RetrofitClientInstance.retrofitInstance.create(FileUploadService::class.java)
val requestBody = file.asRequestBody(file.extension.toMediaTypeOrNull())
val filePart = MultipartBody.Part.createFormData(
"blob",file.name,requestBody
)
val call = fileUploadService.uploadFile(filePart)
call.enqueue(object: Callback<FileResponse>{
override fun onFailure(call: Call<FileResponse>, t: Throwable) {
Log.d(TAG,"Fckd")
}
override fun onResponse(call: Call<FileResponse>, response: Response<FileResponse>) {
Log.d(TAG,"success"+response.toString()+" "+response.body().toString()+" "+response.body()?.status)
}
})
}
Thanks to @jimmy0251
Because it's an integer. You need to declare them as floating point numbers or decimals, or cast to such in the calculation.
Just delete module-info.java at your Project Explorer tab.
Careful - append()
will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>')
.
Use text()
to replace element content with text, or append(document.createTextNode(x))
to append a text node.
You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:
class Dictlist(dict):
def __setitem__(self, key, value):
try:
self[key]
except KeyError:
super(Dictlist, self).__setitem__(key, [])
self[key].append(value)
Output example:
>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}
Class methods can't change or know the value of any instance variable. That should be the criteria for knowing if an instance method can be a class method.
It seems that this is not an uncommon problem.
Check this first.
If that doesn't help, you can install a local DNS server on Windows, such as this. Configure Windows to use localhost as the DNS server. This server can be configured to be authoritative for whatever fake domains you need, and to forward requests on to the real DNS servers for all other requests.
I personally think this is a bit over the top, and can't see why the hosts file wouldn't work. But it should solve the problem you're having. Make sure you set up your normal DNS servers as forwarders as well.
Try something like this:
@players.include?(p.name) ? false : true
You can put the condition after the WHEN
clause, like so:
SELECT
CASE
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
WHEN DS.DES = 'N' THEN 'Early Term'
WHEN DS.DES = 'Y' THEN 'Complete'
END
FROM
....
Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...
Tracking branches are local branches that have a direct relationship to a remote branch
Not exactly. The SO question "Having a hard time understanding git-fetch
" includes:
There's no such concept of local tracking branches, only remote tracking branches.
Soorigin/master
is a remote tracking branch formaster
in theorigin
repo.
But actually, once you establish an upstream branch relationship between:
master
origin/master
Then you can consider master
as a local tracking branch: It tracks the remote tracking branch origin/master
which, in turn, tracks the master branch of the upstream repo origin
.
@praneeth-nidarshan has covered mostly all the steps, except some:
$ sudo apt-get install php-pear
sh: phpize: not found
ERROR: `phpize’ failed
$ sudo apt-get install php7.2-dev
$ sudo pecl install mcrypt-1.0.1
extension=mcrypt.so
to your php.ini configuration file; if you don't know where it is, search with:$ sudo php -i | grep 'Configuration File'
if discount and discount != 0
..
end
update, it will false
for discount = false
Since you are going to work with a DirectoryInfo object anyway, I'd go with an extension
public static bool IsEmpty(this DirectoryInfo directoryInfo)
{
return directoryInfo.GetFileSystemInfos().Count() == 0;
}
A single way to remove sessions is setting it to null;
Session["your_session"] = null;
my_styles.xml
and save it in res/values
.Add the following code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ListFont" parent="@android:style/Widget.ListView">
<item name="android:textColor">#FF0000</item>
<item name="android:typeface">sans</item>
</style>
</resources>
Add your style to your Activity
definition in your AndroidManifest.xml
as an android:theme
attribute, and assign as value the name of the style you created. For example:
<activity android:name="your.activityClass" android:theme="@style/ListFont">
If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId. If this is not what you are looking for, please elaborate your question.
You need to have superuser privileges,
sudo npm install -g <package name>
If you don't want to chain (a huge number of) try-except clauses, you may try your codes in a loop and break upon 1st success.
Example with codes which can be put into functions:
for code in (
lambda: a / b,
lambda: a / (b + 1),
lambda: a / (b + 2),
):
try: print(code())
except Exception as ev: continue
break
else:
print("it failed: %s" % ev)
Example with arbitrary codes (statements) directly in the current scope:
for i in 2, 1, 0:
try:
if i == 2: print(a / b)
elif i == 1: print(a / (b + 1))
elif i == 0: print(a / (b + 2))
break
except Exception as ev:
if i:
continue
print("it failed: %s" % ev)
Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none;
on a submit button in the form.
I had the same issue, but none of the above worked for me. They did put me in to the right direction though.
For example when I set the "Copy Local" to "true" for System.Web.Mvc reference, it automatically sets it back to False.
I have multiple projects which depend on the System.Web.Mvc reference in my solution, but only one caused this problem. In VS 2012 this reference is labeled with the yellow attention triangle.
Find this reference => remove it => re-add it
That fixed it for me. Hope this helps
Based on W3schools default transition value is: all 0s ease 0s
, which should be the cross-browser compatible way of disabling the transition.
Here is a link: https://www.w3schools.com/cssref/css3_pr_transition.asp
In case anyone wants an alternative method...
If it is the last subdirectory in the path, you can use this one-liner:
cd "c:\directory\subdirectory\filename.exe\..\.." && dir /ad /b /s
This would return the following:
c:\directory\subdirectory
The .... drops back to the previous directory. /ad shows only directories /b is a bare format listing /s includes all subdirectories. This is used to get the full path of the directory to print.
It does includes boundaries.
declare @startDate date = cast('15-NOV-2016' as date)
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT c1
2016-11-15
2016-11-20
2016-11-30
declare @r1 int = 10
declare @r2 int = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15
Mike's suggestion sounds like the "right way". I came across this thread wanting to specify the user to run vncserver
under on reboot and wanted to keep all my cron jobs in one place.
I was getting the following error for the VNC cron:
vncserver: The USER environment variable is not set. E.g.:
In my case, I was able to use sudo
to specify who to run the task as.
@reboot sudo -u [someone] vncserver ...
See this snippet: (C#)
private Microsoft.Office.Interop.Excel.Application xla;
Workbook wb;
Worksheet ws;
Range rg;
..........
xla = new Microsoft.Office.Interop.Excel.Application();
wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
ws = (Worksheet)xla.ActiveSheet;
rg = (Range)ws.Cells[1, 2];
rg.ColumnWidth = 10;
rg.Value2 = "Frequency";
rg = (Range)ws.Cells[1, 3];
rg.ColumnWidth = 15;
rg.Value2 = "Impudence";
rg = (Range)ws.Cells[1, 4];
rg.ColumnWidth = 8;
rg.Value2 = "Phase";
You can use find
find . -type d > output.txt
or tree
tree -d > output.txt
tree
, If not installed on your system.
If you are using ubuntu
sudo apt-get install tree
If you are using mac os
.
brew install tree
I created a lightweight SMTP Email sender for PHP if anybody needs it here is the URL
https://github.com/jerryurenaa/EZMAIL
Tested in both environments production and development.
I hope it helps new folks looking for a simple solution.
Try something like:
ffmpeg -i "path to file" -f null /dev/null
It writes the frame number to stderr, so you can retrieve the last frame from this.
Here is a working example.
Keypoints are:
Accounts
JsonProperty
attribute.
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://coderwall.com/mdeiters.json");
var user = JsonConvert.DeserializeObject<User>(json);
}
-
public class User
{
/// <summary>
/// A User's username. eg: "sergiotapia, mrkibbles, matumbo"
/// </summary>
[JsonProperty("username")]
public string Username { get; set; }
/// <summary>
/// A User's name. eg: "Sergio Tapia, John Cosack, Lucy McMillan"
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// A User's location. eh: "Bolivia, USA, France, Italy"
/// </summary>
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("endorsements")]
public int Endorsements { get; set; } //Todo.
[JsonProperty("team")]
public string Team { get; set; } //Todo.
/// <summary>
/// A collection of the User's linked accounts.
/// </summary>
[JsonProperty("accounts")]
public Account Accounts { get; set; }
/// <summary>
/// A collection of the User's awarded badges.
/// </summary>
[JsonProperty("badges")]
public List<Badge> Badges { get; set; }
}
public class Account
{
public string github;
}
public class Badge
{
[JsonProperty("name")]
public string Name;
[JsonProperty("description")]
public string Description;
[JsonProperty("created")]
public string Created;
[JsonProperty("badge")]
public string BadgeUrl;
}
I'm going to agree somewhat with the person who wrote (paraphrased here): "For a link in an existing web page, the browser will always open the link in a new tab if the new page is part of the same web site as the existing web page." For me, at least, this "general rule" works in Chrome, Firefox, Opera, IE, Safari, SeaMonkey, and Konqueror.
Anyway, there is a less complicated way to take advantage of what the other person presented. Assuming we are talking about your own web site ("thissite.com" below), where you want to control what the browser does, then, below, you want "specialpage.htm" to be EMPTY, no HTML at all in it (saves time sending data from the server!).
var wnd, URL; //global variables
//specifying "_blank" in window.open() is SUPPOSED to keep the new page from replacing the existing page
wnd = window.open("http://www.thissite.com/specialpage.htm", "_blank"); //get reference to just-opened page
//if the "general rule" above is true, a new tab should have been opened.
URL = "http://www.someothersite.com/desiredpage.htm"; //ultimate destination
setTimeout(gotoURL(),200); //wait 1/5 of a second; give browser time to create tab/window for empty page
function gotoURL()
{ wnd.open(URL, "_self"); //replace the blank page, in the tab, with the desired page
wnd.focus(); //when browser not set to automatically show newly-opened page, this MAY work
}
http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css
Line 11:
.postItem img {
height: auto;
width: 450px;
}
You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:
<img src="theSource" style="width:30px;" />
Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.
You can use a Dictionary to keep track of the keys and values.
For instance...
dictOfStuff = {} ##Make a Dictionary
x = "Buffalo" ##OR it can equal the input of something, up to you.
dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to what ever you like
print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.
A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.
You can simply do it like this with an object literal:
function makeGamePlayer(name,totalScore,gamesPlayed) {
return {
name: name,
totalscore: totalScore,
gamesPlayed: gamesPlayed
};
}
Another way is to download source code then change following vaiables in variables.less
@font-family-sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif;
@font-family-serif: Georgia, "Times New Roman", Times, serif;
//** Default monospace fonts for `<code>`, `<kbd>`, and `<pre>`.
@font-family-monospace: Menlo, Monaco, Consolas, "Courier New", monospace;
@font-family-base: @font-family-sans-serif;
And then compile it to .css
file
Not a php pro. but i recently ran into this wall too and this is what i came up with.
function tag_contents($string, $tag_open, $tag_close){
foreach (explode($tag_open, $string) as $key => $value) {
if(strpos($value, $tag_close) !== FALSE){
$result[] = substr($value, 0, strpos($value, $tag_close));;
}
}
return $result;
}
$string = "i love cute animals, like [animal]cat[/animal],
[animal]dog[/animal] and [animal]panda[/animal]!!!";
echo "<pre>";
print_r(tag_contents($string , "[animal]" , "[/animal]"));
echo "</pre>";
//result
Array
(
[0] => cat
[1] => dog
[2] => panda
)
The spring configuration precedence is as follows.
So your configuration will be overridden at the command-line if you wish to do that. But the recommendation is to avoid overriding, though you can use multiple profiles.
The top post has 'as TextView' appended on the end. You might get other compiler errors if you leave this on. The following should be fine.
val text: TextView = findViewById(R.id.android_text) as TextView
Where 'android_text' is the ID of your textView
Use the $
metacharacter to match the end of a string.
In Perl, this looks like:
my $str = 'red/white/blue';
my($last_match) = $str =~ m/.*\/(.*)$/;
Written in JavaScript, this looks like:
var str = 'red/white/blue'.match(/.*\/(.*)$/);
We can Supply parameter in different way after some search I found some useful
<plugin>
<artifactId>${release.artifactId}</artifactId>
<version>${release.version}-${release.svm.version}</version>...
...
Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .
While Running build we need supply value for those parameter as follows.
RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74
Here I am supplying
release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74
It worked for me. Thanks
Slightly shorter version using methods chain:
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
.Select(g => new {Value = g.Key, Count = g.Count()})
.OrderByDescending(x=>x.Count);
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
private void TurnOnAutocomplete()
{
textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
string[] arrayOfWowrds = new string[];
try
{
//Read in data Autocomplete list to a string[]
string[] arrayOfWowrds = new string[];
}
catch (Exception err)
{
MessageBox.Show(err.Message, "File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
collection.AddRange(arrayOFWords);
textBox.AutoCompleteCustomSource = collection;
}
You only need to call this once after you have your data needed for the autocomplete list. Once bound it stays with the textBox. You do not need to or want to call it every time the text is changed in the textBox, that will kill your program.
Here is my performant approach to paging when using LINQ to objects:
public static IEnumerable<IEnumerable<T>> Page<T>(this IEnumerable<T> source, int pageSize)
{
Contract.Requires(source != null);
Contract.Requires(pageSize > 0);
Contract.Ensures(Contract.Result<IEnumerable<IEnumerable<T>>>() != null);
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
var currentPage = new List<T>(pageSize)
{
enumerator.Current
};
while (currentPage.Count < pageSize && enumerator.MoveNext())
{
currentPage.Add(enumerator.Current);
}
yield return new ReadOnlyCollection<T>(currentPage);
}
}
}
This can then be used like so:
var items = Enumerable.Range(0, 12);
foreach(var page in items.Page(3))
{
// Do something with each page
foreach(var item in page)
{
// Do something with the item in the current page
}
}
None of this rubbish Skip
and Take
which will be highly inefficient if you are interested in multiple pages.
A deferred can be used in place of a mutex. This is essentially the same as the multiple ajax usage scenarios.
MUTEX
var mutex = 2;
setTimeout(function() {
callback();
}, 800);
setTimeout(function() {
callback();
}, 500);
function callback() {
if (--mutex === 0) {
//run code
}
}
DEFERRED
function timeout(x) {
var dfd = jQuery.Deferred();
setTimeout(function() {
dfd.resolve();
}, x);
return dfd.promise();
}
jQuery.when(
timeout(800), timeout(500)).done(function() {
// run code
});
When using a Deferred as a mutex only, watch out for performance impacts (http://jsperf.com/deferred-vs-mutex/2). Though the convenience, as well as additional benefits supplied by a Deferred is well worth it, and in actual (user driven event based) usage the performance impact should not be noticeable.
Non C++11 solution: With the <ctime>
header, you could use strftime
. Make sure your buffer is large enough, you wouldn't want to overrun it and wreak havoc later.
#include <iostream>
#include <ctime>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo);
std::string str(buffer);
std::cout << str;
return 0;
}
This is visual representation of how performances compare to each other.
A more modern approach to waiting for elements:
while(!document.querySelector(".my-selector")) {
await new Promise(r => setTimeout(r, 500));
}
// now the element is loaded
Note that this code would need to be wrapped in an async function.
There are multiple ways to do it. If you have the string which you want to replace you can use the replace
or replaceAll
methods of the String
class. If you are looking to replace a substring you can get the substring using the substring
API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.
Finally, I solved this. (It works till now..)
My solution is like this...
Prepare the layout to show when an error occurred instead of Web Page (a dirty 'page not found message') The layout has one button, "RELOAD" with some guide messages.
If an error occurred, Remember using boolean and show the layout we prepare.
Here is my full source. Check this out.
public class MyWebViewActivity extends ActionBarActivity implements OnClickListener {
private final String TAG = MyWebViewActivity.class.getSimpleName();
private WebView mWebView = null;
private final String URL = "http://www.google.com";
private LinearLayout mlLayoutRequestError = null;
private Handler mhErrorLayoutHide = null;
private boolean mbErrorOccured = false;
private boolean mbReloadPressed = false;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
((Button) findViewById(R.id.btnRetry)).setOnClickListener(this);
mlLayoutRequestError = (LinearLayout) findViewById(R.id.lLayoutRequestError);
mhErrorLayoutHide = getErrorLayoutHideHandler();
mWebView = (WebView) findViewById(R.id.webviewMain);
mWebView.setWebViewClient(new MyWebViewClient());
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
mWebView.setWebChromeClient(getChromeClient());
mWebView.loadUrl(URL);
}
@Override
public boolean onSupportNavigateUp() {
return super.onSupportNavigateUp();
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btnRetry) {
if (!mbErrorOccured) {
return;
}
mbReloadPressed = true;
mWebView.reload();
mbErrorOccured = false;
}
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
}
else {
finish();
}
super.onBackPressed();
}
class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
if (mbErrorOccured == false && mbReloadPressed) {
hideErrorLayout();
mbReloadPressed = false;
}
super.onPageFinished(view, url);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mbErrorOccured = true;
showErrorLayout();
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
private WebChromeClient getChromeClient() {
final ProgressDialog progressDialog = new ProgressDialog(MyWebViewActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
return new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
};
}
private void showErrorLayout() {
mlLayoutRequestError.setVisibility(View.VISIBLE);
}
private void hideErrorLayout() {
mhErrorLayoutHide.sendEmptyMessageDelayed(10000, 200);
}
private Handler getErrorLayoutHideHandler() {
return new Handler() {
@Override
public void handleMessage(Message msg) {
mlLayoutRequestError.setVisibility(View.GONE);
super.handleMessage(msg);
}
};
}
}
Addition:Here is layout....
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rLayoutWithWebView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="@+id/webviewMain"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="@+id/lLayoutRequestError"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="@color/white"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<Button
android:id="@+id/btnRetry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minWidth="120dp"
android:text="RELOAD"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>
Now since the GhostDriver comes bundled with the PhantomJS, it has become even more convenient to use it through Selenium.
I tried the Node installation of PhantomJS, as suggested by Pykler, but in practice I found it to be slower than the standalone installation of PhantomJS. I guess standalone installation didn't provided these features earlier, but as of v1.9, it very much does so.
Now you can use like this
import selenium.webdriver
driver = selenium.webdriver.PhantomJS()
driver.get('http://google.com')
# do some processing
driver.quit()
I just discovered the Hmisc package:
Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.
library(Hmisc)
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th
Encryption has not only cpu, but also some network overhead.
As it was said before best and most simply way i found was
var getPrintObject=function(object)
{
return JSON.stringify(object);
}
Check if you're not incrementing with some variable that its value is an empty string like ''.
Example:
$total = '';
$integers = range(1, 5);
foreach($integers as $integer) {
$total += $integer;
}
Please try the below code for repeated fade-out/fade-in animation
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.3f);
anim.setRepeatCount(Animation.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
anim.setDuration(300);
view.setAnimation(anim); // to start animation
view.setAnimation(null); // to stop animation
You can't modify a collection while you're iterating over it with foreach. You might try using a regular for() statement.
You may need to iterate backwards from the end of the collection to make sure you cover every item in the collection and don't accidentally overrun the end of the collection after removing an item (since the length would change). I can't remember if .NET accounts for that possibility or not.
Add the below lines to your main app.
Remove org.activiti.spring.boot.SecurityAutoConfiguration.class if you're not using activiti.
Similarly, remove the one for actuator if you're not using spring-boot-actuator.
@EnableAutoConfiguration(exclude = {
org.activiti.spring.boot.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration.class,
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class })
Swift 3
let string = "www.stackoverflow.com"
let first3Characters = String(string.characters.prefix(3)) // www
let lastCharacters = string.characters.dropFirst(4) // stackoverflow.com (it would be a collection)
//or by index
let indexOfFouthCharacter = olNumber.index(olNumber.startIndex, offsetBy: 4)
let first3Characters = olNumber.substring(to: indexOfFouthCharacter) // www
let lastCharacters = olNumber.substring(from: indexOfFouthCharacter) // .stackoverflow.com
Good article for understanding, why do we need this
I am programming about 12 years and only 3 months ago I have met a situation where it was really convenient to use do-while as one iteration was always necessary before checking a condition. So guess your big-time is ahead :).
I have had the same error. And after I have already thought my mind is broken, because I had rename almost all my models properties the solution was delete one reference on All Syncfusion Controls and add references to the individual controls of this controls. (From Nuget)
This question didn't specifically address my concerns (outlined here) but in case anyone wants to do this with a parameterized number of columns and no coercion:
> require(dplyr)
> dbNames <- c('a','b','c','d')
> emptyTableOut <-
data.frame(
character(),
matrix(integer(), ncol = 3, nrow = 0), stringsAsFactors = FALSE
) %>%
setNames(nm = c(dbNames))
> glimpse(emptyTableOut)
Observations: 0
Variables: 4
$ a <chr>
$ b <int>
$ c <int>
$ d <int>
As divibisan states on the linked question,
...the reason [coercion] occurs [when cbinding matrices and their constituent types] is that a matrix can only have a single data type. When you cbind 2 matrices, the result is still a matrix and so the variables are all coerced into a single type before converting to a data.frame
Though both @pkozlowski.opensource's and @Mark's answers are correct, I'd like to share my slightly modified version where I always select the first item in the list, regardless of its value:
<select ng-options="option.value as option.name for option in typeOptions" ng-init="form.type=typeOptions[0].value">
</select>
This is all nicely lined up including the field label. Lining up the field label was the tricky part.
<div class="form-group">
<label class="control-label col-md-5">Create a</label>
<div class="col-md-7">
<label class="radio-inline control-label">
<input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
</label>
<label class="radio-inline control-label">
<input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
</label>
</div>
</div>
<div class="form-group">
@Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
<div class="col-md-7">
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
</label>
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
</label>
</div>
</div>
For me the easiest way to get it to work, is to put the component.requestFocus();
line, after the setVisible(true);
line, at the bottom of your frame or panel constructor.
This probably has something to do with asking for the focus, after all components have been created, because creating a new component, after asking for the focus request, will make your component loose te focus, and make the focus go to your newly created component. At least, that's what I assume.
Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"
Not what you asked for, but I do this because of a focus bug in WebKit with spinboxes:
// temporary fix for focus bug with webkit input type=number ui
if (navigator.userAgent.indexOf("AppleWebKit") > -1 && navigator.userAgent.indexOf("Mobile") == -1)
{
var els = document.querySelectorAll("input[type=number]");
for (var el in els)
el.type = "text";
}
It might give you an idea to help with what you need.
To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
For the sake of completeness, here is an alternative emphasizing that REQUEST_URI
starts with a slash (at least in .htaccess
files):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it
Just don't use %{REQUEST_URI} (.*)/$
. Because in the root directory REQUEST_URI
equals /
, the leading slash, and it would be misinterpreted as a trailing slash.
If you are interested in more reading:
(update: this technique is now implemented in Laravel 5.5)
If you are dealing with money I suggest checking the Money design pattern (originally from Martin Fowler's book on enterprise architectural design).
I suggest reading this link for the motivation: http://wiki.moredesignpatterns.com/space/Value+Object+Motivation+v2
if someone is still facing this issue, for me it started to occur after I changed my mysql/data
with mysql/backup
earlier to solve another issue.
I tried a lot of methods, and finally found the solution was very simple! Just click on this icon(Reset session) after opening PhPMyAdmin(it was loading in my case) just below the logo of PhPMyAdmin. It fixed the issue in one-click!
For me, the error code was #1142
PhpMyAdmin Reset Session
Oracle has two different ways of making views updatable:-
I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.
Use the tee
command:
echo "hello" | tee logfile.txt
Turn on debug logging to get a better picture of what is going on.
You can tell if the session cookies are being set by using a browser-side debugger to look at the headers returned in HTTP responses. (There are other ways too.)
One possibility is that SpringSecurity is setting secure session cookies, and your next page requested has an "http" URL instead of an "https" URL. (The browser won't send a secure cookie for an "http" URL.)
The constant values (uses in fixtures or assertions) should be initialized in their declarations and final
(as never change)
the object under test should be initialized in the setup method because we may set things on. Of course we may not set something now but we could set it later. Instantiating in the init method would ease the changes.
dependencies of the object under test if these are mocked, should not even be instantiated by yourself : today the mock frameworks can instantiate it by reflection.
A test without dependency to mock could look like :
public class SomeTest {
Some some; //instance under test
static final String GENERIC_ID = "123";
static final String PREFIX_URL_WS = "http://foo.com/ws";
@Before
public void beforeEach() {
some = new Some(new Foo(), new Bar());
}
@Test
public void populateList()
...
}
}
A test with dependencies to isolate could look like :
@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public class SomeTest {
Some some; //instance under test
static final String GENERIC_ID = "123";
static final String PREFIX_URL_WS = "http://foo.com/ws";
@Mock
Foo fooMock;
@Mock
Bar barMock;
@Before
public void beforeEach() {
some = new Some(fooMock, barMock);
}
@Test
public void populateList()
...
}
}
In Excel 2003 you should be able to create a formatting rule like:
=A1<>""
and then drag/copy this to other cells as needed.
If that doesn't work, try =Len(A1)>0
.
If there may be spaces in the cell which you will consider blank, then do:
=Len(Trim(A1))>0
Let me know if you can't get any of these to work. I have an old machine running XP and Office 2003, I can fire it up to troubleshoot if needed.
if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True
, like this:
df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)
This would look something like below:
You can do few more things as well. Take a look at Pandas plotting doc.
You could have multiple Python versions on your macOS.
You may check that by command
, type
or which
command, like:
which -a python python2 python2.7 python3 python3.6
Or type python
in Terminal and hit Tab few times for auto completion, which is equivalent to:
compgen -c python
By default python
/pip
commands points to the first binary found in PATH
environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin
which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local
(such as /usr/local/bin
) are provided by external packages.
It is generally advised, that when working with multiple versions, for Python 2 you may use python2
/pip2
command, respectively for Python 3 you can use python3
/pip3
, but it depends on your configuration which commands are available.
It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python
formula has been upgraded to Python 3.x and a python@2
formula will be added for installing Python 2.7. Before, python
formula was pointing to Python 2.
For instance, if you've installed different version via Homebrew, try the following command:
brew list python python3
or:
brew list | grep ^python
it'll show you all Python files installed with the package.
Alternatively you may use apropos
or locate python
command to locate more Python related files.
To check any environment variables related to Python, run:
env | grep ^PYTHON
To address your issues:
Error: No such keg: /usr/local/Cellar/python
Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3
).
The locate database (
/var/db/locate.database
) does not exist.
Follow the advice and run:
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
After the database is rebuild, you can use locate
command.
Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable
in Java.
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFromMySqlDatabase extends JFrame
{
public TableFromMySqlDatabase()
{
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/yourdb";
String userid = "root";
String password = "sesame";
String sql = "SELECT * FROM animals";
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:
Otherwise the code will throw an SQLException
stating that the driver cannot be found.
Now in my example, yourdb
is the name of the database and animals
is the name of the table that I am performing a query against.
Here is what will be output:
Parting note:
You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.
Do something like this:
int showLimit = 20;
/* Get all Tasks available (with limit set). */
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> allTasks = mgr.getRunningTasks(showLimit);
/* Loop through all tasks returned. */
for (ActivityManager.RunningTaskInfo aTask : allTasks)
{
Log.i("MyApp", "Task: " + aTask.baseActivity.getClassName());
if (aTask.baseActivity.getClassName().equals("com.android.email.activity.MessageList"))
running=true;
}
There are many questions about REST auth patterns here on SO. These are the most relevant for your question:
Basically you need to choose between using API keys (least secure as the key may be discovered by an unauthorized user), an app key and token combo (medium), or a full OAuth implementation (most secure).
Try this:
select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2
The number in the having should match the amount of people. If you also need the Status to be Complete
use this where
clause instead of the previous one:
where personName in ('Ryan', 'Holly') and status = 'Complete'
This was my problem, which may help someone else -- although it wasn't the OP's issue:
DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.ToString());
I determined the problem by outputting my path to a log file, and finding it not formatting correctly. Correct for me was quite simply:
DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.FullName.ToString());
In my experience, working with Firebase is a huge advantage if you are trying to do user management, database, messaging sort of app since all of these features are already well integrated.
Like others have said, if you're just focused on the database/querying aspect, stick to mongo.
if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
alert('hello world');
}
This is the only one solution that worked for me (it's not a onepage website). It's working with Chrome, Firefox and Safari.
Actually it's best to use:
IF DB_ID('dms') IS NOT NULL
--code mine :)
print 'db exists'
See https://docs.microsoft.com/en-us/sql/t-sql/functions/db-id-transact-sql and note that this does not make sense with the Azure SQL Database.
A good example of the 307 Internal Redirect
in action is when Google Chrome encounters a HTTP call to a domain it knows as requiring Strict Transport Security.
The browser redirects seamlessly, using the same method as the original call.
I'm assuming you're talking about com.google.common.base.Predicate<T>
from Guava.
From the API:
Determines a
true
orfalse
value for a given input. For example, aRegexPredicate
might implementPredicate<String>
, and return true for any string that matches its given regular expression.
This is essentially an OOP abstraction for a boolean
test.
For example, you may have a helper method like this:
static boolean isEven(int num) {
return (num % 2) == 0; // simple
}
Now, given a List<Integer>
, you can process only the even numbers like this:
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
for (int number : numbers) {
if (isEven(number)) {
process(number);
}
}
With Predicate
, the if
test is abstracted out as a type. This allows it to interoperate with the rest of the API, such as Iterables
, which have many utility methods that takes Predicate
.
Thus, you can now write something like this:
Predicate<Integer> isEven = new Predicate<Integer>() {
@Override public boolean apply(Integer number) {
return (number % 2) == 0;
}
};
Iterable<Integer> evenNumbers = Iterables.filter(numbers, isEven);
for (int number : evenNumbers) {
process(number);
}
Note that now the for-each loop is much simpler without the if
test. We've reached a higher level of abtraction by defining Iterable<Integer> evenNumbers
, by filter
-ing using a Predicate
.
Iterables.filter
Predicate
allows Iterables.filter
to serve as what is called a higher-order function. On its own, this offers many advantages. Take the List<Integer> numbers
example above. Suppose we want to test if all numbers are positive. We can write something like this:
static boolean isAllPositive(Iterable<Integer> numbers) {
for (Integer number : numbers) {
if (number < 0) {
return false;
}
}
return true;
}
//...
if (isAllPositive(numbers)) {
System.out.println("Yep!");
}
With a Predicate
, and interoperating with the rest of the libraries, we can instead write this:
Predicate<Integer> isPositive = new Predicate<Integer>() {
@Override public boolean apply(Integer number) {
return number > 0;
}
};
//...
if (Iterables.all(numbers, isPositive)) {
System.out.println("Yep!");
}
Hopefully you can now see the value in higher abstractions for routines like "filter all elements by the given predicate", "check if all elements satisfy the given predicate", etc make for better code.
Unfortunately Java doesn't have first-class methods: you can't pass methods around to Iterables.filter
and Iterables.all
. You can, of course, pass around objects in Java. Thus, the Predicate
type is defined, and you pass objects implementing this interface instead.
If you can not stop the service in Services, you can stop your windows service exe in Task Manager. After that, you can remove the service.
Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:
const profiles = await Profile.find({ user: {$exists: true, $ne: null }}) .select("-gallery") .sort( {_id: -1} ) .skip( skip ) .limit(10) .select(exclude) .populate({ path: 'user', match: { role: {$eq: customer}}, select: '-password -verified -_id -__v' }) .exec(); And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match). { "code": 200, "profiles": [ { "description": null, "province": "West Midlands", "country": "UK", "postal_code": "83000", "user": null }, { "description": null, "province": "Madrid", "country": "Spain", "postal_code": "43000", "user": { "role": "customer", "name": "pedrita", "email": "[email protected]", "created_at": "2020-06-05T11:05:36.450Z" } } ], "page": 1 }
Thanks in advance.
The examples contained in this blog post do the trick.
As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:
Directory.CreateDirectory(Path.GetDirectoryName(filePath))
Here is the implementation of LinkedList<T>#toArray(T[])
:
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
In short, you could only create generic arrays through Array.newInstance(Class, int)
where int
is the size of the array.
You need the /g for global matching
replace(/\n/g, "<br />");
This works for me for \n
- see this answer if you might have \r\n
NOTE: The dupe is the most complete answer for any combination of \r\n
, \r
or \n
var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");_x000D_
console.log(messagetoSend);
_x000D_
<textarea id="x" rows="9">_x000D_
Line 1_x000D_
_x000D_
_x000D_
Line 2_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
Line 3_x000D_
</textarea>
_x000D_
UPDATE
It seems some visitors of this question have text with the breaklines escaped as
some text\r\nover more than one line"
In that case you need to escape the slashes:
replace(/\\r\\n/g, "<br />");
NOTE: All browsers will ignore \r
in a string when rendering.
Try:
String path1 = "path1";
String path2 = "path2";
String joinedPath = new File(path1, path2).toString();
Try this
public class NetworkUtil {
public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int TYPE_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_WIFI = 1;
public static final int NETWORK_STATUS_MOBILE = 2;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static int getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
int status = 0;
if (conn == NetworkUtil.TYPE_WIFI) {
status = NETWORK_STATUS_WIFI;
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = NETWORK_STATUS_MOBILE;
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = NETWORK_STATUS_NOT_CONNECTED;
}
return status;
}
}
And for the BroadcastReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
int status = NetworkUtil.getConnectivityStatusString(context);
Log.e("Sulod sa network reciever", "Sulod sa network reciever");
if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
new ForceExitPause(context).execute();
} else {
new ResumeForceExitPause(context).execute();
}
}
}
}
Don't forget to put this into your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<receiver
android:name="NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
Hope this will help you Cheers!
Just replace -H
with -h
. Check man grep
for more details on options
find . -name '*.bar' -exec grep -hn FOO {} \;
I was looking into this and loved the approach from peege using a for loop! (because I'm learning VBA at the moment)
However, if we are trying to match "any" value of another column, how about using nested loops like the following?
Sub MatchAndColor()
Dim lastRow As Long
Dim sheetName As String
sheetName = "Sheet1" 'Insert your sheet name here
lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row
For lRowA = 1 To lastRow 'Loop through all rows
For lRowB = 1 To lastRow
If Sheets(sheetName).Cells(lRowA, "A") = Sheets(sheetName).Cells(lRowB, "B") Then
Sheets(sheetName).Cells(lRowA, "A").Interior.ColorIndex = 3 'Set Color to RED
End If
Next lRowB
Next lRowA
End Sub
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
rising_edge is defined as:
FUNCTION rising_edge (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
RETURN (s'EVENT AND (To_X01(s) = '1') AND
(To_X01(s'LAST_VALUE) = '0'));
END;
FUNCTION To_X01 ( s : std_ulogic ) RETURN X01 IS
BEGIN
RETURN (cvt_to_x01(s));
END;
CONSTANT cvt_to_x01 : logic_x01_table := (
'X', -- 'U'
'X', -- 'X'
'0', -- '0'
'1', -- '1'
'X', -- 'Z'
'X', -- 'W'
'0', -- 'L'
'1', -- 'H'
'X' -- '-'
);
If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.
Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk)
to be more descriptive than the (clk'event and clk = '1')
variant.
To help understand what do $#
, $0
and $1
, ..., $n
do, I use this script:
#!/bin/bash
for ((i=0; i<=$#; i++)); do
echo "parameter $i --> ${!i}"
done
Running it returns a representative output:
$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
https://github.com/google/iosched
This is the repo for the Google I/O App.
(Current version is 2015, also has tags for 2011 through 2014).
Sources for these books: http://commonsware.com/books
https://github.com/yanchenko/droidparts (a shameless plug)
If we are talking about class types - not primitives, the following trick has to be done:
Integer someInt;
Character someChar;
someChar = (char)Integer.parseInt(String.valueOf(someInt));
Add m.Ename
to your SELECT
query:
select distinct e.Ename as Employee, m.mgr as reports_to, m.Ename as Manager
from EMPLOYEES e
inner join Employees m on e.mgr = m.EmpID;
First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]
$doc = [xml]@'
<xml>
<Section name="BackendStatus">
<BEName BE="crust" Status="1" />
<BEName BE="pizza" Status="1" />
<BEName BE="pie" Status="1" />
<BEName BE="bread" Status="1" />
<BEName BE="Kulcha" Status="1" />
<BEName BE="kulfi" Status="1" />
<BEName BE="cheese" Status="1" />
</Section>
</xml>
'@
Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:
$doc.xml.Section.BEName
Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where
$doc.xml.Section.BEName | ? { $_.Status -eq 1 }
The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).
If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:
$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }
Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.
Java 5+ has all the tools you need for this kind of thing. You will want to:
ExecutorService
;ExecutorService
;BlockingQueue
.I say "if necessary" for (3) because from my experience it's an unnecessary step. All you do is submit new tasks to the consumer executor service. So:
final ExecutorService producers = Executors.newFixedThreadPool(100);
final ExecutorService consumers = Executors.newFixedThreadPool(100);
while (/* has more work */) {
producers.submit(...);
}
producers.shutdown();
producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
consumers.shutdown();
consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
So the producers
submit directly to consumers
.
Find one element
To find the element with a given name in an array you can use find
:
arr.find(item=>item.name=="k1");
Note that find
will return just one item (namely the first match):
{
"name": "k1",
"value": "abc"
}
Find all elements
In your original array there's only one item occurrence of each name.
If the array contains multiple elements with the same name and you want them all then use filter
, which will return an array.
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
arr.push({name:"k1", value:"def"});_x000D_
_x000D_
var item;_x000D_
_x000D_
// find the first occurrence of item with name "k1"_x000D_
item = arr.find(item=>item.name=="k1");_x000D_
console.log(item);_x000D_
_x000D_
// find all occurrences of item with name "k1"_x000D_
// now item is an array_x000D_
item = arr.filter(item=>item.name=="k1");_x000D_
console.log(item);
_x000D_
Find indices
Similarly, for indices you can use findIndex
(for finding the first match) and filter
+ map
to find all indices.
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
arr.push({name:"k1", value:"def"});_x000D_
_x000D_
var idx;_x000D_
_x000D_
// find index of the first occurrence of item with name "k1"_x000D_
idx = arr.findIndex(item=>item.name == "k1");_x000D_
console.log(idx, arr[idx].value);_x000D_
_x000D_
// find indices of all occurrences of item with name "k1"_x000D_
// now idx is an array_x000D_
idx = arr.map((item, i) => item.name == "k1" ? i : '').filter(String);_x000D_
console.log(idx);
_x000D_
What about [AllowHtml]
attribute above property?
you can try it too:
$(document).ajaxError(
function (event, jqXHR, ajaxSettings, thrownError) {
alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
});
Updated: August 06, 2020.
Let's assume we have an array:
let numbers: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
For iOS and macOS you can use system-wide random source in Xcode's framework GameKit
. Here you can find GKRandomSource
class with its sharedRandom()
class method:
import GameKit
private func randomNumberGenerator() -> Int {
let random = GKRandomSource.sharedRandom().nextInt(upperBound: numbers.count)
return numbers[random]
}
randomNumberGenerator()
Also you can use a randomElement()
method that returns a random element of a collection:
let randomNumber = numbers.randomElement()!
print(randomNumber)
Or use arc4random_uniform()
. Pay attention that this method returns UInt32
.
let generator = Int(arc4random_uniform(10))
print(generator)
And, of course, we can use a makeIterator()
method that returns an iterator over the elements of the collection.
let iterator: Int = (1...10).makeIterator().shuffled().first!
print(iterator)
The final example you see here returns a random value within the specified range with a help of static func random(in range: ClosedRange<Int>) -> Int
.
let randomizer = Int.random(in: 1...10)
print(randomizer)
Android Studio -> Device File Explorer (right bottom corner) -> data -> data -> {package.id} -> shared-prefs
Note: You need to connect mobile device to android studio and selected application should be in debug mode
I use port 465 all the time.
The answer by danorton is outdated. As he and Wikipedia say, port 465 was initially planned for the SMTPS encryption and quickly deprecated 15 years ago. But a lot of ISPs are still using port 465, especially to be in compliance with the current recommendations of RFC 8314, which encourages the use of implicit TLS instead of the use of the STARTTLS command with port 587. (See section 3.3). Using port 465 is the only way to begin an implicitly secure session with an SMTP server that is acting as a mail submission agent (MSA).
Basically, what RFC 8314 recommends is that cleartext email exchanges be abandoned and that all three common IETF mail protocols be used only in implicit TLS sessions for consistency when possible. The recommended secure ports, then, are 465, 993, and 995 for SMTPS, IMAP4S, and POP3S, respectively.
Although RFC 8314 certainly allows the continued use of explicit TLS with port 587 and the STARTTLS command, doing so opens up the mail user agent (MUA, the mail client) to a downgrade attack where a man-in-the-middle intercepts the STARTTLS request to upgrade to TLS security but denies it, thus forcing the session to remain in cleartext.
I don't know what kind of homework this is, but most probably the teacher doesn't want an answer where you just call a "magical" existing function (even though that's the recommended way to do it), but he wants to see if you can implement this by your own.
Back in the days, my teacher used to say something like "I want to see if you can program by yourself, not if you can find it in the system." Well, how wrong he was ;) ..
Anyway, if your teacher is the same, here is the hard way to do it..
std::string LongToString(long value)
{
std::string output;
std::string sign;
if(value < 0)
{
sign + "-";
value = -value;
}
while(output.empty() || (value > 0))
{
output.push_front(value % 10 + '0')
value /= 10;
}
return sign + output;
}
You could argue that using std::string
is not "the hard way", but I guess what counts in the actual agorithm.
The code looks unnecessarily complicated. Here is my version:
void strrev(char* str) {
size_t len = strlen(str);
char buf[len];
for (size_t i = 0; i < len; i++) {
buf[i] = str[len - 1 - i];
};
for (size_t i = 0; i < len; i++) {
str[i] = buf[i];
}
}
Even this works.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:drawable="@android:color/white" />
</selector>
I added the android:drawable
attribute to each item, and their values are colors.
By the way, why do they say that color
is one of the attributes of selector
? They don't write that android:drawable
is required.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="hex_color"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>
Suppose your drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
There are two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
SATELLITE
or HYBRID
well, it is just a watermark, you can hide it if you change the <div>
that has z-index=100
I use
setInterval(function(){
$("*").each(function() {
if ($(this).css("zIndex") == 100) {
$(this).css("zIndex", "-100");
}
})}
, 10);
or you can use
map.addListener('idle', function(e) {
//same function
}
but it is not as responsive as setInterval
From Code Complete
8 Defensive Programming
8.2 Assertions
An assertion is code that’s used during development—usually a routine or macro—that allows a program to check itself as it runs. When a assertion is true, that means everything is operating as expected. When it’s false, that means it has detected an unexpected error in the code. For example, if the system assumes that a customer-information file will never have more than 50,000 records, the program might contain an assertion that the number of records is less than or equal to 50,000. As long as the number of records is less than or equal to 50,000, the assertion will be silent. If it encounters more than 50,000 records, however, it will loudly “assert” that there is a error in the program.
Assertions are especially useful in large, complicated programs and in high-reliability programs. They enable programmers to more quickly flush out mismatched interface assumptions, errors that creep in when the code is modified, and so on.
An assertion usually takes two arguments: a boolean expression that describes the assumption that’s supposed to be true and a message to display if it isn’t.
(…)
Normally, you don’t want users to see assertion messages in production code; assertions are primarily for use during development and maintenance. Assertions are normally compiled into the code at development time and compiled out of the code for production. During development, assertions flush out contradictory assumptions, unexpected conditions, bad values passed to routines, and so on. During production, they are compiled out of the code so that the assertions don’t degrade system performance.
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
Take a look at SimpleDateFormat
:
java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));
You can do this in a couple of ways.
One, is to build up the query yourself and execute it.
SET @sql = 'SELECT ' + @columnName + ' FROM yourTable'
sp_executesql @sql
If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.
Alternatively, you can write a CASE statement...
SELECT
CASE @columnName
WHEN 'Col1' THEN Col1
WHEN 'Col2' THEN Col2
ELSE NULL
END as selectedColumn
FROM
yourTable
This is a bit more long winded, but a whole lot more secure.
I just wanted to answer my question properly as some people do not read the comments below an answer. So here it is:
(function($) {
$.fn.nodoubletapzoom = function() {
$(this).bind('touchstart', function preventZoom(e) {
var t2 = e.timeStamp
, t1 = $(this).data('lastTouch') || t2
, dt = t2 - t1
, fingers = e.originalEvent.touches.length;
$(this).data('lastTouch', t2);
if (!dt || dt > 500 || fingers > 1) return; // not double-tap
e.preventDefault(); // double tap - prevent the zoom
// also synthesize click events we just swallowed up
$(this).trigger('click').trigger('click');
});
};
})(jQuery);
I did not write this, i just modified it. I found the iOS-only version here: https://gist.github.com/2047491 (thanks Kablam)
If your version of PHP does not include this function:
<?php
function http_response_code($code = NULL) {
if ($code !== NULL) {
switch ($code) {
case 100: $text = 'Continue';
break;
case 101: $text = 'Switching Protocols';
break;
case 200: $text = 'OK';
break;
case 201: $text = 'Created';
break;
case 202: $text = 'Accepted';
break;
case 203: $text = 'Non-Authoritative Information';
break;
case 204: $text = 'No Content';
break;
case 205: $text = 'Reset Content';
break;
case 206: $text = 'Partial Content';
break;
case 300: $text = 'Multiple Choices';
break;
case 301: $text = 'Moved Permanently';
break;
case 302: $text = 'Moved Temporarily';
break;
case 303: $text = 'See Other';
break;
case 304: $text = 'Not Modified';
break;
case 305: $text = 'Use Proxy';
break;
case 400: $text = 'Bad Request';
break;
case 401: $text = 'Unauthorized';
break;
case 402: $text = 'Payment Required';
break;
case 403: $text = 'Forbidden';
break;
case 404: $text = 'Not Found';
break;
case 405: $text = 'Method Not Allowed';
break;
case 406: $text = 'Not Acceptable';
break;
case 407: $text = 'Proxy Authentication Required';
break;
case 408: $text = 'Request Time-out';
break;
case 409: $text = 'Conflict';
break;
case 410: $text = 'Gone';
break;
case 411: $text = 'Length Required';
break;
case 412: $text = 'Precondition Failed';
break;
case 413: $text = 'Request Entity Too Large';
break;
case 414: $text = 'Request-URI Too Large';
break;
case 415: $text = 'Unsupported Media Type';
break;
case 500: $text = 'Internal Server Error';
break;
case 501: $text = 'Not Implemented';
break;
case 502: $text = 'Bad Gateway';
break;
case 503: $text = 'Service Unavailable';
break;
case 504: $text = 'Gateway Time-out';
break;
case 505: $text = 'HTTP Version not supported';
break;
default:
exit('Unknown http status code "' . htmlentities($code) . '"');
break;
}
$protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
header($protocol . ' ' . $code . ' ' . $text);
$GLOBALS['http_response_code'] = $code;
} else {
$code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);
}
return $code;
}
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
You should use small caps "or" and "and" instead of OR and AND.
And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).
Here is a code sample with your three keywords working fine:
Here is the file ts.txt
:
*** test cases ***
mytest
${color} = set variable Red
Run Keyword If '${color}' == 'Red' log to console \nexecuted with single condition
Run Keyword If '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink' log to console \nexecuted with multiple or
${color} = set variable Blue
${Size} = set variable Small
${Simple} = set variable Simple
${Design} = set variable Simple
Run Keyword If '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}' log to console \nexecuted with multiple and
${Size} = set variable XL
${Design} = set variable Complicated
Run Keyword Unless '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple' log to console \nexecuted with unless and multiple or
and here is what I get when I execute it:
$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest | PASS |
------------------------------------------------------------------------------
This works..
var $targetGrid = $("#myGridId");
$(window).resize(function () {
var jqGridWrapperId = "#gbox_" + $targetGrid.attr('id') //here be dragons, this is generated by jqGrid.
$targetGrid.setGridWidth($(jqGridWrapperId).parent().width()); //perhaps add padding calculation here?
});
You could (but you shouldn't) use reflection for the job:
import java.lang.reflect.Field;
public class Outer {
public class Inner {
}
public static void main(String[] args) throws Exception {
// Create the inner instance
Inner inner = new Outer().new Inner();
// Get the implicit reference from the inner to the outer instance
// ... make it accessible, as it has default visibility
Field field = Inner.class.getDeclaredField("this$0");
field.setAccessible(true);
// Dereference and cast it
Outer outer = (Outer) field.get(inner);
System.out.println(outer);
}
}
Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)
Tickcount is good, however i suggest running it 100 or 1000 times, and calculating an average. Not only makes it more measurable - in case of really fast/short functions, but helps dealing with some one-off effects caused by the overhead.
I've had trouble with git revert in the past (mainly because I'm not quite certain how it works.) I've had trouble reverting because of merge problems..
My simple solution is this.
Step 1.
git clone <your repos URL> .
your project in another folder, then:
Step 2.
git reset --hard <the commit you wanna go to>
then Step 3.
in your latest (and main) project dir (the one that has the problematic last commit) paste the files of step 2
Step 4.
git commit -m "Fixing the previous messy commit"
Step 5.
Enjoy
ALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL
where {DataType}
is the current data type of that column (For example int
or varchar(10)
)
y_prob = model.predict(x)
y_classes = y_prob.argmax(axis=-1)
As suggested here.