You don't really need to install or use any third party tools.
The drivers located in ...\Android\Sdk\extras\google\usb_driver
work just fine.
Step 1: In Device Manager
, Right click on the malfunctioning Android ADB Interface
driver
Step 2: Select Update Driver Software
Step 3: Select Browse my computer for driver software
Step 4: Select Let me pick from a list of device drivers on my computer
Step 5: Select Have Disk
This window pops up:
Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver)
or browse to it.
Step 7: Click Ok
This window pops up:
Step 8: Select Android ADB Interface
and click Next
The window below pops up with a warning:
That's it. You driver installation will start and in a few seconds, you should be able to see your device
In the listing provided by PenguinTD, I do not understand why the ranges are reversed, it works without having to reverse the ranges. Linear range conversion is based upon the linear equation Y=Xm+n
, where m
and n
are derived from the given ranges. Rather than refer to the ranges as min
and max
, it would be better to refer to them as 1 and 2. So the formula would be:
Y = (((X - x1) * (y2 - y1)) / (x2 - x1)) + y1
Where Y=y1
when X=x1
, and Y=y2
when X=x2
. x1
, x2
, y1
& y2
can be given any positive
or negative
value. Defining the expression in a macro makes it more useful,it can then be used with any argument names.
#define RangeConv(X, x1, x2, y1, y2) (((float)((X - x1) * (y2 - y1)) / (x2 - x1)) + y1)
The float
cast would ensure floating point division in the case where all the arguments are integer
values.
Depending on the application it may not be necessary to check the ranges x1=x2
and y1==y2
.
Now a days, the easiest way I found to have a more updated version of Python is to install it via conda into a conda environment.
Install conda(you may need a virtualenv for this)
pip install conda
I'm adding this answer here because no manual download is needed. conda
will do that for you.
Now create an environment for the Python version you want. In this example I will use 3.5.2
, because it it the latest version at this time of writing (Aug 2016).
conda create -n py35 python=3.5.2
Will create a environment for conda to install packages
To activate this environment(I'm assuming linux otherwise check the conda docs):
source activate py35
Now install what you need either via pip or conda in the environemnt(conda has better binary package support).
conda install <package_name>
I've found the following "pattern" to be very useful:
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
function MainCtrl (scope, rootscope, location, thesocket, ...) {
where, MainCtrl is a controller. I am uncomfortable relying on the parameter names of the Controller function doing a one-for-one mimic of the instances for fear that I might change names and muck things up. I much prefer explicitly using $inject for this purpose.
Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.
So in your myDirective
return {
link: function (scope, element, attr) {
element.html('Hello world');
}
}
If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers
angular.element(document.querySelectorAll("[my-directive]"));
however you would need to use jquery to support IE8 and backwards
angular.element($("[my-directive]"));
or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?
dateadd(day,0,'10/15/2008 10:06:32 PM')
Here's what you need to do to fix the issue on Arch Linux :
Enable the multilib
repository on your system if you have not already done so by uncommenting the [multilib]
section in /etc/pacman.conf
:
[multilib]
Include = /etc/pacman.d/mirrorlist
Update pacman :
# pacman -Suy
Install the 32 bit version of libstdc++5 :
# pacman -S lib32-libstdc++5
This is a hard question to answer definitively because the terms and often misused or confused.
Often, an emulator is a complete re-implementation of a particular device or platform. The emulator acts exactly like the real device would. For example, a NES emulator implements the CPU, the sound chip, the video output, the controller signals, etc. The unmodified code from a NES castridge can be dumped and then the resulting image can be loaded into our emulator and played.
A simulator is a partial implementation of a device/platform, it does just enough for its own purposes. For example, the iPhone Simulator runs an "iPhone app" that has been specifically compiled to target x86 and the Cocoa API rather than the real device's ARM CPU and Cocoa Touch API. However, the binary that we run in the simulator would not work on the real device.
A regular expression might not be the most effective tool for this job.
Try using parse_url()
, combined with pathinfo()
:
$url = 'http://php.net/manual/en/function.preg-match.php';
$path = parse_url($url, PHP_URL_PATH);
$pathinfo = pathinfo($path);
echo $pathinfo['dirname'], '/', $pathinfo['filename'];
The above code outputs:
/manual/en/function.preg-match
In GNU/Linux, try to use ls
, namei
, getfacl
, stat
.
[flying@lempstacker ~]$ ls -ldh /tmp
drwxrwxrwt. 23 root root 4.0K Nov 8 15:41 /tmp
[flying@lempstacker ~]$ namei -l /tmp
f: /tmp
dr-xr-xr-x root root /
drwxrwxrwt root root tmp
[flying@lempstacker ~]$ getfacl /tmp
getfacl: Removing leading '/' from absolute path names
# file: tmp
# owner: root
# group: root
# flags: --t
user::rwx
group::rwx
other::rwx
[flying@lempstacker ~]$
or
[flying@lempstacker ~]$ stat -c "%a" /tmp
1777
[flying@lempstacker ~]$ stat -c "%n %a" /tmp
/tmp 1777
[flying@lempstacker ~]$ stat -c "%A" /tmp
drwxrwxrwt
[flying@lempstacker ~]$ stat -c "%n %A" /tmp
/tmp drwxrwxrwt
[flying@lempstacker ~]$
[flying@lempstacker ~]$ ls -lh /tmp/anaconda.log
-rw-r--r-- 1 root root 0 Nov 8 08:31 /tmp/anaconda.log
[flying@lempstacker ~]$ namei -l /tmp/anaconda.log
f: /tmp/anaconda.log
dr-xr-xr-x root root /
drwxrwxrwt root root tmp
-rw-r--r-- root root anaconda.log
[flying@lempstacker ~]$ getfacl /tmp/anaconda.log
getfacl: Removing leading '/' from absolute path names
# file: tmp/anaconda.log
# owner: root
# group: root
user::rw-
group::r--
other::r--
[flying@lempstacker ~]$
or
[flying@lempstacker ~]$ stat -c "%a" /tmp/anaconda.log
644
[flying@lempstacker ~]$ stat -c "%n %a" /tmp/anaconda.log
/tmp/anaconda.log 644
[flying@lempstacker ~]$ stat -c "%A" /tmp/anaconda.log
-rw-r--r--
[flying@lempstacker ~]$ stat -c "%n %A" /tmp/anaconda.log
/tmp/anaconda.log -rw-r--r--
[flying@lempstacker ~]$
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
In my case, I was using Laravel 5 and I had forgotten to change the mail globals in the .env file that is located in your directory root folder (these variables override your mail configuration)
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=yourpassword
by default, the mailhost is:
MAIL_HOST=mailtraper.io
I was getting the same error but that worked for me.
You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window
and document
both fit the bill (with just a few differences).
From mozilla dev network:
addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.
So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.
Foreign keys work with unique constraints as well as primary keys. From Books Online:
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table
For transactional replication, you need the primary key. From Books Online:
Tables published for transactional replication must have a primary key. If a table is in a transactional replication publication, you cannot disable any indexes that are associated with primary key columns. These indexes are required by replication. To disable an index, you must first drop the table from the publication.
Both answers are for SQL Server 2005.
With SQLServer 2005 Express, what I found was that even with autocommit off, insertions into a Db table were committed without my actually issuing a commit command from the Management Studio session. The only difference was, when autocommit was off, I could roll back all the insertions; with *autocommit on, I could not.* Actually, I was wrong. With autocommit mode off, I see the changes only in the QA (Query Analyzer) window from which the commands were issued. If I popped a new QA (Query Analyzer) window, I do not see the changes made by the first window (session), i.e. they are NOT committed! I had to issue explicit commit or rollback commands to make changes visible to other sessions(QA windows) -- my bad! Things are working correctly.
To do a cross server query, check out the system stored procedure: sp_addlinkedserver in the help files.
Once the server is linked you can run a query against it.
100% working code with demo You can also send multiple emails using this answer.
Download Project HERE
Step 1: Download mail, activation, additional jar files and add in your project libs folder in android studio. I added a screenshot see below Download link
Login with gmail (using your from mail) and TURN ON toggle button LINK
Most of the people forget about this step i hope you will not.
Step 2 : After completing this process. Copy and past this classes into your project.
GMail.java
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GMail {
final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
String fromEmail;
String fromPassword;
List<String> toEmailList;
String emailSubject;
String emailBody;
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public GMail() {
}
public GMail(String fromEmail, String fromPassword,
List<String> toEmailList, String emailSubject, String emailBody) {
this.fromEmail = fromEmail;
this.fromPassword = fromPassword;
this.toEmailList = toEmailList;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", smtpAuth);
emailProperties.put("mail.smtp.starttls.enable", starttls);
Log.i("GMail", "Mail server properties set.");
}
public MimeMessage createEmailMessage() throws AddressException,
MessagingException, UnsupportedEncodingException {
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
for (String toEmail : toEmailList) {
Log.i("GMail", "toEmail: " + toEmail);
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");// for a html email
// emailMessage.setText(emailBody);// for a text email
Log.i("GMail", "Email Message created.");
return emailMessage;
}
public void sendEmail() throws AddressException, MessagingException {
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromEmail, fromPassword);
Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
Log.i("GMail", "Email sent successfully.");
}
}
SendMailTask.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import java.util.List;
public class SendMailTask extends AsyncTask {
private ProgressDialog statusDialog;
private Activity sendMailActivity;
public SendMailTask(Activity activity) {
sendMailActivity = activity;
}
protected void onPreExecute() {
statusDialog = new ProgressDialog(sendMailActivity);
statusDialog.setMessage("Getting ready...");
statusDialog.setIndeterminate(false);
statusDialog.setCancelable(false);
statusDialog.show();
}
@Override
protected Object doInBackground(Object... args) {
try {
Log.i("SendMailTask", "About to instantiate GMail...");
publishProgress("Processing input....");
GMail androidEmail = new GMail(args[0].toString(),
args[1].toString(), (List) args[2], args[3].toString(),
args[4].toString());
publishProgress("Preparing mail message....");
androidEmail.createEmailMessage();
publishProgress("Sending email....");
androidEmail.sendEmail();
publishProgress("Email Sent.");
Log.i("SendMailTask", "Mail Sent.");
} catch (Exception e) {
publishProgress(e.getMessage());
Log.e("SendMailTask", e.getMessage(), e);
}
return null;
}
@Override
public void onProgressUpdate(Object... values) {
statusDialog.setMessage(values[0].toString());
}
@Override
public void onPostExecute(Object result) {
statusDialog.dismiss();
}
}
Step 3 : Now you can change this class according to your needs also you can send multiple mail using this class. i provide xml and java file both.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="30dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="From Email" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:cursorVisible="true"
android:editable="true"
android:ems="10"
android:enabled="true"
android:inputType="textEmailAddress"
android:padding="5dp"
android:textColor="#000000">
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Password (For from email)" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPassword"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="To Email" />
<EditText
android:id="@+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:inputType="textEmailAddress"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Subject" />
<EditText
android:id="@+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:padding="5dp"
android:textColor="#000000" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Body" />
<EditText
android:id="@+id/editText5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:inputType="textMultiLine"
android:padding="35dp"
android:textColor="#000000" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Email" />
</LinearLayout>
SendMailActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
public class SendMailActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button send = (Button) this.findViewById(R.id.button1);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("SendMailActivity", "Send Button Clicked.");
String fromEmail = ((TextView) findViewById(R.id.editText1))
.getText().toString();
String fromPassword = ((TextView) findViewById(R.id.editText2))
.getText().toString();
String toEmails = ((TextView) findViewById(R.id.editText3))
.getText().toString();
List<String> toEmailList = Arrays.asList(toEmails
.split("\\s*,\\s*"));
Log.i("SendMailActivity", "To List: " + toEmailList);
String emailSubject = ((TextView) findViewById(R.id.editText4))
.getText().toString();
String emailBody = ((TextView) findViewById(R.id.editText5))
.getText().toString();
new SendMailTask(SendMailActivity.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
}
});
}
}
Note Dont forget to add internet permission in your AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
Hope it work if it not then just comment down below.
empty()
needs to access the value by reference (in order to check whether that reference points to something that exists), and PHP before 5.5 didn't support references to temporary values returned from functions.
However, the real problem you have is that you use empty()
at all, mistakenly believing that "empty" value is any different from "false".
Empty is just an alias for !isset($thing) || !$thing
. When the thing you're checking always exists (in PHP results of function calls always exist), the empty()
function is nothing but a negation operator.
PHP doesn't have concept of emptyness. Values that evaluate to false are empty, values that evaluate to true are non-empty. It's the same thing. This code:
$x = something();
if (empty($x)) …
and this:
$x = something();
if (!$x) …
has always the same result, in all cases, for all datatypes (because $x
is defined empty()
is redundant).
Return value from the method always exists (even if you don't have return
statement, return value exists and contains null
). Therefore:
if (!empty($r->getError()))
is logically equivalent to:
if ($r->getError())
background-image: url(/images/poster.png);
background-position: center;
background-position-y: 50px;
background-repeat: no-repeat;
JAD and/or JADclipse Eclipse plugin, for sure.
I believe you can also do it while creating the dialog (copied from a project I did):
dialog = $('#dialog').dialog({
modal: true,
autoOpen: false,
width: 700,
height: 500,
minWidth: 700,
minHeight: 500,
position: ["center", 200],
close: CloseFunction,
overlay: {
opacity: 0.5,
background: "black"
}
});
Note close: CloseFunction
I'm running python 3.5 and subprocess.call(['./test.sh']) doesn't work for me.
I give you three solutions depends on what you wanna do with the output.
1 - call script. You will see output in your terminal. output is a number.
import subprocess
output = subprocess.call(['test.sh'])
2 - call and dump execution and error into string. You don't see execution in your terminal unless you print(stdout). Shell=True as argument in Popen doesn't work for me.
import subprocess
from subprocess import Popen, PIPE
session = subprocess.Popen(['test.sh'], stdout=PIPE, stderr=PIPE)
stdout, stderr = session.communicate()
if stderr:
raise Exception("Error "+str(stderr))
3 - call script and dump the echo commands of temp.txt in temp_file
import subprocess
temp_file = open("temp.txt",'w')
subprocess.call([executable], stdout=temp_file)
with open("temp.txt",'r') as file:
output = file.read()
print(output)
Don't forget to take a look at the doc subprocess
:not()
pseudo class:For selecting everything but a certain element (or elements). We can use the :not()
CSS pseudo class. The :not()
pseudo class requires a CSS
selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.
/* This query selects All div elements except for */_x000D_
div:not(.foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
<nav id="foo">test</nav>_x000D_
<nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
</ul>
_x000D_
We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor_x000D_
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>
_x000D_
Try the jQuery starts-with
selector, '^=', eg
[id^="jander"]
I have to ask though, why don't you want to do this using classes?
A simple off the shelf pretty printer in Go. One can compile it to a binary through:
go build -o jsonformat jsonformat.go
It reads from standard input, writes to standard output and allow to set indentation:
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
)
func main() {
indent := flag.String("indent", " ", "indentation string/character for formatter")
flag.Parse()
src, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "problem reading: %s", err)
os.Exit(1)
}
dst := &bytes.Buffer{}
if err := json.Indent(dst, src, "", *indent); err != nil {
fmt.Fprintf(os.Stderr, "problem formatting: %s", err)
os.Exit(1)
}
if _, err = dst.WriteTo(os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "problem writing: %s", err)
os.Exit(1)
}
}
It allows to run a bash commands like:
cat myfile | jsonformat | grep "key"
Because these two lines ...
EmployeeService es = new EmployeeService();
CityService cs = new CityService();
... don't take a parameter in the constructor, I guess that you create a context within the classes. When you load the city1
...
Payroll.Entities.City city1 = cs.SelectCity(...);
...you attach the city1
to the context in CityService
. Later you add a city1
as a reference to the new Employee
e1
and add e1
including this reference to city1
to the context in EmployeeService
. As a result you have city1
attached to two different context which is what the exception complains about.
You can fix this by creating a context outside of the service classes and injecting and using it in both services:
EmployeeService es = new EmployeeService(context);
CityService cs = new CityService(context); // same context instance
Your service classes look a bit like repositories which are responsible for only a single entity type. In such a case you will always have trouble as soon as relationships between entities are involved when you use separate contexts for the services.
You can also create a single service which is responsible for a set of closely related entities, like an EmployeeCityService
(which has a single context) and delegate the whole operation in your Button1_Click
method to a method of this service.
You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'
The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.
Use
find \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print
or
find \( -path "./tmp" -o -path "./scripts" \) -prune -false -o -name "*_peaks.bed"
or
find \( -path "./tmp" -path "./scripts" \) ! -prune -o -name "*_peaks.bed"
The order is important. It evaluates from left to right. Always begin with the path exclusion.
Do not use -not
(or !
) to exclude whole directory. Use -prune
.
As explained in the manual:
-prune The primary shall always evaluate as true; it
shall cause find not to descend the current
pathname if it is a directory. If the -depth
primary is specified, the -prune primary shall
have no effect.
and in the GNU find manual:
-path pattern
[...]
To ignore a whole
directory tree, use -prune rather than checking
every file in the tree.
Indeed, if you use -not -path "./pathname"
,
find will evaluate the expression for each node under "./pathname"
.
find expressions are just condition evaluation.
\( \)
- groups operation (you can use -path "./tmp" -prune -o -path "./scripts" -prune -o
, but it is more verbose).-path "./script" -prune
- if -path
returns true and is a directory, return true for that directory and do not descend into it.-path "./script" ! -prune
- it evaluates as (-path "./script") AND (! -prune)
. It revert the "always true" of prune to always false. It avoids printing "./script"
as a match.-path "./script" -prune -false
- since -prune
always returns true, you can follow it with -false
to do the same than !
.-o
- OR operator. If no operator is specified between two expressions, it defaults to AND operator.Hence, \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print
is expanded to:
[ (-path "./tmp" OR -path "./script") AND -prune ] OR ( -name "*_peaks.bed" AND print )
The print is important here because without it is expanded to:
{ [ (-path "./tmp" OR -path "./script" ) AND -prune ] OR (-name "*_peaks.bed" ) } AND print
-print
is added by find - that is why most of the time, you do not need to add it in you expression. And since -prune
returns true, it will print "./script" and "./tmp".
It is not necessary in the others because we switched -prune
to always return false.
Hint: You can use find -D opt expr 2>&1 1>/dev/null
to see how it is optimized and expanded,
find -D search expr 2>&1 1>/dev/null
to see which path is checked.
Three things need to care for:
Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:
foo.h:
namespace foo {
void bar();
}
foo.cc:
namespace foo {
namespace { // wrong
void bar() { cout << "hello"; };
}
}
other.cc file:
#include "foo.h"
void baz() {
foo::bar();
}
str_replace is considerably faster.
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);
More generally, under most circumstances, underscore functions that take a list and argument as the first two arguments, provide access to the list index as the next to last argument to the iterator. This is an important distinction when it comes to the two underscore functions, _.reduce and _.reduceRight, that take 'memo' as their third argument -- in the case of these two the index will not be the second argument, but the third:
var destination = (function() {
var fields = ['_333st', 'offroad', 'fbi'];
return _.reduce(waybillInfo.destination.split(','), function(destination, segment, index) {
destination[fields[index]] = segment;
return destination;
}, {});
})();
console.log(destination);
/*
_333st: "NYARFTW TX"
fbi: "FTWUP"
offroad: "UP"
The following is better of course but not demonstrate my point:
var destination = _.object(['_333st', 'offroad', 'fbi'], waybillInfo.destination.split(','));
*/
So if you wanted you could get the index using underscore itself: _.last(_.initial(arguments))
. A possible exception (I haven't tried) is _.map, as it can take an object instead of a list: "If list is a JavaScript object, iterator's arguments will be (value, key, list)." -- see: http://underscorejs.org/#map
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
The differences I could see is that Robocopy has a lot more options, but I didn't find any of them particularly helpful unless I'm doing something special.
I did some benchmarking of several copy routines and found XCOPY and ROBOCOPY to be the fastest, but to my surprise, XCOPY consistently edged out Robocopy.
It's ironic that robocopy retries a copy that fails, but it also failed a lot in my benchmark tests, where xcopy never did.
I did full file (byte by byte) file compares after my benchmark tests.
Here are the switches I used with robocopy in my tests:
**"/E /R:1 /W:1 /NP /NFL /NDL"**.
If anyone knows a faster combination (other than removing /E, which I need), I'd love to hear.
Another interesting/disappointing thing with robocopy is that if a copy does fail, by default it retries 1,000,000 times with a 30 second delay between each try. If you are running a long batch file unattended, you may be very disappointed when you come back after a few hours to find it's still trying to copy a particular file.
The /R and /W switches let you change this behavior.
If there's a way to attach files here, I can share my results.
I also included FastCopy and Windows Copy in my tests and each test was run 10 times. Note, the differences were pretty significant. The 95% confidence intervals had no overlap.
Here is a simple solution put this CSS
@media print{
.noprint{
display:none;
}
}
and here is the HTML
<div class="noprint">
element that need to be hidden when printing
</div>
I had the same problem. Thank you to everyone else who answered - I was able to get a solution together using parts of several of these answers.
My solution is using swift 5
The problem that we are trying to solve is that we may have images with different aspect ratios in our TableViewCell
s but we want them to render with consistent widths. The images should, of course, render with no distortion and fill the entire space. In my case, I was fine with some "cropping" of tall, skinny images, so I used the content mode .scaleAspectFill
To do this, I created a custom subclass of UITableViewCell
. In my case, I named it StoryTableViewCell
. The entire class is pasted below, with comments inline.
This approach worked for me when also using a custom Accessory View and long text labels. Here's an image of the final result:
Rendered Table View with consistent image width
class StoryTableViewCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
// ==== Step 1 ====
// ensure we have an image
guard let imageView = self.imageView else {return}
// create a variable for the desired image width
let desiredWidth:CGFloat = 70;
// get the width of the image currently rendered in the cell
let currentImageWidth = imageView.frame.size.width;
// grab the width of the entire cell's contents, to be used later
let contentWidth = self.contentView.bounds.width
// ==== Step 2 ====
// only update the image's width if the current image width isn't what we want it to be
if (currentImageWidth != desiredWidth) {
//calculate the difference in width
let widthDifference = currentImageWidth - desiredWidth;
// ==== Step 3 ====
// Update the image's frame,
// maintaining it's original x and y values, but with a new width
self.imageView?.frame = CGRect(imageView.frame.origin.x,
imageView.frame.origin.y,
desiredWidth,
imageView.frame.size.height);
// ==== Step 4 ====
// If there is a texst label, we want to move it's x position to
// ensure it isn't overlapping with the image, and that it has proper spacing with the image
if let textLabel = self.textLabel
{
let originalFrame = self.textLabel?.frame
// the new X position for the label is just the original position,
// minus the difference in the image's width
let newX = textLabel.frame.origin.x - widthDifference
self.textLabel?.frame = CGRect(newX,
textLabel.frame.origin.y,
contentWidth - newX,
textLabel.frame.size.height);
print("textLabel info: Original =\(originalFrame!)", "updated=\(self.textLabel!.frame)")
}
// ==== Step 4 ====
// If there is a detail text label, do the same as step 3
if let detailTextLabel = self.detailTextLabel {
let originalFrame = self.detailTextLabel?.frame
let newX = detailTextLabel.frame.origin.x-widthDifference
self.detailTextLabel?.frame = CGRect(x: newX,
y: detailTextLabel.frame.origin.y,
width: contentWidth - newX,
height: detailTextLabel.frame.size.height);
print("detailLabel info: Original =\(originalFrame!)", "updated=\(self.detailTextLabel!.frame)")
}
// ==== Step 5 ====
// Set the image's content modoe to scaleAspectFill so it takes up the entire view, but doesn't get distorted
self.imageView?.contentMode = .scaleAspectFill;
}
}
}
Add PresentationCore.dll
to your references. This dll url in my pc - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\PresentationCore.dll
I will show you some examples:
const string &dontDoThis(const string &s)
{
string local = s;
return local;
}
You can't return local
by reference, because local
is destroyed at the end of the body of dontDoThis
.
const string &shorterString(const string &s1, const string &s2)
{
return (s1.size() < s2.size()) ? s1 : s2;
}
Here, you can return by reference both s1
and s2
because they were defined before shorterString
was called.
char &get_val(string &str, string::size_type ix)
{
return str[ix];
}
usage code as below:
string s("123456");
cout << s << endl;
char &ch = get_val(s, 0);
ch = 'A';
cout << s << endl; // A23456
get_val
can return elements of s
by reference because s
still exists after the call.
class Student
{
public:
string m_name;
int age;
string &getName();
};
string &Student::getName()
{
// you can return by reference
return m_name;
}
string& Test(Student &student)
{
// we can return `m_name` by reference here because `student` still exists after the call
return stu.m_name;
}
usage example:
Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);
class String
{
private:
char *str_;
public:
String &operator=(const String &str);
};
String &String::operator=(const String &str)
{
if (this == &str)
{
return *this;
}
delete [] str_;
int length = strlen(str.str_);
str_ = new char[length + 1];
strcpy(str_, str.str_);
return *this;
}
You could then use the operator=
above like this:
String a;
String b;
String c = b = a;
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
SELECT column1 FROM table WHERE ISNUMERIC(column1) = 1
Note, as Damien_The_Unbeliever has pointed out, this will include any valid numeric type.
To filter out columns containing non-digit characters (and empty strings), you could use
SELECT column1 FROM table WHERE column1 not like '%[^0-9]%' and column1 != ''
If(Not System.IO.Directory.Exists(YourPath)) Then
System.IO.Directory.CreateDirectory(YourPath)
End If
I would prefer std::distance(vec.begin(), it)
as it will allow me to change the container without any code changes. For example, if you decide to use std::list
instead of std::vector
which doesn't provide a random access iterator your code will still compile. Since std::distance picks up the optimal method depending on iterator traits you'll not have any performance degradation either.
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'
Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)
print Result.groups()
Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.
I'm a beginner too and I faced that issue a couple of times myself.
document.querySelector('.project_list_div').offsetHeight;
If you need
then you can use this CircularArrayList for Java in this way (for example):
CircularArrayList<String> buf = new CircularArrayList<String>(4);
buf.add("A");
buf.add("B");
buf.add("C");
buf.add("D"); // ABCD
String pop = buf.remove(0); // A <- BCD
buf.add("E"); // BCDE
String interiorElement = buf.get(i);
All these methods run in O(1).
String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());
Object creation variants.
Variant 1 : 'new Object()' -> Object constructor without arguments.
var p1 = new Object(); // 'new Object()' create and return empty object -> {}
var p2 = new Object(); // 'new Object()' create and return empty object -> {}
console.log(p1); // empty object -> {}
console.log(p2); // empty object -> {}
// p1 and p2 are pointers to different objects
console.log(p1 === p2); // false
console.log(p1.prototype); // undefined
// empty object which is in fact Object.prototype
console.log(p1.__proto__); // {}
// empty object to which p1.__proto__ points
console.log(Object.prototype); // {}
console.log(p1.__proto__ === Object.prototype); // true
// null, which is in fact Object.prototype.__proto__
console.log(p1.__proto__.__proto__); // null
console.log(Object.prototype.__proto__); // null
Variant 2 : 'new Object(person)' -> Object constructor with argument.
const person = {
name: 'no name',
lastName: 'no lastName',
age: -1
}
// 'new Object(person)' return 'person', which is pointer to the object ->
// -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p1 = new Object(person);
// 'new Object(person)' return 'person', which is pointer to the object ->
// -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p2 = new Object(person);
// person, p1 and p2 are pointers to the same object
console.log(p1 === p2); // true
console.log(p1 === person); // true
console.log(p2 === person); // true
p1.name = 'John'; // change 'name' by 'p1'
p2.lastName = 'Doe'; // change 'lastName' by 'p2'
person.age = 25; // change 'age' by 'person'
// when print 'p1', 'p2' and 'person', it's the same result,
// because the object they points is the same
console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }
Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.
const person = {
name: 'no name',
lastName: 'no lastName',
age: -1,
getInfo: function getName() {
return `${this.name} ${this.lastName}, ${this.age}!`;
}
}
var p1 = Object.create(person);
var p2 = Object.create(person);
// 'p1.__proto__' and 'p2.__proto__' points to
// the same object -> 'person'
// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(p1.__proto__);
console.log(p2.__proto__);
console.log(p1.__proto__ === p2.__proto__); // true
console.log(person.__proto__); // {}(which is the Object.prototype)
// 'person', 'p1' and 'p2' are different
console.log(p1 === person); // false
console.log(p1 === p2); // false
console.log(p2 === person); // false
// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);
console.log(p1); // empty object - {}
console.log(p2); // empty object - {}
// add properties to object 'p1'
// (properties with the same names like in object 'person')
p1.name = 'John';
p1.lastName = 'Doe';
p1.age = 25;
// add properties to object 'p2'
// (properties with the same names like in object 'person')
p2.name = 'Tom';
p2.lastName = 'Harrison';
p2.age = 38;
// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);
// { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);
// { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);
// use by '__proto__'(link from 'p1' to 'person'),
// person's function 'getInfo'
console.log(p1.getInfo()); // John Doe, 25!
// use by '__proto__'(link from 'p2' to 'person'),
// person's function 'getInfo'
console.log(p2.getInfo()); // Tom Harrison, 38!
Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.
// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
var p1 = Object.create(Object.prototype);
// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
var p2 = Object.create(Object.prototype);
console.log(p1); // {}
console.log(p2); // {}
console.log(p1 === p2); // false
console.log(p1.prototype); // undefined
console.log(p2.prototype); // undefined
console.log(p1.__proto__ === Object.prototype); // true
console.log(p2.__proto__ === Object.prototype); // true
Variant 4 : 'new SomeFunction()'
// 'this' in constructor-function 'Person'
// represents a new instace,
// that will be created by 'new Person(...)'
// and returned implicitly
function Person(name, lastName, age) {
this.name = name;
this.lastName = lastName;
this.age = age;
//-----------------------------------------------------------------
// !--- only for demonstration ---
// if add function 'getInfo' into
// constructor-function 'Person',
// then all instances will have a copy of the function 'getInfo'!
//
// this.getInfo: function getInfo() {
// return this.name + " " + this.lastName + ", " + this.age + "!";
// }
//-----------------------------------------------------------------
}
// 'Person.prototype' is an empty object
// (before add function 'getInfo')
console.log(Person.prototype); // Person {}
// With 'getInfo' added to 'Person.prototype',
// instances by their properties '__proto__',
// will have access to the function 'getInfo'.
// With this approach, instances not need
// a copy of the function 'getInfo' for every instance.
Person.prototype.getInfo = function getInfo() {
return this.name + " " + this.lastName + ", " + this.age + "!";
}
// after function 'getInfo' is added to 'Person.prototype'
console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }
// create instance 'p1'
var p1 = new Person('John', 'Doe', 25);
// create instance 'p2'
var p2 = new Person('Tom', 'Harrison', 38);
// Person { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);
// Person { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);
// 'p1.__proto__' points to 'Person.prototype'
console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }
// 'p2.__proto__' points to 'Person.prototype'
console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }
console.log(p1.__proto__ === p2.__proto__); // true
// 'p1' and 'p2' points to different objects(instaces of 'Person')
console.log(p1 === p2); // false
// 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo'
// and use 'getInfo' with 'p1'-instance's data
console.log(p1.getInfo()); // John Doe, 25!
// 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo'
// and use 'getInfo' with 'p2'-instance's data
console.log(p2.getInfo()); // Tom Harrison, 38!
First, I wouldn't use document.body. Instead add an empty container:
index.html:
<html>
<head></head>
<body>
<div id="app"></div>
</body>
</html>
Then opt to only render your <App />
element:
main.js:
var App = require('./App.js');
ReactDOM.render(<App />, document.getElementById('app'));
Within App.js
you can import your other components and ignore your DOM render code completely:
App.js:
var SampleComponent = require('./SampleComponent.js');
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component!</h1>
<SampleComponent name="SomeName" />
</div>
);
}
});
SampleComponent.js:
var SampleComponent = React.createClass({
render: function() {
return (
<div>
<h1>Sample Component!</h1>
</div>
);
}
});
Then you can programmatically interact with any number of components by importing them into the necessary component files using require
.
A) The main GUI thread will run endlessly on the call to Application.Run, so your while loop will never be reached
B) You would never want to have an endless loop like that (the while(true) loop) - it would simply freeze the thread. Not really sure what you're trying to achieve there.
I would create and show the "main" (initial) form in the Main method (as Visual Studio does for you by default). Then in your button handler, create the other form and show it as well as hiding the main form (not closing it). Then, ensure that the main form is shown again when that form is closed via an event. Example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 otherForm = new Form2();
otherForm.FormClosed += new FormClosedEventHandler(otherForm_FormClosed);
this.Hide();
otherForm.Show();
}
void otherForm_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
}
i use php5.6
code:
$person = ["name"=>"mohammed", "age"=>30];
$person['addr'] = "Sudan";
print_r($person)
output
Array( ["name"=>"mohammed", "age"=>30, "addr"=>"Sudan"] )
First of all, Don't repeat yourself.
Then, please be careful not to overengineer, sometimes it is just a waste of time, and makes someone lose focus on what is important. Review the zen of python from time to time.
Take a look at active projects
the fabric repository is also a good one to look at.
yourapp/models/logicalgroup.py
User
, Group
and related models can go under yourapp/models/users.py
Poll
, Question
, Answer
... could go under yourapp/models/polls.py
__all__
inside of yourapp/models/__init__.py
request.GET
/ request.POST
...etctastypie
or piston
Take advantage of middleware / templatetags
Take advantage of model managers
User
can go in a UserManager(models.Manager)
.models.Model
.queryset
could go in a models.Manager
.User
one at a time, so you may think that it should live on the model itself, but when creating the object, you probably don't have all the details:Example:
class UserManager(models.Manager):
def create_user(self, username, ...):
# plain create
def create_superuser(self, username, ...):
# may set is_superuser field.
def activate(self, username):
# may use save() and send_mail()
def activate_in_bulk(self, queryset):
# may use queryset.update() instead of save()
# may use send_mass_mail() instead of send_mail()
Make use of forms where possible
A lot of boilerplate code can be eliminated if you have forms that map to a model. The ModelForm documentation
is pretty good. Separating code for forms from model code can be good if you have a lot of customization (or sometimes avoid cyclic import errors for more advanced uses).
Use management commands when possible
yourapp/management/commands/createsuperuser.py
yourapp/management/commands/activateinbulk.py
if you have business logic, you can separate it out
django.contrib.auth
uses backends, just like db has a backend...etc.setting
for your business logic (e.g. AUTHENTICATION_BACKENDS
)django.contrib.auth.backends.RemoteUserBackend
yourapp.backends.remote_api.RemoteUserBackend
yourapp.backends.memcached.RemoteUserBackend
backend example:
class User(db.Models):
def get_present_name(self):
# property became not deterministic in terms of database
# data is taken from another service by api
return remote_api.request_user_name(self.uid) or 'Anonymous'
could become:
class User(db.Models):
def get_present_name(self):
for backend in get_backends():
try:
return backend.get_present_name(self)
except: # make pylint happy.
pass
return None
more about design patterns
more about interface boundaries
yourapp.models
yourapp.vendor
yourapp.libs
yourapp.libs.vendor
or yourapp.vendor.libs
In short, you could have
yourapp/core/backends.py
yourapp/core/models/__init__.py
yourapp/core/models/users.py
yourapp/core/models/questions.py
yourapp/core/backends.py
yourapp/core/forms.py
yourapp/core/handlers.py
yourapp/core/management/commands/__init__.py
yourapp/core/management/commands/closepolls.py
yourapp/core/management/commands/removeduplicates.py
yourapp/core/middleware.py
yourapp/core/signals.py
yourapp/core/templatetags/__init__.py
yourapp/core/templatetags/polls_extras.py
yourapp/core/views/__init__.py
yourapp/core/views/users.py
yourapp/core/views/questions.py
yourapp/core/signals.py
yourapp/lib/utils.py
yourapp/lib/textanalysis.py
yourapp/lib/ratings.py
yourapp/vendor/backends.py
yourapp/vendor/morebusinesslogic.py
yourapp/vendor/handlers.py
yourapp/vendor/middleware.py
yourapp/vendor/signals.py
yourapp/tests/test_polls.py
yourapp/tests/test_questions.py
yourapp/tests/test_duplicates.py
yourapp/tests/test_ratings.py
or anything else that helps you; finding the interfaces you need and the boundaries will help you.
IIRC, something like:
set tabstop=2 shiftwidth=2 expandtab
should do the trick. If you already have tabs, then follow it up with a nice global RE to replace them with double spaces.
If you already have tabs you want to replace,
:retab
What are iml files in Android Studio project?
A Google search on iml file
turns up:
IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.
(from this page)
why not to use gradle scripts to integrate with external modules that you add to your project.
You do "use gradle scripts to integrate with external modules", or your own modules.
However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml
files and the metadata in .idea/
directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle
. This is also why you don't bother putting .iml
files or .idea/
in version control, as their contents will be regenerated.
If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?
To a large extent, you can't.
You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle
, how to find files in that structure. However, other metadata (compileSdkVersion
, dependencies, etc.) will not be nearly as easily replicated.
Other alternatives include:
Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio
Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts
Have everyone use one IDE
The most portable way to get the hostname of the current computer in Java is as follows:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class getHostName {
public static void main(String[] args) throws UnknownHostException {
InetAddress iAddress = InetAddress.getLocalHost();
String hostName = iAddress.getHostName();
//To get the Canonical host name
String canonicalHostName = iAddress.getCanonicalHostName();
System.out.println("HostName:" + hostName);
System.out.println("Canonical Host Name:" + canonicalHostName);
}
}
A framework or other similar schema will run/interpret a script to do a task. A program is compiled and run by a machine to do a task
for me it was that i had "ENGINE=MyISAM" kind of tables , once i changed it to "ENGINE=InnoDB" it worked:) in PhpMyAdmin on Azure App Service :)
The bundle id (app ID) has a binding relationship with the apple id (apple id is the Apple development account, which also belongs to a certain development team). When the app is created, the bundle id (app ID) is already associated with you The development team is bound, so your app is being sent to other colleagues, he opens it in Xcode, and connects the real machine with a data cable to debug it will report the error as above;
To Solution
Follow the prompts to change the bundle id
Because some functions, such as third-party login, are bound to the bundle id to apply for the app key, etc., the bundle id cannot be modified. Then please find the apple id account registered by the bundle id before. Here, I will change It’s ok to become the apple id account I registered in the company group
If other colleagues in your group can run this app successfully on a real machine, it means that the "description file" corresponding to the apple id "certificate" used by him is correct.
Create a new column with the desired column name: COLNew.
ALTER TABLE {tableName} ADD COLUMN COLNew {type};
Copy contents of old column COLOld to new column COLNew.
INSERT INTO {tableName} (COLNew) SELECT {COLOld} FROM {tableName}
Note: brackets are necessary in above line.
One way to get this error is trying to add a usercontrol to a form while the project is set to compile as x64. Visual Studio throws the unhelpful: "Failed to load toolbox item . It will be removed from the toolbox."
Workaround is to design with "Any CPU" and compile to x64 as necessary.
After running into the same issue - here're some of my thoughts:
As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:
for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:
if (window.chrome)
$("[type=video\\\/mp4]").each(function()
{
$(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
});
Unfortunately it's a bad Chrome hack, but hey, at least it works.
Source: user: eithedog
This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec
Also check your version of crome here: html5test
Don't parse it. Just ask.
import socket
try:
socket.inet_aton(addr)
# legal
except socket.error:
# Not legal
For pushing a single tag: git push <reponame> <tagname>
For instance, git push production 1.0.0
. Tags are not bound to branches, they are bound to commits.
When you want to have the tag's content in the master branch, do that locally on your machine. I would assume that you continued developing in your local master branch. Then just a git push origin master
should suffice.
Late to the party, but this may help anyone looking for a quick solution:
you can use bin(ord('b')).replace('b', '')
bin() it gives you the binary representation with a 'b' after the last bit, you have to remove it. Also ord() gives you the ASCII number to the char or 8-bit/1 Byte coded character.
Cheers
By default VS is not made to run PHP, but you can do it with extensions:
You can install an add-on with the extension manager, PHP Tools for Visual Studio.
If you want to install it inside VS, go to Tools > Extension Manager > Online Gallery > Search for PHP where you will find PHP Tools (the link above) for Visual Studio. Also you have VS.Php for Visual Studio. Both are not free.
You have also a cool PHP compiler called Phalanger:
If I'm not mistaken, the code you wrote above is JavaScript (jQuery) and not PHP.
If you want cool standalone IDE's for PHP: (Free)
var divs = $("div[class*='alert-box']");
import sys
import select
def heardEnter():
i,o,e = select.select([sys.stdin],[],[],0.0001)
for s in i:
if s == sys.stdin:
input = sys.stdin.readline()
return True
return False
Padding is a way to add kind of a margin inside the Div.
Just Use
div { padding-left: 20px; }
And to mantain the size, you would have to -20px from the original width of the Div.
Your bat file should be in the directory that the bat file is/was in when you opened it. However if you want to put it into a different directory you can do so with cd [whatever directory]
... Could not load file or assembly 'X' or one of its dependencies ...
Most likely it fails to load another dependency.
you could try to check the dependencies with a dependency walker.
I.e: https://www.dependencywalker.com/
Also check your build configuration (x86 / 64)
Edit: I also had this problem once when I was copying dlls in zip from a "untrusted" network share. The file was locked by Windows and the FileNotFoundException was raised.
See here: Detected DLLs that are from the internet and "blocked" by CASPOL
Removing workbench.xmi under workspace/.metadata/.plugins/org.eclipse.e4.workbench/ worked for me. It did not remove the existing projects.
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
it is work for me with parse Server
{
"ContractID": "203-17-DC0101-00003-10011",
"Supplier":"Sample Co., Ltd",
"Value":12345.80,
"Curency":"USD",
"StartDate": {
"__type": "Date",
"iso": "2017-08-22T06:11:00.000Z"
}
}
It`s possible to use MySQL specific syntax sugar:
SELECT ... date_field + INTERVAL 1 DAY
Looks much more pretty instead of DATE_ADD function
Maybe this can help :)
Controller
$scope.scrollevent = function($e){
// Your code
}
Html
<div scroll scroll-event="scrollevent">//scrollable content</div>
Or
<body scroll scroll-event="scrollevent">//scrollable content</body>
Directive
.directive("scroll", function ($window) {
return {
scope: {
scrollEvent: '&'
},
link : function(scope, element, attrs) {
$("#"+attrs.id).scroll(function($e) { scope.scrollEvent != null ? scope.scrollEvent()($e) : null })
}
}
})
As a similar approach to the accepted answer that might be considered a bit more readable, elegant, and general (YMMV), you can leverage the map
method:
# OP example
df['var3'].map(lambda n: '{:,.2%}'.format(n))
# also works on a series
series_example.map(lambda n: '{:,.2%}'.format(n))
Performance-wise, this is pretty close (marginally slower) than the OP solution.
As an aside, if you do choose to go the pd.options.display.float_format
route, consider using a context manager to handle state per this parallel numpy example.
If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).
Referring to Alexey Mezenin
answer:
While using his answer, I had to add something directly to the Request Object and used:
$request->request->add(['variable', 'value']);
Using this it adds two variables :
$request[0] = 'variable', $request[1] = 'value'
If you are a newbie like me and you needed an associate array the correct way to do is
$request->request->add(['variable' => 'value']);
Hope I saved your some time
PS: Thank you @Alexey
, you really helped me out with your answer
Or use the menu: Tools->Preferences->Database->NLS and change language and territory.
With new version of flutter and material theme u need to use the "Padding" widgett too in order to have an image that doesn't fill its container.
For example if you want to insert a rounded image in the AppBar u must use padding or your image will always be as high as the AppBar.
Hope this will help someone
InkWell(
onTap: () {
print ('Click Profile Pic');
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ClipOval(
child: Image.asset(
'assets/images/profile1.jpg',
),
),
),
),
The message you received is common when you have ruby 2.0.0p0 (2013-02-24)
on top of Windows.
The message "DL is deprecated, please use Fiddle
" is not an error; it's only a warning.
The source is the Deprecation notice for DL introduced some time ago in dl.rb
( see revisions/37910 ).
On Windows the lib/ruby/site_ruby/2.0.0/readline.rb
file still requires dl.rb
so the warning message comes out when you require 'irb'
( because irb requires 'readline'
) or when anything else wants to require 'readline'
.
You can open readline.rb
with your favorite text editor and look up the code ( near line 4369 ):
if RUBY_VERSION < '1.9.1'
require 'Win32API'
else
require 'dl'
class Win32API
DLL = {}
We can always hope for an improvement to work out this deprecation in future releases of Ruby.
EDIT: For those wanting to go deeper about Fiddle vs DL, let it be said that their purpose is to dynamically link external libraries with Ruby; you can read on the ruby-doc website about DL or Fiddle.
Disclaimer: I'm not a MySQL expert ... but this is my understanding of the issues.
I think TEXT is stored outside the mysql row, while I think VARCHAR is stored as part of the row. There is a maximum row length for mysql rows .. so you can limit how much other data you can store in a row by using the VARCHAR.
Also due to VARCHAR forming part of the row, I suspect that queries looking at that field will be slightly faster than those using a TEXT chunk.
I would turn it into CSV form, like so:
$string_version = implode(',', $original_array)
You can turn it back by doing:
$destination_array = explode(',', $string_version)
For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.
Another guide shows you how to save a stream with the VLC Player.
it works for me, try This.. you need to configure your terminal with remote access.
git config --global user.name "abc"
git config --global user.email "[email protected]"
;WITH
CteProductLookup(ProductId, oid)
AS
...
if you like to use for URLRequest httpBody
extension Dictionary {
func toString() -> String? {
return (self.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}) as Array).joined(separator: "&")
}
}
// print: Fields=sdad&ServiceId=1222
app:elevation="0dp"
but not
android:elevation="0dp"
worked for me on android L
All can be defined as in f:ajax
attiributes.
i.e.
<p:selectOneMenu id="employees" value="#{mymb.employeesList}" required="true">
<f:selectItems value="#{mymb.employeesList}" var="emp" itemLabel="#{emp.employeeName}" />
<f:ajax event="valueChange" listener="#{mymb.handleChange}" execute="@this" render="@all" />
</p:selectOneMenu>
event: it can be normal DOM Events like click
, or valueChange
execute: This is a space separated list of client ids of components that will participate in the "execute" portion of the Request Processing Lifecycle.
render: The clientIds of components that will participate in the "render" portion of the Request Processing Lifecycle. After action done, you can define which components should be refresh. Id, IdList or these keywords can be added: @this
, @form
, @all
, @none
.
You can reache the whole attribute list by following link: http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/f/ajax.html
Also, note that XDocument
is supported in Xbox 360 and Windows Phone OS 7.0.
If you target them, develop for XDocument
or migrate from XmlDocument
.
Adding my two cents, based on a performance issue I observed.
If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.
In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP
) are mentioned as important settings to check.
Note: Paul White mentioned max server memory
aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server
Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP
.
Why is cost threshold for parallelism ignored?
Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.
Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan
I'm not sure what the minimum required version of Visual Studio is, but in VS2015 you can use
Public ReadOnly Property Name As String
It is read-only for public access but can be privately modified using _Name
Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,
public class PersonHelper
{
public static Person person;
}
I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.
This is not so easy because basically popups are not supported in windows forms. Although windows forms is based on win32 and in win32 popup are supported. If you accept a few tricks, following code will set you going with a popup. You decide if you want to put it to good use :
class PopupWindow : Control
{
private const int WM_ACTIVATE = 0x0006;
private const int WM_MOUSEACTIVATE = 0x0021;
private Control ownerControl;
public PopupWindow(Control ownerControl)
:base()
{
this.ownerControl = ownerControl;
base.SetTopLevel(true);
}
public Control OwnerControl
{
get
{
return (this.ownerControl as Control);
}
set
{
this.ownerControl = value;
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.Style = WindowStyles.WS_POPUP |
WindowStyles.WS_VISIBLE |
WindowStyles.WS_CLIPSIBLINGS |
WindowStyles.WS_CLIPCHILDREN |
WindowStyles.WS_MAXIMIZEBOX |
WindowStyles.WS_BORDER;
createParams.ExStyle = WindowsExtendedStyles.WS_EX_LEFT |
WindowsExtendedStyles.WS_EX_LTRREADING |
WindowsExtendedStyles.WS_EX_RIGHTSCROLLBAR |
WindowsExtendedStyles.WS_EX_TOPMOST;
createParams.Parent = (this.ownerControl != null) ? this.ownerControl.Handle : IntPtr.Zero;
return createParams;
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr SetActiveWindow(HandleRef hWnd);
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_ACTIVATE:
{
if ((int)m.WParam == 1)
{
//window is being activated
if (ownerControl != null)
{
SetActiveWindow(new HandleRef(this, ownerControl.FindForm().Handle));
}
}
break;
}
case WM_MOUSEACTIVATE:
{
m.Result = new IntPtr(MouseActivate.MA_NOACTIVATE);
return;
//break;
}
}
base.WndProc(ref m);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillRectangle(SystemBrushes.Info, 0, 0, Width, Height);
e.Graphics.DrawString((ownerControl as VerticalDateScrollBar).FirstVisibleDate.ToLongDateString(), this.Font, SystemBrushes.InfoText, 2, 2);
}
}
Experiment with it a bit, you have to play around with its position and its size. Use it wrong and nothing shows.
Use __LINE__
, but what is its type?
LINE The presumed line number (within the current source file) of the current source line (an integer constant).
As an integer constant, code can often assume the value is __LINE__ <= INT_MAX
and so the type is int
.
To print in C, printf()
needs the matching specifier: "%d"
. This is a far lesser concern in C++ with cout
.
Pedantic concern: If the line number exceeds INT_MAX
1 (somewhat conceivable with 16-bit int
), hopefully the compiler will produce a warning. Example:
format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]
Alternatively, code could force wider types to forestall such warnings.
printf("Not logical value at line number %ld\n", (long) __LINE__);
//or
#include <stdint.h>
printf("Not logical value at line number %jd\n", INTMAX_C(__LINE__));
Avoid printf()
To avoid all integer limitations: stringify. Code could directly print without a printf()
call: a nice thing to avoid in error handling2 .
#define xstr(a) str(a)
#define str(a) #a
fprintf(stderr, "Not logical value at line number %s\n", xstr(__LINE__));
fputs("Not logical value at line number " xstr(__LINE__) "\n", stderr);
1 Certainly poor programming practice to have such a large file, yet perhaps machine generated code may go high.
2 In debugging, sometimes code simply is not working as hoped. Calling complex functions like *printf()
can itself incur issues vs. a simple fputs()
.
Raystorm had a good answer. I'm not a big fan of Rules either. I do something similar, except that I create the following utility class to help readability and usability, which is one of the big plus'es of annotations in the first place.
Add this utility class:
import org.junit.Assert;
public abstract class ExpectedRuntimeExceptionAsserter {
private String expectedExceptionMessage;
public ExpectedRuntimeExceptionAsserter(String expectedExceptionMessage) {
this.expectedExceptionMessage = expectedExceptionMessage;
}
public final void run(){
try{
expectException();
Assert.fail(String.format("Expected a RuntimeException '%s'", expectedExceptionMessage));
} catch (RuntimeException e){
Assert.assertEquals("RuntimeException caught, but unexpected message", expectedExceptionMessage, e.getMessage());
}
}
protected abstract void expectException();
}
Then for my unit test, all I need is this code:
@Test
public void verifyAnonymousUserCantAccessPrivilegedResourceTest(){
new ExpectedRuntimeExceptionAsserter("anonymous user can't access privileged resource"){
@Override
protected void expectException() {
throw new RuntimeException("anonymous user can't access privileged resource");
}
}.run(); //passes test; expected exception is caught, and this @Test returns normally as "Passed"
}
Here's a sample class:
public class Increment
{
public static void main(String [] args)
{
for (int i = 0; i < args.length; ++i)
{
System.out.println(args[i]);
}
}
}
If I disassemble this class using javap.exe I get this:
Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 23
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_0
12: iload_1
13: aaload
14: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
17: iinc 1, 1
20: goto 2
23: return
}
If I change the loop so it uses i++ and disassemble again I get this:
Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 23
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_0
12: iload_1
13: aaload
14: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
17: iinc 1, 1
20: goto 2
23: return
}
When I compare the two, TextPad tells me that the two are identical.
What this says is that from the point of view of the generated byte code there's no difference in a loop. In other contexts there is a difference between ++i and i++, but not for loops.
The problem based on Chrome is not about the xml namespace which is xmlns="http://www.w3.org/1999/xhtml"
. Without the namesspace attribute, it won't work with IE either.
Because of the security restriction, you have to add the --allow-file-access-from-files
flag when you start the chrome. I think linux/*nix users can do that easily via the terminal but for windows users, you have to open the properties of the Chrome shortcut and add it in the target destination as below;
Right-Click -> Properties -> Target
Here is a sample full path with the flags which I use on my machine;
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files
I hope showing this step-by-step will help windows users for the problem, this is why I've added this post.
I have used this simple method and it's worked successfully
function uploadImage(e) {
var file = e.target.files[0];
let reader = new FileReader();
reader.onload = (e) => {
let image = e.target.result;
console.log(image);
};
reader.readAsDataURL(file);
}
What about .GlobalEnv$a <- "new"
? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign()
function.
You can use the VisibleChanged
event handler.
private void DataGridView1_VisibleChanged(object sender, System.EventArgs e)
{
var grid = sender as DataGridView;
grid.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
}
For an iPhone 7/7 Plus or newer, use these three Haptic feedback APIs.
let generator = UINotificationFeedbackGenerator()
generator.notificationOccured(style: .error)
Available styles are .error
, .success
, and .warning
. Each has its own distinctive feel.
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to communicate successes, failures, and warnings.
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccured()
Available styles are .heavy
, .medium
, and .light
. These are simple vibrations with varying degrees of "hardness".
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to simulate physical impacts
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
This is the least noticeable of all the haptics, and so is the most suitable for when haptics should not be taking over the app experience.
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to indicate a change in selection.
There are a couple of things worth remembering when using these APIs.
You do not actually create the haptic. You request the system generate a haptic. The system will decide based on the below:
Therefore, the system will silently ignore your request for a haptic if it is not possible. If this is due to an unsupported device, you could try this:
func haptic() {
// Get whether the device can generate haptics or not
// If feedbackSupportLevel is nil, will assign 0
let feedbackSupportLevel = UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int ?? 0
switch feedbackSupportLevel {
case 2:
// 2 means the device has a Taptic Engine
// Put Taptic Engine code here, using the APIs explained above
case 1:
// 1 means no Taptic Engine, but will support AudioToolbox
// AudioToolbox code from the myriad of other answers!
default: // 0
// No haptic support
// Do something else, like a beeping noise or LED flash instead of haptics
}
Substitute the comments in the switch
-case
statements, and this haptic generation code will be portable to other iOS devices. It will generate the highest level of haptic possible.
prepare()
method, to put it in a state of readiness. Using your Game Over example: You may know that the game is about to end, by the user having very low HP, or a dangerous monster being near them.
In this case, preparing the Taptic Engine would create a higher-quality, more responsive experience.
For example, let's say your app uses a pan gesture recogniser to change the portion of the world visible. You want a haptic to generate when the user 'looks' round 360 degrees. Here is how you could use prepare()
:
@IBAction func userChangedViewablePortionOfWorld(_ gesture: UIPanGestureRecogniser!) {
haptic = UIImpactFeedbackGenerator(style: .heavy)
switch gesture.state {
case .began:
// The user started dragging the screen.
haptic.prepare()
case .changed:
// The user trying to 'look' in another direction
// Code to change viewable portion of the virtual world
if virtualWorldViewpointDegreeMiddle = 360.0 {
haptic.impactOccured()
}
default:
break
}
Make sure you have MainActivity
and .ScanActivity
into your AndroidManifest.xml
file:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ScanActivity">
</activity>
I have solved the issue by using UINavigationController when presenting. In MainVC, when presenting VC1
let vc1 = VC1()
let navigationVC = UINavigationController(rootViewController: vc1)
self.present(navigationVC, animated: true, completion: nil)
In VC1, when I would like to show VC2 and dismiss VC1 in same time (just one animation), I can have a push animation by
let vc2 = VC2()
self.navigationController?.setViewControllers([vc2], animated: true)
And in VC2, when close the view controller, as usual we can use:
self.dismiss(animated: true, completion: nil)
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections
node in Web.config
file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
Finaly I got it!!!
import csv
def select_index(index):
csv_file = open('oscar_age_female.csv', 'r')
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
l = line['Index']
if l == index:
print(line[' "Name"'])
select_index('11')
"Bette Davis"
Json Convert To C# Class = https://json2csharp.com/json-to-csharp
after the schema comes out
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string myJSON = client.DownloadString("http://xxx/xx/xx.json");
var valueSet = JsonConvert.DeserializeObject<Root>(myJSON);
The biggest one of our mistakes is that we can't match the class structure with json.
This connection will do the process automatically. You will code it later ;) = https://json2csharp.com/json-to-csharp
that's it.
Right, but as long as you use ASCII characters even a multibyte character set would still give a limitation of exactly 30 characters... so unless you want to put hearts and smiling cats in you're DB names your fine...
I think the solution here is not working with an update of the python version anymore, one way to do it with a new python function for it is:
extracted_data = data[['Column Name1','Column Name2']].to_numpy()
which gives you the desired outcome.
The documentation you can find here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy
Delete your package-lock.json
file and node_modules
folder.
Then do npm cache clean
npm cache clean --force
do
npm install
again and run
First of all i say that you should google this as it is defined in detail in many places
Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.
/* Demonstrating Global variables */
#include <stdio.h>
int add_numbers( void ); /* ANSI function prototype */
/* These are global variables and can be accessed by functions from this point on */
int value1, value2, value3;
int add_numbers( void )
{
auto int result;
result = value1 + value2 + value3;
return result;
}
main()
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, final_result);
}
Sample Program Output
The sum of 10 + 20 + 30 is 60
The scope of global variables can be restricted by carefully placing the declaration. They are visible from the declaration until the end of the current source file.
#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );
static int n2; /* n2 is known from this point onwards */
void no_access( void )
{
n1 = 10; /* illegal, n1 not yet known */
n2 = 5; /* valid */
}
static int n1; /* n1 is known from this point onwards */
void all_access( void )
{
n1 = 10; /* valid */
n2 = 3; /* valid */
}
Static:
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.
I suggest you to see this tutorial list
AUTO:
C, C++
(Called automatic variables.)
All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[1]
Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.
In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory.SEE WIKIPEDIA
You can have a form do the work for you.
def my_model_view(request, mymodel_id):
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
model = get_object_or_404(MyModel, pk=mymodel_id)
form = MyModelForm(instance=model)
return render(request, 'model.html', { 'form': form})
Then in the template:
<table>
{% for field in form %}
<tr>
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
</tr>
{% endfor %}
</table>
I know I'm late to the party but just wanted to mention that the Jumpout II theme really is amazing.. I have a lot of themes and this one really is great for a # of reasons..
it handles glare very well (yes even pure black on matte screens can produce glare, unfortunately my new matte monitor - has a more "glary" coating than my old one).. this is a grayish-black background
it has enough colors that you can easily see read even dense code - some themes that look nice at first use too much of one color and it makes dense code harder to digest
the comments are all gray, this is even better than dark green which is my 2nd favorite choice.. it really helps the code pop out..
so basically this is a great anti-glare, anti-dense-code theme
p.s. please note I change the font of all the themes I use to Consolas 11 or 12 depending on the monitor. Consolas I find to be the best programming font out there. It looks great, easy to read and very well suited to LCD anti-aliasing. I tried so many programming fonts but I always come back to this one quickly. And it is not too narrow.. I'm not in the narrow camp, I believe narrow font aficionados don't program with ultra wide monitors - maybe program on a macbook or something just as bad :)
p.p.s I know solarized is supposed to be some kind of ultimate, magical, life-enhancing nirvana-inducing theme but I just don't get it.. I tried but failed to find it anything but annoying
With SQL server you can use this
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY];
with mysql server you can do the following
SELECT * FROM my_table WHERE YEAR(date_field) = '2006' AND MONTH(date_field) = '9' AND DAY(date_field) = '11'
var TableIDvalue = "myTable";_x000D_
var TableLastSortedColumn = -1;_x000D_
_x000D_
function SortTable() {_x000D_
var sortColumn = parseInt(arguments[0]);_x000D_
var type = arguments.length > 1 ? arguments[1] : 'T';_x000D_
var dateformat = arguments.length > 2 ? arguments[2] : '';_x000D_
var table = document.getElementById(TableIDvalue);_x000D_
var tbody = table.getElementsByTagName("tbody")[0];_x000D_
var rows = tbody.getElementsByTagName("tr");_x000D_
_x000D_
var arrayOfRows = new Array();_x000D_
_x000D_
type = type.toUpperCase();_x000D_
_x000D_
dateformat = dateformat.toLowerCase();_x000D_
_x000D_
for (var i = 0, len = rows.length; i < len; i++) {_x000D_
arrayOfRows[i] = new Object;_x000D_
arrayOfRows[i].oldIndex = i;_x000D_
var celltext = rows[i].getElementsByTagName("td")[sortColumn].innerHTML.replace(/<[^>]*>/g, "");_x000D_
if (type == 'D') {_x000D_
arrayOfRows[i].value = GetDateSortingKey(dateformat, celltext);_x000D_
} else {_x000D_
var re = type == "N" ? /[^\.\-\+\d]/g : /[^a-zA-Z0-9]/g;_x000D_
arrayOfRows[i].value = celltext.replace(re, "").substr(0, 25).toLowerCase();_x000D_
}_x000D_
}_x000D_
_x000D_
if (sortColumn == TableLastSortedColumn) {_x000D_
arrayOfRows.reverse();_x000D_
} else {_x000D_
TableLastSortedColumn = sortColumn;_x000D_
switch (type) {_x000D_
case "N":_x000D_
arrayOfRows.sort(CompareRowOfNumbers);_x000D_
break;_x000D_
case "D":_x000D_
arrayOfRows.sort(CompareRowOfNumbers);_x000D_
break;_x000D_
default:_x000D_
arrayOfRows.sort(CompareRowOfText);_x000D_
}_x000D_
}_x000D_
var newTableBody = document.createElement("tbody");_x000D_
_x000D_
for (var i = 0, len = arrayOfRows.length; i < len; i++) {_x000D_
newTableBody.appendChild(rows[arrayOfRows[i].oldIndex].cloneNode(true));_x000D_
}_x000D_
table.replaceChild(newTableBody, tbody);_x000D_
}_x000D_
_x000D_
function CompareRowOfText(a, b) {_x000D_
var aval = a.value;_x000D_
var bval = b.value;_x000D_
return (aval == bval ? 0 : (aval > bval ? 1 : -1));_x000D_
}_x000D_
_x000D_
function deleteRow(i) {_x000D_
document.getElementById('myTable').deleteRow(i)_x000D_
}
_x000D_
<table id="myTable" border="1">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
<input type="button" onclick="javascript: SortTable(0, 'T');" value="SORT" /></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Shaa</td>_x000D_
<td>ABC</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cnubha</td>_x000D_
<td>XYZ</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Fine</td>_x000D_
<td>MNO</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Amit</td>_x000D_
<td>PQR</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sultan</td>_x000D_
<td>FGH</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Hello</td>_x000D_
<td>UST</td>_x000D_
<td><input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)" /></td>_x000D_
</tr>_x000D_
_x000D_
</tbody>_x000D_
</table>
_x000D_
Open your SQL command line and type the following:
SQL> connect / as sysdba
Once connected,you can enter the following query to get details of username and password:
SQL> select username,password from dba_users;
This will list down the usernames,but passwords would not be visible.But you can identify the particular username and then change the password for that user. For changing the password,use the below query:
SQL> alter user username identified by password;
Here username is the name of user whose password you want to change and password is the new password.
I would change the query in the following ways:
group by
.left outer join
to ensure that all data is available.count(<fieldname>)
you can eliminate the comparisons to is null
. This is important for the second and third calculated values.mde
table. These use mde.mdeid
.The following version follows your example by using union all
:
SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
SUM(TOTALMAILED) as TotalMailed,
SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
from MailDataExtract
where SentDate is not null
group by SentDate
) union all
(select MDE.ReturnMailDate AS ReceiptDate, 0,
COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by MDE.ReturnMailDate;
)
) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;
The following does something similar using full outer join
:
SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
from MailDataExtract
where SentDate is not null
group by cast(SentDate as date)
) sd full outer join
(select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by cast(MDE.ReturnMailDate as date)
) mde
on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;
%ComSpec% /c %systemroot%\notepad.exe
This is my solution with prepared statements and stored procedure is returning several rows not only one value.
<?php
require 'config.php';
header('Content-type:application/json');
$connection->set_charset('utf8');
$mIds = $_GET['ids'];
$stmt = $connection->prepare("CALL sp_takes_string_returns_table(?)");
$stmt->bind_param("s", $mIds);
$stmt->execute();
$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($response);
$stmt->close();
$connection->close();
Simply said and without revealing the kitchen secrets:
a set in general, is a collection that contains no duplicate elements, and whose elements are in no particular order. So, A HashSet<T>
is similar to a generic List<T>
, but is optimized for fast lookups (via hashtables, as the name implies) at the cost of losing order.
Here is a simple analogy; Imagine you are downloading movies online, with O(1), if it takes 5 minutes to download one movie, it will still take the same time to download 20 movies. So it doesn't matter how many movies you are downloading, they will take the same time(5 minutes) whether it's one or 20 movies. A normal example of this analogy is when you go to a movie library, whether you are taking one movie or 5, you will simply just pick them at once. Hence spending the same time.
However, with O(n), if it takes 5 minutes to download one movie, it will take about 50 minutes to download 10 movies. So time is not constant or is somehow proportional to the number of movies you are downloading.
You can do this in Java too. And no, it's not a good practice. :)
(And use the ===
in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)
I have encountered this issue!
Luckily, I determine 2 ways and understand some things but the rest is not clear.
Hope someone discuss or support if you know.
List<Person> person = this.PersonRepository.findById(0)
person.setName("Neo");
This.PersonReository.save(person);
You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types1. That is, at least one of the operands has to be of a user-defined type. As with other overloaded functions, operators can be overloaded for a certain set of parameters only once.
Not all operators can be overloaded in C++. Among the operators that cannot be overloaded are: .
::
sizeof
typeid
.*
and the only ternary operator in C++, ?:
Among the operators that can be overloaded in C++ are these:
+
-
*
/
%
and +=
-=
*=
/=
%=
(all binary infix); +
-
(unary prefix); ++
--
(unary prefix and postfix)&
|
^
<<
>>
and &=
|=
^=
<<=
>>=
(all binary infix); ~
(unary prefix)==
!=
<
>
<=
>=
||
&&
(all binary infix); !
(unary prefix)new
new[]
delete
delete[]
=
[]
->
->*
,
(all binary infix); *
&
(all unary prefix) ()
(function call, n-ary infix)However, the fact that you can overload all of these does not mean you should do so. See the basic rules of operator overloading.
In C++, operators are overloaded in the form of functions with special names. As with other functions, overloaded operators can generally be implemented either as a member function of their left operand's type or as non-member functions. Whether you are free to choose or bound to use either one depends on several criteria.2 A unary operator @
3, applied to an object x, is invoked either as operator@(x)
or as x.operator@()
. A binary infix operator @
, applied to the objects x
and y
, is called either as operator@(x,y)
or as x.operator@(y)
.4
Operators that are implemented as non-member functions are sometimes friend of their operand’s type.
1 The term “user-defined” might be slightly misleading. C++ makes the distinction between built-in types and user-defined types. To the former belong for example int, char, and double; to the latter belong all struct, class, union, and enum types, including those from the standard library, even though they are not, as such, defined by users.
2 This is covered in a later part of this FAQ.
3 The @
is not a valid operator in C++ which is why I use it as a placeholder.
4 The only ternary operator in C++ cannot be overloaded and the only n-ary operator must always be implemented as a member function.
Continue to The Three Basic Rules of Operator Overloading in C++.
The main difference between the two types of fetching is a moment when data gets loaded into a memory.
I have attached 2 photos to help you understand this.
Use that code.that will help to solve your problem
@media print
{
@page { margin: 0; }
body { margin: 1.6cm; }
}
In my case, I still wanted the open on odd pages option but this would produce a blank page with the chapter name in the header. I didn't want the header. And so to avoid this I used this at the end of the chapter:
\clearpage
\thispagestyle{plain}
This let's you keep the blank page on the last even page of the chapter but without the header.
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
I wrote this script to skip or execute tests if there are changes:
#!/bin/bash
set -e -o pipefail -u
paths=()
while [ "$1" != "--" ]; do
paths+=( "$1" ); shift
done
shift
if git diff --quiet --exit-code "${BASE_BRANCH:-origin/master}"..HEAD ${paths[@]}; then
echo "No changes in ${paths[@]}, skipping $@..." 1>&2
exit 0
fi
echo "Changes found in ${paths[@]}, running $@..." 1>&2
exec "$@"
So you can do something like:
./scripts/git-run-if-changed.sh cmd vendor go.mod go.sum fixtures/ tools/ -- go test
This might give the increased relevance to the head part that you want. It won't double it, but it might possibly good enough for your sake:
SELECT pages.*,
MATCH (head, body) AGAINST ('some words') AS relevance,
MATCH (head) AGAINST ('some words') AS title_relevance
FROM pages
WHERE MATCH (head, body) AGAINST ('some words')
ORDER BY title_relevance DESC, relevance DESC
-- alternatively:
ORDER BY title_relevance + relevance DESC
An alternative that you also want to investigate, if you've the flexibility to switch DB engine, is Postgres. It allows to set the weight of operators and to play around with the ranking.
I wanted to be able to find and replace text but also include matched groups in the content I insert. I wrote this short script to do that:
https://gist.github.com/turtlemonvh/0743a1c63d1d27df3f17
The key component of that is something that looks like like this:
print(re.sub(pattern, template, text).rstrip("\n"))
Here's an example of how that works:
# Find everything that looks like 'dog' or 'cat' followed by a space and a number
pattern = "((cat|dog) (\d+))"
# Replace with 'turtle' and the number. '3' because the number is the 3rd matched group.
# The double '\' is needed because you need to escape '\' when running this in a python shell
template = "turtle \\3"
# The text to operate on
text = "cat 976 is my favorite"
Calling the above function with this yields:
turtle 976 is my favorite
'Use Chrome, invite troubles' - Anonymous. (Just a symbolic reference)
Well, Chrome is notoriously famous for a lot of default security-enabled utilities, and that's where your problem originates from.
This can, however, be undone by 'setting the default email client' (as the default email client is unset), or by setting up the default handler under 'chrome://settings/handlers' (by default, it's set to 'Ignore').
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
packages:
I have had issues converting json to dataframe/csv. For my case I did:
Token <- "245432532532"
source <- "http://......."
header_type <- "applcation/json"
full_token <- paste0("Bearer ", Token)
response <- GET(n_source, add_headers(Authorization = full_token, Accept = h_type), timeout(120), verbose())
text_json <- content(response, type = 'text', encoding = "UTF-8")
jfile <- fromJSON(text_json)
df <- as.data.frame(jfile)
then from df to csv.
In this format it should be easy to convert it to multiple .csvs if needed.
The important part is content function should have type = 'text'
.
Taken from a google search, add this ItemDecoration to your RecyclerView
:
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
private boolean mShowFirstDivider = false;
private boolean mShowLastDivider = false;
public DividerItemDecoration(Context context, AttributeSet attrs) {
final TypedArray a = context
.obtainStyledAttributes(attrs, new int[]{android.R.attr.listDivider});
mDivider = a.getDrawable(0);
a.recycle();
}
public DividerItemDecoration(Context context, AttributeSet attrs, boolean showFirstDivider,
boolean showLastDivider) {
this(context, attrs);
mShowFirstDivider = showFirstDivider;
mShowLastDivider = showLastDivider;
}
public DividerItemDecoration(Drawable divider) {
mDivider = divider;
}
public DividerItemDecoration(Drawable divider, boolean showFirstDivider,
boolean showLastDivider) {
this(divider);
mShowFirstDivider = showFirstDivider;
mShowLastDivider = showLastDivider;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if (mDivider == null) {
return;
}
if (parent.getChildPosition(view) < 1) {
return;
}
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
outRect.top = mDivider.getIntrinsicHeight();
} else {
outRect.left = mDivider.getIntrinsicWidth();
}
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (mDivider == null) {
super.onDrawOver(c, parent, state);
return;
}
// Initialization needed to avoid compiler warning
int left = 0, right = 0, top = 0, bottom = 0, size;
int orientation = getOrientation(parent);
int childCount = parent.getChildCount();
if (orientation == LinearLayoutManager.VERTICAL) {
size = mDivider.getIntrinsicHeight();
left = parent.getPaddingLeft();
right = parent.getWidth() - parent.getPaddingRight();
} else { //horizontal
size = mDivider.getIntrinsicWidth();
top = parent.getPaddingTop();
bottom = parent.getHeight() - parent.getPaddingBottom();
}
for (int i = mShowFirstDivider ? 0 : 1; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
if (orientation == LinearLayoutManager.VERTICAL) {
top = child.getTop() - params.topMargin;
bottom = top + size;
} else { //horizontal
left = child.getLeft() - params.leftMargin;
right = left + size;
}
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
// show last divider
if (mShowLastDivider && childCount > 0) {
View child = parent.getChildAt(childCount - 1);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
if (orientation == LinearLayoutManager.VERTICAL) {
top = child.getBottom() + params.bottomMargin;
bottom = top + size;
} else { // horizontal
left = child.getRight() + params.rightMargin;
right = left + size;
}
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
private int getOrientation(RecyclerView parent) {
if (parent.getLayoutManager() instanceof LinearLayoutManager) {
LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
return layoutManager.getOrientation();
} else {
throw new IllegalStateException(
"DividerItemDecoration can only be used with a LinearLayoutManager.");
}
}
}
The Response was Empty. Most of the case the codes will stats with 1xx, 2xx, 3xx, 4xx, 5xx.
Just run
docker restart $(docker ps -q)
Update
For Docker 1.13.1
use docker restart $(docker ps -a -q)
as in answer lower.
A delayed response but to give multiple packages using annotation based approach we can use as below:
@ComponentScan({"com.my.package.one","com.my.package.subpackage.two","com.your.package.supersubpackage.two"})
The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:
TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();
inline just:
C-M-S-%
(if binding keys still default) than
replace-string
^J
For old-school CD keys, it was just a matter of making up an algorithm for which CD keys (which could be any string) are easy to generate and easy to verify, but the ratio of valid-CD-keys to invalid-CD-keys is so small that randomly guessing CD keys is unlikely to get you a valid one.
Starcraft and Half-life both used the same checksum, where the 13th digit verified the first 12. Thus, you could enter anything for the first 12 digits, and guess the 13th (there's only 10 possibilities), leading to the infamous 1234-56789-1234
The algorithm for verifying is public, and looks something like this:
x = 3;
for(int i = 0; i < 12; i++)
{
x += (2 * x) ^ digit[i];
}
lastDigit = x % 10;
Windows XP takes quite a bit of information, encrypts it, and puts the letter/number encoding on a sticker. This allowed MS to both verify your key and obtain the product-type (Home, Professional, etc.) at the same time. Additionally, it requires online activation.
The full algorithm is rather complex, but outlined nicely in this (completely legal!) paper, published in Germany.
Of course, no matter what you do, unless you are offering an online service (like World of Warcraft), any type of copy protection is just a stall: unfortunately, if it's any game worth value, someone will break (or at least circumvent) the CD-key algorithm, and all other copyright protections.
For online-services, life is a bit simpler, since even with the binary file you need to authenticate with their servers to make any use of it (eg. have a WoW account). The CD-key algorithm for World of Warcraft - used, for instance, when buying playtime cards - probably looks something like this:
- Generate a very large cryptographically-secure random number.
- Store it in our database and print it on the card.
Then, when someone enters a playtime-card number, check if it's in the database, and if it is, associate that number with the current user so it can never be used again.
For online services, there is no reason not to use the above scheme; using anything else can lead to problems.
How about this?
(A=1 OR B=1 OR C=1)
AND NOT (A=1 AND B=1 AND C=1)
And if A, B and C can have null values you would need the following:
(A=1 OR B=1 OR C=1)
AND NOT ( (A=1 AND A is not null) AND (B=1 AND B is not null) AND (C=1 AND C is not null) )
This is scalable to larger number of fields and hence more applicable.
There are multiple option to get column number and column information such as:
let's check them.
local_df = pd.DataFrame(np.random.randint(1,12,size=(2,6)),columns =['a','b','c','d','e','f']) 1. local_df.shape[1] --> Shape attribute return tuple as (row & columns) (0,1).
local_df.info() --> info Method will return detailed information about data frame and it's columns such column count, data type of columns, Not null value count, memory usage by Data Frame
len(local_df.columns) --> columns attribute will return index object of data frame columns & len function will return total available columns.
local_df.head(0) --> head method with parameter 0 will return 1st row of df which actually nothing but header.
Assuming number of columns are not more than 10. For loop fun: li_count =0 for x in local_df: li_count =li_count + 1 print(li_count)
Pick one or more from:
So, you can check that your application is listening successfully by running lsof -i
as root on the machine and look for a python
entry with the corresponding port you've specified.
Non-root users generally cannot bind to ports < 1024.
You'll need to look at iptables -nvL
to see if there's a rule that would prevent access to the ip:port that you are trying to bind your application to.
If there is an upstream firewall and you don't know much about it, you'll need to talk to your network administrators.
Python 3:
import urllib.request
wp = urllib.request.urlopen("http://google.com")
pw = wp.read()
print(pw)
Python 2:
import urllib
import sys
wp = urllib.urlopen("http://google.com")
for line in wp:
sys.stdout.write(line)
While I have tested both the Codes in respective versions.
A small usage of np.nan ! = np.nan
s[s==s]
Out[953]:
0 1.0
1 2.0
2 3.0
3 4.0
5 5.0
dtype: float64
More Info
np.nan == np.nan
Out[954]: False
To me it sounds like the simplest way to expose your git repository on the server (which seems to be a Windows machine) would be to share it as a network resource.
Right click the folder "MY_GIT_REPOSITORY" and select "Sharing". This will give you the ability to share your git repository as a network resource on your local network. Make sure you give the correct users the ability to write to that share (will be needed when you and your co-workers push to the repository).
The URL for the remote that you want to configure would probably end up looking something like
file://\\\\189.14.666.666\MY_GIT_REPOSITORY
If you wish to use any other protocol (e.g. HTTP, SSH) you'll have to install additional server software that includes servers for these protocols. In lieu of these the file sharing method is probably the easiest in your case right now.
Based upon your source variable (sourcePath = "C:\Minecraft\bin\"
) I suspect your hard code is pointing at the wrong place
fso.CopyFile "C:\Minecraft\options.txt", destinationPath, false
should be
fso.CopyFile "C:\Minecraft\bin\options.txt", destinationPath
or
fso.CopyFile sourcePath & "options.txt", destinationPath
You can delete individual names with del
:
del x
or you can remove them from the globals()
object:
for name in dir():
if not name.startswith('_'):
del globals()[name]
This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.
Modules you've imported (import os
) are going to remain imported because they are referenced by sys.modules
; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.
Annotate the property like below
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():
builder.ForNpgsqlUseIdentityColumns();
This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().
Open Terminal
cd to/the/program/location
ruby program.rb
or add #!/usr/bin/env ruby
in the first of your program (script tell that this is executed using Ruby Interpreter)
Open Terminal
cd to/the/program/location
chmod 777 program.rb
./program.rb
OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.
OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.
OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.
So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.
I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK
$(".pushme").click(function () {
var button = $(this);
button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")
});
This ternary operator has an implicit return.
If the expression before ?
is true
it returns "DON'T PUSH ME"
, else returns "PUSH ME"
This if-else statement:
if (condition) { return A }
else { return B }
has the equivalent ternary expression:
condition ? A : B
Insert single quotes.
Example
$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
It depends on where you're displaying the text. On the console or a textbox for example, \n will suffice. On a RichTextBox I think you need both.
Just to add to the answers above,
I was having a 2 regular buttons as shown below. (No type="submit"anywhere)
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.
As a workaround,
I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.
<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
Well, my intention was never to submit on Enter, so the above given hack just works fine.
Safe Area is a layout guide (Safe Area Layout Guide).
The layout guide representing the portion of your view that is unobscured by bars and other content. In iOS 11+, Apple is deprecating the top and bottom layout guides and replacing them with a single safe area layout guide.
When the view is visible onscreen, this guide reflects the portion of the view that is not covered by other content. The safe area of a view reflects the area covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area incorporates the screen's bezel, as defined by the overscanCompensationInsets
property of UIScreen.) It also covers any additional space defined by the view controller's additionalSafeAreaInsets
property. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide always matches the edges of the view.
For the view controller's root view, the safe area in this property represents the entire portion of the view controller's content that is obscured, and any additional insets that you specified. For other views in the view hierarchy, the safe area reflects only the portion of that view that is obscured. For example, if a view is entirely within the safe area of its view controller's root view, the edge insets in this property are 0.
According to Apple, Xcode 9 - Release note
Interface Builder uses UIView.safeAreaLayoutGuide as a replacement for the deprecated Top and Bottom layout guides in UIViewController. To use the new safe area, select Safe Area Layout Guides in the File inspector for the view controller, and then add constraints between your content and the new safe area anchors. This prevents your content from being obscured by top and bottom bars, and by the overscan region on tvOS. Constraints to the safe area are converted to Top and Bottom when deploying to earlier versions of iOS.
Here is simple reference as a comparison (to make similar visual effect) between existing (Top & Bottom) Layout Guide and Safe Area Layout Guide.
Safe Area Layout:
AutoLayout
How to work with Safe Area Layout?
Follow these steps to find solution:
Here is sample snapshot, how to enable safe area layout and edit constraint.
Here is result of above changes
Layout Design with SafeArea
When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.
Most apps that use standard, system-provided UI elements like navigation bars, tables, and collections automatically adapt to the device's new form factor. Background materials extend to the edges of the display and UI elements are appropriately inset and positioned.
For apps with custom layouts, supporting iPhone X should also be relatively easy, especially if your app uses Auto Layout and adheres to safe area and margin layout guides.
Here is sample code (Ref from: Safe Area Layout Guide):
If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks:
Assuming we have the green view as a property in our view controller:
private let greenView = UIView()
We might have a function to set up the views and constraints called from viewDidLoad:
private func setupView() {
greenView.translatesAutoresizingMaskIntoConstraints = false
greenView.backgroundColor = .green
view.addSubview(greenView)
}
Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view:
let margins = view.layoutMarginsGuide
NSLayoutConstraint.activate([
greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
])
Now unless you are targeting iOS 11 only you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:
if #available(iOS 11, *) {
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
])
} else {
let standardSpacing: CGFloat = 8.0
NSLayoutConstraint.activate([
greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
])
}
Result:
Following UIView
extension, make it easy for you to work with SafeAreaLayout programatically.
extension UIView {
// Top Anchor
var safeAreaTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.topAnchor
} else {
return self.topAnchor
}
}
// Bottom Anchor
var safeAreaBottomAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.bottomAnchor
} else {
return self.bottomAnchor
}
}
// Left Anchor
var safeAreaLeftAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.leftAnchor
} else {
return self.leftAnchor
}
}
// Right Anchor
var safeAreaRightAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return self.safeAreaLayoutGuide.rightAnchor
} else {
return self.rightAnchor
}
}
}
Here is sample code in Objective-C:
Here is Apple Developer Official Documentation for Safe Area Layout Guide
Safe Area is required to handle user interface design for iPhone-X. Here is basic guideline for How to design user interface for iPhone-X using Safe Area Layout
$value = ( array_key_exists($key, $array) && !empty($array[$key]) )
? $array[$key]
: 'non-existant or empty value key';
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
VAR is used for creating those variable whose value will change over the course of time in your application. It is same as VAR of swift, whereas VAL is used for creating those variable whose value will not change over the course of time in your application.It is same as LET of swift.
For people who are still getting error despite of passing absolute path, should check that if file has a valid name. For me I was trying to create a file with '/' in the file name. As soon as I removed '/', I was able to create the file.
I solved the error by modifying the following property in hibernate.cfg.xml
<property name="hibernate.hbm2ddl.auto">validate</property>
Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
And the Scala version:
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
def gcd(nums: Iterable[Int]): Int = nums.reduce(gcd)
def lcm(a: Int, b: Int): Int = if (a == 0 || b == 0) 0 else a * b / gcd(a, b)
def lcm(nums: Iterable[Int]): Int = nums.reduce(lcm)
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
Here is a generic solution using a helper method. This can also handle an enum of any underlying type (byte, sbyte, uint, long, etc.)
Helper Method:
static IEnumerable<object> GetEnum<T>() {
var type = typeof(T);
var names = Enum.GetNames(type);
var values = Enum.GetValues(type);
var pairs =
Enumerable.Range(0, names.Length)
.Select(i => new {
Name = names.GetValue(i)
, Value = values.GetValue(i) })
.OrderBy(pair => pair.Name);
return pairs;
}//method
View Model:
public IEnumerable<object> EnumSearchTypes {
get {
return GetEnum<SearchTypes>();
}
}//property
ComboBox:
<ComboBox
SelectedValue ="{Binding SearchType}"
ItemsSource ="{Binding EnumSearchTypes}"
DisplayMemberPath ="Name"
SelectedValuePath ="Value"
/>
1---Enable protected mode for all zones You need to enable protected mode for all zones from Internet Options -> Security tab. To enable protected mode for all zones
Open Internet Explorer browser.
Go to menu Tools -> Internet Options.
Click on Security tab.
Select Internet from "Select a zone to view or change security settings" and Select(check) check box "Enable Protected Mode" from In the "Security level for this zone" block .
Apply same thing for all other 3 zones -> Local Internet, Trusted Sites and Restricted Sites
This setting will resolve error related to "Protected Mode settings are not the same for all zones.
2-- Set IE browser's zoom level 100%
Open Internet Explorer browser.
Go to menu View -> Zoom -> Select 100%
Log location:
${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log
Get log as a text and save to workspace:
cat ${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log >> log.txt
For me, I was receiving this error when connecting to the new IP Address I had configured FileZilla to bind to and saved the configuration. After trying all of the other answers unsuccessfully, I decided to connect to the old IP Address to see what came up; lo and behold it responded.
I restarted the FileZilla Windows Service and it immediately came back listening on the correct IP. Pretty elementary, but it cost me some time today as a noob to FZ.
Hopefully this helps someone out in the same predicament.
It doesn't matter if the random_state is 0 or 1 or any other integer. What matters is that it should be set the same value, if you want to validate your processing over multiple runs of the code. By the way I have seen random_state=42
used in many official examples of scikit as well as elsewhere also.
random_state
as the name suggests, is used for initializing the internal random number generator, which will decide the splitting of data into train and test indices in your case. In the documentation, it is stated that:
If random_state is None or np.random, then a randomly-initialized RandomState object is returned.
If random_state is an integer, then it is used to seed a new RandomState object.
If random_state is a RandomState object, then it is passed through.
This is to check and validate the data when running the code multiple times. Setting random_state
a fixed value will guarantee that same sequence of random numbers are generated each time you run the code. And unless there is some other randomness present in the process, the results produced will be same as always. This helps in verifying the output.
For python 3, urllib is split into 3 modules...
import urllib.request
req = urllib.request.Request(url="http://localhost/", headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'})
handler = urllib.request.urlopen(req)
UPDATE
For Bootstrap 3, change .on('shown', ...)
to .on('shown.bs.tab', ....)
This is based off of @dubbe answer and this SO accepted answer. It handles the issue with window.scrollTo(0,0)
not working correctly. The problem is that when you replace the url hash on tab shown, the browser will scroll to that hash since its an element on the page. To get around this, add a prefix so the hash doesn't reference an actual page element
// Javascript to enable link to tab
var hash = document.location.hash;
var prefix = "tab_";
if (hash) {
$('.nav-tabs a[href="'+hash.replace(prefix,"")+'"]').tab('show');
}
// Change hash for page-reload
$('.nav-tabs a').on('shown', function (e) {
window.location.hash = e.target.hash.replace("#", "#" + prefix);
});
Example of use
If you have tab-pane with id="mytab" you need to put your link like this:
<a href="yoursite.com/#tab_mytab">Go to Specific Tab </a>
In res folder select the XML file in which you want to view your images,
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/imagep1" />
List<T>
equality does not check them element-by-element. You can use LINQ's SequenceEqual
method for that:
var a = ints1.SequenceEqual(ints2);
To ignore order, use SetEquals
:
var a = new HashSet<int>(ints1).SetEquals(ints2);
This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:
var counts = ints1
.GroupBy(v => v)
.ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
int c;
if (counts.TryGetValue(n, out c)) {
counts[n] = c-1;
} else {
ok = false;
break;
}
}
var res = ok && counts.Values.All(c => c == 0);
Finally, if you are fine with an O(N*LogN)
solution, you can sort the two sequences, and compare them for equality using SequenceEqual
.
You can use jQuery to get text in textbox (work well for me), check in image detail
Code:
$(document.evaluate( "xpath" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()
Example:
$(document.evaluate( "//*[@id='mail']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()
Inject this above query to your code. Image detail:
Unfortunately, there is no guaranteed way to do it at time of selection.
Some browsers support the accept
attribute for input
tags. This is a good start, but cannot be relied upon completely.
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
You can use a cfinput
and run a validation to check the file extension at submission, but not the mime-type. This is better, but still not fool-proof. Files on OSX often have no file extensions or users could maliciously mislabel the file types.
ColdFusion's cffile
can check the mime-type using the contentType
property of the result (cffile.contentType
), but that can only be done after the upload. This is your best bet, but is still not 100% safe as mime-types could still be wrong.
The use of -X [WHATEVER]
merely changes the request's method string used in the HTTP request. This is easier to understand with two examples — one with -X [WHATEVER]
and one without — and the associated HTTP request headers for each:
# curl -XPANTS -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.224.86.126) port 80 (#0)
> PANTS / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*
# curl -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.33.50.167) port 80 (#0)
> GET / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*
If you want to delete items after some time, e.g. after a month, just use Time To Live option. It will not count write units.
In your case, I would add ttl when logs expire and leave those after a user is deleted. TTL would make sure logs are removed eventually.
When Time To Live is enabled on a table, a background job checks the TTL attribute of items to see if they are expired.
DynamoDB typically deletes expired items within 48 hours of expiration. The exact duration within which an item truly gets deleted after expiration is specific to the nature of the workload and the size of the table. Items that have expired and not been deleted will still show up in reads, queries, and scans. These items can still be updated and successful updates to change or remove the expiration attribute will be honored.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/howitworks-ttl.html
Sorry to break the news to ya, but there is no way to do this in IE11. I have been troubling with this for some time, but I finally had to see it as a lost course, and just navigate to the files manually.
But where are the files? That depends on a lot of things, I have found them these places on different machines:
This can be done via "run" (Windows+r) and then typing in shell:cache
or by navigating to it through the internet options in IE11 (AskLeo has a fine guide to this, I'm not affiliated in any way).
- Click on the gear icon, then Internet options.
- In the General tab, underneath “Browsing history”, click on Settings.
- In the resulting “Website Data” dialog, click on View files.
- This will open the folder we’re interested in: your Internet Explorer cache.
Make a search for "cookie" to see the cookies only
The path for cookies can be found here via regedit:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cookies
Common path (in 7 & 8)
%APPDATA%\Microsoft\Windows\Cookies
%APPDATA%\Microsoft\Windows\Cookies\Low
Common path (Win 10)
shell:cookies
shell:cookies\low
%userprofile%\AppData\Local\Microsoft\Windows\INetCookies
%userprofile%\AppData\Local\Microsoft\Windows\INetCookies\Low
If all above fail, try setting the following properties for your input, to have it take max space but not overflow:
input {
min-width: 100%;
max-width: 100%;
}
This is what I usually do ,please refer my function below :
This function can extract first number occurance from any string you can modify and use this function according to your usage
public static int GetFirstNumber(this string strInsput)
{
int number = 0;
string strNumber = "";
bool bIsContNo = true;
bool bNoOccued = false;
try
{
var arry = strInsput.ToCharArray(0, strInsput.Length - 1);
foreach (char item in arry)
{
if (char.IsNumber(item))
{
strNumber = strNumber + item.ToString();
bIsContNo = true;
bNoOccued = true;
}
else
{
bIsContNo = false;
}
if (bNoOccued && !bIsContNo)
{
break;
}
}
number = Convert.ToInt32(strNumber);
}
catch (Exception ex)
{
return 0;
}
return number;
}
Use substring
String strOut = "abcdefghijklmnopqrtuvwxyz"
String result = strOut.substring(0, 8) + "...";// count start in 0 and 8 is excluded
System.out.pritnln(result);
Note: substring(int first, int second) takes two parameters. The first is inclusive and the second is exclusive.
See: RFC 3092: Etymology of "Foo", D. Eastlake 3rd et al.
Quoting only the relevant definitions from that RFC for brevity:
Used very generally as a sample name for absolutely anything, esp. programs and files (esp. scratch files).
First on the standard list of metasyntactic variables used in syntax examples (bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, thud). [JARGON]
Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'
So, you need to do below
>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418236200
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418256000
Escape special characters with a backslash. \.
, \*
, \+
, \\d
, and so on. If you are unsure, you may escape any non-alphabetical character whether it is special or not. See the javadoc for java.util.regex.Pattern for further information.
Notice that your error message only contains five K, V
pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different of()
methods, accepting between zero and five key-value pairings. There is not an of(...)
overload accepting a varags parameter because K
and V
can be different types.
You want an ImmutableMap.Builder
:
ImmutableMap<String,String> myMap = ImmutableMap.<String, String>builder()
.put("key1", "value1")
.put("key2", "value2")
.put("key3", "value3")
.put("key4", "value4")
.put("key5", "value5")
.put("key6", "value6")
.put("key7", "value7")
.put("key8", "value8")
.put("key9", "value9")
.build();
From the Java EE documentation:
public abstract boolean unique
(Optional) Whether the property is a unique key. This is a shortcut for the UniqueConstraint annotation at the table level and is useful for when the unique key constraint is only a single field. This constraint applies in addition to any constraint entailed by primary key mapping and to constraints specified at the table level.
See doc
I'm using the "Trim Right Whitespace" exactly working on my "Show-Grp-of-UID.CMD". :) Other idea for improvement are welcome.. ^_^
One of Androids powerful feature is the AsyncTask class.
To work with it, you have to first extend it and override doInBackground
(...).
doInBackground
automatically executes on a worker thread, and you can add some
listeners on the UI Thread to get notified about status update, those functions are
called: onPreExecute()
, onPostExecute()
and onProgressUpdate()
You can find a example here.
Refer to below post for other alternatives:
The answer is "No, one can't find the median of an arbitrary, unsorted dataset in linear time". The best one can do as a general rule (as far as I know) is Median of Medians (to get a decent start), followed by Quickselect. Ref: [https://en.wikipedia.org/wiki/Median_of_medians][1]
The AdamOptimizer class creates additional variables, called "slots", to hold values for the "m" and "v" accumulators.
See the source here if you're curious, it's actually quite readable: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py#L39 . Other optimizers, such as Momentum and Adagrad use slots too.
These variables must be initialized before you can train a model.
The normal way to initialize variables is to call tf.initialize_all_variables()
which adds ops to initialize the variables present in the graph when it is called.
(Aside: unlike its name suggests, initialize_all_variables() does not initialize anything, it only add ops that will initialize the variables when run.)
What you must do is call initialize_all_variables() after you have added the optimizer:
...build your model...
# Add the optimizer
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Add the ops to initialize variables. These will include
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()
# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
sess.run(train_op)