Here is a good example on how to do a command if a file does or does not exist:
if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit
We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"
Use the XCOPY command:
xcopy "C:\myprogram\html\data.sql" /c /d /h /e /i /y "C:\myprogram\sync\"
I will explain what the /c /d /h /e /i /y
means:
/C Continues copying even if errors occur.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/H Copies hidden and system files also.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/T Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
/I If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
`To see all the commands type`xcopy /? in cmd
Call other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
Path/sync.bat
Path/myprogram.ini
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
You can use this class:
using System.Collections.Specialized;
class Post_File
{
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] boundarybytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // the first time it itereates, you need to make sure it doesn't put too many new paragraphs down or it completely messes up poor webbrick.
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
wr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
var nvc2 = new NameValueCollection();
nvc2.Add("Accepts-Language", "en-us,en;q=0.5");
wr.Headers.Add(nvc2);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
Stream rs = wr.GetRequestStream();
bool firstLoop = true;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
if (firstLoop)
{
rs.Write(boundarybytesF, 0, boundarybytesF.Length);
firstLoop = false;
}
else
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
}
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, new FileInfo(file).Name, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
}
use it:
NameValueCollection nvc = new NameValueCollection();
//nvc.Add("id", "TTR");
nvc.Add("table_name", "uploadfile");
nvc.Add("commit", "uploadfile");
Post_File.HttpUploadFile("http://example/upload_file.php", @"C:\user\yourfile.docx", "uploadfile", "application/vnd.ms-excel", nvc);
example server upload_file.php
:
m('File upload '.(@copy($_FILES['uploadfile']['tmp_name'],getcwd().'\\'.'/'.$_FILES['uploadfile']['name']) ? 'success' : 'failed'));
function m($msg) {
echo '<div style="background:#f1f1f1;border:1px solid #ddd;padding:15px;font:14px;text-align:center;font-weight:bold;">';
echo $msg;
echo '</div>';
}
Is this value intended? if (scroll <= 500) { ...
This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"
asort()
- Maintains key association: yes.
sort()
- Maintains key association: no.
add dependency for retrofit2
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
create class for base url
public class ApiClient
{
public static final String BASE_URL = "base_url";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
after that create class model to get value
public class ApprovalModel {
@SerializedName("key_parameter")
private String approvalName;
public String getApprovalName() {
return approvalName;
}
}
create interface class
public interface ApiInterface {
@GET("append_url")
Call<CompanyDetailsResponse> getCompanyDetails();
}
after that in main class
if(Connectivity.isConnected(mContext)){
final ProgressDialog mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage("Loading...");
mProgressDialog.show();
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<CompanyDetailsResponse> call = apiService.getCompanyDetails();
call.enqueue(new Callback<CompanyDetailsResponse>() {
@Override
public void onResponse(Call<CompanyDetailsResponse>call, Response<CompanyDetailsResponse> response) {
mProgressDialog.dismiss();
if(response!=null && response.isSuccessful()) {
List<CompanyDetails> companyList = response.body().getCompanyDetailsList();
if (companyList != null&&companyList.size()>0) {
for (int i = 0; i < companyList.size(); i++) {
Log.d(TAG, "" + companyList.get(i));
}
//get values
}else{
//show alert not get value
}
}else{
//show error message
}
}
@Override
public void onFailure(Call<CompanyDetailsResponse>call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
mProgressDialog.dismiss();
}
});
}else{
//network error alert box
}
This might help:
<input type="number" step="1" pattern="\d+" />
step
is for convenience (and could be set to another integer), but pattern
does some actual enforcing.
Note that since pattern
matches the whole expression, it wasn't necessary to express it as ^\d+$
.
Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e
here (presumably for scientific notation) as well as -
for negative numbers, and Chrome also allows for .
whereas Firefox is tighter in rejecting unless the .
is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)
Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).
Solved in may of 2018 with the new Android Studio 3.1. Delete the .gradle, .idea and build directories inside your app folder. Then try to run it again and you won't see the error.
Looks like you have recently installed flex-layout package. Try removing this package folder from your node_modules folder and reinstalling previous version of this package.
Recently (2 days before current date), angular released latest angular-cli version (v9.0.1) due to which many packages are updated to support this latest cli version. In your case you might have old cli version and when you installed this package it was downloaded for latest cli version by default. So try downgrading your package version. Worked for me atleast.
Also, dont forget to downgrade the version of your package in package.json file
I am a slow learner of javascript promises, by default all async functions return a promise, you can wrap your result as:
(async () => {
//Optional "await"
await yourAsyncFunctionOrPromise()
.then(function (result) {
return result +1;
})
.catch(function (error) {
return error;
})()
})
"The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise. If the Promise is rejected, the await expression throws the rejected value."
"top" is usually available on Solaris.
If not then revert to "vmstat" which is available on most UNIX system.
It should look something like this (from an AIX box)
vmstat System configuration: lcpu=4 mem=12288MB ent=2.00 kthr memory page faults cpu ----- ----------- ------------------------ ------------ ----------------------- r b avm fre re pi po fr sr cy in sy cs us sy id wa pc ec 2 1 1614644 585722 0 0 1 22 104 0 808 29047 2767 12 8 77 3 0.45 22.3
the colums "avm" and "fre" tell you the total memory and free memery.
a "man vmstat" should get you the gory details.
If you are using mysql client you can set up the resultFormat per session e.g.
mysql -h localhost -u root --resutl-format=json
or
mysql -h localhost -u root --vertical
Check out the full list of arguments here.
ConfigurationManager.AppSettings
is actually a property, so you need to use square brackets.
Overall, here's what you need to do:
SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.
// Select 1 from table_name will return false if the table does not exist.
$val = mysql_query('select 1 from `table_name` LIMIT 1');
if($val !== FALSE)
{
//DO SOMETHING! IT EXISTS!
}
else
{
//I can't find it...
}
Admittedly, it is more Pythonic than of the PHP idiom, but on the other hand, you don't have to worry about dealing with a copious amount of extra data.
So, this answer has been marked down at least twice as of the time I am writing this message. Assuming that I had made some gargantuan error, I went and I ran some benchmarks, and this is what I found that my solution is over 10% faster than the nearest alternative when the table does not exist, and it over 25% faster when the table does exist:
:::::::::::::::::::::::::BEGINNING NON-EXISTING TABLE::::::::::::::::::::::::::::::
23.35501408577 for bad select
25.408507823944 for select from schema num rows -- calls mysql_num_rows on select... from information_schema.
25.336688995361 for select from schema fetch row -- calls mysql_fetch_row on select... from information_schema result
50.669058799744 for SHOW TABLES FROM test
:::::::::::::::::::::::::BEGINNING EXISTING TABLE::::::::::::::::::::::::::::::
15.293519973755 for good select
20.784908056259 for select from schema num rows
21.038464069366 for select from schema fetch row
50.400309085846 for SHOW TABLES FROM test
I tried running this against DESC, but I had a timeout after 276 seconds (24 seconds for my answer, 276 to fail to complete the description of a non existing table).
For good measure, I am benchmarking against a schema with only four tables in it and this is an almost fresh MySQL install (this is the only database so far). To see the export, look here.
This particular solution is also more database independent as the same query will work in PgSQL and Oracle.
mysql_query()
returns FALSE for errors that aren't "this table doesn't exist".
If you need to guarantee that the table doesn't exist, use mysql_errno()
to get the error code and compare it to the relevant MySQL errors.
The concerns with cryptography in client-side (browser) javascript are detailed below. All but one of these concerns does not apply to the WebCrypto API, which is now reasonably well supported.
For an offline app, you must still design and implement a secure keystore.
Aside: If you are using Node.js, use the builtin crypto API.
I presume the primary concern is someone with physical access to the computer reading the localStorage
for your site, and you want cryptography to help prevent that access.
If someone has physical access you are also open to attacks other and worse than reading. These include (but are not limited to): keyloggers, offline script modification, local script injection, browser cache poisoning, and DNS redirects. Those attacks only work if the user uses the machine after it has been compromised. Nevertheless, physical access in such a scenario means you have bigger problems.
So keep in mind that the limited scenario where local crypto is valuable would be if the machine is stolen.
There are libraries that do implement the desired functionality, e.g. Stanford Javascript Crypto Library. There are inherent weaknesses, though (as referred to in the link from @ircmaxell's answer):
Each of these weaknesses corresponds with a category of cryptographic compromise. In other words, while you may have "crypto" by name, it will be well below the rigour one aspires to in practice.
All that being said, the actuarial assessment is not as trivial as "Javascript crypto is weak, do not use it". This is not an endorsement, strictly a caveat and it requires you to completely understand the exposure of the above weaknesses, the frequency and cost of the vectors you face, and your capacity for mitigation or insurance in the event of failure: Javascript crypto, in spite of its weaknesses, may reduce your exposure but only against thieves with limited technical capacity. However, you should presume Javascript crypto has no value against a determined and capable attacker who is targeting that information. Some would consider it misleading to call the data "encrypted" when so many weaknesses are known to be inherent to the implementation. In other words, you can marginally decrease your technical exposure but you increase your financial exposure from disclosure. Each situation is different, of course - and the analysis of reducing the technical exposure to financial exposure is non-trivial. Here is an illustrative analogy: Some banks require weak passwords, in spite of the inherent risk, because their exposure to losses from weak passwords is less than the end-user costs of supporting strong passwords.
If you read the last paragraph and thought "Some guy on the Internet named Brian says I can use Javascript crypto", do not use Javascript crypto.
For the use case described in the question it would seem to make more sense for users to encrypt their local partition or home directory and use a strong password. That type of security is generally well tested, widely trusted, and commonly available.
Invoke mysql with the -N
(the alias for -N
is --skip-column-names
) option:
mysql -N ...
use testdb;
select * from names;
+------+-------+
| 1 | pete |
| 2 | john |
| 3 | mike |
+------+-------+
3 rows in set (0.00 sec)
Credit to ErichBSchulz for pointing out the -N alias.
To remove the grid (the vertical and horizontal lines) around the results use -s
(--silent
). Columns are separated with a TAB
character.
mysql -s ...
use testdb;
select * from names;
id name
1 pete
2 john
3 mike
To output the data with no headers and no grid just use both -s
and -N
.
mysql -sN ...
I created a WSGI middleware that stores the raw body from the environ['wsgi.input']
stream. I saved the value in the WSGI environ so I could access it from request.environ['body_copy']
within my app.
This isn't necessary in Werkzeug or Flask, as request.get_data()
will get the raw data regardless of content type, but with better handling of HTTP and WSGI behavior.
This reads the entire body into memory, which will be an issue if for example a large file is posted. This won't read anything if the Content-Length
header is missing, so it won't handle streaming requests.
from io import BytesIO
class WSGICopyBody(object):
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
length = int(environ.get('CONTENT_LENGTH') or 0)
body = environ['wsgi.input'].read(length)
environ['body_copy'] = body
# replace the stream since it was exhausted by read()
environ['wsgi.input'] = BytesIO(body)
return self.application(environ, start_response)
app.wsgi_app = WSGICopyBody(app.wsgi_app)
request.environ['body_copy']
Old thread, but the question is still relevant, so...
(1) The example in your question now DOES work in Firefox. However in addition to calling the event handler (which displays an alert), it ALSO clicks on the link, causing navigation (once the alert is dismissed).
(2) To JUST call the event handler (without triggering navigation) merely replace:
document.getElementById('linkid').click();
with
document.getElementById('linkid').onclick();
remove super.onBackPressed()
from public void onBackPressed()
work great.
its tested in android 9
Here, I summarize a few ways which may return different results to your question, so be careful:
# First assign your "id"s to an R object.
# Here's a hypothetical example:
id <- c("a","b","b","c","c","c","d","d","d","d")
#To return ALL MINUS ONE duplicated values:
id[duplicated(id)]
## [1] "b" "c" "c" "d" "d" "d"
#To return ALL duplicated values by specifying fromLast argument:
id[duplicated(id) | duplicated(id, fromLast=TRUE)]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
#Yet another way to return ALL duplicated values, using %in% operator:
id[ id %in% id[duplicated(id)] ]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
Hope these help. Good luck.
import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json
maybe?
if you are trying to send a file
files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json
ahh thanks @LukasGraf now i better understand what his original code is doing
import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print
print req.json # maybe?
Mongoose and multiple database in single node.js project
use useDb to solve this issue
example
//product databse
const myDB = mongoose.connection.useDb('product');
module.exports = myDB.model("Snack", snackSchema);
//user databse
const myDB = mongoose.connection.useDb('user');
module.exports = myDB.model("User", userSchema);
If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.
Command for this is,
ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest
PRIMARY KEY (wardNo, BHTNo, TestID)
I think you set the marquee width related to 5 images total width. It works fine
ex: <marquee style="width:700px"></marquee>
A simple way to remove spaces from the whole string is to use the explode function and print the whole string using a for loop.
$text = $_POST['string'];
$a=explode(" ", $text);
$count=count($a);
for($i=0;$i<$count; $i++){
echo $a[$i];
}
imageView.image = [UIImage imageNamed:@"myImage.png"];
I've published instructions for how to run the Firefox SQLite Manager outside of Firefox, since FF hase become so bloated in the last few releases. It's really easy and I've even compiled a DMG for the sqlite gui if anyone wants it.
The struct's name is ReducedForm
; you need to make an object (instance of the struct
or class
) and use that. Do this:
ReducedForm MyReducedForm;
MyReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
MyReducedForm.iSimplifiedDenominator = iDenominator/iGreatCommDivisor;
I suspect the problem is because the json represents an object with the list of users as a property. Try deserializing to something like:
public class UsersResponse
{
public List<User> Data { get; set; }
}
what about this simple inArray function:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
angular.element(document).ready(function () {
//your logic here
});
If you know the root password, you can try
su -c "<command1> ; <command2>"
I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;
SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;
Result: Paddy O'Reilly
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: base_url + "chat/post_action",
data: {textbox: $("#textbox").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have missed this bracket
return false;
});
});
Example of integer division using bash to divide $a by $b:
echo $((a/b))
you can't declare two model on one view, try to use Html.Action("Person", "[YourController]")
& Html.Action("Order", "[YourController]")
.
Good luck.
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
I followed the answers by @wize and @mdelolmo and I got the solution. Thanks Tons. But, I tuned these solutions a little bit to improve the memory consumption.
Problems I observed:
They save the instance of Fragment
which is replaced. In my case, it is a Fragment which holds MapView
and I thought its costly. So, I am maintaining the FragmentPagerPositionChanged (POSITION_NONE or POSITION_UNCHANGED)
instead of Fragment
itself.
Here is my implementation.
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
private SwitchFragListener mSwitchFragListener;
private Switch mToggle;
private int pagerAdapterPosChanged = POSITION_UNCHANGED;
private static final int TOGGLE_ENABLE_POS = 2;
public DemoCollectionPagerAdapter(FragmentManager fm, Switch toggle) {
super(fm);
mToggle = toggle;
mSwitchFragListener = new SwitchFragListener();
mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSwitchFragListener.onSwitchToNextFragment();
}
});
}
@Override
public Fragment getItem(int i) {
switch (i)
{
case TOGGLE_ENABLE_POS:
if(mToggle.isChecked())
{
return TabReplaceFragment.getInstance();
}else
{
return DemoTab2Fragment.getInstance(i);
}
default:
return DemoTabFragment.getInstance(i);
}
}
@Override
public int getCount() {
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
return "Tab " + (position + 1);
}
@Override
public int getItemPosition(Object object) {
// This check make sures getItem() is called only for the required Fragment
if (object instanceof TabReplaceFragment
|| object instanceof DemoTab2Fragment)
return pagerAdapterPosChanged;
return POSITION_UNCHANGED;
}
/**
* Switch fragments Interface implementation
*/
private final class SwitchFragListener implements
SwitchFragInterface {
SwitchFragListener() {}
public void onSwitchToNextFragment() {
pagerAdapterPosChanged = POSITION_NONE;
notifyDataSetChanged();
}
}
/**
* Interface to switch frags
*/
private interface SwitchFragInterface{
void onSwitchToNextFragment();
}
}
Demo link here.. https://youtu.be/l_62uhKkLyM
For demo purpose, used 2 fragments TabReplaceFragment
and DemoTab2Fragment
at position two. In all the other cases I'm using DemoTabFragment
instances.
Explanation:
I'm passing Switch
from Activity to the DemoCollectionPagerAdapter
. Based on the state of this switch we will display correct fragment. When the switch check is changed, I'm calling the SwitchFragListener
's onSwitchToNextFragment
method, where I'm changing the value of pagerAdapterPosChanged
variable to POSITION_NONE
. Check out more about POSITION_NONE. This will invalidate the getItem and I have logics to instantiate the right fragment over there. Sorry, if the explanation is a bit messy.
Once again big thanks to @wize and @mdelolmo for the original idea.
Hope this is helpful. :)
Let me know if this implementation has any flaws. That will be greatly helpful for my project.
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
If you want to dynamicallly display your Symfony 2 version in pages, for example in footer, you can do it this way.
Create a service:
<?php
namespace Project\Bundle\DuBundle\Twig;
class SymfonyVersionExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
//this is the name of the function you will use in twig
new \Twig_SimpleFunction('symfony_version', array($this, 'b'))
);
}
public function getName()
{
//return 'number_employees';
return 'symfony_version_extension';
}
public function b()
{
$symfony_version = \Symfony\Component\HttpKernel\Kernel::VERSION;
return $symfony_version;
}
}
Register in service.yml
dut.twig.symfony_version_extension:
class: Project\Bundle\DutBundle\Twig\SymfonyVersionExtension
tags:
- { name: twig.extension }
#arguments: []
And you can call it anywhere. In Controller, wrap it in JSON, or in pages example footer
<p> Built With Symfony {{ symfony_version() }} Version MIT License</p>
Now every time you run composer update to update your vendor, symfony version will also automatically update in your template.I know this is overkill but this is how I do it in my projects and it is working.
I have solved this problem by importing the following dependency. you must manually import httpclient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
jmeter is now just installed with
brew install jmeter
This version includes the plugin manager that you can use to download the additional plugins.
OUTDATED:
If you want to include the plugins (JMeterPlugins Standard, Extras, ExtrasLibs, WebDriver and Hadoop) use:
brew install jmeter --with-plugins
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
FOO = $PATH all: @echo $(FOO) @echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
First of all, you would have to allocate memory:
char * S = new char[R.length() + 1];
then you can use strcpy
with S
and R.c_str()
:
std::strcpy(S,R.c_str());
You can also use R.c_str()
if the string doesn't get changed or the c string is only used once. However, if S
is going to be modified, you should copy the string, as writing to R.c_str()
results in undefined behavior.
Note: Instead of strcpy
you can also use str::copy
.
Xcode 8 beta 2 • Swift 3
let myString = "Hello World"
let myRange = myString.startIndex..<myString.index(myString.startIndex, offsetBy: 5)
let mySubString = myString.substring(with: myRange) // Hello
Xcode 7 • Swift 2.0
let myString = "Hello World"
let myRange = Range<String.Index>(start: myString.startIndex, end: myString.startIndex.advancedBy(5))
let mySubString = myString.substringWithRange(myRange) // Hello
or simply
let myString = "Hello World"
let myRange = myString.startIndex..<myString.startIndex.advancedBy(5)
let mySubString = myString.substringWithRange(myRange) // Hello
Mozilla's MDN suggests something like the following [source]:
p {
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
}
in command line first reach the directory where psql is present then write commands like this:
psql [database name] [username]
and then press enter psql asks for password give the user password:
then write
> \i [full path and file name with extension]
then press enter insertion done.
Test castEnum = static_cast<Test>(a-1);
will cast a
to A
. If you don't want to substruct 1, you can redefine the enum
:
enum Test
{
A:1, B
};
In this case Test castEnum = static_cast<Test>(a);
could be used to cast a
to A
.
Use random.uniform(a, b):
>>> random.uniform(1.5, 1.9)
1.8733202628557872
Also it'd work to just specify ifelse()
twice:
plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))
I just came across the same issue while trying to query a MySQL Database from Pentaho.
Error connecting to database [Local MySQL DB] : org.pentaho.di.core.exception.KettleDatabaseException: Error occured while trying to connect to the database
Exception while loading class org.gjt.mm.mysql.Driver
Expanding post by @user979331 the solution is:
copy the .jar file (mysql-connector-java-5.1.31-bin.jar) and paste it in your Lib folder:
PC: C:\Program Files\pentaho\design-tools\data-integration\lib
Mac: /Applications/data-integration/lib
Restart Pentaho (Data Integration) and re-test the MySQL Connection.
Additional interesting replies from others that could also help:
Use the throw statement.
JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".
If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.
The Law of Leaky Abstractions by Joel Spolsky
http://www.joelonsoftware.com/articles/LeakyAbstractions.html
jqyery this is another version with jquery a little less shorter.
assuming that the <a>
element is inside de <li>
element
$(li).click(function(){
$(this).children().click();
});
Explain what video describe to resolve problem
After Changing Password of root (Mysql Account). Accessing to phpmyadmin page will be denied because phpMyAdmin use root/''(blank) as default username/password. To resolve this problem, you need to reconfig phpmyadmin. Edit file config.inc.php in folder %wamp%\apps\phpmyadmin4.1.14 (Not in %wamp%)
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
If you have more than 1 DB server, add "i++" to file and continue add new config as above
A violation like that means that there's something seriously wrong with the code, and it's unreliable. I can see that a program might want to try to save the user's data in a way that one hopes won't write over previous data, in the hope that the user's data isn't already corrupted, but there is by definition no standard method of dealing with undefined behavior.
Kernel resides in OS.Actually it is a memory space specially provided for handling the os functions.Some even say OS handles Resources of system and Kernel is one which is heart of os and maintain,manage i.e.keep track of os.
-- Step 1: Create temp table. create table Billing ( TAP_ID char(10), ACCT_NUM char(10));
SELECT * FROM BILLING;
-- Step 2: Create Control file.
load data infile IN_DATA.txt into table Billing fields terminated by ',' (TAP_ID, ACCT_NUM)
-- Step 3: Create input data file. IN_DATA.txt file content: 100,15678966
-- Step 4: Execute command from run: .. client\bin>sqlldr username@db-sis__id/password control='Billing.ctl'
you could perhaps use:
application/x-binary
Here's a link which provides two other solutions without using any visited flags.
https://leetcode.com/problems/binary-tree-postorder-traversal/
This is obviously a stack-based solution due to the lack of parent pointer in the tree. (We wouldn't need a stack if there's parent pointer).
We would push the root node to the stack first. While the stack is not empty, we keep pushing the left child of the node from top of stack. If the left child does not exist, we push its right child. If it's a leaf node, we process the node and pop it off the stack.
We also use a variable to keep track of a previously-traversed node. The purpose is to determine if the traversal is descending/ascending the tree, and we can also know if it ascend from the left/right.
If we ascend the tree from the left, we wouldn't want to push its left child again to the stack and should continue ascend down the tree if its right child exists. If we ascend the tree from the right, we should process it and pop it off the stack.
We would process the node and pop it off the stack in these 3 cases:
array1.equals(array2)
is the same as array1 == array2
, i.e. is it the same array. As @alf points out it's not what most people expect.
Arrays.equals(array1, array2)
compares the contents of the arrays.
Similarly array.toString()
may not be very useful and you need to use Arrays.toString(array)
.
//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
List<String> wives = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new FileReader(fileName));
// for each line
for(String line = input.readLine(); line != null; line = input.readLine()) {
wives.add(line);
}
input.close();
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
return null;
}
return wives;
}
To make the answer more general than Ubuntu (I have Redhat):
gtk is usually installed under /usr, but possibly in other locations. This should be visible in environment variables. Check with
env | grep gtk
Then try to find where your gtk files are stored. For example, use locate
and grep.
locate gtk | grep /usr/lib
In this way, I found /usr/lib64/gtk-2.0
, which contains the subdirectory 2.10.0
, which contains many .so library files. My conclusion is that I have gtk+ version 2.10. This is rather consistent with the rpm command on Redhat: rpm -qa | grep gtk2
, so I think my conclusion is right.
dump the headers in one file and the payload of the response in a different file
curl -k -v -u user:pass "url" --trace-ascii headers.txt >> response.txt
1) Add selected class to target element
2) Find all children of parent element excluding target element
3) Remove class from target element
<div id = "outer">
<div class="item" id="inner1">Div 1 </div>
<div class="item" id="inner2">Div 2 </div>
<div class="item" id="inner3">Div 3 </div>
<div class="item" id="inner4">Div 4 </div>
</div>
function getSiblings(target) {
target.classList.add('selected');
let siblings = document.querySelecttorAll('#outer .item:not(.currentlySelected)')
target.classList.remove('selected');
return siblings
}
Here's another way, but with the advantage that it launches Terminal, brings it to the front, and creates only one window.
I like this when I want to be neatly presented with the results of my script.
tell application "Terminal"
activate
set shell to do script "echo 1" in window 1
do script "echo 2" in shell
do script "echo 3" in shell
end tell
The negation pseudo-class seems to be what you are looking for.
table:not(.dojoxGrid) {color:red;}
Use git show:
git show --summary
This will show the names of created or removed files, but not the names of changed files. The git show
command supports a wide variety of output formats that show various types of information about commits.
Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window
)
This is an example of his idea:
Html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
</script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello !</h1>
</body>
</html>
init.js (Based on this answer)
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function(i) {
return _args[i];
}
};
}());
script.js
// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);
alert(a);
Here's the plnkr. Hope it help !
Here's mine command for reference:
mongoexport --db AppDB --collection files --pretty --out output.json
On Windows 7 (MongoDB 3.4), one has to move the cmd to the place where mongod.exe
and mongo.exe
file resides =>
C:\MongoDB\Server\3.4\bin
else it won't work saying it does not recongnize mongoexport
command.
I have been asking this question for a long time, but I think there is no silver bullet for that.
What I currently do is mocking the DAO objects and keeping a in memory representation of a good collection of objects that represent interesting cases of data that could live on the database.
The main problem I see with that approach is that you're covering only the code that interacts with your DAO layer, but never testing the DAO itself, and in my experience I see that a lot of errors happen on that layer as well. I also keep a few unit tests that run against the database (for the sake of using TDD or quick testing locally), but those tests are never run on my continuous integration server, since we don't keep a database for that purpose and I think tests that run on CI server should be self-contained.
Another approach I find very interesting, but not always worth since is a little time consuming, is to create the same schema you use for production on an embedded database that just runs within the unit testing.
Even though there's no question this approach improves your coverage, there are a few drawbacks, since you have to be as close as possible to ANSI SQL to make it work both with your current DBMS and the embedded replacement.
No matter what you think is more relevant for your code, there are a few projects out there that may make it easier, like DbUnit.
I found a similar way with margin-left
, but it can be left
as well.
#inner {
width: 100%;
max-width: 65px; /* To adapt to screen width. It can be whatever you want. */
left: 65px; /* This has to be approximately the same as the max-width. */
}
The easiest way can be inline style on modal-dialog
div :
<div class="modal" id="myModal">
<div class="modal-dialog" style="width:1250px;">
<div class="modal-content">
...
</div>
</div>
</div>
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
To create multiple sub-folders
mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}
Yes, a menu gives you the bar but it doesn't give you any items to put in the bar. You need something like (from one of my own projects):
<!-- Menu. -->
<Menu Width="Auto" Height="20" Background="#FFA9D1F4" DockPanel.Dock="Top">
<MenuItem Header="_Emulator">
<MenuItem Header="Load..." Click="MenuItem_Click" />
<MenuItem Header="Load again" Click="menuEmulLoadLast" />
<Separator />
<MenuItem Click="MenuItem_Click">
<MenuItem.Header>
<DockPanel>
<TextBlock>Step</TextBlock>
<TextBlock Width="10"></TextBlock>
<TextBlock HorizontalAlignment="Right">F2</TextBlock>
</DockPanel>
</MenuItem.Header>
</MenuItem>
:
This is one of those "you were technically accurate, but you didn't answer my question" but it doesn't mean the above were wrong or misguided - they just didn't run into my issue.
So, I figure I'll give an answer.
As the others mentioned (spot on), I created a file:
<?php
phpinfo();
?>
So that worked great. However, it showed "(none)"
So where do you find (none)!?
In my case, on Windows, you just go to where php is installed; I had already had installed it in c:\php
I believe it would be the same steps on other platforms.
Then, from a command line, powershell for ex, type: notepad c:\php\php.ini
Tell it yes, you do want to create it, then add whatever changes you needed in the first place. For me, for example:
extension_dir = "c:\php\ext"
extension=mysqli
upload_max_filesize = 25M
post_max_size = 13M
max_execution_time = 300
Then save. Fixed!
By the way - if you do "file new" and then "save as" Notepad will helpfully rename your file to php.ini.txt. Friends let friends NOT AVOID THE CLI.
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
SELECT ORDER_NO, DELIVERY_ADDRESS
from IFSAPP.PURCHASE_ORDER_TAB
where ORDER_NO in ('52000077','52000079','52000167','52000297','52000204','52000409','52000126')
ORDER BY instr('52000077,52000079,52000167,52000297,52000204,52000409,52000126',ORDER_NO)
worked really great
Swift 2.3 solution
Easier solution that won't break with Realm updates
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
print("App Path: \(dirPaths)")
The .realm file should be inside "Documents"
Use the built-in isinstance()
function.
import pandas as pd
def f(var):
if isinstance(var, pd.DataFrame):
print("do stuff")
Firstly, the below method doesn't compile as it is missing the return type and it should be Long.MAX_VALUE
in place of Long.Max_value
.
public static boolean isBiggerThanMaxLong(long value) {
return value > Long.Max_value;
}
The above method can never return true
as you are comparing a long
value with Long.MAX_VALUE
, see the method signature you can pass only long
there.Any long
can be as big as the Long.MAX_VALUE
, it can't be bigger than that.
You can try something like this with BigInteger class :
public static boolean isBiggerThanMaxLong(BigInteger l){
return l.compareTo(BigInteger.valueOf(Long.MAX_VALUE))==1?true:false;
}
The below code will return true
:
BigInteger big3 = BigInteger.valueOf(Long.MAX_VALUE).
add(BigInteger.valueOf(Long.MAX_VALUE));
System.out.println(isBiggerThanMaxLong(big3)); // prints true
If you want to due this in component.ts
HTML:
<button class="class1 class2" (click)="clicked($event)">Click me</button>
Component:
clicked(event) {
event.target.classList.add('class3'); // To ADD
event.target.classList.remove('class1'); // To Remove
event.target.classList.contains('class2'); // To check
event.target.classList.toggle('class4'); // To toggle
}
For more options, examples and browser compatibility visit this link.
You may also want to look at some of the more specialised types, like ListIterator, NavigableSet and (if you're interested in maps) NavigableMap.
Does it have to be specifically an InputStreamReader? How about using StringReader?
Otherwise, you could use StringBufferInputStream, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).
When you cast an object reference you are just casting the type of the reference, not the type of the object. casting won't change the actual type of the object.
Java doesn't have implicit rules for converting Object types. (Unlike primitives)
Instead you need to provide how to convert one type to another and call it manually.
public class TestA {}
public class TestB extends TestA{
TestB(TestA testA) {
// build a TestB from a TestA
}
}
List<TestA> result = ....
List<TestB> data = new List<TestB>();
for(TestA testA : result) {
data.add(new TestB(testA));
}
This is more verbose than in a language with direct support, but it works and you shouldn't need to do this very often.
The Eclipse (software) page on Wikipedia summarizes it pretty well:
Releases
Since 2006, the Eclipse Foundation has coordinated an annual Simultaneous Release. Each release includes the Eclipse Platform as well as a number of other Eclipse projects. Until the Galileo release, releases were named after the moons of the solar system.
So far, each Simultaneous Release has occurred at the end of June.
Release Main Release Platform version Projects Photon 27 June 2018 4.8 Oxygen 28 June 2017 4.7 Neon 22 June 2016 4.6 Mars 24 June 2015 4.5 Mars Projects Luna 25 June 2014 4.4 Luna Projects Kepler 26 June 2013 4.3 Kepler Projects Juno 27 June 2012 4.2 Juno Projects Indigo 22 June 2011 3.7 Indigo projects Helios 23 June 2010 3.6 Helios projects Galileo 24 June 2009 3.5 Galileo projects Ganymede 25 June 2008 3.4 Ganymede projects Europa 29 June 2007 3.3 Europa projects Callisto 30 June 2006 3.2 Callisto projects Eclipse 3.1 28 June 2005 3.1 Eclipse 3.0 28 June 2004 3.0
To summarize, Helios, Galileo, Ganymede, etc are just code names for versions of the Eclipse platform (personally, I'd prefer Eclipse to use traditional version numbers instead of code names, it would make things clearer and easier). My suggestion would be to use the latest version, i.e. Eclipse Oxygen (4.7) (in the original version of this answer, it said "Helios (3.6.1)").
On top of the "platform", Eclipse then distributes various Packages (i.e. the "platform" with a default set of plugins to achieve specialized tasks), such as Eclipse IDE for Java Developers, Eclipse IDE for Java EE Developers, Eclipse IDE for C/C++ Developers, etc (see this link for a comparison of their content).
To develop Java Desktop applications, the Helios release of Eclipse IDE for Java Developers should suffice (you can always install "additional plugins" if required).
I had the same issue and basically resolved it by pointing to a specific port number that my MySQL server was running on. Below is the command. Please edit the code to fit your case i.e your port number,your mysql server username,your password.
mysql -u root -pYourMysqlRootPassword -P3307
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
</httpErrors>
</system.webServer>
To pull a remote branch locally, I do the following:
git checkout -b branchname
// creates a local branch with the same name and checks out on it
git pull origin branchname
// pulls the remote one onto your local one
The only time I did this and it didn't work, I deleted the repo, cloned it again and repeated the above 2 steps; it worked.
The answers above will work for changing the values.
If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:
go to your 'Formulas' tab
choose "Name Manager"
a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.
Auto PY to EXE - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.
py2exe is probably what you want, but it only works on Windows.
PyInstaller works on Windows and Linux.
Py2app works on the Mac.
In case you want to use it for copy protection and you need it to return always the same serial on one computer (of course as far as first hdd or ssd is not changed) I would recommend code below. For ManagementClass you need to add reference to System.Management. P.S. Without "InterfaceType" and "DeviceID" check that method can return serial of random disk or serial of USB flash drive which connected to pc right now.
public static string GetSerial()
{
try
{
var mc = new ManagementClass("Win32_DiskDrive");
var moc = mc.GetInstances();
var res = string.Empty;
var resList = new List<string>(moc.Count);
foreach (ManagementObject mo in moc)
{
try
{
if (mo["InterfaceType"].ToString().Replace(" ", string.Empty) == "USB")
{
continue;
}
}
catch
{
}
try
{
res = mo["SerialNumber"].ToString().Replace(" ", string.Empty);
resList.Add(res);
if (mo["DeviceID"].ToString().Replace(" ", string.Empty).Contains("0"))
{
if (!string.IsNullOrWhiteSpace(res))
{
return res;
}
}
}
catch
{
}
}
res = resList[0];
if (!string.IsNullOrWhiteSpace(res))
{
return res;
}
}
catch
{
}
return string.Empty;
}
You need to make sure the frame is fully loaded the best way to do it is to use onload:
<iframe id="nesgt" src="" onload="custom()"></iframe>
function custom(){
document.getElementById("nesgt").contentWindow.document;
}
this function will run automatically when the iframe is fully loaded.
it could be done with setTimeout but we can't get the exact time of the frame load.
hope this helps someone.
I've worked on a high-volume system using MySQL and I've tried both MyISAM and InnoDB.
I found that the table-level locking in MyISAM caused serious performance problems for our workload which sounds similar to yours. Unfortunately I also found that performance under InnoDB was also worse than I'd hoped.
In the end I resolved the contention issue by fragmenting the data such that inserts went into a "hot" table and selects never queried the hot table.
This also allowed deletes (the data was time-sensitive and we only retained X days worth) to occur on "stale" tables that again weren't touched by select queries. InnoDB seems to have poor performance on bulk deletes so if you're planning on purging data you might want to structure it in such a way that the old data is in a stale table which can simply be dropped instead of running deletes on it.
Of course I have no idea what your application is but hopefully this gives you some insight into some of the issues with MyISAM and InnoDB.
if (child is IContainer ? false : true)
127.0.0.1 always points to localhost. On your home network you should have an IP address assigned by your internet router (dsl/cablemodem/whatever). You need to bind your website to this address. You should then be able to use the machine name to get to the website, but I would recommend actually editing the hosts file of the client computer in question to point a specific name at that computer. The hosts file can be found at c:\windows\system32\drivers\etc\hosts (use notepad) and the entry would look like:
192.168.1.1 mycomputername
If you're using jQuery, use .data()
:
div.data('myval', 20);
You can store arbitrary data with .data()
, but you're restricted to just strings when using .attr()
.
It is indeed much less simple than it seems :-) Nick's suggestion is a good one.
To get started, keep in mind that any worthwhile comparison method will essentially work by converting the images into a different form -- a form which makes it easier to pick similar features out. Usually, this stuff doesn't make for very light reading ...
One of the simplest examples I can think of is simply using the color space of each image. If two images have highly similar color distributions, then you can be reasonably sure that they show the same thing. At least, you can have enough certainty to flag it, or do more testing. Comparing images in color space will also resist things such as rotation, scaling, and some cropping. It won't, of course, resist heavy modification of the image or heavy recoloring (and even a simple hue shift will be somewhat tricky).
http://en.wikipedia.org/wiki/RGB_color_space
http://upvector.com/index.php?section=tutorials&subsection=tutorials/colorspace
Another example involves something called the Hough Transform. This transform essentially decomposes an image into a set of lines. You can then take some of the 'strongest' lines in each image and see if they line up. You can do some extra work to try and compensate for rotation and scaling too -- and in this case, since comparing a few lines is MUCH less computational work than doing the same to entire images -- it won't be so bad.
http://homepages.inf.ed.ac.uk/amos/hough.html
http://rkb.home.cern.ch/rkb/AN16pp/node122.html
http://en.wikipedia.org/wiki/Hough_transform
I have experienced that this error occurs when you either move the excel file to the destination other than where your r file is located or when you move your r file to the destination other than where your excel file is located.
Good Practice:
You also have import Dataset option at Environment Block, just click there and get your required packages installed & from next time use this option to read datasets. You will not get this error again. I also appreciate the above provided answers.
You want to do the following:
ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
ON [dbo].[SCHEDULE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF (UPDATE(QtyToRepair))
BEGIN
UPDATE SCHEDULE SET modified = GETDATE()
, ModifiedUser = SUSER_NAME()
, ModifiedHost = HOST_NAME()
FROM SCHEDULE S
INNER JOIN Inserted I ON S.OrderNo = I.OrderNo AND S.PartNumber = I.PartNumber
WHERE S.QtyToRepair <> I.QtyToRepair
END
END
Please note that this trigger will fire each time you update the column no matter if the value is the same or not.
$("#id").change(function(){
//does some stuff;
});
First, Single
throws an exception if there is more than one element satisfying the criteria. Second, your criteria should only check if the Correct
property is true
. Right now, you are checking if a
is equal to a.Correct
(which will not even compile).
You should use First
(which will throw if there are no such elements), or FirstOrDefault
(which will return null
for a reference type if there isn't such element):
// this will return the first correct answer,
// or throw an exception if there are no correct answers
var correct = answers.First(a => a.Correct);
// this will return the first correct answer,
// or null if there are no correct answers
var correct = answers.FirstOrDefault(a => a.Correct);
// this will return a list containing all answers which are correct,
// or an empty list if there are no correct answers
var allCorrect = answers.Where(a => a.Correct).ToList();
You can do via Page directive.
For example:
<%@ page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8"%>
The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.
You could use id in span directly in your html.
<span id="span_id">Client</span>
Then your jQuery code would be
$("#span_id").text();
Some one helped me to check errors and found that he used val() instead of text(), it is not possible to use val() function in span. So
$("#span_id").val();
will return null.
These two procedures let me reset the sequence and reset the sequence based on data in a table (apologies for the coding conventions used by this client):
CREATE OR REPLACE PROCEDURE SET_SEQ_TO(p_name IN VARCHAR2, p_val IN NUMBER)
AS
l_num NUMBER;
BEGIN
EXECUTE IMMEDIATE 'select ' || p_name || '.nextval from dual' INTO l_num;
-- Added check for 0 to avoid "ORA-04002: INCREMENT must be a non-zero integer"
IF (p_val - l_num - 1) != 0
THEN
EXECUTE IMMEDIATE 'alter sequence ' || p_name || ' increment by ' || (p_val - l_num - 1) || ' minvalue 0';
END IF;
EXECUTE IMMEDIATE 'select ' || p_name || '.nextval from dual' INTO l_num;
EXECUTE IMMEDIATE 'alter sequence ' || p_name || ' increment by 1 ';
DBMS_OUTPUT.put_line('Sequence ' || p_name || ' is now at ' || p_val);
END;
CREATE OR REPLACE PROCEDURE SET_SEQ_TO_DATA(seq_name IN VARCHAR2, table_name IN VARCHAR2, col_name IN VARCHAR2)
AS
nextnum NUMBER;
BEGIN
EXECUTE IMMEDIATE 'SELECT MAX(' || col_name || ') + 1 AS n FROM ' || table_name INTO nextnum;
SET_SEQ_TO(seq_name, nextnum);
END;
Use %g with big enough width, for example '%.99g'. It will print in fixed-point notation for any reasonably big number.
EDIT: it doesn't work
>>> '%.99g' % 0.0000001
'9.99999999999999954748111825886258685613938723690807819366455078125e-08'
Need to add lazy for TapGestureRecognizer to register
since the 'self' in UITapGestureRecognizer(target: self ...) will be nil if it's not a lazy var. Even if you set isUserInteractionEnable = true, it won't register without lazy var.
lazy var imageSelector : UIImageView = {
let image = UIImageView(image: "imageName.png")
//now add tap gesture
image.isUserInteractionEnabled = true
image.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageSelector)))
return image
}()
@objc private func handleImageSelector() {
print("Pressed image selector")
}
(Can't comment yet with enough reputation , let me add a sidenote)
Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000 on it .
yourNumber=1001;
yourString= yourNumber.ToString("D3"); // "1001"
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected
Trail sample on Fiddler https://dotnetfiddle.net/qLrePt
CODE
<?php
# setup test array.
$cats = array();
$cats[] = (object) array('id' => 15);
$cats[] = (object) array('id' => 18);
$cats[] = (object) array('id' => 23);
function extract_ids($array = array())
{
$ids = array();
foreach ($array as $object) {
$ids[] = $object->id;
}
return $ids;
}
$cat_ids = extract_ids($cats);
var_dump($cats);
var_dump($cat_ids);
?>
OUTPUT
# var_dump($cats);
array(3) {
[0]=>
object(stdClass)#1 (1) {
["id"]=>
int(15)
}
[1]=>
object(stdClass)#2 (1) {
["id"]=>
int(18)
}
[2]=>
object(stdClass)#3 (1) {
["id"]=>
int(23)
}
}
# var_dump($cat_ids);
array(3) {
[0]=>
int(15)
[1]=>
int(18)
[2]=>
int(23)
}
I know its using a loop, but it's the simplest way to do it! And using a function it still ends up on a single line.
Following Ronald Example I would like to add that it should be considered if the origin and end dates must be included or not in the days count between two dates. I faced the same problem and ended up using a third option with apply. It could be memory inefficient but helps to understand the problem:
survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))
survey$diff_1 <- as.numeric(
as.Date(as.character(survey$date), format="%Y/%m/%d")-
as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
)
survey$diff_2<- as.numeric(
difftime(survey$date ,survey$tx_start , units = c("days"))
)
survey$diff_3 <- apply(X = survey[,c("date", "tx_start")],
MARGIN = 1,
FUN = function(x)
length(
seq.Date(
from = as.Date(x[2]),
to = as.Date(x[1]),
by = "day")
)
)
This gives the following date differences:
date tx_start diff_1 diff_2 diff_3
1 2012/07/26 2012/01/01 207 206.9583 208
2 2012/07/25 2012/01/01 206 205.9583 207
Just wrap the textarea with the label and set the textarea style to
vertical-align: middle;
Here is some magic for all textareas on the page:)
<style>
label textarea{
vertical-align: middle;
}
</style>
<label>Blah blah blah Description: <textarea>dura bura</textarea></label>
For right pad you need String.format("%0$-15s", str)
i.e. -
sign will "right" pad and no -
sign will "left" pad
See my example:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.nextLine();
Scanner line = new Scanner( s1);
line=line.useDelimiter(" ");
String language = line.next();
int mark = line.nextInt();;
System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);
}
System.out.println("================================");
}
}
The input must be a string and a number
example input : Google 1
It depends on what you want to do with the script (or any other program you want to run).
If you just want to run the script system
is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).
If you want to either feed the shell script via its standard input or consume its standard output you can use popen
(and pclose
) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.
Both of these are library functions that do a lot under the hood, but if they don't meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.
The system calls of interest are fork
, execve
, and waitpid
. You may want to use one of the library wrappers around execve
(type man 3 exec
for a list of them). You may also want to use one of the other wait functions (man 2 wait
has them all). Additionally you may be interested in the system calls clone
and vfork
which are related to fork.
fork
duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process's process id (or an error) returned.
execve
replaces the current program with a new program (keeping the same process id).
waitpid
is used by a parent process to wait on a particular child process to finish.
Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won't need, changing the session, or changing the environmental variables.
You may also be interested in the pipe
and dup2
system calls. pipe
creates a pipe (with both an input and an output file descriptor). dup2
duplicates a file descriptor as a specific file descriptor (dup
is similar but duplicates a file descriptor to the lowest available file descriptor).
You can check this solved your problem...
#headermenu ul{
text-align: center;
}
#headermenu li {
list-style-type: none;
display: inline-block;
}
#headermenu ul li a{
float: left;
}
You need to add your files to your working copy, before you commit your changes to the repository:
svn add <file|folder>
Afterwards:
svn commit
See here for detailed information about svn add
.
TortoiseSVN
It works with TortoiseSVN, because it adds the file to your working copy automatically (commit dialog):
If you want to include an unversioned file, just check that file to add it to the commit.
Don't put the @ before the id
new { id = "1" }
The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route
Another method for cleaner argument passing would be splatting.
Define your parameters and values as a hashtable like this:
$params = @{ 'class' = 'Win32_BIOS';
'computername'='SERVER-R2';
'filter'='drivetype=3';
'credential'='Administrator' }
And then call your commandlet like this:
Get-WmiObject @params
Microsoft Docs: About Splatting
TechNet Magazine 2011: Windows PowerShell: Splatting
For those crazy enough to use Fish shell on EC2, here's a handy snippet for your /home/ec2-user/.config/fish/config.fish. The hostdata command now will list all your tags as well as the public IP and hostname.
set -x INSTANCE_ID (wget -qO- http://instance-data/latest/meta-data/instance-id)
set -x REGION (wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')
function hostdata
aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | sed -r 's/TAGS\t(.*)\t.*\t.*\t(.*)/\1="\2"/'
ec2-metadata | grep public-hostname
ec2-metadata | grep public-ipv4
end
Clearing the Cache of your React Native Project: if you are sure the module exists, try this steps:
if there is no value inserted, the default value should be null,empty
In the table definition, make this datetime
column allows null, be not defining NOT NULL
:
...
DateTimeColumn DateTime,
...
I HAVE ALLOWED NULL VARIABLES THOUGH.
Then , just insert NULL
in this column:
INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);
Or, you can make use of the DEFAULT constaints:
...
DateTimeColumn DateTime DEFAULT NULL,
...
Then you can ignore it completely in the INSERT
statement and it will be inserted withe the NULL
value:
INSERT INTO Table(name, ...)
VALUES('foo bar', ..);
You can continue chaining them like you've done.
results = results.Where (o => o.OrderStatus == OrderStatus.Open);
results = results.Where (o => o.InvoicePaid);
This represents an AND.
One other thing to check is whether your current user is authorised to connect to the X display. In my case, root was not allowed to do that and matplotlib was complaining with the same error.
user@debian:~$ xauth list
debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xauth add debian/unix:10 MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xterm
source: http://www.debian-administration.org/articles/494 https://debian-administration.org/article/494/Getting_X11_forwarding_through_ssh_working_after_running_su
When your class implements Comparable, the compareTo
method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals()
comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b")
would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
Alternatively, you can also use a special function known as the linear-gradient() function to split browser screen into two equal halves. Check out the following code snippet:
body
{
background-image:linear-gradient(90deg, lightblue 50%, skyblue 50%);
}
Here, linear-gradient() function accepts three arguments
90deg
for vertical division of screen.( Similarly, you can use 180deg
for horizontal division of screen)lightblue
color is used to represent the left half of the screen.skyblue
color has been used to represent the right half of the split screen.
Here, 50%
has been used for equal division of the browser screen. You can use any other value if you don't want an equal division of the screen.
Hope this helps. :)
Happy Coding!1. Include the Open Graph XML namespace extension to your HTML declaration
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://ogp.me/ns/fb#">
2. Inside your <head></head>
use the following meta tag to define the image you want to use
<meta property="og:image" content="fully_qualified_image_url_here" />
Read more about open graph protocol here.
After doing the above, use the Facebook "Object Debugger" if the image does not show up correctly. Also note the first time shared it still won't show up unless height and width are also specified, see Share on Facebook - Thumbnail not showing for the first time
I too ran into this, what caused this for me is that while cloning the repo I was pushing my changes to, I picked up the clone URL from an incognito tab without signing in. (I am still clueless on how it effects). That for some reason led to git picking another user account. When i tried it again from a proper signed in page it worked like usual for me.
If you have created dynamic Web project and have placed the required image in WebContent then you can access the image by using below mentioned code in Spring MVC:
<img src="Refresh.png" alt="Refresh" height="50" width="50">
You can also create folder named img and place the image inside the folder img and place that img folder inside WebContent then you can access the image by using below mentioned code:
<img src="img/Refresh.png" alt="Refresh" height="50" width="50">
It should also be mentioned that the "pk" should be a key field. The self-join
SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk
by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried
SELECT * FROM db.table HAVING COUNT(someField) > 1
above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.
The best example of an abstract class is GenericServlet
. GenericServlet
is the parent class of HttpServlet
. It is an abstract class.
When inheriting 'GenericServlet' in a custom servlet class, the service()
method must be overridden.
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program`enter code here`
{
static void Main(string[] args)
{
using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
{
writer.WriteLine("Information about this package.");
writer.WriteLine("========================");
}
}
}
}
}
}
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
If you are in a directory where only root have access to write in system. Then you can directly use wget www.example.com/wget-test
using a standard user account. So it will hit the url but because of having no write permission file won't be saved..
This method is working fine for me as i am using this method for a cronjob.
Thanks.
sthx
You shouldn't be using the BinaryFormatter
for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.
If it's stored in the database, hopefully, as a varbinary
- then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.
With any luck - I'm hoping that fileContent
here is the byte array? In which case you can just do
System.IO.File.WriteAllBytes("hello.pdf", fileContent);
First, we need to filter the XML so as to parse that change objects become array
//catch xml
$xmlElement = file_get_contents ('php://input');
//change become array
$Data = (array)simplexml_load_string($xmlElement);
//and see
print_r($Data);
I know this is a very old question but I didn't see anybody talking about the main difference between process.stdout.write
and console.log
and I just want to mention it.
As Mauvis Leford and TK-421 pointed out, the console.log
adds a line-break
character at the end of the line (\n
) but that's not all what it does.
The code has not changed since at least 0.10.X
version and now we have a a 5.X
version.
Here is the code:
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
As you can see, there is a part that says .apply(this, arguments)
and that makes a big difference on functionality. It is easier to explain that with examples:
process.stdout.write
has a very basic functionality, you can just write something in there, like this:
process.stdout.write("Hello World\n");
If you don't put the break line at the end you will get a weird character after your string, something like this:
process.stdout.write("Hello World"); //Hello World%
(I think that means something like "the end of the program", so you will see it only if you process.stdout.write
was used at the end of your file and you didn't add the break line)
On the other hand, console.log
can do more.
You can use it in the same way
console.log("Hello World"); //You don't need the break line here because it was already formated
and also that weird character did disappear
You can write more than one string
console.log("Hello", "World");
You can make associations
console.log("Hello %s", "World") //Useful when "World" is inside a variable
An that's it, that added functionality is given thanks to the util.format.apply
part (I could talk a lot about what exactly this does but you get my point, you can read more here).
I hope somebody find this information useful.
According to Dangerously Set innerHTML,
Improper use of the
innerHTML
can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.Our design philosophy is that it should be "easy" to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. The prop name
dangerouslySetInnerHTML
is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.After fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key
__html
and your sanitized data as the value. Here is an example using the JSX syntax:
function createMarkup() {
return {
__html: 'First · Second' };
};
<div dangerouslySetInnerHTML={createMarkup()} />
Read more about it using below link:
documentation: React DOM Elements - dangerouslySetInnerHTML.
Go to File > Source Control > Go Online
, select the files you changed, and finish the process.
Two approaches are to write to a string buffer or to write lines to a list and join them later. I think the StringIO
approach is more pythonic, but didn't work before Python 2.6.
from io import StringIO
with StringIO() as s:
print("Hello", file=s)
print("Goodbye", file=s)
# And later...
with open('myfile', 'w') as f:
f.write(s.getvalue())
You can also use these without a ContextMananger
(s = StringIO()
). Currently, I'm using a context manager class with a print
function. This fragment might be useful to be able to insert debugging or odd paging requirements:
class Report:
... usual init/enter/exit
def print(self, *args, **kwargs):
with StringIO() as s:
print(*args, **kwargs, file=s)
out = s.getvalue()
... stuff with out
with Report() as r:
r.print(f"This is {datetime.date.today()}!", 'Yikes!', end=':')
public async Task<bool> Update(MyObject item)
{
Context.Entry(await Context.MyDbSet.FirstOrDefaultAsync(x => x.Id == item.Id)).CurrentValues.SetValues(item);
return (await Context.SaveChangesAsync()) > 0;
}
If I may I could give you some new code for the same task, in my code you can create a so called 'document'(not really)and it is saved, and can be opened up again. It is also stored as a string file though(not a document). Here is the code:
#include "iostream"
#include "windows.h"
#include "string"
#include "fstream"
using namespace std;
int main() {
string saveload;
cout << "---------------------------" << endl;
cout << "|enter 'text' to write your document |" << endl;
cout << "|enter 'open file' to open the document |" << endl;
cout << "----------------------------------------" << endl;
while (true){
getline(cin, saveload);
if (saveload == "open file"){
string filenamet;
cout << "file name? " << endl;
getline(cin, filenamet, '*');
ifstream loadFile;
loadFile.open(filenamet, ifstream::in);
cout << "the text you entered was: ";
while (loadFile.good()){
cout << (char)loadFile.get();
Sleep(100);
}
cout << "" << endl;
loadFile.close();
}
if (saveload == "text") {
string filename;
cout << "file name: " << endl;
getline(cin, filename,'*');
string textToSave;
cout << "Enter your text: " << endl;
getline(cin, textToSave,'*');
ofstream saveFile(filename);
saveFile << textToSave;
saveFile.close();
}
}
return 0;
}
Just take this code and change it to serve your purpose. DREAM BIG,THINK BIG, DO BIG
On a rooted device, you might use:
String pkg = context.getPackageName();
String shellCmd = "rm -r /data/app/" + pkg + "*.apk\n"
+ "rm -r /data/data/" + pkg + "\n"
// TODO remove data on the sd card
+ "sync\n"
+ "reboot\n";
Util.sudo(shellCmd);
If your app use multiple webview you will still have troubles : localStorage is not correctly shared accross all webviews.
If you want to share the same data in multiple webviews the only way is to repair it with a java database and a javascript interface.
This page on github shows how to do this.
hope this help!
I had the same problem with something like
@foreach (var item in Model)
{
@Html.DisplayFor(m => !item.IsIdle, "BoolIcon")
}
I solved this just by doing
@foreach (var item in Model)
{
var active = !item.IsIdle;
@Html.DisplayFor(m => active , "BoolIcon")
}
When you know the trick, it's simple.
The difference is that, in the first case, I passed a method as a parameter whereas in the second case, it's an expression.
The easiest way is to use lubridate:
library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)
This function automatically returns objects of class POSIXct
and will work with either factors or characters.
@Prashant Tukadiya answer works. But if you want to save the value in UserDefaults and then compare it to other date you get yout int64 truncated so it can cause problems. I found a solution.
Swift 4:
You can save int64 as string in UserDefaults:
let value: String(Date().millisecondsSince1970)
let stringValue = String(value)
UserDefaults.standard.set(stringValue, forKey: "int64String")
Like that you avoid Int truncation.
And then you can recover the original value:
let int64String = UserDefaults.standard.string(forKey: "int64String")
let originalValue = Int64(int64String!)
This allow you to compare it with other date values:
let currentTime = Date().millisecondsSince1970
let int64String = UserDefaults.standard.string(forKey: "int64String")
let originalValue = Int64(int64String!) ?? 0
if currentTime < originalValue {
return false
} else {
return true
}
Hope this helps someone who has same problem
I experienced this error due to my corporate network using one proxy while on premise, and a second (completely different) proxy when VPN'd from the outside. I was originally configured for the on-premise proxy, received the error, and then had to update my config to use the alternate, off-prem, proxy when working elsewhere.
This is simple but the developer gets confused due to multiple views having the same attributes in different configurations/namespaces.
In the case of the TextInputLayout we have every time a different view and with params either with TextInputEditText or directly to TextInputLayout.
I was using all the above fixes: But I found that I was using
app:textColorHint="@color/textcolor_black"
actually i should be using
android:textColorHint="@color/textcolor_black"
As an attribute of TextinputLayout
textcolor_black.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/black_txt" android:state_enabled="true" />
<item android:color="@color/black_txt" android:state_selected="true" />
<item android:color="@color/txtColorGray" android:state_selected="false" />
<item android:color="@color/txtColorGray" android:state_enabled="false" />
</selector>
You can use strcpy to populate it. You can also initialize it from another struct.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct name {
char first[20];
char last[20];
};
int main() {
struct name sara;
struct name other;
strcpy(sara.first,"Sara");
strcpy(sara.last, "Black");
other = sara;
printf("struct: %s\t%s\n", sara.first, sara.last);
printf("other struct: %s\t%s\n", other.first, other.last);
}
For a really thorough explanation and workaround, not only for indexOf but other array functions missing in IE check out the StackOverflow question Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.)
For newer versions of sdk you have to set flag activity task.
public void onClick(View v)
{
Intent myactivity = new Intent(context.getApplicationContext(), OtherActivity.class);
myactivity.addFlags(FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(myactivity);
}
When the DOM is finished loading you can add your code in the $(document).ready()
function.
Remove the onclick from here:
<input type="submit" name="submit" value="Submit" onClick="PopUp()" />
Try this:
$(document).ready(function(){
setTimeout(function(){
PopUp();
},5000); // 5000 to load it after 5 seconds from page load
});
In SL5 I found this to work:
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat=dd-MMMM-yy hh:mm}">
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat='Justification Date: \{0:dd-MMMM-yy hh:mm\}'}">
I have a simple answer to this problem. I created a thread to update the time. In the thread i run a while loop which gets the time and update it. Check the below code and do not forget to mark it as right answer.
from tkinter import *
from tkinter import *
import _thread
import time
def update():
while True:
t=time.strftime('%I:%M:%S',time.localtime())
time_label['text'] = t
win = Tk()
win.geometry('200x200')
time_label = Label(win, text='0:0:0', font=('',15))
time_label.pack()
_thread.start_new_thread(update,())
win.mainloop()
This moment.utc(stringDate, format).toDate()
worked for me.
This not.moment.utc(date).toDate()
What I tend to do is replace the null values in the SELECT statement with something appropriate.
SELECT ISNULL(firstname, '') FROM people
Here I replace every null with a blank string. Your code won't throw in error in that case.
Our approach is simple, but it works! :)
When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.
<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
function logOut() {
window.close = function () {
window.open('Default.aspx', '_blank');
};
}
</script>
It is possible, if you're using a browser which supports the CSS :valid
pseudo-class and the pattern
validation attribute on inputs -- which includes most modern browsers except IE9.
For instance, to change the text of an input from black to green when the correct answer is entered:
input {_x000D_
color: black;_x000D_
}_x000D_
input:valid {_x000D_
color: green;_x000D_
}
_x000D_
<p>Which country has fifty states?</p>_x000D_
_x000D_
<input type="text" pattern="^United States$">
_x000D_
Before Rails 2.x the preferred way to get the current environment was using the RAILS_ENV
constant. Likewise, you can use RAILS_DEFAULT_LOGGER
to get the current logger or RAILS_ROOT
to get the path to the root folder.
Starting from Rails 2.x, Rails introduced the Rails
module with some special methods:
This isn't just a cosmetic change. The Rails module offers capabilities not available using the standard constants such as StringInquirer
support.
There are also some slight differences. Rails.root
doesn't return a simple String
buth a Path
instance.
Anyway, the preferred way is using the Rails
module. Constants are deprecated in Rails 3 and will be removed in a future release, perhaps Rails 3.1.
This deals with computational round-off. You set the epsilon as desired:
bool IsInteger(float value)
{
return fabs(ceilf(value) - value) < EPSILON;
}
I know this is a very old question but feel this adds a valuable alternative of how to deal with the console issue. Place the following code before any call to console.* (so your very first script).
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
Reference:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js
In case anyone else faces this, it's a case of PHP not having access to the mysql client libraries. Having a MySQL server on the system is not the correct fix. Fix for ubuntu (and PHP 5):
sudo apt-get install php5-mysql
After installing the client, the webserver should be restarted. In case you're using apache, the following should work:
sudo service apache2 restart
Just Remove * from your select clause, and mention all column names explicitly and omit the FIRSTNAME column. After this write CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME. The above query will give you the only one FIRSTNAME column.
The error message is due to the unfortunate fact that PHP will implicitly declare an unknown token as a constant string of the same name.
That is, it's trying to interpret this (note the missing quote marks):
$_POST[department]
The only valid way this would be valid syntax in PHP is if there was previously a constant department
defined. So sadly, rather than dying with a Fatal error at this point, it issues this Notice and acts as though a constant had been defined with the same name and value:
// Implicit declaration of constant called department with value 'department'
define('department', 'department');
There are various ways you can get this error message, but they all have the same root cause - a token that could be a constant.
$my_array[bad_key]
This is what the problem is in your case, and it's because you've got string array keys that haven't been quoted. Fixing the string keys will fix the bug:
Change:
$department = mysql_real_escape_string($_POST[department]);
...(etc)...
To:
$department = mysql_real_escape_string($_POST['department']);
...(etc)...
var_without_dollar
Another reason you might see this error message is if you leave off the $
from a variable, or $this->
from a member. Eg, either of the following would cause a similar error message:
my_local; // should be $my_local
my_member; // should be $this->my_member
$bad-variable-name
A similar but more subtle issue can result if you try to use a disallowed character in a variable name - a hyphen (-
) instead of an underscore _
would be a common case.
For example, this is OK, since underscores are allowed in variable names:
if (123 === $my_var) {
do_something();
}
But this isn't:
if (123 === $my-var) {
do_something();
}
It'll be interpreted the same as this:
if (123 === $my - var) { // variable $my minus constant 'var'
do_something();
}
In order to refer to a class constant you need to specify the class scope with ::
, if you miss this off PHP will think you're talking about a global define()
.
Eg:
class MyClass {
const MY_CONST = 123;
public function my_method() {
return self::MY_CONST; // This is fine
}
public function my_method() {
return MyClass::MY_CONST; // This is fine
}
public function my_bad_method() {
return MY_CONST; // BUG - need to specify class scope
}
}
There are some system-defined constants that only exist in newer versions of PHP, for example the mode option constants for round()
such as PHP_ROUND_HALF_DOWN
only exist in PHP 5.3 or later.
So if you tried to use this feature in PHP 5.2, say:
$rounded = round($my_var, 0, PHP_ROUND_HALF_DOWN);
You'd get this error message:
Use of undefined constant PHP_ROUND_HALF_DOWN - assumed 'PHP_ROUND_HALF_DOWN' Warning (2): Wrong parameter count for round()
Install NODE.JS on windows before installing aptana
Try the following link http://blueashes.com/2011/web-development/install-nodejs-on-windows/
I had the same problem and could not find a solution. Mark90 is right there are a lot info.plist files and you should edit the correct. Go to Project, under TARGETS select the project (not the tests), in the tab bar select Info and add the permission under "Custom iOS Target Properties".
You can try:
System.arraycopy(sourceArray, 0, targetArray, 0, targetArray.length);// copies whole array
// copies elements 1 and 2 from sourceArray to targetArray
System.arraycopy(sourceArray, 1, targetArray, 0, 2);
See javadoc for System.
Here's another possible reason besides the console.log
issue (at least in IE11):
When the console is not open, IE does pretty aggressive caching, so make sure that any $.ajax
calls or XMLHttpRequest
calls have caching set to false.
For example:
$.ajax({cache: false, ...})
When the developer console is open, caching is less aggressive. Seems to be a bug (or maybe a feature?)
Quickly : you can do :
// Fixed-size list
List list = Arrays.asList(array);
// Growable list
list = new LinkedList(Arrays.asList(array));
// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));
and to reverse
// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);
// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);
In the beginning, a compiler was responsible for turning a high-level language (defined as higher level than assembler) into object code (machine instructions), which would then be linked (by a linker) into an executable.
At one point in the evolution of languages, compilers would compile a high-level language into pseudo-code, which would then be interpreted (by an interpreter) to run your program. This eliminated the object code and executables, and allowed these languages to be portable to multiple operating systems and hardware platforms. Pascal (which compiled to P-Code) was one of the first; Java and C# are more recent examples. Eventually the term P-Code was replaced with bytecode, since most of the pseudo-operations are a byte long.
A Just-In-Time (JIT) compiler is a feature of the run-time interpreter, that instead of interpreting bytecode every time a method is invoked, will compile the bytecode into the machine code instructions of the running machine, and then invoke this object code instead. Ideally the efficiency of running object code will overcome the inefficiency of recompiling the program every time it runs.
In my case (using Laravel 5.3) adding only the following 2 middleware allowed me to access session data in my API routes:
\App\Http\Middleware\EncryptCookies::class
\Illuminate\Session\Middleware\StartSession::class
Whole declaration ($middlewareGroups
in Kernel.php):
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
'throttle:60,1',
'bindings',
],
Here is simple way using Top object.
eg: If absolute element size is 60px.
.absolute-element {
position:absolute;
height:60px;
top: calc(50% - 60px);
}
You can also use ng-pattern
and I feel that will be a best practice. Similarly try to use ng-message
. Please look the ng-pattern attribute on the following html. The code snippet is partial but hope you understand it.
angular.module('myApp', ['ngMessages']);
angular.module("myApp.controllers",[]).controller("registerCtrl", function($scope, Client) {
$scope.ph_numbr = /^(\+?(\d{1}|\d{2}|\d{3})[- ]?)?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
});
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{ 'has-error' : (registration.phone.$invalid || registration.phone.$pristine)}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number" class="form-control" ng-pattern="ph_numbr" id="inputPhone" name="phone" placeholder="Phone" ng-model="user.phone" ng-required="true">
<div class="help-block" ng-messages="registration.phone.$error">
<p ng-message="required">Phone number is required.</p>
<p ng-message="pattern">Phone number is invalid.</p>
</div>
</div>
</div>
</form>
There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider
JS
var myvar=15;
function init(){
document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;
HTML
<input id="EditBanner" type="button" value="Edit Image" />
Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.
In my case , my -Dloader.path="lib"
contains other jars that doesn't need.
for example,mvn dependency:copy-dependencies
lists 100 jar files.but my lib
directory contains 101 jar files.
This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.
In this case, tester method needs to have access to Class, and you can construct
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, Foo.class)
and then
List<Foo> list = mapper.readValue(new File("input.json"), type);
Import your library project to Intellij from Eclipse project (this step only applies if you created your library in Eclipse).
Right click on module and choose Open Module Settings.
Setup libraries of v7 jar file
Setup library module of v7
Setup app module dependency of v7 library module
You need to escape the % with another...
del "D:\TEST\TEST 100%%\Archive*.TXT"
Solved by adding the following dependency into pom.xml file :
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList = parameterList.Where(param => param != null).ToList();
There are some libraries around there:
Commons-BeanUtils: ConvertUtils -> Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.
Commons-Lang: ArrayUtils -> Operations on arrays, primitive arrays (like int[]) and primitive wrapper arrays (like Integer[]).
Spring framework: Spring has an excellent support for PropertyEditors, that can also be used to transform Objects to/from Strings.
Dozer: Dozer is a powerful, yet simple Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.
ModelMapper: ModelMapper is an intelligent object mapping framework that automatically maps objects to each other. It uses a convention based approach to map objects while providing a simple refactoring safe API for handling specific use cases.
MapStruct: MapStruct is a compile-time code generator for bean mappings, resulting in fast (no usage of reflection or similar), dependency-less and type-safe mapping code at runtime.
Orika: Orika uses byte code generation to create fast mappers with minimal overhead.
Selma: Compile-time code-generator for mappings
JMapper: Bean mapper generation using Annotation, XML or API (seems dead, last updated 2 years ago)
Smooks: The Smooks JavaBean Cartridge allows you to create and populate Java objects from your message data (i.e. bind data to) (suggested by superfilin in comments). (No longer under active development)
Commons-Convert: Commons-Convert aims to provide a single library dedicated to the task of converting an object of one type to another. The first stage will focus on Object to String and String to Object conversions. (seems dead, last update 2010)
Transmorph: Transmorph is a free java library used to convert a Java object of one type into an object of another type (with another signature, possibly parameterized). (seems dead, last update 2013)
EZMorph: EZMorph is simple java library for transforming an Object to another Object. It supports transformations for primitives and Objects, for multidimensional arrays and transformations with DynaBeans (seems dead, last updated 2008)
Morph: Morph is a Java framework that eases the internal interoperability of an application. As information flows through an application, it undergoes multiple transformations. Morph provides a standard way to implement these transformations. (seems dead, last update 2008)
Lorentz: Lorentz is a generic object-to-object conversion framework. It provides a simple API to convert a Java objects of one type into an object of another type. (seems dead)
OTOM: With OTOM, you can copy any data from any object to any other object. The possibilities are endless. Welcome to "Autumn". (seems dead)
All you need is in the documentation.
import time
time.strftime('%X %x %Z')
'16:08:12 05/08/03 AEST'
With gazpacho you could pipeline the page straight into a parse-able soup object:
from gazpacho import Soup
url = "http://www.thefamouspeople.com/singers.php"
soup = Soup.get(url)
And run finds on top of it:
soup.find("div")
Try this code-
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
It will return user selected timezone.
If you put set -e
in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.
The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.
Commands whose status is tested by a conditional (such as if
, &&
or ||
) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter is command-that-may-fail || true
. You can also turn set -e
off for a part of the script with set +e
.
An example Extension class to simplify this: -
internal static class String
{
public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;
private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}
Usage
"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)
"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something' (End Characters removed)
"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!' (Only End instances removed)
Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll
instead. Almost all selector strings used for jQuery work with DOM methods as well:
const anchors = document.querySelectorAll('a[href$="ABC"]');
Or, if you know that there's only one matching element:
const anchor = document.querySelector('a[href$="ABC"]');
You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use
a[href$=ABC]
but quotes are more flexible and generally more reliable.
It could be something like
var myvar = from a in context.MyEntity
join b in context.MyEntity2 on a.key equals b.key
select new { prop1 = a.prop1, prop2= b.prop1};
public static void deleteLine(String line, String filePath) {
File file = new File(filePath);
File file2 = new File(file.getParent() + "\\temp" + file.getName());
PrintWriter pw = null;
Scanner read = null;
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel src = null;
FileChannel dest = null;
try {
pw = new PrintWriter(file2);
read = new Scanner(file);
while (read.hasNextLine()) {
String currline = read.nextLine();
if (line.equalsIgnoreCase(currline)) {
continue;
} else {
pw.println(currline);
}
}
pw.flush();
fis = new FileInputStream(file2);
src = fis.getChannel();
fos = new FileOutputStream(file);
dest = fos.getChannel();
dest.transferFrom(src, 0, src.size());
} catch (IOException e) {
e.printStackTrace();
} finally {
pw.close();
read.close();
try {
fis.close();
fos.close();
src.close();
dest.close();
} catch (IOException e) {
e.printStackTrace();
}
if (file2.delete()) {
System.out.println("File is deleted");
} else {
System.out.println("Error occured! File: " + file2.getName() + " is not deleted!");
}
}
}
A general answer for a general question... Transitions can't animate properties that are auto. If you have a transition not working, check that the starting value of the property is explicitly set. (For example, to make a node collapse, when it's height is auto and must stay that way, put the transition on max-height instead. Give max-height a sensible initial value, then transition it to 0)
Typically you model the enum itself as a class with the enum
stereotype
You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:
1.) change type of ID to int
instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea
First option requires to change every table that has a reference to this table, BUT it's worth it.
Actually you can still have a Map
with the original keys after converting to array with Array.from
. That's possible by returning an array, where the first item is the key
, and the second is the transformed value
.
const originalMap = new Map([
["thing1", 1], ["thing2", 2], ["thing3", 3]
]);
const arrayMap = Array.from(originalMap, ([key, value]) => {
return [key, value + 1]; // return an array
});
const alteredMap = new Map(arrayMap);
console.log(originalMap); // Map { 'thing1' => 1, 'thing2' => 2, 'thing3' => 3 }
console.log(alteredMap); // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }
If you don't return that key as the first array item, you loose your Map
keys.
There are many, many ways to code this, but here is one possible way. I'm assuming MS SQL
We'll start by getting row count (Another Quick Example) and then do if/else
-- Let's get our row count and assign it to a var that will be used
-- in our if stmt
DECLARE @HasExistingRows int -- I'm assuming it can fit into an int
SELECT @HasExistingRows = Count(*)
ELSE 0 -- false
FROM
INCIDENTS
WHERE {Your Criteria}
GROUP BY {Required Grouping}
Now we can do the If / Else Logic MSDN Docs
-- IF / Else / Begin / END Syntax
IF @HasExistingRows = 0 -- No Existing Rows
BEGIN
{Insert Logic for No Existing Rows}
END
ELSE -- existing rows are found
BEGIN
{Insert logic for existing rows}
END
Another faster way (inspired by Mahmoud Gamal's comment):
Forget the whole variable creation / assignment - look up "EXISTS" - MSDN Docs 2.
IF EXISTS ({SELECT Query})
BEGIN
{INSERT Version 1}
END
ELSE
BEGIN
{INSERT version 2}
END